First commit

This commit is contained in:
2026-10-27 12:42:57 +01:00
commit 7dd9f4b14d
74 changed files with 33018 additions and 0 deletions

View File

@@ -0,0 +1,260 @@
# 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.

158
backend/docs/game-engine.md Normal file
View File

@@ -0,0 +1,158 @@
# Game engine
`backend/src/game/` is a small but real Magic rules engine. It consumes the compiled
effect AST from `backend/src/effects/types.ts` directly — there is no second card
language. Card definitions are immutable input; a `GameObject` is the per-game
instance that moves between zones.
## Quick start
Run the data imports first (see the root README), then:
```ts
import { Game } from './src/game/game.js'
import { deckFromOracleIds } from './src/game/catalog.js'
const game = new Game({
seed: 1,
startingLife: 40,
startingHandSize: 7,
commander: true,
players: [
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 },
],
})
game.start()
```
`commander: true` creates each supplied commander in that player's command zone. The
`deck` should contain the other 99 cards; `validateCommanderDeck(commander, cards)`
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.
For tests or hand-authored cards, build a `CardDefinition` yourself:
```ts
const bolt: CardDefinition = {
oracleId: 'lightning-bolt',
name: 'Lightning Bolt',
typeLine: 'Instant',
manaCost: '{R}',
manaValue: 1,
abilities: [{
kind: 'spell',
optional: false,
text: 'Lightning Bolt deals 3 damage to any target.',
effects: [{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }],
}],
}
```
## Actions
| Method | Purpose |
| ------ | ------- |
| `start()` | Shuffles libraries, draws opening hands, begins turn 1. |
| `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. |
| `castSpell(playerId, cardId, { targets, x, mode })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. |
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. |
| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. |
| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. |
| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. |
| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. |
| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. |
| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. |
| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. |
| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. |
| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. |
| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. |
| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. |
Actions that use the stack move priority to the next living player. Non-instant,
non-flash spells can only be cast in the active player's main phase with an empty
stack. Targets may be supplied explicitly; if omitted, the first legal target is
chosen automatically, which keeps scripted games short. A search effect that matches
several cards pauses instead: other actions are refused until its controller calls
`chooseSearchCard` (the match API uses the `choose_search` action).
## Turn structure
```text
untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers
-> declare blockers -> combat damage -> end combat -> postcombat main
-> end step -> cleanup -> next player's turn
```
The starting player skips their first draw. Cleanup discards down to seven cards,
clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn`
effects, and empties mana pools. The engine advances phases when every living
player passes in turn; it does not stop at every rules-defined priority window.
The match manager calls `autoAdvance()` after each action, so priority is only
shown to players who can actually do something.
## Supported
- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
cease to exist when they leave the battlefield.
- Commander: command-zone casting, `{2}` tax per previous cast from the command
zone, return to the command zone instead of graveyard/exile/hand/library, and a
loss at 21 combat damage from one commander. Deck construction is validated by
`validateCommanderDeck`.
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
abilities plus automatic tapping of untapped mana sources when paying.
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
putting/removing counters, mill, energy, and choice costs.
- Abilities: spell effects, activated abilities, triggered abilities (enters,
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static
effects, and basic replacement effects for entering tapped/with counters.
- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability,
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy,
attach, restrictions, conditional and modal effects, dig, and divided damage.
- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
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.
## Known limitations
- Some effect nodes are accepted but intentionally do nothing yet:
`prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`,
`put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`.
Unsupported oracle lines are already marked by the compiler and never reach here.
- 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
protection/menace/defender are not implemented unless expressed as a compiled
restriction.
- 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
effects with several matching cards do pause for the player's pick.
- Opening hands are kept automatically; there is no mulligan flow.
- 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
multiplayer matches, validates decks, and sends each player a personalized view
(own hand only, libraries as counts) over SSE.
- There is no persistence, account system, or reconnect grace period; a server
restart drops all matches.
## Tests
```bash
cd backend
npx tsx --test test/game.test.ts test/commander.test.ts
```
The tests cover turn flow, priority, spell resolution, triggers, mana and summoning
sickness, static and temporary pumps, combat, counterspells, tokens, searching,
entering tapped/with counters, decking, lethal damage, commander tax and damage,
decklist import, and multi-defender combat.