This commit is contained in:
2026-10-29 15:21:05 +01:00
parent bb85881cac
commit bc05b63083
36 changed files with 4654 additions and 5080 deletions

View File

@@ -997,7 +997,13 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
match = sentence.match(/^add ((?:\{[^}]+\})(?:,? ?(?:or )?\{[^}]+\})*)$/)
if (match) {
const symbols = match[1].match(/\{[^}]+\}/g)
if (symbols) return { op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols } }
if (symbols) {
return {
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols, ...(/\bor\b/i.test(match[1]) ? { oneOf: true } : {}) },
}
}
}
match = sentence.match(/^add (one|two|three|four|five|x) mana of any (one )?color( in your commander's color identity)?$/)
@@ -2068,6 +2074,11 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined {
if (sentence === 'this enters tapped') {
return [{ op: 'enters_tapped', target: { kind: 'self' } }]
}
match = sentence.match(/^as this enters, you may pay (\w+) life\. if you don't, it enters tapped$/)
if (match) {
const amount = parseValue(match[1])
if (amount) return [{ op: 'enters_tapped', target: { kind: 'self' }, unlessCost: { kind: 'pay_life', amount } }]
}
const entersTappedUnless = sentence.match(/^this enters tapped unless (.+)$/)
if (entersTappedUnless) {
const unless = parseCondition(entersTappedUnless[1])
@@ -2475,7 +2486,7 @@ function compileFace(face: CardFace | { name: string; oracle_text?: string; type
const ability = compileLine(line, face.name, known, isSpell)
if (!(ability.kind === 'unsupported' && ability.reason === 'empty')) abilities.push(ability)
}
return { name: face.name, status: statusOf(abilities), abilities }
return { name: face.name, typeLine: face.type_line, status: statusOf(abilities), abilities }
}
export function compileCard(card: Card): CompiledCard {
@@ -2485,7 +2496,7 @@ export function compileCard(card: Card): CompiledCard {
const status: Status = statuses.includes('unsupported')
? statuses.every(value => value === 'unsupported') ? 'unsupported' : 'partial'
: statuses.includes('partial') ? 'partial' : 'supported'
return { oracle_id: card.oracle_id, name: card.name, status, abilities: [], faces }
return { oracle_id: card.oracle_id, name: card.name, typeLine: card.type_line, status, abilities: [], faces }
}
const face = compileFace(
@@ -2495,6 +2506,7 @@ export function compileCard(card: Card): CompiledCard {
return {
oracle_id: card.oracle_id,
name: card.name,
typeLine: card.type_line,
status: face.status,
abilities: face.abilities,
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
// Human-authored card implementations live in one plain-text file per oracle
// id under data/card-overrides/. The file is pseudocode in the same syntax the
// Human-authored card implementations live in one JavaScript file per oracle
// id under data/card-overrides/. The file uses the same builder API the
// formatter prints, so it stays readable and can be re-compiled by the engine.
import { readFileSync, statSync } from 'node:fs'
@@ -9,8 +9,8 @@ import { allCards } from '../cards.js'
import type { Card } from '../cards.js'
import { compileCard, statusOf } from './compile.js'
import { formatCard } from './format.js'
import { parsePseudoCard, PseudoParseError } from './pseudo.js'
import type { CompiledCard, CompiledFace } from './types.js'
import { parseCardSource, SourceParseError } from './source.js'
import type { Ability, CompiledCard, CompiledFace } from './types.js'
export type ImplementationStatus = 'supported' | 'partial' | 'unsupported'
@@ -37,7 +37,7 @@ export function overridesDir(): string {
function overrideFile(oracleId: string): string {
if (!ORACLE_ID.test(oracleId)) throw new Error(`Invalid oracle id: ${oracleId}`)
return join(overridesDir(), `${oracleId}.pseudo.txt`)
return join(overridesDir(), `${oracleId}.js`)
}
function isMissing(error: unknown): boolean {
@@ -67,7 +67,7 @@ export async function readAllOverrides(): Promise<Map<string, string>> {
}
for (const name of names) {
const oracleId = name.replace(/\.pseudo\.txt$/, '')
const oracleId = name.replace(/\.js$/, '')
if (name === oracleId || !ORACLE_ID.test(oracleId)) continue
const override = await readOverride(oracleId)
if (override) result.set(oracleId, override.source)
@@ -99,31 +99,45 @@ function facesStatus(faces: CompiledFace[]): ImplementationStatus {
return faces.some(face => face.status === 'partial') ? 'partial' : 'supported'
}
/** Parses manual pseudocode and turns it into the same AST the compiler emits. */
/** Copies the oracle label onto manual abilities so the stack log stays readable. */
function fillAbilityText(abilities: Ability[], generated: Ability[] | undefined): void {
abilities.forEach((ability, index) => {
const source = generated?.[index]
if (source && 'text' in source && source.text) {
(ability as Ability & { text?: string }).text = source.text
}
})
}
/** Parses manual JavaScript and turns it into the same AST the compiler emits. */
export function compileImplementation(card: Card, source: string): CompiledCard {
const parsed = parsePseudoCard(source)
const parsed = parseCardSource(source)
if (card.card_faces?.length) {
if (!parsed.faces?.length) {
throw new PseudoParseError(
`this card has ${card.card_faces.length} faces; add "## <face name>" sections`,
throw new SourceParseError(
`this card has ${card.card_faces.length} faces; export faces(face(...), ...)`,
1,
)
}
if (parsed.faces.length !== card.card_faces.length) {
throw new PseudoParseError(
throw new SourceParseError(
`expected ${card.card_faces.length} faces, found ${parsed.faces.length}`,
1,
)
}
const generated = compileCard(card)
const faces: CompiledFace[] = card.card_faces.map((face, index) => {
const manualFace = parsed.faces![index]
if (manualFace.name.toLowerCase() !== face.name.toLowerCase()) {
throw new PseudoParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1)
throw new SourceParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1)
}
const generatedFace = generated.faces?.find(entry => entry.name.toLowerCase() === face.name.toLowerCase())
fillAbilityText(manualFace.abilities, generatedFace?.abilities)
return {
name: face.name,
typeLine: manualFace.typeLine ?? face.type_line,
status: statusOf(manualFace.abilities),
abilities: manualFace.abilities,
}
@@ -132,6 +146,7 @@ export function compileImplementation(card: Card, source: string): CompiledCard
return {
oracle_id: card.oracle_id,
name: card.name,
typeLine: card.type_line,
status: facesStatus(faces),
abilities: [],
faces,
@@ -140,12 +155,14 @@ export function compileImplementation(card: Card, source: string): CompiledCard
}
if (parsed.faces?.length) {
throw new PseudoParseError('this card has no faces; remove the "##" sections', 1)
throw new SourceParseError('this card has no faces; export card(...) instead of faces(...)', 1)
}
fillAbilityText(parsed.abilities, compileCard(card).abilities)
return {
oracle_id: card.oracle_id,
name: card.name,
typeLine: parsed.typeLine ?? card.type_line,
status: statusOf(parsed.abilities),
abilities: parsed.abilities,
manual: true,

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,13 +1,14 @@
// Natural language -> card pseudocode through an OpenRouter-hosted model.
// The model is told to emit pseudocode only, and the answer is parsed before
// it reaches the editor, so prose or a guess never becomes an implementation.
// Natural language -> card source through an OpenRouter-hosted model.
// The model is told to emit the JavaScript card DSL only, and the answer is
// parsed before it reaches the editor, so prose or a guess never becomes an
// implementation.
import type { Card } from '../cards.js'
import { compileImplementation } from './implementations.js'
export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite'
const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions'
const MAX_TOKENS = 700
const MAX_TOKENS = 1200
export class TranslationError extends Error {
readonly status: number
@@ -22,160 +23,164 @@ export class TranslationError extends Error {
// Kept compact: it is both the model's only context and the format contract.
// Anything not listed here is rejected by the parser, so the model must not
// invent operations.
export const PSEUDO_GUIDE = `Pseudocode is line-oriented. Ability headers sit at column 0 and end with a colon. Their effects are indented two spaces, one call per line. Semicolons separate multiple effects on one line.
export const SOURCE_GUIDE = `The source is a JavaScript expression evaluated by a safe interpreter. It is never run as JavaScript: only the names listed here exist.
Multi-face cards use "## <exact face name>" lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed.
A card exports its type line and an array of abilities:
Ability headers:
on <trigger>[ if <condition>][ (may)]:
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]:
static[ if <condition>]:
spell[(may)]:
keyword <Keyword>[ value]
keywords <Keyword>, <Keyword>
additional cost[(may)]: <cost>
chapter <I>, <II>[(may)]:
level <min>-<max>[: <power>/<toughness>]
level <min>+[: <power>/<toughness>]
level_pt(<power>/<toughness>)
export default card('Creature — Human Cleric', [
triggered(when.enters(self), [gainLife(you, 1)]),
activated([tapCost()], [addMana(you, mana('{G}'))]),
])
Triggers:
enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target),
enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target),
deals_damage(target, player|creature|permanent|any), deals_combat_damage(...),
upkeep(you|opponent|each_player), end_step(...), begin_combat(...),
first_main_phase(...), postcombat_main_phase(...), becomes_level(N),
cast(you|opponent|each_player, <spell selector>|any spell[, targets this][, or copy][, #N each turn]),
draw(you|opponent|each_player[, #N each turn]), counter_placed(target[, counter]),
becomes_target(target), gain_life(you|opponent|each_player), lose_life(...)
Multi-face cards export face sections in card order:
export default faces(
face('Front', 'Instant', [ ...abilities ]),
face('Back', 'Creature — Human', [ ...abilities ]),
)
Abilities:
keyword('Flying') one keyword
keyword('Ward', '{2}') keyword with a value
keywords('Flying', 'Trample') several simple keywords
triggered(event, [effects], { condition, optional })
activated([costs], [effects], { condition, timing: 'sorcery', activationsPerTurn, optional })
staticAbility([staticEffects], { condition })
spell([effects], { optional })
additionalCost([costs], { optional })
alternativeCost([costs], { condition })
overload('{6}{U}')
chapter(['I', 'II'], [effects], { optional })
levelBand(min, max, power, toughness) max may be null
levelPt(power, toughness)
unsupported('short reason', 'original oracle text')
Any effect list (triggered, activated, staticAbility, spell, chapter, ifThen,
schedule and each modal mode) takes an array or a callback: () => effect, or
() => { effect; effect }.
Triggers (when.*):
enters(target), dies(target), attacks(target), blocks(target), attacksOrBlocks(target),
entersOrAttacks(target), entersOrDies(target), leavesBattlefield(target),
dealsDamage(target, 'player'|'creature'|'permanent'|'any', { combat }),
upkeep(who), endStep(who), beginCombat(who), firstMainPhase(who), postcombatMainPhase(who),
cast(who, spellSelector, { targetsSelf, orCopy, ordinal }), becomesLevel(N),
draw(who, ordinal), counterPlaced(target, counter), becomesTarget(target),
lifeGained(who), lifeLost(who)
who is you, opponent or eachPlayer.
Selectors (chainable):
permanents, cards, creatures
.withType('land'), .withSubtype('dragon'), .withSupertype('legendary')
.withColor('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')
.ownedBy('you'|'opponent'), .named('Name'), .inZone('battlefield'|'hand'|'graveyard'|'library'|'exile'|'stack'|'command')
.withCounter('+1/+1', 1), .powerAtLeast(N), .powerAtMost(N), .toughnessAtLeast(N),
.toughnessAtMost(N), .manaValueAtLeast(N), .manaValueAtMost(N), .matchingAny()
Targets:
this, the triggering object, the chosen target, any target, target player,
target opponent, each opponent, each player, target player or planeswalker,
target spell, target ability, target <selector>, each <selector>,
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>])
self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker
target(selector, { count, upTo, includeSelf }) one target
each(selector) every matching object
pick(selector, { count, upTo }) choose without targeting
divided(N, selector) or divided('any', selector) damage divided among targets
targetSpell(selector), targetAbility(selector)
target(you|opponent|eachOpponent|eachPlayer|targetPlayer|thatPlayer|itsController|itsOwner)
Selectors begin with optional state words: other, tapped, untapped, attacking, token,
equipped, enchanted. Then optional colors (white blue black red green colorless),
supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls",
"you own", "you don't own", "with <keyword>", "without <keyword>",
"power N+" / "power N or less", "toughness N+" / "toughness N or less",
"mana value N+" / "mana value N or less", "named <name>",
"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack".
Values: a number, X, itsPower, itsToughness, count(selector), cardsInHand(player),
maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector),
totalPower(selector), anyNumber(), eventAmount()
Values: a number, X, count(<selector>), its power, its toughness,
cards in your hand, cards in that player's hand, total power of <selector>,
total mana value of <selector>, greatest number of <selector> an opponent controls,
that much, any number.
Costs:
manaCost('{2}{G}'), tapCost(), untapCost(), tapOther(selector), energyCost(N),
loyalty(N), payLife(value), discardCost(value, { player, random }), sacrificeCost(selector),
sacrificeSelf(), exileSelf(), exileFromGraveyard(selector, amount), reveal(selector),
choice([[cost, ...], [cost, ...]]), returnToHandCost(selector), behold(selector),
waterbend(value), blight(value), chooseCost('text'), putCounterCost(counter, selector),
removeCountersCost(counter, amount, selector), forage(), collectEvidence(N), millCost(value)
Costs: {T}, {Q}, {2}{G}, {E} xN, +1 loyalty, -2 loyalty, pay N life,
discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice <selector>,
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard,
reveal <selector> from your hand, return <selector> to its owner's hand,
behold <selector>, waterbend <value>, blight <value>, choose <text>,
put <counter> counter on <selector>, forage, collect evidence N, mill N card(s).
A choice is written (cost or cost) or (cost + cost).
Effects, one call per line:
damage(target, amount[, from source])
damage_divided(amount, target)
draw(player, amount)
discard(player, amount[, at random])
mill(player, amount)
gain_life(player, amount)
lose_life(player, amount)
pump(target, power/toughness[, duration])
set_pt(target, power/toughness[, duration])
grant(target, Keyword[ value][, duration])
put_counters(target, counter, amount)
remove_counters(target, counter, amount)
proliferate()
create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword])
destroy(target), exile(target), tap(target), untap(target), regenerate(target)
sacrifice(player, target[, unless cost])
counter(spell|ability, target[, unless cost])
return_to_hand(target), put_on_top(target)
return_to_battlefield(target[, tapped][, transformed][, amount counter counters])
scry(player, amount), surveil(player, amount)
search(player, selector, amount, to hand|battlefield|graveyard|top|bottom[, tapped][, shuffle])
shuffle(player)
add_mana(player, {G}{G} | amount mana of any color)
fight(a, b)
energy(player, amount)
attach(this, target)
restrict(target, cant_attack|cant_block|doesnt_untap[, duration])
prevent_damage(target, amount|all[, duration])
prevent_combat_damage(target, amount|all[, duration])
gain_control(target[, duration])
emblem("text")
transform(target)
pay(cost)
look_top(player, amount[, reorder])
level_up(N)
put_from_among(amount[, selector], to hand|graveyard|battlefield|top|bottom)
dig(amount, up to? pick [selector] to hand|battlefield[ tapped], rest bottom|graveyard|top[ any|random][, optional])
Other keyword actions: action_name(target) or action_name(amount, detail)
Nested blocks:
if <condition>:
<effects>
choose <min>[-<max>]:
1. <effects separated by ;>
2. <effects separated by ;>
schedule(next_upkeep|next_end_step):
<effects>
Effects:
damage(target, amount, fromSource), damageDivided(amount, target)
draw(player, amount), discard(player, amount, { random }), mill(player, amount)
gainLife(player, amount), loseLife(player, amount)
pump(target, power, toughness, duration), setPt(target, power, toughness, { duration })
grant(target, keyword, { value, duration }), putCounters(target, counter, amount)
removeCounters(target, counter, amount), proliferate()
createToken(player, amount, token({ types, subtypes, colors, power, toughness, keywords, tapped }))
createToken(player, amount, copyOf(target, { notLegendary }))
destroy(target), exile(target), sacrifice(player, target, unlessCost)
counter('spell'|'ability', target, unlessCost), returnToHand(target)
returnToBattlefield(target, { tapped, transformed, counters: { counter, amount } })
putOnTop(target), tap(target), untap(target), scry(player, amount), surveil(player, amount)
search(player, selector, amount, { destination, tapped, shuffle, zones, split })
shuffle(player), addMana(player, mana('{G}{G}') | anyColor(value, { oneColor, restriction }))
fight(a, b), regenerate(target), energy(player, amount), attach(target)
restrict(target, 'cant_attack'|'cant_block'|'doesnt_untap', duration)
keywordAction('action name', { target, amount, detail })
preventDamage(target, amount | 'all', { combatOnly, duration })
gainControl(target, duration), emblem('text'), transform(target)
pay([costs]), ifThen(condition, [effects]), modal(min, max, [[effects], [effects]])
lookTop(player, amount, { reorder }), schedule('next_upkeep'|'next_end_step', [effects])
levelUp(N), putFromAmong(player, amount, { selector, destination }), dig(player, amount, { ... })
exileGraveyards(), hideaway(amount), playExiled(player, { free })
Static effects:
pump(target, power/toughness)
grant(target, Keyword[ value])
restrict(target, rule[ detail][ if <condition>])
enters_tapped(target[, unless <condition>])
enters_with_counters(target, counter, amount)
grant_ability(target):
<one ability block>
set_pt(target[, base], power/toughness|?)
control(target)
choose(creature_type|color|card_name|player|opponent|number)
replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent)
cost_reduction(target, amount|{R}{G}[, if <condition>])
staticPump(target, power, toughness), staticGrant(target, keyword, { value })
grantAbility(target, ability), staticRestrict(target, rule, { value, comparison, detail, condition })
entersTapped(target, { unless }), entersWithCounters(target, counter, amount)
staticSetPt(target, power, toughness, { base }), control(target)
choose('creature_type'|'color'|'card_name'|'player'|'opponent'|'number')
replace(what, { target, instead }), costReduction(target, amount | '{R}{G}', { condition })
costIncrease(amount, { spellType }), searchRestriction('you'|'opponent', amount),
exileInsteadOfGraveyard('you'|'opponent')
Common conditions: you control <selector>, you control at least N <selector>,
an opponent controls <selector>, it is your turn, it isn't your turn,
this is tapped, this is untapped, this is attacking, <player> has at least N life,
<player> has at most N life, <player> has N+ cards in their graveyard,
<player> has no cards in hand, a creature died this turn,
you gained at least N life this turn, you drew N+ cards this turn,
you cast it from your hand, this is in your graveyard, this is on the battlefield,
you're the monarch, you have the initiative, it was kicked,
you've cast a spell this turn, you've cast a noncreature spell this turn,
no creatures attacked this turn, you do, you don't, otherwise.
Conditions:
youControl(selector, atLeast), opponentControls(selector, atLeast), yourTurn(),
notYourTurn(), sourceTapped(), sourceUntapped(), sourceAttacking(),
lifeAtLeast(player, N), lifeAtMost(player, N), lifeAboveStarting(player, N),
cardsInGraveyard(player, N), handEmpty(player), creatureDiedThisTurn('you'|'opponent'),
youGainedLifeThisTurn(N), youDrewCardsThisTurn(N), spellsCastLastTurn(who, N),
noSpellsLastTurn(), attackedThisTurn(), youAttackedThisTurn(),
defendingPlayerControls(selector), targets(selector), wasKicked(), youCastIt({ fromHand }),
inGraveyard(), onBattlefield(), monarch(), initiative(), citysBlessing(), suspended(),
bargained(), wasCreature(), opponentLostLifeThisTurn(), lifeChangedThisTurn(),
descendedThisTurn(), permanentLeftBattlefieldThisTurn(), nonlandPermanentsEnteredThisTurn(N),
attackedWithTotalPower(N), yourCreaturesTotalPower(N), opponentControlsMoreLands(),
distinctPowers(N), graveyardCardTypes(N), noObjects(selector), cardsInHandAtMost(who, N),
notTheirTurn(), noAttackers(), opponentPoison(N), tributeNotPaid(), hadCounters(counter),
manaFromTreasure(), manaSpent(N), noManaSpent(), manaSymbolSpent('{G}'), kickedWith('{2}'),
moreCardsThanEachOpponent(), firstCombatPhase(), notToken(), castSpellThisTurn({ noncreature }),
fullParty(), graveyardCount(selector, N), creaturePowerGreaterThanBase('power'|'toughness'),
ifYouDo(), ifYouDont(), otherwise(), youControlCommander(), distinctNames(selector, N),
opponentDamagedThisTurn(N), attackedWithCreatures(N), libraryAtMost(N)
Durations: permanent (default), until end of turn, until your next turn,
until end of combat, until its controller's next untap step,
for as long as this remains on the battlefield.
Durations: permanent (default), untilEndOfTurn, untilYourNextTurn,
untilEndOfYourNextTurn, untilEndOfCombat, untilControllersNextUntapStep,
whileSourceOnBattlefield.
Players: you, opponent, each_opponent, each_player, target_player, that_player,
its_controller, its_owner.
Players: you, opponent, eachOpponent, eachPlayer, targetPlayer, thatPlayer,
itsController, itsOwner.
Example:
on enters(this):
gain_life(you, 1)
activate {T}:
add_mana(you, {G})
export default card('Creature — Human Cleric', [
triggered(when.enters(self), [gainLife(you, 1)]),
activated([tapCost()], [addMana(you, mana('{G}'))]),
spell([draw(you, 2)]),
])`
spell:
draw(you, 2)`
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the JavaScript card source language below.
Output rules:
- Answer with pseudocode only. No explanation, no code fences, no card header, no comments.
- Use only the syntax below. Never invent an operation or a keyword argument.
- If an ability cannot be expressed, use: unsupported (<short reason>): <original oracle text>
- For multi-face cards, output only the "## <face name>" sections in the given order.
- Answer with card source only. No explanation, no code fences, no comments.
- Start with card('Type line', [...]) using the exact type line given for the card.
- Use only the names and shapes below. Never invent an operation or a keyword argument.
- If an ability cannot be expressed, use: unsupported('short reason', 'original oracle text')
- For multi-face cards, output only the faces(...) sections in the given order.
${PSEUDO_GUIDE}`
${SOURCE_GUIDE}`
function describeCard(card: Card): string {
if (card.card_faces?.length) {
@@ -226,7 +231,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-Title': 'Commander card pseudocode translator',
'X-Title': 'Commander card source translator',
},
body: JSON.stringify({
model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL,
@@ -261,7 +266,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
compileImplementation(card, source)
} catch (error) {
throw new TranslationError(
`The model did not return valid pseudocode: ${error instanceof Error ? error.message : String(error)}`,
`The model did not return valid card source: ${error instanceof Error ? error.message : String(error)}`,
)
}

View File

@@ -67,7 +67,7 @@ export type Value =
| { kind: 'event_amount' }
export type ManaSpec =
| { kind: 'symbols'; symbols: string[]; restriction?: string }
| { kind: 'symbols'; symbols: string[]; oneOf?: boolean; restriction?: string }
| { kind: 'any_color'; amount: Value; oneColor: boolean; restriction?: string }
export interface TokenSpec {
@@ -268,7 +268,7 @@ export type StaticEffect =
| { op: 'grant'; target: Target; keyword: string; value?: string }
| { op: 'grant_ability'; target: Target; ability: Ability }
| { op: 'restriction'; target: Target; rule: string; value?: Value; comparison?: 'or_greater' | 'or_less'; detail?: string; condition?: Condition }
| { op: 'enters_tapped'; target: Target; unless?: Condition }
| { op: 'enters_tapped'; target: Target; unless?: Condition; unlessCost?: Cost }
| { op: 'enters_with_counters'; target: Target; counter: string; amount: Value }
| { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean }
| { op: 'control'; target: Target }
@@ -345,6 +345,8 @@ export type Ability =
export interface CompiledFace {
name: string
/** Scryfall type line, or the type line declared in card source. */
typeLine?: string
status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[]
}
@@ -352,6 +354,8 @@ export interface CompiledFace {
export interface CompiledCard {
oracle_id: string
name: string
/** Scryfall type line, or the type line declared in card source. */
typeLine?: string
status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[]
faces?: CompiledFace[]

View File

@@ -25,16 +25,22 @@ function numberOrUndefined(value: string | undefined): number | undefined {
}
function basicLandAbility(typeLine: string): Ability[] {
if (!/basic land/i.test(typeLine)) return []
const subtype = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/)[0] ?? ''
const color = BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined)
if (!color) return []
if (!/\bland\b/i.test(typeLine)) return []
const subtypes = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/) ?? []
const colors = [...new Set(subtypes.map(subtype => BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined))
.filter((color): color is string => Boolean(color)))]
if (!colors.length) return []
const symbols = colors.map(color => `{${color}}`)
return [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
effects: [{
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols, ...(symbols.length > 1 ? { oneOf: true } : {}) },
}],
optional: false,
text: `{T}: Add {${color}}.`,
text: `{T}: Add ${symbols.join(' or ')}.`,
}]
}
@@ -43,8 +49,9 @@ function definitionFrom(
compiled: CompiledCard | undefined,
face?: CardFace,
faceAbilities?: Ability[],
typeLineOverride?: string,
): CardDefinition {
const typeLine = face?.type_line ?? card.type_line
const typeLine = typeLineOverride ?? compiled?.typeLine ?? face?.type_line ?? card.type_line
return {
oracleId: card.oracle_id,
name: face?.name ?? card.name,
@@ -64,7 +71,7 @@ function definitionFrom(
export function cardDefinitionFromCard(card: Card, compiled?: CompiledCard): CardDefinition {
const face = card.card_faces?.[0]
const compiledFace = compiled?.faces?.[0]
return definitionFrom(card, compiled, face, compiledFace?.abilities)
return definitionFrom(card, compiled, face, compiledFace?.abilities, compiledFace?.typeLine)
}
function load(): Map<string, CardDefinition> {

View File

@@ -23,6 +23,7 @@ import type {
GameConfig,
ManaColor,
ManaPool,
MulliganState,
PendingChoice,
PendingSearch,
Phase,
@@ -195,8 +196,10 @@ export class Game {
phase: Phase = 'beginning'
step: Step = 'untap'
priority = ''
status: 'not_started' | 'active' | 'finished' = 'not_started'
status: 'not_started' | 'mulligan' | 'active' | 'finished' = 'not_started'
winner?: string
/** Opening-hand choices, keyed by player id. */
readonly mulligans = new Map<string, MulliganState>()
/** Blocks all other actions until the searching player picks a card. */
pendingSearch?: PendingSearch
/** "As this enters, choose..." prompts, in entry order. */
@@ -258,6 +261,9 @@ export class Game {
energy: 0,
poison: 0,
}))
for (const player of this.players) {
this.mulligans.set(player.id, { count: 0, kept: false, bottom: 0 })
}
for (const playerConfig of config.players) {
for (const definition of playerConfig.deck) {
@@ -290,7 +296,10 @@ export class Game {
return object
}
/** Starts the game, shuffles libraries, draws opening hands, and begins turn 1. */
/**
* Starts the game, shuffles libraries, and draws opening hands. With mulligans
* enabled, turn 1 waits until every player keeps; otherwise it begins immediately.
*/
start(): void {
if (this.status !== 'not_started') throw new GameError('Game already started')
for (const player of this.players) this.shuffleLibrary(player)
@@ -301,8 +310,69 @@ export class Game {
}
}
if (!this.config.mulligans) {
this.beginGame()
return
}
this.status = 'mulligan'
this.turn = 1
this.activePlayer = this.firstPlayer
}
/** Keeps the opening hand; turn 1 begins once every living player has kept. */
keepHand(playerId: string): void {
const mulligan = this.requireMulligan(playerId)
if (mulligan.kept) throw new GameError('You already kept your hand')
if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first')
mulligan.kept = true
const player = this.getPlayer(playerId)
this.logMessage(`${player.name} keeps their hand${mulligan.count ? ` after ${mulligan.count} mulligan${mulligan.count === 1 ? '' : 's'}` : ''}`)
if (this.players.every(entry => entry.lost || this.mulligans.get(entry.id)?.kept)) this.beginGame()
}
/** Shuffles the hand back and draws a new one; each mulligan bottoms one more card. */
mulligan(playerId: string): void {
const mulligan = this.requireMulligan(playerId)
if (mulligan.kept) throw new GameError('You already kept your hand')
if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first')
const player = this.getPlayer(playerId)
for (const id of [...player.hand]) this.moveToZone(id, 'library', { silent: true })
this.shuffleLibrary(player)
for (let i = 0; i < this.startingHandSize; i++) {
if (!player.library.length) break
this.drawCard(player.id, true)
}
mulligan.count++
mulligan.bottom = Math.min(Math.max(0, mulligan.count - 1), player.hand.length)
this.logMessage(`${player.name} mulligans${mulligan.bottom
? ` and puts ${mulligan.bottom} card${mulligan.bottom === 1 ? '' : 's'} on the bottom`
: ''}`)
}
/** Puts one card from a mulliganed opening hand on the bottom of the library. */
putOnBottom(playerId: string, cardId: string): void {
const mulligan = this.requireMulligan(playerId)
if (mulligan.kept) throw new GameError('You already kept your hand')
if (mulligan.bottom <= 0) throw new GameError('You have no cards to put on the bottom')
const player = this.getPlayer(playerId)
if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand')
this.moveToZone(cardId, 'library', { silent: true })
mulligan.bottom--
}
private requireMulligan(playerId: string): MulliganState {
if (this.status !== 'mulligan') throw new GameError('The game is not in its mulligan step')
const player = this.getPlayer(playerId)
if (player.lost) throw new GameError('You have left the game')
const mulligan = this.mulligans.get(playerId)
if (!mulligan) throw new GameError(`Unknown player: ${playerId}`)
return mulligan
}
private beginGame(): void {
// Leyline-style "begin the game with it on the battlefield" cards.
for (const player of this.players) {
if (player.lost) continue
for (const id of [...player.hand]) {
const object = this.getObject(id)
const beginsOnBattlefield = (object.definition.abilities ?? []).some(ability =>
@@ -773,7 +843,7 @@ export class Game {
/** Marks a player as having forfeited. */
concede(playerId: string): void {
if (this.status !== 'active') throw new GameError('Game is not active')
if (this.status !== 'active' && this.status !== 'mulligan') throw new GameError('Game is not active')
this.losePlayer(playerId)
if (this.priority === playerId) this.priority = this.nextAlivePlayer(playerId)
}
@@ -783,7 +853,7 @@ export class Game {
if (this.phase !== 'combat' || this.step !== 'declare_blockers') throw new GameError('Not in the declare blockers step')
if (this.stack.length) throw new GameError('Cannot declare blockers while the stack is not empty')
if (this.pendingSearch) throw new GameError('Choose a card from your library first')
if (this.pendingChoice) throw new GameError('Choose a creature type first')
if (this.pendingChoice) throw new GameError('Resolve the pending choice first')
if (this.priority !== playerId) throw new GameError('You do not have priority')
const seen = new Set<string>()
@@ -843,7 +913,7 @@ export class Game {
pass(playerId?: string): void {
if (this.status !== 'active') throw new GameError('Game is not active')
if (this.pendingSearch) throw new GameError('Choose a card from your library first')
if (this.pendingChoice) throw new GameError('Choose a creature type first')
if (this.pendingChoice) throw new GameError('Resolve the pending choice first')
const actual = playerId ?? this.priority
if (this.priority !== actual) throw new GameError('You do not have priority')
const alive = this.alivePlayers().length
@@ -947,7 +1017,7 @@ export class Game {
chooseSearchCard(playerId: string, cardId: string): void {
const pending = this.pendingSearch
if (!pending) throw new GameError('No search is waiting for a choice')
if (this.pendingChoice) throw new GameError('Choose a creature type first')
if (this.pendingChoice) throw new GameError('Resolve the pending choice first')
if (pending.playerId !== playerId) throw new GameError('You are not searching your library')
const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId)
if (!object) throw new GameError('That card is not a legal choice')
@@ -992,7 +1062,7 @@ export class Game {
*/
chooseCreatureType(playerId: string, type: string): void {
const pending = this.pendingChoice
if (!pending) throw new GameError('No choice is waiting')
if (!pending || pending.what !== 'creature_type') throw new GameError('No choice is waiting')
if (pending.playerId !== playerId) throw new GameError('You are not choosing this permanent\'s type')
const chosen = CREATURE_TYPES.find(entry => entry.toLowerCase() === type.trim().toLowerCase())
if (!chosen) throw new GameError('Choose a creature type')
@@ -1003,6 +1073,32 @@ export class Game {
this.logMessage(`${this.getPlayer(playerId).name} chooses ${chosen} for ${object.definition.name}`)
}
/**
* Answers an "as this enters, you may pay a cost; otherwise it enters tapped"
* replacement. The match API uses the `choose_cost` action.
*/
chooseCostPayment(playerId: string, pay: boolean): void {
const pending = this.pendingChoice
if (!pending || pending.what !== 'pay_cost' || !pending.cost) throw new GameError('No cost payment is waiting')
if (pending.playerId !== playerId) throw new GameError('You are not choosing this payment')
const object = this.objects.get(pending.sourceId)
if (object && object.zone === 'battlefield') {
if (pay) {
const context = this.contextFor(object, playerId, [], 0, 0)
if (!this.tryPayUnless(pending.cost, playerId, object, context)) throw new GameError('Cannot pay the cost')
this.pendingChoices.shift()
const detail = pending.amount === undefined ? 'the cost' : `${pending.amount} life`
this.logMessage(`${this.getPlayer(playerId).name} pays ${detail} for ${object.definition.name}`)
return
}
this.pendingChoices.shift()
object.tapped = true
this.logMessage(`${object.definition.name} enters tapped`)
return
}
this.pendingChoices.shift()
}
/**
* Passes priority for players who cannot do anything meaningful. Stops at the
* first player who can act, or when the turn ends, so turns never run on.
@@ -1289,10 +1385,15 @@ export class Game {
const source = this.players
.flatMap(entry => entry.battlefield)
.map(id => this.objects.get(id))
.find((object): object is GameObject => Boolean(object && object.zone === 'battlefield'
&& object.controller === player.id
&& !object.tapped
&& this.findFreeManaAbility(object) !== undefined))
.map(object => {
if (!object || object.zone !== 'battlefield' || object.controller !== player.id || object.tapped) return undefined
const found = this.findFreeManaAbility(object)
if (!found) return undefined
return { object, allowed: this.manaAbilityAllowedColors(object, found.ability) }
})
.filter((entry): entry is { object: GameObject; allowed: Set<ManaColor> | undefined } => Boolean(entry))
.filter(entry => this.neededColor(player, cost, entry.allowed) !== undefined)
.sort((a, b) => (a.allowed?.size ?? Number.MAX_SAFE_INTEGER) - (b.allowed?.size ?? Number.MAX_SAFE_INTEGER))[0]?.object
if (!source) break
this.autoManaDepth++
try {
@@ -1321,37 +1422,128 @@ export class Game {
const found = this.findFreeManaAbility(source)
if (!found) return
const player = this.getPlayer(source.controller)
const color = this.manaAbilityColor(source, found.ability, player, cost)
if (!color) return
for (const entry of found.ability.costs) {
if (entry.kind === 'tap') source.tapped = true
}
const color = this.neededColor(player, cost)
for (const effect of found.ability.effects) {
if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color)
}
}
private neededColor(player: PlayerState, cost: ManaCost): ManaColor {
for (const color of cost.colored) {
if (player.manaPool[color] <= 0) return color
}
const hybridColor = cost.hybrid.flatMap(entry => entry.colors).find(color => player.manaPool[color] <= 0)
return hybridColor ?? 'W'
private manaAbilityColor(
source: GameObject,
ability: Extract<Ability, { kind: 'activated' }>,
player: PlayerState,
cost: ManaCost,
): ManaColor | undefined {
return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability))
}
private addMana(playerId: string, mana: ManaSpec, preferred: ManaColor = 'W'): void {
private manaAbilityAllowedColors(
source: GameObject,
ability: Extract<Ability, { kind: 'activated' }>,
): Set<ManaColor> | undefined {
for (const effect of ability.effects) {
if (effect.op !== 'add_mana') continue
if (effect.mana.kind === 'symbols' && effect.mana.oneOf) {
return new Set(effect.mana.symbols.map(colorOfSymbol))
}
return this.anyColorRestrictionColors(effect.mana, source.controller)
}
return undefined
}
private neededColor(player: PlayerState, cost: ManaCost, allowed?: Set<ManaColor>): ManaColor | undefined {
for (const color of cost.colored) {
if (player.manaPool[color] > 0) continue
return allowed && !allowed.has(color) ? undefined : color
}
for (const hybrid of cost.hybrid) {
if (hybrid.colors.some(color => player.manaPool[color] > 0)) continue
return hybrid.colors.find(color => !allowed || allowed.has(color))
}
if (allowed) return MANA_COLORS.find(color => allowed.has(color))
return 'W'
}
private addMana(playerId: string, mana: ManaSpec, preferred?: ManaColor): void {
const player = this.getPlayer(playerId)
if (mana.kind === 'symbols') {
if (mana.oneOf) {
const colors = mana.symbols.map(colorOfSymbol)
const color = preferred && colors.includes(preferred) ? preferred : colors[0]
if (color) player.manaPool[color]++
return
}
for (const symbol of mana.symbols) player.manaPool[colorOfSymbol(symbol)]++
} else {
const amount = this.value(mana.amount, {
source: this.playerSource(playerId),
controller: playerId,
targets: [],
x: 0,
mode: 0,
})
for (let i = 0; i < amount; i++) player.manaPool[preferred]++
return
}
const amount = this.value(mana.amount, {
source: this.playerSource(playerId),
controller: playerId,
targets: [],
x: 0,
mode: 0,
})
const allowed = this.anyColorRestrictionColors(mana, playerId)
if (allowed?.size === 0) return
let color: ManaColor = preferred ?? 'W'
if (allowed && !allowed.has(color)) {
color = MANA_COLORS.find(entry => allowed.has(entry)) ?? 'W'
}
for (let i = 0; i < amount; i++) player.manaPool[color]++
}
/**
* Colors a land could produce for an "any color that a land ... could
* produce" restriction. Colorless and snow are not colors.
*/
private landManaColors(playerId: string, opponentsOnly: boolean, seen = new Set<string>()): Set<ManaColor> {
const colors = new Set<ManaColor>()
const opponents = this.opponentsOf(playerId)
for (const object of this.battlefieldObjects()) {
if (!this.isLand(object) || seen.has(object.id)) continue
if (opponentsOnly ? !opponents.includes(object.controller) : object.controller !== playerId) continue
seen.add(object.id)
for (const ability of object.definition.abilities ?? []) {
if (ability.kind !== 'activated') continue
for (const effect of ability.effects) {
if (effect.op !== 'add_mana') continue
if (effect.mana.kind === 'symbols') {
for (const symbol of effect.mana.symbols) {
for (const letter of symbol.match(/[WUBRG]/gi) ?? []) colors.add(letter.toUpperCase() as ManaColor)
}
} else {
const nested = this.anyColorRestrictionColors(effect.mana, object.controller, seen)
if (nested) {
for (const color of nested) colors.add(color)
} else {
for (const color of MANA_COLORS) if (color !== 'C') colors.add(color)
}
}
}
}
seen.delete(object.id)
}
return colors
}
/** The colors an any-color mana source may produce, when the restriction is known. */
private anyColorRestrictionColors(
mana: ManaSpec,
playerId: string,
seen?: Set<string>,
): Set<ManaColor> | undefined {
if (mana.kind !== 'any_color') return undefined
if (mana.restriction === 'a land an opponent controls could produce') {
return this.landManaColors(playerId, true, seen)
}
if (mana.restriction === 'a land you control could produce') {
return this.landManaColors(playerId, false, seen)
}
return undefined
}
private payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void {
@@ -1378,7 +1570,7 @@ export class Game {
case 'energy':
return player.energy >= cost.amount
case 'pay_life':
return player.life > this.value(cost.amount, this.staticContext(source))
return player.life >= this.value(cost.amount, this.staticContext(source))
case 'discard':
return player.hand.length >= this.value(cost.amount, this.staticContext(source))
case 'sacrifice':
@@ -2497,9 +2689,19 @@ export class Game {
for (const effect of staticSource.ability.effects) {
if (effect.op === 'enters_tapped') {
if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue
if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) {
object.tapped = true
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
if (effect.unlessCost && !object.tapped) {
const context = this.staticContext(staticSource.source)
this.pendingChoices.push({
playerId: object.controller,
sourceId: object.id,
what: 'pay_cost',
cost: effect.unlessCost,
amount: effect.unlessCost.kind === 'pay_life' ? this.value(effect.unlessCost.amount, context) : undefined,
})
continue
}
object.tapped = true
} else if (effect.op === 'enters_with_counters') {
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
const amount = this.value(effect.amount, this.staticContext(staticSource.source))
@@ -2773,9 +2975,8 @@ export class Game {
/**
* Affordability check that mirrors auto-tapping without changing the game.
* shortcut: any_color sources are counted as flexible even when they must
* produce one color, so rare "one color only" sources can be overestimated;
* upgrade if a card ever needs an exact color split from such a source.
* shortcut: only land-based any_color restrictions are modelled; mana
* restricted by a commander identity or a spell type is still flexible.
*/
private canAffordMana(playerId: string, symbols: string, x: number): boolean {
if (!symbols) return true
@@ -2783,6 +2984,7 @@ export class Game {
const cost = parseManaCost(symbols, x)
const pool = { ...player.manaPool }
let flexible = 0
const restricted: { colors: Set<ManaColor>; amount: number }[] = []
for (const object of this.battlefieldObjects()) {
if (object.controller !== playerId) continue
const found = this.findFreeManaAbility(object)
@@ -2792,23 +2994,32 @@ export class Game {
if (effect.mana.kind === 'symbols') {
for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++
} else {
flexible += this.value(effect.mana.amount, {
const amount = this.value(effect.mana.amount, {
source: object,
controller: playerId,
targets: [],
x: 0,
mode: 0,
})
const allowed = this.anyColorRestrictionColors(effect.mana, playerId)
if (!allowed) flexible += amount
else if (allowed.size) restricted.push({ colors: allowed, amount })
}
}
}
let life = player.life
restricted.sort((a, b) => a.colors.size - b.colors.size)
const take = (color: ManaColor): boolean => {
if (pool[color] > 0) {
pool[color]--
return true
}
const source = restricted.find(entry => entry.amount > 0 && entry.colors.has(color))
if (source) {
source.amount--
return true
}
if (flexible > 0) {
flexible--
return true
@@ -2824,7 +3035,9 @@ export class Game {
if (!(hybrid.life > 0 && life >= hybrid.life)) return false
life -= hybrid.life
}
const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + flexible
const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0)
+ flexible
+ restricted.reduce((total, entry) => total + entry.amount, 0)
return remaining >= cost.generic
}
@@ -2923,6 +3136,21 @@ export class Game {
}
changed = true
}
for (const player of this.alivePlayers()) {
const legends = new Map<string, GameObject[]>()
for (const object of this.battlefieldObjects()) {
if (object.controller !== player.id || !/\blegendary\b/i.test(object.definition.typeLine)) continue
const name = object.definition.name.toLowerCase()
legends.set(name, [...(legends.get(name) ?? []), object])
}
for (const copies of legends.values()) {
// shortcut: keeps the first copy found, not the player's choice; ask when the API can pause for it
for (const extra of copies.slice(1)) {
this.moveToZone(extra, 'graveyard', { silent: false })
changed = true
}
}
}
}
}
@@ -3248,7 +3476,7 @@ export class Game {
private requirePriority(playerId: string): void {
if (this.status !== 'active') throw new GameError('Game is not active')
if (this.pendingSearch) throw new GameError('Choose a card from your library first')
if (this.pendingChoice) throw new GameError('Choose a creature type first')
if (this.pendingChoice) throw new GameError('Resolve the pending choice first')
if (this.priority !== playerId) throw new GameError('You do not have priority')
}

View File

@@ -28,6 +28,7 @@ export interface ActionPayload {
mode?: number
overload?: boolean
choice?: string
pay?: boolean
position?: { x?: unknown; y?: unknown }
attackers?: { attackerId: string; defenderId: string }[]
blocks?: { blockerId: string; attackerId: string }[]
@@ -110,6 +111,8 @@ export interface MatchView {
priority: string
status: string
winner?: string
/** Present during the opening mulligan step. */
mulligans?: { player: string; count: number; kept: boolean; bottom: number }[]
stack: { id: string; kind: string; label: string; controller: string }[]
log: string[]
hand: CardView[]
@@ -129,6 +132,8 @@ export interface MatchView {
what: string
sourceId: string
sourceName: string
/** Life total to display for a `pay_life` cost. */
amount?: number
/** Choices to offer, populated only for the chooser. */
options: string[]
}
@@ -363,6 +368,7 @@ export function startMatch(matchId: string, token: string | undefined): void {
startingHandSize: 7,
firstPlayer: match.seats[0].playerId,
commander: true,
mulligans: true,
players: match.seats.map(entry => ({
id: entry.playerId,
name: entry.name,
@@ -424,6 +430,15 @@ export function performAction(matchId: string, token: string | undefined, action
try {
switch (action.type) {
case 'keep_hand':
game.keepHand(seat.playerId)
break
case 'mulligan':
game.mulligan(seat.playerId)
break
case 'mulligan_bottom':
game.putOnBottom(seat.playerId, requireId(action.cardId))
break
case 'play_land':
game.playLand(seat.playerId, requireId(action.cardId))
break
@@ -446,6 +461,10 @@ export function performAction(matchId: string, token: string | undefined, action
if (typeof action.choice !== 'string') throw new MatchError('Missing type choice')
game.chooseCreatureType(seat.playerId, action.choice)
break
case 'choose_cost':
if (typeof action.pay !== 'boolean') throw new MatchError('Missing cost payment choice')
game.chooseCostPayment(seat.playerId, action.pay)
break
case 'attack':
if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers')
game.declareAttackers(seat.playerId, action.attackers.map(entry => ({
@@ -579,6 +598,9 @@ function serialize(match: Match, viewerId: string): MatchView {
priority: game.priority,
status: game.status,
winner: game.winner,
mulligans: game.status === 'mulligan'
? game.players.map(player => ({ player: player.id, ...game.mulligans.get(player.id)! }))
: undefined,
stack: game.stack.map(item => ({
id: item.id,
kind: item.kind,
@@ -597,7 +619,8 @@ function serialize(match: Match, viewerId: string): MatchView {
what: choice.what,
sourceId: choice.sourceId,
sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent',
options: choice.playerId === viewerId ? [...CREATURE_TYPES] : [],
amount: choice.amount,
options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [],
}
: undefined,
pendingSearch: search

View File

@@ -1,6 +1,6 @@
// The runtime game model. Card definitions are immutable input; objects are the
// per-game instances that move between zones.
import type { Ability, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js'
import type { Ability, Cost, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js'
export type ManaColor = 'W' | 'U' | 'B' | 'R' | 'G' | 'C'
export type ManaPool = Record<ManaColor, number>
@@ -38,6 +38,17 @@ export interface GameConfig {
firstPlayer?: string
/** Enables command-zone casting, commander tax, and commander damage. */
commander?: boolean
/** Waits for every player to keep an opening hand before turn 1. */
mulligans?: boolean
}
/** One player's opening-hand choice while the game is in its mulligan step. */
export interface MulliganState {
/** Mulligans taken so far. */
count: number
kept: boolean
/** Cards still to put on the bottom of the library. */
bottom: number
}
export interface PlayerState {
@@ -140,11 +151,15 @@ export interface PendingSearch {
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }
}
/** An "as this enters, choose..." pause. Blocks all actions until its controller picks. */
/** An "as this enters..." pause. Blocks all actions until its controller picks. */
export interface PendingChoice {
playerId: string
sourceId: string
what: 'creature_type'
what: 'creature_type' | 'pay_cost'
/** Cost to pay to avoid entering tapped. */
cost?: Cost
/** Life total to display for a `pay_life` cost. */
amount?: number
}
export interface CombatAttack {

View File

@@ -23,7 +23,7 @@ import {
writeOverride,
type ImplementationStatus,
} from './effects/implementations.js'
import { PseudoParseError } from './effects/pseudo.js'
import { SourceParseError } from './effects/source.js'
import { translateCard, TranslationError } from './effects/translate.js'
import { importDeckText } from './game/commander.js'
import { cardArt, cardImage, playmatImage, scryfallArtUrl, scryfallImageUrl } from './images.js'
@@ -89,7 +89,7 @@ app.setErrorHandler((error, request, reply) => {
if (error instanceof CardsUnavailableError) {
return reply.code(503).send({ error: error.message })
}
if (error instanceof PseudoParseError) {
if (error instanceof SourceParseError) {
return reply.code(400).send({ error: error.message, line: error.line })
}
if (error instanceof TranslationError || error instanceof MatchError || error instanceof AuthError) {