Kkdjskjd
This commit is contained in:
@@ -3,9 +3,9 @@
|
||||
The card database from Scryfall is English prose. The game engine cannot execute
|
||||
prose, so `backend/src/effects/` compiles every oracle-text line into a small
|
||||
JSON AST. The AST is the canonical form for the engine. A pretty-printer renders
|
||||
the same AST as readable pseudocode, and a matching parser reads that pseudocode
|
||||
back, so a human can replace the generated implementation of a card without
|
||||
touching JSON.
|
||||
the same AST as readable card source, and a matching interpreter reads that
|
||||
source back, so a human can replace the generated implementation of a card
|
||||
without touching JSON.
|
||||
|
||||
This is deliberately **not** a rules engine. It answers "what does the card
|
||||
say?" in machine-readable form. "What happens when it resolves?" belongs to the
|
||||
@@ -18,10 +18,10 @@ Scryfall oracle text
|
||||
-> normalize (card name, "this creature", contractions, reminder text)
|
||||
-> classify (keyword / triggered / activated / static / spell effect)
|
||||
-> parse targets, values, costs, conditions, durations
|
||||
-> JSON AST + pseudocode rendering
|
||||
-> JSON AST + card-source rendering
|
||||
|
||||
data/card-overrides/<oracle_id>.pseudo.txt
|
||||
-> pseudocode parser
|
||||
data/card-overrides/<oracle_id>.js
|
||||
-> safe source interpreter
|
||||
-> JSON AST used instead of the generated one
|
||||
```
|
||||
|
||||
@@ -34,16 +34,16 @@ a guessed effect. A wrong effect is worse than a missing one.
|
||||
From `backend/`:
|
||||
|
||||
```bash
|
||||
npm run compile:cards # writes data/card-effects.json and .pseudo.txt
|
||||
npm test # compiler, pseudocode parser, and engine tests
|
||||
npm run compile:cards # writes data/card-effects.json and data/card-effects.js
|
||||
npm test # compiler, source interpreter, and engine tests
|
||||
npm run dev # API for the frontend editor
|
||||
```
|
||||
|
||||
Current output over the imported Commander pool (32,116 cards):
|
||||
|
||||
```text
|
||||
Cards: 14,141 supported, 10,119 partial, 7,856 unsupported
|
||||
Ability lines: 37,983/60,470 parsed (62.8%)
|
||||
Cards: 14,239 supported, 10,088 partial, 7,789 unsupported
|
||||
Ability lines: 38,132/60,470 parsed (63.1%)
|
||||
```
|
||||
|
||||
- **supported** — every ability line parsed.
|
||||
@@ -58,40 +58,200 @@ patterns updates the numbers.
|
||||
| File | Contents |
|
||||
| ---- | -------- |
|
||||
| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card |
|
||||
| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode |
|
||||
| `data/card-overrides/<oracle_id>.pseudo.txt` | Human-authored implementations, one file per card |
|
||||
| `data/card-effects.js` | The same cards rendered as card source |
|
||||
| `data/card-overrides/<oracle_id>.js` | Human-authored implementations, one file per card |
|
||||
|
||||
The two generated files are git-ignored. Overrides are ordinary source files and
|
||||
should be committed.
|
||||
|
||||
## Pseudocode
|
||||
Compiled cards carry the Scryfall `typeLine`, and the game catalog uses it.
|
||||
An override can declare its own type line with `card(...)`; that value wins when
|
||||
the card is loaded into a game.
|
||||
|
||||
```text
|
||||
# Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
## Card source
|
||||
|
||||
# Llanowar Elves [supported]
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
Card source looks like a JavaScript module, but it is **not executed as
|
||||
JavaScript**. `src/effects/source.ts` tokenizes and evaluates a deliberately
|
||||
small expression subset against a fixed builder API. There is no `eval`, no
|
||||
`new Function`, no imports, no property writes and no access to globals: an
|
||||
unrecognized name or method is a parse error. This matters because
|
||||
`PUT /cards/:oracleId/implementation` is unauthenticated.
|
||||
|
||||
# Krenko, Mob Boss [supported]
|
||||
activate {T}:
|
||||
create_token(you, count(creature goblin you control), 1/1 red goblin creature)
|
||||
A card exports its type line and an array of abilities:
|
||||
|
||||
```js
|
||||
export default card('Creature — Human Cleric', [
|
||||
keywords('Flying', 'Ward {2}'),
|
||||
triggered(when.enters(each(permanents.other().withType('creature'))), [
|
||||
gainLife(you, 1),
|
||||
]),
|
||||
activated([tapCost()], [
|
||||
addMana(you, mana('{G}')),
|
||||
]),
|
||||
])
|
||||
```
|
||||
|
||||
Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads
|
||||
it back into the same AST the compiler produces. Blocks are indented two spaces.
|
||||
A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a
|
||||
new section for a multi-face card. Use `(no abilities)` when a face has none.
|
||||
Plain `export default [...]` is still accepted and uses the Scryfall type line.
|
||||
Multi-face cards export `faces(face('Name', 'Type line', [...]), ...)` in card order:
|
||||
|
||||
```js
|
||||
export default faces(
|
||||
face('Front', 'Instant', [spell([draw(you, 2)])]),
|
||||
face('Back', 'Creature — Human', [keyword('Flying')]),
|
||||
)
|
||||
```
|
||||
|
||||
Every effect list also accepts a callback. A single expression is one effect; a
|
||||
block is several effects, separated by newlines, `;` or `,`:
|
||||
|
||||
```js
|
||||
export default card('Creature — Human Cleric', [
|
||||
triggered(when.enters(self), () => draw(you, 1)),
|
||||
activated([tapCost()], () => {
|
||||
gainLife(you, 1)
|
||||
draw(you, 1)
|
||||
}),
|
||||
])
|
||||
```
|
||||
|
||||
Arrays stay valid and are still used for costs, `modal` modes, ability lists,
|
||||
`card`, `faces` and `face`. The formatter emits callbacks for effect lists and
|
||||
`card(typeLine, abilities)` at the top level.
|
||||
|
||||
The formatter writes the same shape, so a generated implementation can be
|
||||
copied, edited and saved as an override. `formatCard` and `parseCardSource`
|
||||
round-trip: comments are ignored, a leading `// Card [status]` line is optional,
|
||||
and `const` declarations are allowed for reuse:
|
||||
|
||||
```js
|
||||
const dragons = permanents.withType('creature').withSubtype('dragon').youControl()
|
||||
|
||||
export default card('Creature — Human Cleric', [
|
||||
staticAbility([staticPump(each(dragons), 1, 1)]),
|
||||
])
|
||||
```
|
||||
|
||||
### Abilities
|
||||
|
||||
| Call | Meaning |
|
||||
| ---- | ------- |
|
||||
| `keyword(name, value)` | One keyword, optionally parameterized |
|
||||
| `keywords(...names)` | Several keywords from one oracle line |
|
||||
| `triggered(event, effects, options)` | `When`/`Whenever`/`At` ability |
|
||||
| `activated(costs, effects, options)` | Cost `:` effect, including loyalty |
|
||||
| `staticAbility(effects, options)` | Continuous effect or restriction |
|
||||
| `spell(effects, options)` | Effect line of an instant or sorcery |
|
||||
| `additionalCost(costs, options)` | Additional cost |
|
||||
| `alternativeCost(costs, options)` | Alternative cast, possibly free |
|
||||
| `overload(cost)` | Overload alternate cost |
|
||||
| `chapter(chapters, effects, options)` | Saga chapter ability |
|
||||
| `levelBand(min, max, power, toughness)` | Level band |
|
||||
| `levelPt(power, toughness)` | Level P/T line |
|
||||
| `unsupported(reason, text)` | Preserved text plus a reason |
|
||||
|
||||
`options` accepts `condition` and `optional`; activated abilities also accept
|
||||
`timing: 'sorcery'` and `activationsPerTurn`.
|
||||
|
||||
### Selectors and targets
|
||||
|
||||
Selectors start from `permanents`, `cards` or `creatures` and chain filters:
|
||||
|
||||
```js
|
||||
permanents.withType('creature').withSubtype('dragon').withColor('red')
|
||||
.other().tapped().youControl().powerAtLeast(4)
|
||||
```
|
||||
|
||||
Available filters include `withType`, `withSubtype`, `withSupertype`,
|
||||
`withColor`, `withKeyword`, `withoutKeyword`, `withoutType`, `other`, `tapped`,
|
||||
`untapped`, `attacking`, `token`, `nontoken`, `equipped`, `enchanted`,
|
||||
`youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`,
|
||||
`inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`,
|
||||
`toughnessAtLeast`/`toughnessAtMost`, `manaValueAtLeast`/`manaValueAtMost`
|
||||
and `matchingAny`.
|
||||
|
||||
Targets wrap a selector or player:
|
||||
|
||||
```js
|
||||
target(permanents.withType('creature'))
|
||||
each(creatures.withColor('red'))
|
||||
pick(cards.withType('land'), { upTo: 2 })
|
||||
divided(3, creatures.attacking())
|
||||
targetSpell(permanents.withType('instant'))
|
||||
targetAbility()
|
||||
```
|
||||
|
||||
Fixed targets are `self`, `triggerSubject`, `previousTarget`, `anyTarget` and
|
||||
`targetPlayerOrPlaneswalker`. Players are `you`, `opponent`, `eachOpponent`,
|
||||
`eachPlayer`, `targetPlayer`, `thatPlayer`, `itsController` and `itsOwner`.
|
||||
|
||||
Values are numbers, `X`, `itsPower`, `itsToughness`, `count(selector)`,
|
||||
`cardsInHand(player)`, `maxCardsInHand()`, `maxOpponentCount(selector)`,
|
||||
`totalManaValue(selector)`, `totalPower(selector)`, `anyNumber()` and
|
||||
`eventAmount()`.
|
||||
|
||||
### Effects, costs and statics
|
||||
|
||||
Effects are camelCase builders, one array entry or callback statement each:
|
||||
|
||||
```js
|
||||
damage(target(permanents.withType('creature')), 3)
|
||||
draw(you, 2)
|
||||
gainLife(you, 1)
|
||||
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 }))
|
||||
putCounters(target(permanents.withType('creature')), '+1/+1', 2)
|
||||
destroy(target(permanents.withType('creature')))
|
||||
addMana(you, mana('{G}{G}'))
|
||||
search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true })
|
||||
pump(each(creatures.youControl()), 1, 1, untilEndOfTurn)
|
||||
```
|
||||
|
||||
Costs are distinct from effects: `manaCost('{2}{U}')`, `tapCost()`,
|
||||
`untapCost()`, `sacrificeSelf()`, `payLife(3)`, `discardCost(1)`,
|
||||
`removeCountersCost('+1/+1', 1)`, `exileSelf()`, `choice([...])` and the rest of
|
||||
the cost builders in `source.ts`.
|
||||
|
||||
Static effects are also distinct, so their AST shape is unambiguous:
|
||||
`staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`,
|
||||
`entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`,
|
||||
`costReduction`, `costIncrease`, `searchRestriction` and
|
||||
`exileInsteadOfGraveyard`. `entersTapped` takes an optional `unlessCost` builder
|
||||
for "you may pay N life; if you don't, it enters tapped":
|
||||
`entersTapped(self, { unlessCost: payLife(2) })`.
|
||||
|
||||
Durations are `permanent` (default), `untilEndOfTurn`, `untilYourNextTurn`,
|
||||
`untilEndOfYourNextTurn`, `untilEndOfCombat`,
|
||||
`untilControllersNextUntapStep` and `whileSourceOnBattlefield`.
|
||||
|
||||
Triggers live under `when`: `when.enters`, `when.dies`, `when.attacks`,
|
||||
`when.blocks`, `when.attacksOrBlocks`, `when.entersOrAttacks`,
|
||||
`when.entersOrDies`, `when.leavesBattlefield`, `when.dealsDamage`,
|
||||
`when.upkeep`, `when.endStep`, `when.beginCombat`, `when.firstMainPhase`,
|
||||
`when.postcombatMainPhase`, `when.cast`, `when.becomesLevel`, `when.draw`,
|
||||
`when.counterPlaced`, `when.becomesTarget`, `when.lifeGained` and
|
||||
`when.lifeLost`.
|
||||
|
||||
Conditions are top-level calls such as `yourTurn()`, `youControl(selector, n)`,
|
||||
`opponentControls(selector)`, `lifeAtLeast(player, n)`, `wasKicked()`,
|
||||
`ifYouDo()`, `ifYouDont()` and `otherwise()`. The full list is the set of
|
||||
condition builders in `source.ts`.
|
||||
|
||||
Nested structures are effect lists (array or callback) or `ifThen`/`modal`:
|
||||
|
||||
```js
|
||||
triggered(when.upkeep(you), [
|
||||
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]),
|
||||
])
|
||||
|
||||
spell([
|
||||
modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]]),
|
||||
])
|
||||
```
|
||||
|
||||
## Manual implementations
|
||||
|
||||
The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a
|
||||
card, edit its pseudocode, and save. The editor toggles between the text view and a
|
||||
node canvas where sockets are wired to define effect order and nested bodies; both
|
||||
edit the same source. The API validates the source before writing it, so a typo
|
||||
never replaces a working file. Overrides take precedence during
|
||||
card, edit its source, and save. The API validates the source before writing it,
|
||||
so a typo never replaces a working file. Overrides take precedence during
|
||||
`npm run compile:cards`; invalid override files stop the compile with the line
|
||||
number.
|
||||
|
||||
@@ -100,7 +260,7 @@ number.
|
||||
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag |
|
||||
| `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` |
|
||||
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output |
|
||||
| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text |
|
||||
| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for card source from the card's oracle text |
|
||||
| `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent |
|
||||
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
|
||||
|
||||
@@ -110,21 +270,20 @@ number.
|
||||
|
||||
The editor's **Draft with AI** button calls
|
||||
`POST /cards/:oracleId/translate`. The backend sends the card's oracle text to
|
||||
an [OpenRouter](https://openrouter.ai/) model and returns pseudocode, without
|
||||
an [OpenRouter](https://openrouter.ai/) model and returns card source, without
|
||||
saving it. The response is parsed before it reaches the browser, so prose or a
|
||||
non-parseable guess is reported as an error instead of replacing the editor.
|
||||
|
||||
Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL`
|
||||
defaults to `google/gemini-2.5-flash-lite`.
|
||||
|
||||
The system prompt contains the syntax reference and a strict output contract:
|
||||
pseudocode only, no explanations, Markdown, code fences or card header, and no
|
||||
invented operations. Output is capped at 700 tokens. A fenced answer is
|
||||
The system prompt contains the source reference and a strict output contract:
|
||||
card source only, no explanations, Markdown, code fences or card header, and no
|
||||
invented operations. Output is capped at 1,200 tokens. A fenced answer is
|
||||
unwrapped defensively, but an invalid answer is not retried (that would spend
|
||||
more tokens). The translator uses the default model only; there is no per-request
|
||||
model picker.
|
||||
|
||||
|
||||
## AST
|
||||
|
||||
The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
@@ -133,6 +292,7 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
{
|
||||
"oracle_id": "...",
|
||||
"name": "Soul Warden",
|
||||
"typeLine": "Creature — Human Cleric",
|
||||
"status": "supported",
|
||||
"abilities": [
|
||||
{
|
||||
@@ -239,7 +399,7 @@ ambiguous pronouns stay unsupported.
|
||||
|
||||
## Adding support
|
||||
|
||||
For a single card, open the frontend editor, edit the pseudocode, and save; no
|
||||
For a single card, open the frontend editor, edit the source, and save; no
|
||||
compiler change is needed. For a whole class of cards:
|
||||
|
||||
1. Run `npm run compile:cards` and pick a frequent unsupported pattern.
|
||||
|
||||
@@ -18,6 +18,7 @@ const game = new Game({
|
||||
startingLife: 40,
|
||||
startingHandSize: 7,
|
||||
commander: true,
|
||||
mulligans: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
|
||||
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 },
|
||||
@@ -32,7 +33,9 @@ in `commander.ts` checks size, singleton, color identity, and the commander type
|
||||
|
||||
`catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds
|
||||
intrinsic mana abilities for basic lands, because Scryfall's oracle text only has
|
||||
reminder text for them and the compiler produces no ability.
|
||||
reminder text for them and the compiler produces no ability. When a compiled card
|
||||
declares a `typeLine`, that value is used instead of Scryfall's; the generated
|
||||
card source carries the type line and an override can change it.
|
||||
|
||||
For tests or hand-authored cards, build a `CardDefinition` yourself:
|
||||
|
||||
@@ -56,7 +59,10 @@ const bolt: CardDefinition = {
|
||||
|
||||
| Method | Purpose |
|
||||
| ------ | ------- |
|
||||
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
|
||||
| `start()` | Shuffles libraries and draws opening hands. With `mulligans: true`, turn 1 waits until every player keeps. |
|
||||
| `keepHand(playerId)` | Keeps the opening hand; begins turn 1 once every living player has kept. |
|
||||
| `mulligan(playerId)` | Shuffles the hand back, draws a new opening hand, and queues bottom-of-library choices (one more each time). |
|
||||
| `putOnBottom(playerId, cardId)` | Puts one chosen card from a mulliganed opening hand on the bottom of its owner's library. |
|
||||
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. |
|
||||
| `castSpell(playerId, cardId, { targets, x, mode, overload })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone, adds commander tax, and can pay the overload cost instead. |
|
||||
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
|
||||
@@ -87,6 +93,10 @@ the permanent, and the match API refuses other priority actions until `chooseCre
|
||||
(the `choose_type` action) receives one of the creature types in `CREATURE_TYPES`.
|
||||
The chosen type is stored on the object and cleared when it leaves the battlefield.
|
||||
|
||||
With mulligans enabled, the game starts in the `mulligan` status. A mulligan shuffles
|
||||
the hand back and draws seven; the second mulligan puts one card on the bottom, the
|
||||
third two, and so on (London rule). Turn 1 begins when every living player has kept.
|
||||
|
||||
## Turn structure
|
||||
|
||||
```text
|
||||
@@ -132,8 +142,8 @@ shown to players who can actually do something.
|
||||
lifelink, vigilance, haste, indestructible. Regeneration shields replace
|
||||
destruction.
|
||||
- State-based actions: life at or below zero, ten poison counters, 21 commander
|
||||
damage from one commander, lethal or deathtouch damage, zero toughness, and
|
||||
drawing from an empty library.
|
||||
damage from one commander, lethal or deathtouch damage, zero toughness, the
|
||||
legend rule, and drawing from an empty library.
|
||||
|
||||
## Known limitations
|
||||
|
||||
@@ -144,11 +154,13 @@ shown to players who can actually do something.
|
||||
- Commander support covers single commanders. Partner, backgrounds, companions,
|
||||
and "choose a commander" variants are not modelled. The engine always takes the
|
||||
command-zone replacement instead of asking.
|
||||
- The legend rule, planeswalker loyalty abilities, attacking planeswalkers, and
|
||||
- Planeswalker loyalty abilities, attacking planeswalkers, and
|
||||
protection/menace/defender are not implemented unless expressed as a compiled
|
||||
restriction.
|
||||
restriction. When the legend rule applies, the engine keeps the first copy it
|
||||
finds and moves the rest to the graveyard instead of asking the controller.
|
||||
- Modal spells choose a mode by index (`options.mode`); optional "you may" choices
|
||||
are not modelled. An optional `pay` is simply not paid when unaffordable. Search
|
||||
are not modelled, except "pay a cost or enter tapped" which pauses for the
|
||||
controller. An optional `pay` is simply not paid when unaffordable. Search
|
||||
effects with several matching cards do pause for the player's pick.
|
||||
- "As this enters, choose a creature type" pauses for a pick and stores the type on
|
||||
the permanent, but no effect reads the chosen type yet. The other `choose` kinds
|
||||
@@ -160,7 +172,9 @@ shown to players who can actually do something.
|
||||
- Overload widens only top-level effect targets; a nested modal or conditional target
|
||||
keeps its printed target. Free alternative costs are modelled only for controlling
|
||||
a commander, and search restrictions cap the searching player's own library.
|
||||
- Opening hands are kept automatically; there is no mulligan flow.
|
||||
- Opening hands use the London mulligan when `mulligans` is enabled: each mulligan
|
||||
draws seven, then puts one more card on the bottom than the previous one. The
|
||||
match API starts with mulligans on.
|
||||
- Replacement/prevention effects, layers, and dependency ordering are simplified.
|
||||
Continuous effects apply in creation order rather than in full rules order.
|
||||
- The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory
|
||||
|
||||
Reference in New Issue
Block a user