261 lines
10 KiB
Markdown
261 lines
10 KiB
Markdown
# Card effect compiler
|
|
|
|
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.
|
|
|
|
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
|
|
engine that consumes these nodes.
|
|
|
|
## Pipeline
|
|
|
|
```text
|
|
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
|
|
|
|
data/card-overrides/<oracle_id>.pseudo.txt
|
|
-> pseudocode parser
|
|
-> JSON AST used instead of the generated one
|
|
```
|
|
|
|
Every line is parsed as a whole. If any part of a line is not understood, the
|
|
line becomes `{ "kind": "unsupported", "reason": ..., "text": ... }` instead of
|
|
a guessed effect. A wrong effect is worse than a missing one.
|
|
|
|
## Commands
|
|
|
|
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 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%)
|
|
```
|
|
|
|
- **supported** — every ability line parsed.
|
|
- **partial** — at least one line parsed, at least one unsupported.
|
|
- **unsupported** — no line parsed.
|
|
|
|
The unsupported lines are the work queue. Re-running the compiler after adding
|
|
patterns updates the numbers.
|
|
|
|
## Output files
|
|
|
|
| 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 |
|
|
|
|
The two generated files are git-ignored. Overrides are ordinary source files and
|
|
should be committed.
|
|
|
|
## Pseudocode
|
|
|
|
```text
|
|
# Soul Warden [supported]
|
|
on enters(each other creature):
|
|
gain_life(you, 1)
|
|
|
|
# Llanowar Elves [supported]
|
|
activate {T}:
|
|
add_mana(you, {G})
|
|
|
|
# Krenko, Mob Boss [supported]
|
|
activate {T}:
|
|
create_token(you, count(creature goblin you control), 1/1 red goblin creature)
|
|
```
|
|
|
|
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.
|
|
|
|
## 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
|
|
`npm run compile:cards`; invalid override files stop the compile with the line
|
|
number.
|
|
|
|
| Method | Path | Purpose |
|
|
| ------ | ---- | ------- |
|
|
| `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 |
|
|
| `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent |
|
|
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
|
|
|
|
`CARD_OVERRIDES_DIR` changes the storage directory (useful for tests).
|
|
|
|
### AI drafts
|
|
|
|
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
|
|
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
|
|
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:
|
|
|
|
```jsonc
|
|
{
|
|
"oracle_id": "...",
|
|
"name": "Soul Warden",
|
|
"status": "supported",
|
|
"abilities": [
|
|
{
|
|
"kind": "triggered",
|
|
"event": {
|
|
"kind": "enters",
|
|
"subject": {
|
|
"kind": "object",
|
|
"selector": { "other": true, "types": ["creature"] },
|
|
"mode": "each"
|
|
}
|
|
},
|
|
"effects": [
|
|
{ "op": "life", "player": "you", "amount": { "kind": "number", "value": 1 }, "mode": "gain" }
|
|
],
|
|
"optional": false,
|
|
"text": "Whenever another creature enters, you gain 1 life."
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
### Ability kinds
|
|
|
|
| Kind | Meaning | Example |
|
|
| ---- | ------- | ------- |
|
|
| `keyword` | One parameterless or parameterized keyword | `Flying`, `Ward {2}`, `Crew 3` |
|
|
| `keywords` | Several keywords on one oracle line | `Flying, vigilance` |
|
|
| `triggered` | `When`/`Whenever`/`At` ability | `When this enters, draw a card.` |
|
|
| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
|
|
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
|
|
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` |
|
|
| `unsupported` | Preserved text plus a reason | `Choose one —` |
|
|
|
|
### Effects
|
|
|
|
| `op` | Payload |
|
|
| ---- | ------- |
|
|
| `damage` | `target`, `amount`, optional `source` |
|
|
| `draw`, `discard`, `mill` | `player`, `amount` |
|
|
| `life` | `player`, `amount`, `mode: gain \| lose` |
|
|
| `pump` | `target`, `power`, `toughness`, `duration` |
|
|
| `grant` | `target`, `keyword`, optional `value`, `duration` |
|
|
| `put_counters`, `remove_counters` | `target`, `counter`, `amount` |
|
|
| `create_token` | `player`, `amount`, `token` |
|
|
| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` |
|
|
| `sacrifice` | `player`, `target`, optional `unless` cost |
|
|
| `counter` | `what`, `target`, optional `unless` cost |
|
|
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` |
|
|
| `search`, `shuffle` | player, selector, destination |
|
|
| `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
|
|
| `scry`, `surveil` | `player`, `amount` |
|
|
| `fight` | two targets |
|
|
| `energy` | `player`, `amount` |
|
|
| `attach` | target to attach this/trigger object to |
|
|
| `restriction` | target, rule, duration |
|
|
| `keyword_action` | `action`, optional `amount`, `detail`, `target` |
|
|
| `proliferate` | no payload |
|
|
|
|
### Targets, values, costs
|
|
|
|
- **Targets** are `self`, `trigger_subject`, `any`, `player`, `spell`, `ability`,
|
|
or `object` with an `ObjectSelector` and mode `target` / `each` / `choose`.
|
|
- **Selectors** carry types, subtypes, controller, colors, zone, tapped/attacking
|
|
state, `other`, `attached: equipped|enchanted`, and `includeSelf`.
|
|
- **Values** are `number`, `x`, `count(selector)`, `source_power`,
|
|
`source_toughness`, `cards_in_hand`, or `event_amount`.
|
|
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
|
|
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
|
|
- **Conditions** cover controlling permanents, turn ownership, tapped source,
|
|
life totals, and graveyard size.
|
|
- **Durations** cover permanent, end of turn, your next turn, the end of your
|
|
next turn, end of combat, controller's next untap step, and while the source
|
|
remains.
|
|
|
|
## How a line is parsed
|
|
|
|
1. Reminder text in parentheses is removed. Card names and "this creature" /
|
|
"this permanent" become `this`.
|
|
2. Pure keyword lines are recognized from Scryfall's keyword list plus the
|
|
parameterized keyword table.
|
|
3. Trigger prefixes (`When this enters`, `Whenever this attacks`, `At the
|
|
beginning of your upkeep`, ...) become a `TriggerEvent`.
|
|
4. A colon splits an activated ability into costs and effects.
|
|
5. A leading duration (`Until end of turn, ...`) moves to the end of the
|
|
effect, where the duration parser expects it.
|
|
6. Otherwise a static effect is attempted.
|
|
7. Instant/sorcery lines fall back to a one-shot effect (`kind: "spell"`).
|
|
8. Anything left over is `unsupported`.
|
|
|
|
Effects are split on sentences, `, then`, and `and` only when both sides parse.
|
|
`When you do, ...` becomes a reflexive `if you do` condition. `it` becomes the
|
|
trigger subject only when no explicit target/`that` appears in the same effect;
|
|
ambiguous pronouns stay unsupported.
|
|
|
|
## Adding support
|
|
|
|
For a single card, open the frontend editor, edit the pseudocode, 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.
|
|
2. Add a regex + AST builder in `src/effects/compile.ts` (or a target/value
|
|
parser in `src/effects/parse.ts`).
|
|
3. Add a focused test in `test/effects.test.ts`.
|
|
4. Run `npm test` and `npm run compile:cards`.
|
|
|
|
Prefer narrow, anchored patterns. A broad pattern that misreads one card is a
|
|
game bug that is hard to find later.
|
|
|
|
## Known gaps
|
|
|
|
The remaining unsupported lines are mostly:
|
|
|
|
- modal abilities (`Choose one —` and bullets)
|
|
- replacement effects (`If ... instead`, `As ... enters, ...`)
|
|
- continuous-effect layers and dependency rules
|
|
- copy, control-change, and type-change effects
|
|
- alternative/additional costs and cost modifiers
|
|
- level/class/saga structures and chapter abilities
|
|
- quoted token abilities and copying tokens
|
|
- complex pronoun/context resolution and "for each" scaling beyond simple counts
|
|
- dice, stickers, attractions, dungeons, and other supplemental mechanics
|
|
|
|
None of these are blocked by the AST; each needs a parser pattern and an engine
|
|
implementation.
|