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

@@ -4,7 +4,7 @@ Online multiplayer Magic: The Gathering (Commander) emulator: Nuxt frontend + Fa
## Layout ## Layout
- `backend/` — Node 24, Fastify 5, TypeScript (ESM, NodeNext). `src/effects/` is the oracle-text compiler/pseudocode DSL, `src/game/` the rules engine and in-memory match manager. - `backend/` — Node 24, Fastify 5, TypeScript (ESM, NodeNext). `src/effects/` is the oracle-text compiler/card-source DSL, `src/game/` the rules engine and in-memory match manager.
- `frontend/` — Nuxt 4 / Vue 3, sources under `app/`. - `frontend/` — Nuxt 4 / Vue 3, sources under `app/`.
- `backend/docs/card-effects.md` and `backend/docs/game-engine.md` are the detailed references for those subsystems; `README.md` has the full API and config tables. - `backend/docs/card-effects.md` and `backend/docs/game-engine.md` are the detailed references for those subsystems; `README.md` has the full API and config tables.
@@ -16,14 +16,15 @@ cd backend && npm install && npm run dev # API only
cd frontend && npm install && npm run dev # UI only cd frontend && npm install && npm run dev # UI only
cd backend && npm test # all backend tests cd backend && npm test # all backend tests
cd backend && npm run import:cards # Scryfall bulk data -> data/cards.json cd backend && npm run import:cards # Scryfall bulk data -> data/cards.json
cd backend && npm run compile:cards # oracle text -> data/card-effects.json + pseudo.txt cd backend && npm run compile:cards # oracle text -> data/card-effects.json + card-effects.js
``` ```
## Things to know ## Things to know
- Backend imports need `.js` extensions (`NodeNext`) even though sources are `.ts`. - Backend imports need `.js` extensions (`NodeNext`) even though sources are `.ts`.
- `backend/data/cards.json` (~21 MB) and `card-effects.json` are generated, not committed; run the import/compile scripts after changing the importer or compiler. Missing card data makes `/cards` return `503`. - `backend/data/cards.json` (~21 MB) and `card-effects.json` are generated, not committed; run the import/compile scripts after changing the importer or compiler. Missing card data makes `/cards` return `503`.
- Manual card implementations live in `backend/data/card-overrides/` (one file per card, pseudocode DSL) and take precedence over generated output when compiling. - Manual card implementations live in `backend/data/card-overrides/` (one file per card, card-source DSL) and take precedence over generated output when compiling.
- Asked to implement a specific card: write that card's override JS, then implement whatever the effect needs in the game engine (`backend/src/game/`) so the card actually works in a game — an override alone is not a finished card.
- The effect compiler is conservative: unparseable oracle lines become `unsupported` with original text — never guess or silently drop them. - The effect compiler is conservative: unparseable oracle lines become `unsupported` with original text — never guess or silently drop them.
- Matches are in memory and lost on restart; accounts, saved decks, playmat preferences, and per-deck card backs are in MongoDB through `backend/src/accounts.ts`. Game seats still use a per-seat token in the frontend's `sessionStorage`; the account login token is in a cookie so the server can gate pages. - Matches are in memory and lost on restart; accounts, saved decks, playmat preferences, and per-deck card backs are in MongoDB through `backend/src/accounts.ts`. Game seats still use a per-seat token in the frontend's `sessionStorage`; the account login token is in a cookie so the server can gate pages.
- Keep style of surrounding code: 2-space indent, single quotes. No linter or formatter is configured. - Keep style of surrounding code: 2-space indent, single quotes. No linter or formatter is configured.

View File

@@ -94,23 +94,24 @@ with its original text, never guessed.
```bash ```bash
cd backend cd backend
npm run compile:cards # data/card-effects.json + data/card-effects.pseudo.txt npm run compile:cards # data/card-effects.json + data/card-effects.js
npm test npm test
``` ```
`data/card-effects.pseudo.txt` is the human-readable pseudocode view. The `data/card-effects.js` is the human-readable card source. The source is also an
pseudocode is also an input format: the frontend editor saves one override file input format: the frontend editor saves one override file per card under
per card under `backend/data/card-overrides/`, and `npm run compile:cards` `backend/data/card-overrides/`, and `npm run compile:cards` validates those files
validates those files and uses them instead of generated output. See and uses them instead of generated output. Card source looks like JavaScript but
[backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL, is evaluated by a safe interpreter with a fixed builder API, never by `eval`.
See [backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL,
current coverage, and how to add support for more cards. current coverage, and how to add support for more cards.
The `/cards` page has an **Editor** view and a **Guide** view that summarizes the The `/cards` page has an **Editor** view and a **Guide** view that summarizes the
pseudocode syntax. **Draft with AI** sends the selected card's oracle text to an source syntax. **Draft with AI** sends the selected card's oracle text to an
OpenRouter model and loads the returned pseudocode into the editor without OpenRouter model and loads the returned source into the editor without saving
saving it. The model is instructed to answer with pseudocode only — no it. The model is instructed to answer with card source only — no explanations,
explanations, Markdown or code fences — and the answer must parse before the API Markdown or code fences — and the answer must parse before the API returns it.
returns it. Set `OPENROUTER_API_KEY` on the backend to enable the button; Set `OPENROUTER_API_KEY` on the backend to enable the button;
`OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. `OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`.
## Game engine ## Game engine
@@ -160,7 +161,7 @@ The frontend has five pages:
- `/` — create a 2–4 player game, join an open lobby, and pick your playmat. - `/` — create a 2–4 player game, join an open lobby, and pick your playmat.
- `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and - `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and
export it again. Decks are stored with your account. export it again. Decks are stored with your account.
- `/cards` — the existing card implementation editor and pseudocode guide. - `/cards` — the existing card implementation editor and source guide.
- `/games/:id` — lobby and game board. The page can also be used as an invite - `/games/:id` — lobby and game board. The page can also be used as an invite
link; a player with no seat gets a join form. link; a player with no seat gets a join form.
@@ -208,7 +209,7 @@ image builds TypeScript and installs production dependencies only.
| `BACKEND_PORT` | `4000` | production | Host port for the API | | `BACKEND_PORT` | `4000` | production | Host port for the API |
| `PORT` | `4000` | backend | Port the API listens on inside the container | | `PORT` | `4000` | backend | Port the API listens on inside the container |
| `CARD_OVERRIDES_DIR` | `backend/data/card-overrides` | backend | Where manual implementations are stored | | `CARD_OVERRIDES_DIR` | `backend/data/card-overrides` | backend | Where manual implementations are stored |
| `OPENROUTER_API_KEY` | — | backend | Enables the editor's AI pseudocode draft | | `OPENROUTER_API_KEY` | — | backend | Enables the editor's AI card-source draft |
| `OPENROUTER_MODEL` | `google/gemini-2.5-flash-lite` | backend | OpenRouter model used for translation | | `OPENROUTER_MODEL` | `google/gemini-2.5-flash-lite` | backend | OpenRouter model used for translation |
When deploying to a real host, set `NUXT_PUBLIC_API_BASE` and `CORS_ORIGIN` to When deploying to a real host, set `NUXT_PUBLIC_API_BASE` and `CORS_ORIGIN` to
@@ -220,15 +221,15 @@ your public URLs. Both values are applied at runtime in the production image.
. .
├── backend/ ├── backend/
│ ├── scripts/import-cards.ts # Scryfall bulk importer │ ├── scripts/import-cards.ts # Scryfall bulk importer
│ ├── scripts/compile-cards.ts # oracle text -> effect AST + pseudocode │ ├── scripts/compile-cards.ts # oracle text -> effect AST + card source
│ ├── src/cards.ts # card store, lookup, and search │ ├── src/cards.ts # card store, lookup, and search
│ ├── src/images.ts # on-disk cache for Scryfall card art │ ├── src/images.ts # on-disk cache for Scryfall card art
│ ├── src/effects/ # effect DSL, compiler, formatter, pseudocode parser │ ├── src/effects/ # effect DSL, compiler, formatter, source interpreter
│ ├── src/effects/translate.ts # natural language -> pseudocode through OpenRouter │ ├── src/effects/translate.ts # natural language -> card source through OpenRouter
│ ├── src/game/ # rules engine, commander rules, match manager │ ├── src/game/ # rules engine, commander rules, match manager
│ ├── src/accounts.ts # Mongo models, auth, decks, and preferences │ ├── src/accounts.ts # Mongo models, auth, decks, and preferences
│ ├── src/server.ts # Fastify entry point and game/deck routes │ ├── src/server.ts # Fastify entry point and game/deck routes
│ ├── test/ # compiler, pseudocode, engine, and commander tests │ ├── test/ # compiler, source, engine, and commander tests
│ ├── docs/card-effects.md # DSL reference and coverage │ ├── docs/card-effects.md # DSL reference and coverage
│ ├── docs/game-engine.md # engine API, rules coverage, limitations │ ├── docs/game-engine.md # engine API, rules coverage, limitations
│ ├── data/cards.json # generated by npm run import:cards │ ├── data/cards.json # generated by npm run import:cards
@@ -246,7 +247,7 @@ your public URLs. Both values are applied at runtime in the production image.
│ ├── app/middleware/auth.ts # redirect signed-out visitors to /account │ ├── app/middleware/auth.ts # redirect signed-out visitors to /account
│ ├── app/utils/auth.ts # login token storage and headers │ ├── app/utils/auth.ts # login token storage and headers
│ ├── app/utils/decks.ts # account deck API and validation │ ├── app/utils/decks.ts # account deck API and validation
│ ├── app/components/PseudoGuide.vue # pseudocode guide view │ ├── app/components/SourceGuide.vue # card source guide view
│ ├── nuxt.config.ts # runtime config (API base URL) │ ├── nuxt.config.ts # runtime config (API base URL)
│ ├── Dockerfile # dev, build, and production stages │ ├── Dockerfile # dev, build, and production stages
│ └── package.json │ └── package.json
@@ -271,10 +272,10 @@ your public URLs. Both values are applied at runtime in the production image.
| `GET` | `/cards/:oracleId/art` | Wide card art crop used for playmats, cached on disk | | `GET` | `/cards/:oracleId/art` | Wide card art crop used for playmats, cached on disk |
| `GET` | `/cards?status=needs-work` | Filter by `supported`, `partial`, `unsupported`, `needs-work`, `manual`, `all` | | `GET` | `/cards?status=needs-work` | Filter by `supported`, `partial`, `unsupported`, `needs-work`, `manual`, `all` |
| `GET` | `/cards?format=modern&color=U&type=creature&rarity=rare&cmcMin=1&cmcMax=3` | Format legality, color identity (`WUBRG` includes that color, `C` colorless, `M` multicolor), card type, rarity, and mana value filters | | `GET` | `/cards?format=modern&color=U&type=creature&rarity=rare&cmcMin=1&cmcMax=3` | Format legality, color identity (`WUBRG` includes that color, `C` colorless, `M` multicolor), card type, rarity, and mana value filters |
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, pseudocode source, manual flag | | `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, card source, manual flag |
| `PUT` | `/cards/:oracleId/implementation` | Validate `{ "source": "..." }` and save the override | | `PUT` | `/cards/:oracleId/implementation` | Validate `{ "source": "..." }` and save the override |
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override and restore generated output | | `DELETE` | `/cards/:oracleId/implementation` | Delete the override and 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 override source, or `404` | | `GET` | `/cards/:oracleId/override` | Raw override source, or `404` |
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts | | `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
| `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` | | `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` |

2
backend/.gitignore vendored
View File

@@ -3,7 +3,7 @@ dist
.env .env
data/cards.json data/cards.json
data/card-effects.json data/card-effects.json
data/card-effects.pseudo.txt data/card-effects.js
data/images/ data/images/
data/playmats/ data/playmats/
data/*.tmp data/*.tmp

View File

@@ -0,0 +1,5 @@
export default [
activated([tapCost()], [
addMana(you, anyColor(1, { restriction: 'a land an opponent controls could produce' })),
]),
]

View File

@@ -0,0 +1,7 @@
export default [
keywords('Flying', 'Ward {2}'),
triggered(
when.enters(each(permanents.other().nontoken().withSubtype('dragon').withType('creature').youControl())),
() => createToken(you, 1, copyOf(triggerSubject, { notLegendary: true })),
),
]

View File

@@ -1,4 +0,0 @@
# Miirym, Sentinel Wyrm [supported]
keywords Flying, Ward {2}
on enters(each other nontoken dragon you control):
create_token(you, 1, copy of the triggering object, not legendary)

View File

@@ -3,9 +3,9 @@
The card database from Scryfall is English prose. The game engine cannot execute 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 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 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 the same AST as readable card source, and a matching interpreter reads that
back, so a human can replace the generated implementation of a card without source back, so a human can replace the generated implementation of a card
touching JSON. without touching JSON.
This is deliberately **not** a rules engine. It answers "what does the card 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 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) -> normalize (card name, "this creature", contractions, reminder text)
-> classify (keyword / triggered / activated / static / spell effect) -> classify (keyword / triggered / activated / static / spell effect)
-> parse targets, values, costs, conditions, durations -> parse targets, values, costs, conditions, durations
-> JSON AST + pseudocode rendering -> JSON AST + card-source rendering
data/card-overrides/<oracle_id>.pseudo.txt data/card-overrides/<oracle_id>.js
-> pseudocode parser -> safe source interpreter
-> JSON AST used instead of the generated one -> 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/`: From `backend/`:
```bash ```bash
npm run compile:cards # writes data/card-effects.json and .pseudo.txt npm run compile:cards # writes data/card-effects.json and data/card-effects.js
npm test # compiler, pseudocode parser, and engine tests npm test # compiler, source interpreter, and engine tests
npm run dev # API for the frontend editor npm run dev # API for the frontend editor
``` ```
Current output over the imported Commander pool (32,116 cards): Current output over the imported Commander pool (32,116 cards):
```text ```text
Cards: 14,141 supported, 10,119 partial, 7,856 unsupported Cards: 14,239 supported, 10,088 partial, 7,789 unsupported
Ability lines: 37,983/60,470 parsed (62.8%) Ability lines: 38,132/60,470 parsed (63.1%)
``` ```
- **supported** — every ability line parsed. - **supported** — every ability line parsed.
@@ -58,40 +58,200 @@ patterns updates the numbers.
| File | Contents | | File | Contents |
| ---- | -------- | | ---- | -------- |
| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card | | `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-effects.js` | The same cards rendered as card source |
| `data/card-overrides/<oracle_id>.pseudo.txt` | Human-authored implementations, one file per card | | `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 The two generated files are git-ignored. Overrides are ordinary source files and
should be committed. 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 ## Card source
# Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
# Llanowar Elves [supported] Card source looks like a JavaScript module, but it is **not executed as
activate {T}: JavaScript**. `src/effects/source.ts` tokenizes and evaluates a deliberately
add_mana(you, {G}) 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] A card exports its type line and an array of abilities:
activate {T}:
create_token(you, count(creature goblin you control), 1/1 red goblin creature) ```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 Plain `export default [...]` is still accepted and uses the Scryfall type line.
it back into the same AST the compiler produces. Blocks are indented two spaces. Multi-face cards export `faces(face('Name', 'Type line', [...]), ...)` in card order:
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. ```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 ## Manual implementations
The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a 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 card, edit its source, and save. The API validates the source before writing it,
node canvas where sockets are wired to define effect order and nested bodies; both so a typo never replaces a working file. Overrides take precedence during
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 `npm run compile:cards`; invalid override files stop the compile with the line
number. number.
@@ -100,7 +260,7 @@ number.
| `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag | | `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag |
| `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` | | `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` |
| `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output | | `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` | `/cards/:oracleId/override` | Raw saved source, `404` when absent |
| `GET` | `/stats` | Supported, partial, unsupported, and manual counts | | `GET` | `/stats` | Supported, partial, unsupported, and manual counts |
@@ -110,21 +270,20 @@ number.
The editor's **Draft with AI** button calls The editor's **Draft with AI** button calls
`POST /cards/:oracleId/translate`. The backend sends the card's oracle text to `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 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. 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` Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL`
defaults to `google/gemini-2.5-flash-lite`. defaults to `google/gemini-2.5-flash-lite`.
The system prompt contains the syntax reference and a strict output contract: The system prompt contains the source reference and a strict output contract:
pseudocode only, no explanations, Markdown, code fences or card header, and no card source only, no explanations, Markdown, code fences or card header, and no
invented operations. Output is capped at 700 tokens. A fenced answer is 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 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 more tokens). The translator uses the default model only; there is no per-request
model picker. model picker.
## AST ## AST
The types live in `src/effects/types.ts`. A card contains one or more abilities: 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": "...", "oracle_id": "...",
"name": "Soul Warden", "name": "Soul Warden",
"typeLine": "Creature — Human Cleric",
"status": "supported", "status": "supported",
"abilities": [ "abilities": [
{ {
@@ -239,7 +399,7 @@ ambiguous pronouns stay unsupported.
## Adding support ## 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: compiler change is needed. For a whole class of cards:
1. Run `npm run compile:cards` and pick a frequent unsupported pattern. 1. Run `npm run compile:cards` and pick a frequent unsupported pattern.

View File

@@ -18,6 +18,7 @@ const game = new Game({
startingLife: 40, startingLife: 40,
startingHandSize: 7, startingHandSize: 7,
commander: true, commander: true,
mulligans: true,
players: [ players: [
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 }, { id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 }, { 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 `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 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: For tests or hand-authored cards, build a `CardDefinition` yourself:
@@ -56,7 +59,10 @@ const bolt: CardDefinition = {
| Method | Purpose | | 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. | | `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. | | `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. | | `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 `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. 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 ## Turn structure
```text ```text
@@ -132,8 +142,8 @@ shown to players who can actually do something.
lifelink, vigilance, haste, indestructible. Regeneration shields replace lifelink, vigilance, haste, indestructible. Regeneration shields replace
destruction. destruction.
- State-based actions: life at or below zero, ten poison counters, 21 commander - State-based actions: life at or below zero, ten poison counters, 21 commander
damage from one commander, lethal or deathtouch damage, zero toughness, and damage from one commander, lethal or deathtouch damage, zero toughness, the
drawing from an empty library. legend rule, and drawing from an empty library.
## Known limitations ## Known limitations
@@ -144,11 +154,13 @@ shown to players who can actually do something.
- Commander support covers single commanders. Partner, backgrounds, companions, - Commander support covers single commanders. Partner, backgrounds, companions,
and "choose a commander" variants are not modelled. The engine always takes the and "choose a commander" variants are not modelled. The engine always takes the
command-zone replacement instead of asking. 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 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 - 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. 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 - "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 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 - 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 keeps its printed target. Free alternative costs are modelled only for controlling
a commander, and search restrictions cap the searching player's own library. 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. - Replacement/prevention effects, layers, and dependency ordering are simplified.
Continuous effects apply in creation order rather than in full rules order. 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 - The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory

View File

@@ -4,13 +4,13 @@ import type { Card } from '../src/cards.js'
import { compileCard } from '../src/effects/compile.js' import { compileCard } from '../src/effects/compile.js'
import { formatCard } from '../src/effects/format.js' import { formatCard } from '../src/effects/format.js'
import { compileImplementation, readAllOverrides } from '../src/effects/implementations.js' import { compileImplementation, readAllOverrides } from '../src/effects/implementations.js'
import { PseudoParseError } from '../src/effects/pseudo.js' import { SourceParseError } from '../src/effects/source.js'
import type { Ability, CompiledCard } from '../src/effects/types.js' import type { Ability, CompiledCard } from '../src/effects/types.js'
const DATA_DIR = join(process.cwd(), 'data') const DATA_DIR = join(process.cwd(), 'data')
const CARDS_FILE = join(DATA_DIR, 'cards.json') const CARDS_FILE = join(DATA_DIR, 'cards.json')
const AST_FILE = join(DATA_DIR, 'card-effects.json') const AST_FILE = join(DATA_DIR, 'card-effects.json')
const PSEUDO_FILE = join(DATA_DIR, 'card-effects.pseudo.txt') const SOURCE_FILE = join(DATA_DIR, 'card-effects.js')
function formatBytes(bytes: number): string { function formatBytes(bytes: number): string {
return `${(bytes / 1024 / 1024).toFixed(1)} MB` return `${(bytes / 1024 / 1024).toFixed(1)} MB`
@@ -55,7 +55,7 @@ for (const card of cards) {
try { try {
result = source === undefined ? compileCard(card) : compileImplementation(card, source) result = source === undefined ? compileCard(card) : compileImplementation(card, source)
} catch (error) { } catch (error) {
if (error instanceof PseudoParseError) { if (error instanceof SourceParseError) {
console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`) console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`)
console.error(` ${error.message}`) console.error(` ${error.message}`)
process.exit(1) process.exit(1)
@@ -80,9 +80,9 @@ for (const card of cards) {
await mkdir(DATA_DIR, { recursive: true }) await mkdir(DATA_DIR, { recursive: true })
const astOutput = JSON.stringify(compiled) const astOutput = JSON.stringify(compiled)
const pseudoOutput = compiled.map(formatCard).join('\n\n') const sourceOutput = compiled.map(formatCard).join('\n\n')
await writeFile(AST_FILE, astOutput) await writeFile(AST_FILE, astOutput)
await writeFile(PSEUDO_FILE, pseudoOutput) await writeFile(SOURCE_FILE, sourceOutput)
console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`) console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`)
console.log( console.log(
@@ -100,4 +100,4 @@ if (samples.length) {
for (const sample of samples) console.log(` - ${sample}`) for (const sample of samples) console.log(` - ${sample}`)
} }
console.log(`Wrote ${formatBytes(Buffer.byteLength(astOutput))} to ${AST_FILE}`) console.log(`Wrote ${formatBytes(Buffer.byteLength(astOutput))} to ${AST_FILE}`)
console.log(`Wrote ${formatBytes(Buffer.byteLength(pseudoOutput))} to ${PSEUDO_FILE}`) console.log(`Wrote ${formatBytes(Buffer.byteLength(sourceOutput))} to ${SOURCE_FILE}`)

View File

@@ -997,7 +997,13 @@ function parseEffect(text: string): Effect | Effect[] | undefined {
match = sentence.match(/^add ((?:\{[^}]+\})(?:,? ?(?:or )?\{[^}]+\})*)$/) match = sentence.match(/^add ((?:\{[^}]+\})(?:,? ?(?:or )?\{[^}]+\})*)$/)
if (match) { if (match) {
const symbols = match[1].match(/\{[^}]+\}/g) 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)?$/) 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') { if (sentence === 'this enters tapped') {
return [{ op: 'enters_tapped', target: { kind: 'self' } }] 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 (.+)$/) const entersTappedUnless = sentence.match(/^this enters tapped unless (.+)$/)
if (entersTappedUnless) { if (entersTappedUnless) {
const unless = parseCondition(entersTappedUnless[1]) 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) const ability = compileLine(line, face.name, known, isSpell)
if (!(ability.kind === 'unsupported' && ability.reason === 'empty')) abilities.push(ability) 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 { export function compileCard(card: Card): CompiledCard {
@@ -2485,7 +2496,7 @@ export function compileCard(card: Card): CompiledCard {
const status: Status = statuses.includes('unsupported') const status: Status = statuses.includes('unsupported')
? statuses.every(value => value === 'unsupported') ? 'unsupported' : 'partial' ? statuses.every(value => value === 'unsupported') ? 'unsupported' : 'partial'
: statuses.includes('partial') ? 'partial' : 'supported' : 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( const face = compileFace(
@@ -2495,6 +2506,7 @@ export function compileCard(card: Card): CompiledCard {
return { return {
oracle_id: card.oracle_id, oracle_id: card.oracle_id,
name: card.name, name: card.name,
typeLine: card.type_line,
status: face.status, status: face.status,
abilities: face.abilities, 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 // Human-authored card implementations live in one JavaScript file per oracle
// id under data/card-overrides/. The file is pseudocode in the same syntax the // 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. // formatter prints, so it stays readable and can be re-compiled by the engine.
import { readFileSync, statSync } from 'node:fs' import { readFileSync, statSync } from 'node:fs'
@@ -9,8 +9,8 @@ import { allCards } from '../cards.js'
import type { Card } from '../cards.js' import type { Card } from '../cards.js'
import { compileCard, statusOf } from './compile.js' import { compileCard, statusOf } from './compile.js'
import { formatCard } from './format.js' import { formatCard } from './format.js'
import { parsePseudoCard, PseudoParseError } from './pseudo.js' import { parseCardSource, SourceParseError } from './source.js'
import type { CompiledCard, CompiledFace } from './types.js' import type { Ability, CompiledCard, CompiledFace } from './types.js'
export type ImplementationStatus = 'supported' | 'partial' | 'unsupported' export type ImplementationStatus = 'supported' | 'partial' | 'unsupported'
@@ -37,7 +37,7 @@ export function overridesDir(): string {
function overrideFile(oracleId: string): string { function overrideFile(oracleId: string): string {
if (!ORACLE_ID.test(oracleId)) throw new Error(`Invalid oracle id: ${oracleId}`) 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 { function isMissing(error: unknown): boolean {
@@ -67,7 +67,7 @@ export async function readAllOverrides(): Promise<Map<string, string>> {
} }
for (const name of names) { for (const name of names) {
const oracleId = name.replace(/\.pseudo\.txt$/, '') const oracleId = name.replace(/\.js$/, '')
if (name === oracleId || !ORACLE_ID.test(oracleId)) continue if (name === oracleId || !ORACLE_ID.test(oracleId)) continue
const override = await readOverride(oracleId) const override = await readOverride(oracleId)
if (override) result.set(oracleId, override.source) 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' 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 { export function compileImplementation(card: Card, source: string): CompiledCard {
const parsed = parsePseudoCard(source) const parsed = parseCardSource(source)
if (card.card_faces?.length) { if (card.card_faces?.length) {
if (!parsed.faces?.length) { if (!parsed.faces?.length) {
throw new PseudoParseError( throw new SourceParseError(
`this card has ${card.card_faces.length} faces; add "## <face name>" sections`, `this card has ${card.card_faces.length} faces; export faces(face(...), ...)`,
1, 1,
) )
} }
if (parsed.faces.length !== card.card_faces.length) { if (parsed.faces.length !== card.card_faces.length) {
throw new PseudoParseError( throw new SourceParseError(
`expected ${card.card_faces.length} faces, found ${parsed.faces.length}`, `expected ${card.card_faces.length} faces, found ${parsed.faces.length}`,
1, 1,
) )
} }
const generated = compileCard(card)
const faces: CompiledFace[] = card.card_faces.map((face, index) => { const faces: CompiledFace[] = card.card_faces.map((face, index) => {
const manualFace = parsed.faces![index] const manualFace = parsed.faces![index]
if (manualFace.name.toLowerCase() !== face.name.toLowerCase()) { 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 { return {
name: face.name, name: face.name,
typeLine: manualFace.typeLine ?? face.type_line,
status: statusOf(manualFace.abilities), status: statusOf(manualFace.abilities),
abilities: manualFace.abilities, abilities: manualFace.abilities,
} }
@@ -132,6 +146,7 @@ export function compileImplementation(card: Card, source: string): CompiledCard
return { return {
oracle_id: card.oracle_id, oracle_id: card.oracle_id,
name: card.name, name: card.name,
typeLine: card.type_line,
status: facesStatus(faces), status: facesStatus(faces),
abilities: [], abilities: [],
faces, faces,
@@ -140,12 +155,14 @@ export function compileImplementation(card: Card, source: string): CompiledCard
} }
if (parsed.faces?.length) { 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 { return {
oracle_id: card.oracle_id, oracle_id: card.oracle_id,
name: card.name, name: card.name,
typeLine: parsed.typeLine ?? card.type_line,
status: statusOf(parsed.abilities), status: statusOf(parsed.abilities),
abilities: parsed.abilities, abilities: parsed.abilities,
manual: true, 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. // Natural language -> card source through an OpenRouter-hosted model.
// The model is told to emit pseudocode only, and the answer is parsed before // The model is told to emit the JavaScript card DSL only, and the answer is
// it reaches the editor, so prose or a guess never becomes an implementation. // parsed before it reaches the editor, so prose or a guess never becomes an
// implementation.
import type { Card } from '../cards.js' import type { Card } from '../cards.js'
import { compileImplementation } from './implementations.js' import { compileImplementation } from './implementations.js'
export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite' export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite'
const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions' const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions'
const MAX_TOKENS = 700 const MAX_TOKENS = 1200
export class TranslationError extends Error { export class TranslationError extends Error {
readonly status: number 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. // 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 // Anything not listed here is rejected by the parser, so the model must not
// invent operations. // 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: export default card('Creature — Human Cleric', [
on <trigger>[ if <condition>][ (may)]: triggered(when.enters(self), [gainLife(you, 1)]),
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]: activated([tapCost()], [addMana(you, mana('{G}'))]),
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>)
Triggers: Multi-face cards export face sections in card order:
enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target),
enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target), export default faces(
deals_damage(target, player|creature|permanent|any), deals_combat_damage(...), face('Front', 'Instant', [ ...abilities ]),
upkeep(you|opponent|each_player), end_step(...), begin_combat(...), face('Back', 'Creature — Human', [ ...abilities ]),
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]), Abilities:
becomes_target(target), gain_life(you|opponent|each_player), lose_life(...) 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: Targets:
this, the triggering object, the chosen target, any target, target player, self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker
target opponent, each opponent, each player, target player or planeswalker, target(selector, { count, upTo, includeSelf }) one target
target spell, target ability, target <selector>, each <selector>, each(selector) every matching object
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>]) 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, Values: a number, X, itsPower, itsToughness, count(selector), cardsInHand(player),
equipped, enchanted. Then optional colors (white blue black red green colorless), maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector),
supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls", totalPower(selector), anyNumber(), eventAmount()
"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, count(<selector>), its power, its toughness, Costs:
cards in your hand, cards in that player's hand, total power of <selector>, manaCost('{2}{G}'), tapCost(), untapCost(), tapOther(selector), energyCost(N),
total mana value of <selector>, greatest number of <selector> an opponent controls, loyalty(N), payLife(value), discardCost(value, { player, random }), sacrificeCost(selector),
that much, any number. 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, Effects:
discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice <selector>, damage(target, amount, fromSource), damageDivided(amount, target)
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard, draw(player, amount), discard(player, amount, { random }), mill(player, amount)
reveal <selector> from your hand, return <selector> to its owner's hand, gainLife(player, amount), loseLife(player, amount)
behold <selector>, waterbend <value>, blight <value>, choose <text>, pump(target, power, toughness, duration), setPt(target, power, toughness, { duration })
put <counter> counter on <selector>, forage, collect evidence N, mill N card(s). grant(target, keyword, { value, duration }), putCounters(target, counter, amount)
A choice is written (cost or cost) or (cost + cost). removeCounters(target, counter, amount), proliferate()
createToken(player, amount, token({ types, subtypes, colors, power, toughness, keywords, tapped }))
Effects, one call per line: createToken(player, amount, copyOf(target, { notLegendary }))
damage(target, amount[, from source]) destroy(target), exile(target), sacrifice(player, target, unlessCost)
damage_divided(amount, target) counter('spell'|'ability', target, unlessCost), returnToHand(target)
draw(player, amount) returnToBattlefield(target, { tapped, transformed, counters: { counter, amount } })
discard(player, amount[, at random]) putOnTop(target), tap(target), untap(target), scry(player, amount), surveil(player, amount)
mill(player, amount) search(player, selector, amount, { destination, tapped, shuffle, zones, split })
gain_life(player, amount) shuffle(player), addMana(player, mana('{G}{G}') | anyColor(value, { oneColor, restriction }))
lose_life(player, amount) fight(a, b), regenerate(target), energy(player, amount), attach(target)
pump(target, power/toughness[, duration]) restrict(target, 'cant_attack'|'cant_block'|'doesnt_untap', duration)
set_pt(target, power/toughness[, duration]) keywordAction('action name', { target, amount, detail })
grant(target, Keyword[ value][, duration]) preventDamage(target, amount | 'all', { combatOnly, duration })
put_counters(target, counter, amount) gainControl(target, duration), emblem('text'), transform(target)
remove_counters(target, counter, amount) pay([costs]), ifThen(condition, [effects]), modal(min, max, [[effects], [effects]])
proliferate() lookTop(player, amount, { reorder }), schedule('next_upkeep'|'next_end_step', [effects])
create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword]) levelUp(N), putFromAmong(player, amount, { selector, destination }), dig(player, amount, { ... })
destroy(target), exile(target), tap(target), untap(target), regenerate(target) exileGraveyards(), hideaway(amount), playExiled(player, { free })
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>
Static effects: Static effects:
pump(target, power/toughness) staticPump(target, power, toughness), staticGrant(target, keyword, { value })
grant(target, Keyword[ value]) grantAbility(target, ability), staticRestrict(target, rule, { value, comparison, detail, condition })
restrict(target, rule[ detail][ if <condition>]) entersTapped(target, { unless }), entersWithCounters(target, counter, amount)
enters_tapped(target[, unless <condition>]) staticSetPt(target, power, toughness, { base }), control(target)
enters_with_counters(target, counter, amount) choose('creature_type'|'color'|'card_name'|'player'|'opponent'|'number')
grant_ability(target): replace(what, { target, instead }), costReduction(target, amount | '{R}{G}', { condition })
<one ability block> costIncrease(amount, { spellType }), searchRestriction('you'|'opponent', amount),
set_pt(target[, base], power/toughness|?) exileInsteadOfGraveyard('you'|'opponent')
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>])
Common conditions: you control <selector>, you control at least N <selector>, Conditions:
an opponent controls <selector>, it is your turn, it isn't your turn, youControl(selector, atLeast), opponentControls(selector, atLeast), yourTurn(),
this is tapped, this is untapped, this is attacking, <player> has at least N life, notYourTurn(), sourceTapped(), sourceUntapped(), sourceAttacking(),
<player> has at most N life, <player> has N+ cards in their graveyard, lifeAtLeast(player, N), lifeAtMost(player, N), lifeAboveStarting(player, N),
<player> has no cards in hand, a creature died this turn, cardsInGraveyard(player, N), handEmpty(player), creatureDiedThisTurn('you'|'opponent'),
you gained at least N life this turn, you drew N+ cards this turn, youGainedLifeThisTurn(N), youDrewCardsThisTurn(N), spellsCastLastTurn(who, N),
you cast it from your hand, this is in your graveyard, this is on the battlefield, noSpellsLastTurn(), attackedThisTurn(), youAttackedThisTurn(),
you're the monarch, you have the initiative, it was kicked, defendingPlayerControls(selector), targets(selector), wasKicked(), youCastIt({ fromHand }),
you've cast a spell this turn, you've cast a noncreature spell this turn, inGraveyard(), onBattlefield(), monarch(), initiative(), citysBlessing(), suspended(),
no creatures attacked this turn, you do, you don't, otherwise. 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, Durations: permanent (default), untilEndOfTurn, untilYourNextTurn,
until end of combat, until its controller's next untap step, untilEndOfYourNextTurn, untilEndOfCombat, untilControllersNextUntapStep,
for as long as this remains on the battlefield. whileSourceOnBattlefield.
Players: you, opponent, each_opponent, each_player, target_player, that_player, Players: you, opponent, eachOpponent, eachPlayer, targetPlayer, thatPlayer,
its_controller, its_owner. itsController, itsOwner.
Example: Example:
on enters(this):
gain_life(you, 1)
activate {T}: export default card('Creature — Human Cleric', [
add_mana(you, {G}) triggered(when.enters(self), [gainLife(you, 1)]),
activated([tapCost()], [addMana(you, mana('{G}'))]),
spell([draw(you, 2)]),
])`
spell: const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the JavaScript card source language below.
draw(you, 2)`
const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below.
Output rules: Output rules:
- Answer with pseudocode only. No explanation, no code fences, no card header, no comments. - Answer with card source only. No explanation, no code fences, no comments.
- Use only the syntax below. Never invent an operation or a keyword argument. - Start with card('Type line', [...]) using the exact type line given for the card.
- If an ability cannot be expressed, use: unsupported (<short reason>): <original oracle text> - Use only the names and shapes below. Never invent an operation or a keyword argument.
- For multi-face cards, output only the "## <face name>" sections in the given order. - 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 { function describeCard(card: Card): string {
if (card.card_faces?.length) { if (card.card_faces?.length) {
@@ -226,7 +231,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
headers: { headers: {
Authorization: `Bearer ${apiKey}`, Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Title': 'Commander card pseudocode translator', 'X-Title': 'Commander card source translator',
}, },
body: JSON.stringify({ body: JSON.stringify({
model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL, model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL,
@@ -261,7 +266,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}):
compileImplementation(card, source) compileImplementation(card, source)
} catch (error) { } catch (error) {
throw new TranslationError( 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' } | { kind: 'event_amount' }
export type ManaSpec = 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 } | { kind: 'any_color'; amount: Value; oneColor: boolean; restriction?: string }
export interface TokenSpec { export interface TokenSpec {
@@ -268,7 +268,7 @@ export type StaticEffect =
| { op: 'grant'; target: Target; keyword: string; value?: string } | { op: 'grant'; target: Target; keyword: string; value?: string }
| { op: 'grant_ability'; target: Target; ability: Ability } | { 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: '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: 'enters_with_counters'; target: Target; counter: string; amount: Value }
| { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean } | { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean }
| { op: 'control'; target: Target } | { op: 'control'; target: Target }
@@ -345,6 +345,8 @@ export type Ability =
export interface CompiledFace { export interface CompiledFace {
name: string name: string
/** Scryfall type line, or the type line declared in card source. */
typeLine?: string
status: 'supported' | 'partial' | 'unsupported' status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[] abilities: Ability[]
} }
@@ -352,6 +354,8 @@ export interface CompiledFace {
export interface CompiledCard { export interface CompiledCard {
oracle_id: string oracle_id: string
name: string name: string
/** Scryfall type line, or the type line declared in card source. */
typeLine?: string
status: 'supported' | 'partial' | 'unsupported' status: 'supported' | 'partial' | 'unsupported'
abilities: Ability[] abilities: Ability[]
faces?: CompiledFace[] faces?: CompiledFace[]

View File

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

View File

@@ -23,6 +23,7 @@ import type {
GameConfig, GameConfig,
ManaColor, ManaColor,
ManaPool, ManaPool,
MulliganState,
PendingChoice, PendingChoice,
PendingSearch, PendingSearch,
Phase, Phase,
@@ -195,8 +196,10 @@ export class Game {
phase: Phase = 'beginning' phase: Phase = 'beginning'
step: Step = 'untap' step: Step = 'untap'
priority = '' priority = ''
status: 'not_started' | 'active' | 'finished' = 'not_started' status: 'not_started' | 'mulligan' | 'active' | 'finished' = 'not_started'
winner?: string 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. */ /** Blocks all other actions until the searching player picks a card. */
pendingSearch?: PendingSearch pendingSearch?: PendingSearch
/** "As this enters, choose..." prompts, in entry order. */ /** "As this enters, choose..." prompts, in entry order. */
@@ -258,6 +261,9 @@ export class Game {
energy: 0, energy: 0,
poison: 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 playerConfig of config.players) {
for (const definition of playerConfig.deck) { for (const definition of playerConfig.deck) {
@@ -290,7 +296,10 @@ export class Game {
return object 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 { start(): void {
if (this.status !== 'not_started') throw new GameError('Game already started') if (this.status !== 'not_started') throw new GameError('Game already started')
for (const player of this.players) this.shuffleLibrary(player) 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. // Leyline-style "begin the game with it on the battlefield" cards.
for (const player of this.players) { for (const player of this.players) {
if (player.lost) continue
for (const id of [...player.hand]) { for (const id of [...player.hand]) {
const object = this.getObject(id) const object = this.getObject(id)
const beginsOnBattlefield = (object.definition.abilities ?? []).some(ability => const beginsOnBattlefield = (object.definition.abilities ?? []).some(ability =>
@@ -773,7 +843,7 @@ export class Game {
/** Marks a player as having forfeited. */ /** Marks a player as having forfeited. */
concede(playerId: string): void { 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) this.losePlayer(playerId)
if (this.priority === playerId) this.priority = this.nextAlivePlayer(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.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.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.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') if (this.priority !== playerId) throw new GameError('You do not have priority')
const seen = new Set<string>() const seen = new Set<string>()
@@ -843,7 +913,7 @@ export class Game {
pass(playerId?: string): void { pass(playerId?: string): void {
if (this.status !== 'active') throw new GameError('Game is not active') 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.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 const actual = playerId ?? this.priority
if (this.priority !== actual) throw new GameError('You do not have priority') if (this.priority !== actual) throw new GameError('You do not have priority')
const alive = this.alivePlayers().length const alive = this.alivePlayers().length
@@ -947,7 +1017,7 @@ export class Game {
chooseSearchCard(playerId: string, cardId: string): void { chooseSearchCard(playerId: string, cardId: string): void {
const pending = this.pendingSearch const pending = this.pendingSearch
if (!pending) throw new GameError('No search is waiting for a choice') 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') if (pending.playerId !== playerId) throw new GameError('You are not searching your library')
const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId) const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId)
if (!object) throw new GameError('That card is not a legal choice') 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 { chooseCreatureType(playerId: string, type: string): void {
const pending = this.pendingChoice 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') 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()) const chosen = CREATURE_TYPES.find(entry => entry.toLowerCase() === type.trim().toLowerCase())
if (!chosen) throw new GameError('Choose a creature type') 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}`) 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 * 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. * 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 const source = this.players
.flatMap(entry => entry.battlefield) .flatMap(entry => entry.battlefield)
.map(id => this.objects.get(id)) .map(id => this.objects.get(id))
.find((object): object is GameObject => Boolean(object && object.zone === 'battlefield' .map(object => {
&& object.controller === player.id if (!object || object.zone !== 'battlefield' || object.controller !== player.id || object.tapped) return undefined
&& !object.tapped const found = this.findFreeManaAbility(object)
&& this.findFreeManaAbility(object) !== undefined)) 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 if (!source) break
this.autoManaDepth++ this.autoManaDepth++
try { try {
@@ -1321,28 +1422,64 @@ export class Game {
const found = this.findFreeManaAbility(source) const found = this.findFreeManaAbility(source)
if (!found) return if (!found) return
const player = this.getPlayer(source.controller) 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) { for (const entry of found.ability.costs) {
if (entry.kind === 'tap') source.tapped = true if (entry.kind === 'tap') source.tapped = true
} }
const color = this.neededColor(player, cost)
for (const effect of found.ability.effects) { for (const effect of found.ability.effects) {
if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color) if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color)
} }
} }
private neededColor(player: PlayerState, cost: ManaCost): ManaColor { private manaAbilityColor(
for (const color of cost.colored) { source: GameObject,
if (player.manaPool[color] <= 0) return color ability: Extract<Ability, { kind: 'activated' }>,
} player: PlayerState,
const hybridColor = cost.hybrid.flatMap(entry => entry.colors).find(color => player.manaPool[color] <= 0) cost: ManaCost,
return hybridColor ?? 'W' ): 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) const player = this.getPlayer(playerId)
if (mana.kind === 'symbols') { 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)]++ for (const symbol of mana.symbols) player.manaPool[colorOfSymbol(symbol)]++
} else { return
}
const amount = this.value(mana.amount, { const amount = this.value(mana.amount, {
source: this.playerSource(playerId), source: this.playerSource(playerId),
controller: playerId, controller: playerId,
@@ -1350,8 +1487,63 @@ export class Game {
x: 0, x: 0,
mode: 0, mode: 0,
}) })
for (let i = 0; i < amount; i++) player.manaPool[preferred]++ 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 { private payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void {
@@ -1378,7 +1570,7 @@ export class Game {
case 'energy': case 'energy':
return player.energy >= cost.amount return player.energy >= cost.amount
case 'pay_life': 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': case 'discard':
return player.hand.length >= this.value(cost.amount, this.staticContext(source)) return player.hand.length >= this.value(cost.amount, this.staticContext(source))
case 'sacrifice': case 'sacrifice':
@@ -2497,9 +2689,19 @@ export class Game {
for (const effect of staticSource.ability.effects) { for (const effect of staticSource.ability.effects) {
if (effect.op === 'enters_tapped') { if (effect.op === 'enters_tapped') {
if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue
if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) { if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
object.tapped = true 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') { } else if (effect.op === 'enters_with_counters') {
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
const amount = this.value(effect.amount, this.staticContext(staticSource.source)) 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. * Affordability check that mirrors auto-tapping without changing the game.
* shortcut: any_color sources are counted as flexible even when they must * shortcut: only land-based any_color restrictions are modelled; mana
* produce one color, so rare "one color only" sources can be overestimated; * restricted by a commander identity or a spell type is still flexible.
* upgrade if a card ever needs an exact color split from such a source.
*/ */
private canAffordMana(playerId: string, symbols: string, x: number): boolean { private canAffordMana(playerId: string, symbols: string, x: number): boolean {
if (!symbols) return true if (!symbols) return true
@@ -2783,6 +2984,7 @@ export class Game {
const cost = parseManaCost(symbols, x) const cost = parseManaCost(symbols, x)
const pool = { ...player.manaPool } const pool = { ...player.manaPool }
let flexible = 0 let flexible = 0
const restricted: { colors: Set<ManaColor>; amount: number }[] = []
for (const object of this.battlefieldObjects()) { for (const object of this.battlefieldObjects()) {
if (object.controller !== playerId) continue if (object.controller !== playerId) continue
const found = this.findFreeManaAbility(object) const found = this.findFreeManaAbility(object)
@@ -2792,23 +2994,32 @@ export class Game {
if (effect.mana.kind === 'symbols') { if (effect.mana.kind === 'symbols') {
for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++ for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++
} else { } else {
flexible += this.value(effect.mana.amount, { const amount = this.value(effect.mana.amount, {
source: object, source: object,
controller: playerId, controller: playerId,
targets: [], targets: [],
x: 0, x: 0,
mode: 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 let life = player.life
restricted.sort((a, b) => a.colors.size - b.colors.size)
const take = (color: ManaColor): boolean => { const take = (color: ManaColor): boolean => {
if (pool[color] > 0) { if (pool[color] > 0) {
pool[color]-- pool[color]--
return true return true
} }
const source = restricted.find(entry => entry.amount > 0 && entry.colors.has(color))
if (source) {
source.amount--
return true
}
if (flexible > 0) { if (flexible > 0) {
flexible-- flexible--
return true return true
@@ -2824,7 +3035,9 @@ export class Game {
if (!(hybrid.life > 0 && life >= hybrid.life)) return false if (!(hybrid.life > 0 && life >= hybrid.life)) return false
life -= hybrid.life 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 return remaining >= cost.generic
} }
@@ -2923,6 +3136,21 @@ export class Game {
} }
changed = true 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 { private requirePriority(playerId: string): void {
if (this.status !== 'active') throw new GameError('Game is not active') 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.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') if (this.priority !== playerId) throw new GameError('You do not have priority')
} }

View File

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

View File

@@ -1,6 +1,6 @@
// The runtime game model. Card definitions are immutable input; objects are the // The runtime game model. Card definitions are immutable input; objects are the
// per-game instances that move between zones. // 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 ManaColor = 'W' | 'U' | 'B' | 'R' | 'G' | 'C'
export type ManaPool = Record<ManaColor, number> export type ManaPool = Record<ManaColor, number>
@@ -38,6 +38,17 @@ export interface GameConfig {
firstPlayer?: string firstPlayer?: string
/** Enables command-zone casting, commander tax, and commander damage. */ /** Enables command-zone casting, commander tax, and commander damage. */
commander?: boolean 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 { export interface PlayerState {
@@ -140,11 +151,15 @@ export interface PendingSearch {
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } 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 { export interface PendingChoice {
playerId: string playerId: string
sourceId: 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 { export interface CombatAttack {

View File

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

View File

@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import type { Card } from '../src/cards.js' import type { Card } from '../src/cards.js'
import { matchesCardFilters } from '../src/cards.js' import { matchesCardFilters } from '../src/cards.js'
import { cardDefinitionFromCard } from '../src/game/catalog.js'
function card(overrides: Partial<Card> = {}): Card { function card(overrides: Partial<Card> = {}): Card {
return { return {
@@ -51,3 +52,41 @@ test('card filters match format legality, color identity, type, rarity, and mana
assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false) assert.equal(matchesCardFilters(cardByIdentity, { cmcMin: 4 }), false)
assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false) assert.equal(matchesCardFilters(cardByIdentity, { cmcMax: 2 }), false)
}) })
test('compiled card types reach the engine definition', () => {
const definition = cardDefinitionFromCard(card(), {
oracle_id: 'test',
name: 'Test Card',
typeLine: 'Artifact Creature — Golem',
status: 'supported',
abilities: [],
})
assert.equal(definition.typeLine, 'Artifact Creature — Golem')
})
test('lands with basic land types get one intrinsic mana ability for their colors', () => {
const vents = cardDefinitionFromCard(card({
name: 'Steam Vents',
type_line: 'Land — Island Mountain',
colors: [],
color_identity: ['U', 'R'],
}))
assert.deepEqual(vents.abilities, [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{U}', '{R}'], oneOf: true },
}],
optional: false,
text: '{T}: Add {U} or {R}.',
}])
const forest = cardDefinitionFromCard(card({ name: 'Forest', type_line: 'Basic Land — Forest' }))
assert.deepEqual(forest.abilities?.[0]?.effects, [{
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{G}'] },
}])
})

View File

@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import { compileText } from '../src/effects/compile.js' import { compileText } from '../src/effects/compile.js'
import { formatAbility } from '../src/effects/format.js' import { formatAbility } from '../src/effects/format.js'
import { parsePseudoCard } from '../src/effects/pseudo.js' import { parseCardSource } from '../src/effects/source.js'
import type { Ability, Effect, Target } from '../src/effects/types.js' import type { Ability, Effect, Target } from '../src/effects/types.js'
function creature(text: string, keywords: string[] = []): Ability[] { function creature(text: string, keywords: string[] = []): Ability[] {
@@ -41,6 +41,33 @@ test('activated mana ability', () => {
}) })
}) })
test('"or" in a mana ability marks the symbols as a choice', () => {
const [ability] = creature('{T}: Add {G} or {U}.')
assert.equal(ability.kind, 'activated')
if (ability.kind !== 'activated') return
assert.deepEqual(ability.effects[0], {
op: 'add_mana',
player: 'you',
mana: { kind: 'symbols', symbols: ['{G}', '{U}'], oneOf: true },
})
})
test('paying life to enter untapped compiles to an enters-tapped replacement', () => {
const [ability] = compileText(
"As this land enters, you may pay 2 life. If you don't, it enters tapped.",
'Steam Vents',
[],
'Land — Island Mountain',
)
assert.equal(ability.kind, 'static')
if (ability.kind !== 'static') return
assert.deepEqual(ability.effects[0], {
op: 'enters_tapped',
target: { kind: 'self' },
unlessCost: { kind: 'pay_life', amount: { kind: 'number', value: 2 } },
})
})
test('search effect keeps destination, tapped, and shuffle', () => { test('search effect keeps destination, tapped, and shuffle', () => {
const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.') const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.')
assert.equal(ability.kind, 'spell') assert.equal(ability.kind, 'spell')
@@ -169,10 +196,10 @@ test('trigger condition cards in graveyard', () => {
assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 }) assert.deepEqual(ability.condition, { kind: 'cards_in_graveyard', player: 'you', atLeast: 7 })
}) })
test('formatter renders pseudocode', () => { test('formatter renders card source', () => {
const [ability] = creature('When this creature enters, draw a card.') const [ability] = creature('When this creature enters, draw a card.')
const text = formatAbility(ability) const text = formatAbility(ability)
assert.match(text, /on enters\(this\)/) assert.match(text, /triggered\(when\.enters\(self\)/)
assert.match(text, /draw\(you, 1\)/) assert.match(text, /draw\(you, 1\)/)
}) })
@@ -201,7 +228,10 @@ test('token copy of the triggering nontoken Dragon loses legendary', () => {
if (effect.op !== 'create_token') return if (effect.op !== 'create_token') return
assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' }) assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' })
assert.equal(effect.notLegendary, true) assert.equal(effect.notLegendary, true)
assert.equal(formatAbility(ability), 'on enters(each other nontoken dragon creature you control):\n create_token(you, 1, copy of the triggering object, not legendary)') assert.equal(
formatAbility(ability),
"triggered(when.enters(each(permanents.other().nontoken().withSubtype('dragon').withType('creature').youControl())), () => createToken(you, 1, copyOf(triggerSubject, { notLegendary: true })))",
)
}) })
test('all effects are typed', () => { test('all effects are typed', () => {
@@ -299,9 +329,9 @@ test('"until the end of your next turn" gets its own duration', () => {
if (effect.op !== 'pump') return if (effect.op !== 'pump') return
assert.equal(effect.duration, 'until_end_of_your_next_turn') assert.equal(effect.duration, 'until_end_of_your_next_turn')
const pseudo = formatAbility(ability) const source = formatAbility(ability)
assert.match(pseudo, /until the end of your next turn/) assert.match(source, /untilEndOfYourNextTurn/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
} }
}) })
@@ -315,7 +345,7 @@ test('parameterized keywords accept an em dash', () => {
assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' }) assert.deepEqual(fabricate, { kind: 'keyword', keyword: 'Fabricate', value: '1' })
}) })
test('counter-removal costs parse and round-trip through pseudocode', () => { test('counter-removal costs parse and round-trip through card source', () => {
const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.') const [self] = creature('{2}{U}, Remove a +1/+1 counter from this: Draw a card, then discard a card.')
assert.equal(self.kind, 'activated') assert.equal(self.kind, 'activated')
if (self.kind !== 'activated') return if (self.kind !== 'activated') return
@@ -324,9 +354,9 @@ test('counter-removal costs parse and round-trip through pseudocode', () => {
{ kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } }, { kind: 'remove_counters', counter: '+1/+1', amount: { kind: 'number', value: 1 } },
]) ])
const pseudo = formatAbility(self) const source = formatAbility(self)
assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/) assert.match(source, /removeCountersCost\('\+1\/\+1', 1\)/)
assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.') const [other] = creature('Remove three spore counters from a creature you control: Create a 1/1 green Saproling creature token.')
assert.equal(other.kind, 'activated') assert.equal(other.kind, 'activated')
@@ -520,7 +550,7 @@ test('spell cost reductions compile their conditions and mana symbols', () => {
}]) }])
}) })
test('new abilities, effects and conditions round-trip through pseudocode', () => { test('new abilities, effects and conditions round-trip through card source', () => {
const abilities: Ability[] = [ const abilities: Ability[] = [
...spell('If you control a commander, you may cast this without paying its mana cost.'), ...spell('If you control a commander, you may cast this without paying its mana cost.'),
...spell('Overload {6}{U}'), ...spell('Overload {6}{U}'),
@@ -541,9 +571,9 @@ test('new abilities, effects and conditions round-trip through pseudocode', () =
), ),
] ]
for (const ability of abilities) { for (const ability of abilities) {
const pseudo = formatAbility(ability) const source = formatAbility(ability)
const reparsed = parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0] const reparsed = parseCardSource(`export default [${source}]`).abilities[0]
assert.ok(reparsed) assert.ok(reparsed)
assert.equal(formatAbility(reparsed), pseudo) assert.equal(formatAbility(reparsed), source)
} }
}) })

View File

@@ -39,6 +39,30 @@ function land(name: string, color: string): CardDefinition {
}) })
} }
function exoticOrchard(): CardDefinition {
return card('Exotic Orchard', {
typeLine: 'Land',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{
op: 'add_mana',
player: 'you',
mana: {
kind: 'any_color',
amount: { kind: 'number', value: 1 },
oneColor: false,
restriction: 'a land an opponent controls could produce',
},
}],
optional: false,
text: '{T}: Add one mana of any color that a land an opponent controls could produce.',
}],
})
}
function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game { function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
const game = new Game({ const game = new Game({
seed: 7, seed: 7,
@@ -77,6 +101,51 @@ test('turns start at the first main phase, draw opening hands, and pass to the n
assert.equal(game.getPlayer('p1').hand.length, 7) assert.equal(game.getPlayer('p1').hand.length, 7)
}) })
test('mulligans draw a new seven and bottom one more card each time', () => {
const game = new Game({
seed: 3,
startingHandSize: 7,
mulligans: true,
players: [
{ id: 'p1', deck: Array.from({ length: 40 }, (_, index) => card(`P1 Card ${index}`)) },
{ id: 'p2', deck: Array.from({ length: 40 }, (_, index) => card(`P2 Card ${index}`)) },
],
})
game.start()
assert.equal(game.status, 'mulligan')
assert.equal(game.getPlayer('p1').hand.length, 7)
game.keepHand('p2')
game.mulligan('p1')
assert.equal(game.getPlayer('p1').hand.length, 7)
assert.equal(game.mulligans.get('p1')?.count, 1)
assert.equal(game.mulligans.get('p1')?.bottom, 0)
game.mulligan('p1')
assert.equal(game.mulligans.get('p1')?.count, 2)
assert.equal(game.mulligans.get('p1')?.bottom, 1)
assert.throws(() => game.keepHand('p1'), /bottom/)
const bottomCard = game.getPlayer('p1').hand[0]
game.putOnBottom('p1', bottomCard)
assert.equal(game.getPlayer('p1').hand.length, 6)
assert.equal(game.getPlayer('p1').library.at(-1), bottomCard)
assert.equal(game.mulligans.get('p1')?.bottom, 0)
game.mulligan('p1')
assert.equal(game.mulligans.get('p1')?.count, 3)
assert.equal(game.mulligans.get('p1')?.bottom, 2)
for (const cardId of [...game.getPlayer('p1').hand.slice(0, 2)]) game.putOnBottom('p1', cardId)
assert.equal(game.getPlayer('p1').hand.length, 5)
game.keepHand('p1')
assert.equal(game.status, 'active')
assert.equal(game.turn, 1)
assert.equal(game.step, 'main')
assert.equal(game.getPlayer('p1').hand.length, 5)
})
test('passing priority twice advances from the main phase into combat', () => { test('passing priority twice advances from the main phase into combat', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }]) const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start() game.start()
@@ -290,6 +359,73 @@ test('activated mana abilities produce mana and creatures have summoning sicknes
assert.equal(game.getPlayer('p1').manaPool.G, 1) assert.equal(game.getPlayer('p1').manaPool.G, 1)
}) })
test('Exotic Orchard is limited to colors an opponent land could produce', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
game.addCard('p2', land('Forest', 'G'), 'battlefield')
const green = game.addCard('p1', spell('Green Spell', [], '{G}'), 'hand')
const blue = game.addCard('p1', spell('Blue Spell', [], '{U}'), 'hand')
assert.equal(game.canPlayCard('p1', green.id), true)
assert.equal(game.canPlayCard('p1', blue.id), false)
assert.throws(() => game.castSpell('p1', blue.id), GameError)
assert.equal(orchard.tapped, false)
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
game.castSpell('p1', green.id)
assert.equal(orchard.tapped, true)
assert.equal(game.getPlayer('p1').manaPool.G, 0)
})
test('Exotic Orchard adds an opponent land color when activated manually', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
game.addCard('p2', land('Island', 'U'), 'battlefield')
game.activateAbility('p1', orchard.id, 0)
assert.equal(game.getPlayer('p1').manaPool.U, 1)
assert.equal(game.getPlayer('p1').manaPool.W, 0)
})
test('Exotic Orchard produces nothing without an opponent land', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
game.activateAbility('p1', orchard.id, 0)
assert.equal(orchard.tapped, true)
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
})
test('a restricted mana source is used before an unrestricted one', () => {
const rainbow = card('Rainbow Land', {
typeLine: 'Land',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: false } }],
optional: false,
text: '{T}: Add one mana of any color.',
}],
})
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const rainbowLand = game.addCard('p1', rainbow, 'battlefield')
const orchard = game.addCard('p1', exoticOrchard(), 'battlefield')
game.addCard('p2', land('Forest', 'G'), 'battlefield')
const gold = game.addCard('p1', spell('Gold Spell', [], '{G}{U}'), 'hand')
assert.equal(game.canPlayCard('p1', gold.id), true)
game.castSpell('p1', gold.id)
assert.equal(orchard.tapped, true)
assert.equal(rainbowLand.tapped, true)
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
})
test('static pump effects apply to matching creatures only', () => { test('static pump effects apply to matching creatures only', () => {
const anthem = card('Glorious Anthem', { const anthem = card('Glorious Anthem', {
typeLine: 'Enchantment', typeLine: 'Enchantment',
@@ -625,6 +761,63 @@ test('static replacement effects make permanents enter tapped with counters', ()
assert.equal(game.getToughness(bear), 3) assert.equal(game.getToughness(bear), 3)
}) })
function shockLand(): CardDefinition {
return card('Steam Vents', {
typeLine: 'Land — Island Mountain',
power: undefined,
toughness: undefined,
abilities: [{
kind: 'static',
effects: [{ op: 'enters_tapped', target: { kind: 'self' }, unlessCost: { kind: 'pay_life', amount: { kind: 'number', value: 2 } } }],
text: "As this land enters, you may pay 2 life. If you don't, it enters tapped.",
}, {
kind: 'activated',
costs: [{ kind: 'tap' }],
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{U}', '{R}'], oneOf: true } }],
optional: false,
text: '{T}: Add {U} or {R}.',
}],
})
}
test('a land can pay life to enter untapped or enter tapped', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const vents = game.addCard('p1', shockLand(), 'hand')
game.playLand('p1', vents.id)
assert.equal(vents.tapped, false)
assert.equal(game.pendingChoice?.what, 'pay_cost')
assert.equal(game.pendingChoice?.amount, 2)
assert.throws(() => game.chooseCostPayment('p2', true), GameError)
game.chooseCostPayment('p1', true)
assert.equal(game.getPlayer('p1').life, 38)
assert.equal(vents.tapped, false)
assert.equal(game.pendingChoice, undefined)
const second = game.addCard('p1', shockLand(), 'hand')
game.moveToZone(second, 'battlefield', { controller: 'p1', silent: false })
assert.equal(game.pendingChoice?.what, 'pay_cost')
game.chooseCostPayment('p1', false)
assert.equal(second.tapped, true)
assert.equal(game.getPlayer('p1').life, 38)
})
test('a choice mana ability adds only the color the spell needs', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const vents = game.addCard('p1', shockLand(), 'battlefield')
const red = game.addCard('p1', spell('Red Spell', [], '{R}'), 'hand')
game.castSpell('p1', red.id)
assert.equal(vents.tapped, true)
assert.equal(game.getPlayer('p1').manaPool.R, 0)
assert.equal(game.getPlayer('p1').manaPool.U, 0)
})
test('a player who runs out of cards loses and the last player wins', () => { test('a player who runs out of cards loses and the last player wins', () => {
const game = new Game({ const game = new Game({
seed: 3, seed: 3,
@@ -658,6 +851,43 @@ test('lethal damage to a player ends the game', () => {
assert.equal(game.getPlayer('p2').life, 0) assert.equal(game.getPlayer('p2').life, 0)
}) })
test('the legend rule leaves one legendary permanent per name under one controller', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const legend = card('Kiora, the Rising Tide', {
typeLine: 'Legendary Creature — Merfolk Wizard',
power: 1,
toughness: 1,
})
const first = game.addCard('p1', legend, 'battlefield')
const second = game.addCard('p1', legend, 'battlefield')
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
game.playLand('p1', forest.id)
assert.equal(first.zone, 'battlefield')
assert.equal(second.zone, 'graveyard')
assert.ok(game.getPlayer('p1').graveyard.includes(second.id))
})
test('the legend rule does not apply across controllers', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start()
const legend = card('Kiora, the Rising Tide', {
typeLine: 'Legendary Creature — Merfolk Wizard',
power: 1,
toughness: 1,
})
const mine = game.addCard('p1', legend, 'battlefield')
const theirs = game.addCard('p2', legend, 'battlefield')
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
game.playLand('p1', forest.id)
assert.equal(mine.zone, 'battlefield')
assert.equal(theirs.zone, 'battlefield')
})
test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => { test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => {
const game = setup([{ id: 'p1' }, { id: 'p2' }]) const game = setup([{ id: 'p1' }, { id: 'p2' }])
game.start() game.start()

View File

@@ -1,92 +0,0 @@
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { formatCard } from '../src/effects/format.js'
import {
compileImplementation,
deleteOverride,
readAllOverrides,
readOverride,
writeOverride,
} from '../src/effects/implementations.js'
import { parsePseudoCard, PseudoParseError } from '../src/effects/pseudo.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000001',
name: 'Test Card',
layout: 'normal',
cmc: 1,
type_line: 'Creature — Human',
colors: [],
color_identity: [],
keywords: [],
}
const SOURCE = `on enters(this):
choose 1:
1. exile(target other creature you own); schedule(next_end_step):
return_to_battlefield(the chosen target)
static:
grant_ability(each enchanted land):
on upkeep(you) (may):
pay({W}{W})
if you do:
gain_life(you, 1)`
test('pseudocode round-trips through the compiler and formatter', () => {
const compiled = compileImplementation(CARD, SOURCE)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
const rendered = formatCard(compiled)
const reparsed = compileImplementation(CARD, rendered)
assert.equal(formatCard(reparsed), rendered)
assert.equal(reparsed.abilities.length, 2)
const [triggered] = reparsed.abilities
assert.equal(triggered.kind, 'triggered')
if (triggered.kind !== 'triggered') return
assert.equal(triggered.effects[0].op, 'modal')
if (triggered.effects[0].op !== 'modal') return
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
const staticAbility = reparsed.abilities[1]
assert.equal(staticAbility.kind, 'static')
if (staticAbility.kind !== 'static') return
assert.equal(staticAbility.effects[0].op, 'grant_ability')
if (staticAbility.effects[0].op !== 'grant_ability') return
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
})
test('invalid pseudocode reports its line', () => {
assert.throws(
() => parsePseudoCard('spell:\n draw(you)'),
(error: unknown) => error instanceof PseudoParseError && error.line === 2,
)
})
test('manual implementations persist one file per card', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
const previous = process.env.CARD_OVERRIDES_DIR
process.env.CARD_OVERRIDES_DIR = dir
t.after(async () => {
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
else process.env.CARD_OVERRIDES_DIR = previous
await rm(dir, { recursive: true, force: true })
})
await writeOverride(CARD.oracle_id, SOURCE)
const stored = await readOverride(CARD.oracle_id)
assert.equal(stored?.source, `${SOURCE}\n`)
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
const compiled = compileImplementation(CARD, stored!.source)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
await deleteOverride(CARD.oracle_id)
assert.equal(await readOverride(CARD.oracle_id), undefined)
})

View File

@@ -1,7 +1,7 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import { findCardByName } from '../src/cards.js' import { findCardByName } from '../src/cards.js'
import { createMatch, getMatchView, joinMatch, leaveMatch, setDeck, startMatch } from '../src/game/rooms.js' import { createMatch, getMatchView, joinMatch, leaveMatch, performAction, setDeck, startMatch } from '../src/game/rooms.js'
function deck(commanderName: string) { function deck(commanderName: string) {
const commander = findCardByName(commanderName) const commander = findCardByName(commanderName)
@@ -36,3 +36,20 @@ test('leaving a started game forfeits the seat instead of erroring', () => {
assert.equal(view.status, 'finished') assert.equal(view.status, 'finished')
assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true) assert.equal(view.players.find(player => player.id === host.playerId)?.lost, true)
}) })
test('started matches wait for both players to keep their opening hands', () => {
const host = createMatch('Host', deck("Atraxa, Praetors' Voice"), 2)
const guest = joinMatch(host.matchId, 'Guest', deck('Kenrith, the Returned King'))
startMatch(host.matchId, host.token)
let view = getMatchView(host.matchId, host.token)
assert.equal(view.status, 'active')
assert.equal(view.game?.status, 'mulligan')
assert.equal(view.game?.mulligans?.length, 2)
performAction(host.matchId, host.token, { type: 'keep_hand' })
performAction(host.matchId, guest.token, { type: 'keep_hand' })
view = getMatchView(host.matchId, host.token)
assert.equal(view.game?.status, 'active')
})

194
backend/test/source.test.ts Normal file
View File

@@ -0,0 +1,194 @@
import assert from 'node:assert/strict'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import type { Card } from '../src/cards.js'
import { formatCard } from '../src/effects/format.js'
import {
compileImplementation,
deleteOverride,
readAllOverrides,
readOverride,
writeOverride,
} from '../src/effects/implementations.js'
import { parseCardSource, SourceParseError } from '../src/effects/source.js'
const CARD: Card = {
oracle_id: '00000000-0000-4000-8000-000000000001',
name: 'Test Card',
layout: 'normal',
cmc: 1,
type_line: 'Creature — Human',
colors: [],
color_identity: [],
keywords: [],
}
const SOURCE = `export default [
triggered(when.enters(self), [
modal(1, 1, [
[
exile(target(permanents.withType('creature').other().ownedBy('you'))),
schedule('next_end_step', [returnToBattlefield(previousTarget)]),
],
]),
]),
staticAbility([
grantAbility(each(permanents.withType('land').enchanted()), triggered(when.upkeep(you), [
pay([manaCost('{W}{W}')]),
ifThen(ifYouDo(), [gainLife(you, 1)]),
], { optional: true })),
]),
]`
test('card source round-trips through the compiler and formatter', () => {
const compiled = compileImplementation(CARD, SOURCE)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
assert.equal(compiled.typeLine, CARD.type_line)
const rendered = formatCard(compiled)
assert.match(rendered, /export default card\('Creature — Human', \[/)
const reparsed = compileImplementation(CARD, rendered)
assert.equal(formatCard(reparsed), rendered)
assert.equal(reparsed.typeLine, CARD.type_line)
assert.equal(reparsed.abilities.length, 2)
const [triggered] = reparsed.abilities
assert.equal(triggered.kind, 'triggered')
if (triggered.kind !== 'triggered') return
assert.equal(triggered.effects[0].op, 'modal')
if (triggered.effects[0].op !== 'modal') return
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
const staticAbility = reparsed.abilities[1]
assert.equal(staticAbility.kind, 'static')
if (staticAbility.kind !== 'static') return
assert.equal(staticAbility.effects[0].op, 'grant_ability')
if (staticAbility.effects[0].op !== 'grant_ability') return
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
})
test('card source declares the card type line for the engine', () => {
const compiled = compileImplementation(CARD, `export default card('Artifact Creature — Golem', [keyword('Vigilance')])`)
assert.equal(compiled.typeLine, 'Artifact Creature — Golem')
assert.match(formatCard(compiled), /export default card\('Artifact Creature — Golem', \[/)
})
test('multi-face card source declares one type line per face', () => {
const faces: Card = {
...CARD,
layout: 'transform',
card_faces: [
{ name: 'Front', type_line: 'Sorcery', colors: [] },
{ name: 'Back', type_line: 'Creature — Human', colors: [] },
],
}
const source = `export default faces(
face('Front', 'Instant', [spell([draw(you, 2)])]),
face('Back', 'Creature — Human', [keyword('Flying')]),
)`
const compiled = compileImplementation(faces, source)
assert.deepEqual(compiled.faces?.map(face => face.typeLine), ['Instant', 'Creature — Human'])
const rendered = formatCard(compiled)
assert.equal(formatCard(compileImplementation(faces, rendered)), rendered)
})
test('effect lists accept callbacks in place of arrays', () => {
const CALLBACK_SOURCE = `export default [
triggered(when.enters(self), () => draw(you, 1)),
triggered(when.dies(self), () => {
draw(you, 1)
gainLife(you, 1);
}),
staticAbility(() => staticPump(each(creatures.youControl()), 1, 1)),
spell([
modal(1, 1, [
() => draw(you, 2),
() => { gainLife(you, 3) },
]),
]),
]`
const compiled = compileImplementation(CARD, CALLBACK_SOURCE)
assert.equal(compiled.status, 'supported')
const [enters, dies, staticAbility, spell] = compiled.abilities
assert.equal(enters.kind, 'triggered')
if (enters.kind !== 'triggered') return
assert.deepEqual(enters.effects.map(effect => effect.op), ['draw'])
assert.equal(dies.kind, 'triggered')
if (dies.kind !== 'triggered') return
assert.deepEqual(dies.effects.map(effect => effect.op), ['draw', 'life'])
assert.equal(staticAbility.kind, 'static')
if (staticAbility.kind !== 'static') return
assert.deepEqual(staticAbility.effects.map(effect => effect.op), ['pump'])
assert.equal(spell.kind, 'spell')
if (spell.kind !== 'spell') return
assert.equal(spell.effects[0].op, 'modal')
if (spell.effects[0].op !== 'modal') return
assert.deepEqual(spell.effects[0].modes.map(mode => mode.map(effect => effect.op)), [['draw'], ['life']])
})
test('invalid source reports its line', () => {
assert.throws(
() => parseCardSource('export default [\n draw(you)\n]'),
(error: unknown) => error instanceof SourceParseError && error.line === 2,
)
})
test('unknown AST discriminants are rejected', () => {
assert.throws(
() => parseCardSource("export default [spell([{ op: 'nope' }])]"),
(error: unknown) => error instanceof SourceParseError && /expected an effect/.test(error.message),
)
assert.throws(
() => parseCardSource("export default [{ kind: 'nope' }]"),
(error: unknown) => error instanceof SourceParseError && /expected an ability/.test(error.message),
)
assert.throws(
() => parseCardSource("export default [triggered(when.nope(self), [])]"),
(error: unknown) => error instanceof SourceParseError,
)
})
test('manual implementations persist one file per card', async (t) => {
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
const previous = process.env.CARD_OVERRIDES_DIR
process.env.CARD_OVERRIDES_DIR = dir
t.after(async () => {
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
else process.env.CARD_OVERRIDES_DIR = previous
await rm(dir, { recursive: true, force: true })
})
await writeOverride(CARD.oracle_id, SOURCE)
const stored = await readOverride(CARD.oracle_id)
assert.equal(stored?.source, `${SOURCE}\n`)
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
const compiled = compileImplementation(CARD, stored!.source)
assert.equal(compiled.manual, true)
assert.equal(compiled.status, 'supported')
await deleteOverride(CARD.oracle_id)
assert.equal(await readOverride(CARD.oracle_id), undefined)
})
test('entersTapped accepts an unlessCost builder and round-trips', () => {
const source = `export default [
staticAbility([entersTapped(self, { unlessCost: payLife(2) })]),
]`
const compiled = compileImplementation(CARD, source)
assert.equal(compiled.status, 'supported')
const rendered = formatCard(compiled)
assert.match(rendered, /entersTapped\(self, \{ unlessCost: payLife\(2\) \}\)/)
const reparsed = compileImplementation(CARD, rendered)
assert.deepEqual(reparsed.abilities, compiled.abilities)
})

View File

@@ -46,40 +46,40 @@ function fakeOpenRouter(content: string) {
} }
} }
test('translation asks for pseudocode only and validates the answer', async () => { test('translation asks for card source only and validates the answer', async () => {
const fake = fakeOpenRouter('spell:\n draw(you, 2)') const fake = fakeOpenRouter('export default [spell([draw(you, 2)])]')
const source = await translateCard(CARD, { const source = await translateCard(CARD, {
apiKey: 'test-key', apiKey: 'test-key',
model: 'test/model', model: 'test/model',
fetch: fake.fetchImpl, fetch: fake.fetchImpl,
}) })
assert.equal(source, 'spell:\n draw(you, 2)') assert.equal(source, 'export default [spell([draw(you, 2)])]')
assert.equal(fake.body.model, 'test/model') assert.equal(fake.body.model, 'test/model')
assert.equal(fake.body.temperature, 0) assert.equal(fake.body.temperature, 0)
assert.equal(fake.body.max_tokens, 700) assert.equal(fake.body.max_tokens, 1200)
assert.equal(fake.headers.Authorization, 'Bearer test-key') assert.equal(fake.headers.Authorization, 'Bearer test-key')
assert.match(fake.body.messages[0].content, /pseudocode only/i) assert.match(fake.body.messages[0].content, /card source only/i)
assert.match(fake.body.messages[0].content, /Never invent an operation/) assert.match(fake.body.messages[0].content, /Never invent an operation/)
assert.match(fake.body.messages[1].content, /Draw two cards\./) assert.match(fake.body.messages[1].content, /Draw two cards\./)
}) })
test('a model code fence is removed before saving', async () => { test('a model code fence is removed before saving', async () => {
const fake = fakeOpenRouter('```\nspell:\n draw(you, 2)\n```') const fake = fakeOpenRouter('```\nexport default [spell([draw(you, 2)])]\n```')
const source = await translateCard(CARD, { const source = await translateCard(CARD, {
apiKey: 'test-key', apiKey: 'test-key',
model: 'test/model', model: 'test/model',
fetch: fake.fetchImpl, fetch: fake.fetchImpl,
}) })
assert.equal(source, 'spell:\n draw(you, 2)') assert.equal(source, 'export default [spell([draw(you, 2)])]')
assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)') assert.equal(cleanTranslation(' export default [spell([draw(you, 2)])] '), 'export default [spell([draw(you, 2)])]')
}) })
test('prose instead of pseudocode is rejected', async () => { test('prose instead of card source is rejected', async () => {
const fake = fakeOpenRouter('Here is the translated card. It draws two cards.') const fake = fakeOpenRouter('Here is the translated card. It draws two cards.')
await assert.rejects( await assert.rejects(
translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }), translateCard(CARD, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl }),
(error: unknown) => error instanceof TranslationError && /valid pseudocode/.test(error.message), (error: unknown) => error instanceof TranslationError && /valid card source/.test(error.message),
) )
}) })
@@ -105,13 +105,13 @@ test('multi-face cards receive their face names in the prompt', async () => {
{ name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] }, { name: 'Back', type_line: 'Creature', oracle_text: 'Flying', colors: [] },
], ],
} }
const fake = fakeOpenRouter('## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying') const fake = fakeOpenRouter("export default faces(face('Front', [triggered(when.enters(self), [draw(you, 1)])]), face('Back', [keyword('Flying')]))")
const source = await translateCard(faces, { const source = await translateCard(faces, {
apiKey: 'test-key', apiKey: 'test-key',
model: 'test/model', model: 'test/model',
fetch: fake.fetchImpl, fetch: fake.fetchImpl,
}) })
assert.equal(source, '## Front\non enters(this):\n draw(you, 1)\n\n## Back\nkeyword Flying') assert.equal(source, "export default faces(face('Front', [triggered(when.enters(self), [draw(you, 1)])]), face('Back', [keyword('Flying')]))")
assert.match(fake.body.messages[1].content, /## Front/) assert.match(fake.body.messages[1].content, /## Front/)
assert.match(fake.body.messages[1].content, /## Back/) assert.match(fake.body.messages[1].content, /## Back/)
}) })

View File

@@ -298,11 +298,14 @@ button.danger {
} }
.badge { .badge {
font-size: 0.7rem; flex: none;
font-size: 0.62rem;
line-height: 1.2;
text-transform: uppercase; text-transform: uppercase;
letter-spacing: 0.03em; letter-spacing: 0.02em;
white-space: nowrap;
border-radius: 99px; border-radius: 99px;
padding: 0.1rem 0.45rem; padding: 0.04rem 0.35rem;
border: 1px solid currentColor; border: 1px solid currentColor;
color: var(--muted); color: var(--muted);
} }
@@ -319,7 +322,7 @@ button.danger {
color: var(--bad); color: var(--bad);
} }
.badge.manual { .badge.verified {
color: var(--accent); color: var(--accent);
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,212 +0,0 @@
<template>
<section class="pseudo-guide">
<header class="guide-head">
<h2>Card pseudocode guide</h2>
<p class="muted">
The editor and the compiler use the same two-way format. The
<strong>Visual</strong> tab is a node canvas: drag sockets to connect an ability to its
effects, and drag green value nodes (players, targets, selectors, costs) into argument
sockets. Selector <strong>OR</strong>/<strong>AND</strong> nodes can combine two selector
slots. It writes the same source as the text editor. Use <strong>Draft with AI</strong> for
a first pass, then review and save.
</p>
</header>
<article>
<h3>Shape</h3>
<p>
One ability per block. The header starts at column 0 and ends with a colon; effects are
indented two spaces, one call per line. A leading <code># Card [status]</code> line is
optional and ignored. Multi-face cards use <code>## Face Name [status]</code> sections in
card order. Use <code>(no abilities)</code> for an empty face.
</p>
<pre># Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
# Llanowar Elves [supported]
activate {T}:
add_mana(you, {G})</pre>
</article>
<article>
<h3>Ability blocks</h3>
<table>
<thead>
<tr><th>Header</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>on &lt;trigger&gt;:</code></td><td><code>on dies(this):</code></td></tr>
<tr><td><code>activate &lt;cost&gt;:</code></td><td><code>activate {2}, {T}:</code></td></tr>
<tr><td><code>static:</code></td><td><code>static:</code></td></tr>
<tr><td><code>spell:</code></td><td>An instant or sorcery effect line.</td></tr>
<tr><td><code>keyword &lt;name&gt;</code></td><td><code>keyword Flying</code></td></tr>
<tr><td><code>keywords &lt;a&gt;, &lt;b&gt;</code></td><td><code>keywords Flying, vigilance</code></td></tr>
<tr><td><code>additional cost: &lt;cost&gt;</code></td><td><code>additional cost: pay 2 life</code></td></tr>
<tr><td><code>if &lt;condition&gt;:</code></td><td>Nested effects, indented below.</td></tr>
<tr><td><code>choose &lt;n&gt;:</code></td><td>Numbered modes <code>1.</code>, <code>2.</code></td></tr>
<tr><td><code>schedule(next_upkeep):</code></td><td>Delayed effects.</td></tr>
</tbody>
</table>
</article>
<article>
<h3>Effect calls</h3>
<p>Effects are lowercase calls. Separate several on one line with <code>;</code>.</p>
<pre>damage(target creature, 3)
draw(you, 2)
gain_life(you, 1)
create_token(you, 1, 1/1 red goblin creature)
put_counters(target creature, +1/+1, 2)
destroy(target creature)
exile(target artifact you control)
add_mana(you, {G}{G})
search(you, creature, 1, to hand, shuffle)
scry(you, 2)
pump(each creature you control, 1/1, until end of turn)</pre>
</article>
<article>
<h3>Targets, values and costs</h3>
<table>
<tbody>
<tr>
<th>Targets</th>
<td><code>this</code>, <code>the triggering object</code>, <code>target creature</code>, <code>each opponent</code>, <code>up to 2 target creatures</code>, <code>any target</code></td>
</tr>
<tr>
<th>Selectors</th>
<td><code>other tapped creature you control</code>, <code>red instant from a graveyard</code>, <code>creature with power 4 or greater</code></td>
</tr>
<tr>
<th>Values</th>
<td><code>2</code>, <code>X</code>, <code>count(creature you control)</code>, <code>its power</code>, <code>that much</code></td>
</tr>
<tr>
<th>Costs</th>
<td><code>{2}{U}</code>, <code>{T}</code>, <code>pay 3 life</code>, <code>discard 1 card(s)</code>, <code>sacrifice this</code>, <code>remove 1 +1/+1 counter(s) from this</code></td>
</tr>
<tr>
<th>Durations</th>
<td><code>until end of turn</code>, <code>until your next turn</code>, <code>until the end of your next turn</code>, <code>for as long as this remains on the battlefield</code></td>
</tr>
</tbody>
</table>
</article>
<article>
<h3>Triggers, conditions and modes</h3>
<pre>on attacks(this):
create_token(you, 1, tapped 1/1 red goblin creature)
on upkeep(you):
if you control at least 3 artifacts:
draw(you, 1)
spell:
choose 1:
1. draw(you, 2)
2. gain_life(you, 3)
static:
grant(each creature you control, Flying)</pre>
<p class="muted">
Common triggers: <code>enters</code>, <code>dies</code>, <code>attacks</code>,
<code>upkeep</code>, <code>end_step</code>, <code>cast</code>,
<code>deals_damage</code>. Always check the generated line after saving.
</p>
</article>
<article>
<h3>When the syntax cannot express it</h3>
<p>
Never guess a wrong effect. Use the preserved form and leave the line unsupported:
</p>
<pre>unsupported (modal bullet outside a choose block): Choose one — ...</pre>
<p class="muted">
The full reference lives in <code>backend/docs/card-effects.md</code>.
</p>
</article>
</section>
</template>
<style scoped>
.pseudo-guide {
flex: 1;
min-height: 0;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.guide-head {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
h3 {
margin-bottom: 0.4rem;
}
p {
line-height: 1.5;
font-size: 0.9rem;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85em;
background: #11151d;
border: 1px solid var(--line);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
pre {
margin: 0.5rem 0 0;
padding: 0.65rem 0.8rem;
background: #11151d;
border: 1px solid var(--line);
border-radius: 6px;
overflow-x: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.82rem;
line-height: 1.5;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.85rem;
}
th,
td {
border-bottom: 1px solid var(--line);
padding: 0.35rem 0.5rem;
text-align: left;
vertical-align: top;
}
th {
white-space: nowrap;
color: var(--muted);
font-weight: 600;
}
tbody th {
width: 7rem;
}
@media (max-width: 800px) {
tbody th {
width: auto;
}
}
</style>

View File

@@ -0,0 +1,227 @@
<template>
<section class="source-guide">
<header class="guide-head">
<h2>Card source guide</h2>
<p class="muted">
Implementations are a small, literal JavaScript expression that the backend evaluates with
its own safe interpreter. It is never run as JavaScript: only the names below exist. The
editor and the compiler use the same two-way format. Use <strong>Draft with AI</strong> for
a first pass, then review and save.
</p>
</header>
<article>
<h3>Shape</h3>
<p>
Export the card's type line and an array of abilities with
<code>card(typeLine, [...])</code>. A leading <code>// Card [status]</code> comment is
optional and ignored. Multi-face cards export
<code>faces(face('Name', 'Type line', [...]), ...)</code> in card order.
</p>
<pre>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}')),
]),
])
export default faces(
face('Front', 'Instant', [spell([draw(you, 2)])]),
face('Back', 'Creature — Human', [keyword('Flying')]),
)</pre>
<p class="muted">
Plain <code>export default [...]</code> is still accepted and uses the Scryfall type line.
Effect lists also accept callbacks: <code>() =&gt; draw(you, 1)</code> for one effect,
or <code>() =&gt; { draw(you, 1); gainLife(you, 1) }</code> for several. Arrays remain
valid; the formatter emits callbacks.
</p>
</article>
<article>
<h3>Abilities</h3>
<table>
<thead>
<tr><th>Call</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>triggered(event, [effects], options)</code></td><td><code>triggered(when.dies(self), [draw(you, 1)])</code></td></tr>
<tr><td><code>activated([costs], [effects], options)</code></td><td><code>activated([manaCost('{2}'), tapCost()], [...])</code></td></tr>
<tr><td><code>staticAbility([effects], options)</code></td><td><code>staticAbility([staticPump(each(creatures.youControl()), 1, 1)])</code></td></tr>
<tr><td><code>spell([effects], options)</code></td><td>An instant or sorcery.</td></tr>
<tr><td><code>keyword(name, value)</code></td><td><code>keyword('Ward', '{2}')</code></td></tr>
<tr><td><code>keywords(...names)</code></td><td><code>keywords('Flying', 'Trample')</code></td></tr>
<tr><td><code>additionalCost([costs])</code></td><td><code>additionalCost([payLife(2)])</code></td></tr>
<tr><td><code>chapter(['I', 'II'], [effects])</code></td><td>Saga chapters.</td></tr>
<tr><td><code>unsupported(reason, text)</code></td><td>Preserve the oracle text when it cannot be expressed.</td></tr>
</tbody>
</table>
<p class="muted">
Options include <code>{ condition, optional }</code>; activated abilities also accept
<code>timing: 'sorcery'</code> and <code>activationsPerTurn</code>.
</p>
</article>
<article>
<h3>Selectors and targets</h3>
<p>
Start from <code>permanents</code>, <code>cards</code> or <code>creatures</code> and chain
filters: <code>withType</code>, <code>withSubtype</code>, <code>withSupertype</code>,
<code>withColor</code>, <code>withKeyword</code>, <code>youControl</code>,
<code>other</code>, <code>tapped</code>, <code>token</code>, <code>powerAtLeast</code>,
<code>manaValueAtMost</code>, <code>named</code>, <code>inZone</code>.
</p>
<pre>target(permanents.withType('creature').other().youControl())
each(creatures.withColor('red').withKeyword('flying'))
pick(cards.withType('land'), { upTo: 2 })
targetSpell(permanents.withType('instant'))
divided(3, creatures.attacking())
self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker</pre>
<p class="muted">
Values: numbers, <code>X</code>, <code>itsPower</code>, <code>itsToughness</code>,
<code>count(selector)</code>, <code>cardsInHand(you)</code>,
<code>totalPower(selector)</code>, <code>eventAmount()</code>.
</p>
</article>
<article>
<h3>Effects and costs</h3>
<pre>damage(target(creature), 3)
draw(you, 2)
gainLife(you, 1)
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 }))
putCounters(target(creature), '+1/+1', 2)
destroy(target(creature))
addMana(you, mana('{G}{G}'))
search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true })
pump(each(creatures.youControl()), 1, 1, untilEndOfTurn)
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)])
modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]])</pre>
<p>
Costs are separate: <code>manaCost('{2}{U}')</code>, <code>tapCost()</code>,
<code>sacrificeSelf()</code>, <code>payLife(3)</code>,
<code>discardCost(1)</code>, <code>removeCountersCost('+1/+1', 1)</code>.
</p>
<p class="muted">
Durations: <code>permanent</code>, <code>untilEndOfTurn</code>,
<code>untilYourNextTurn</code>, <code>untilEndOfYourNextTurn</code>,
<code>untilEndOfCombat</code>, <code>whileSourceOnBattlefield</code>.
</p>
</article>
<article>
<h3>Triggers, statics and conditions</h3>
<pre>triggered(when.attacks(self), [
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1, tapped: true })),
])
triggered(when.upkeep(you), [
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]),
])
staticAbility([
staticGrant(each(creatures.youControl()), 'Flying'),
])</pre>
<p class="muted">
Common triggers: <code>when.enters</code>, <code>when.dies</code>,
<code>when.attacks</code>, <code>when.upkeep</code>, <code>when.endStep</code>,
<code>when.cast</code>, <code>when.dealsDamage</code>. Common conditions:
<code>yourTurn()</code>, <code>youControl(selector, n)</code>, <code>wasKicked()</code>,
<code>ifYouDo()</code>, <code>otherwise()</code>. Always check the compiled result after
saving.
</p>
</article>
<article>
<h3>When the syntax cannot express it</h3>
<p>Never guess a wrong effect. Preserve the oracle text and leave it unsupported:</p>
<pre>unsupported('modal bullet outside a modal block', 'Choose one — ...')</pre>
<p class="muted">
The full reference lives in <code>backend/docs/card-effects.md</code>.
</p>
</article>
</section>
</template>
<style scoped>
.source-guide {
flex: 1;
min-height: 0;
overflow-y: auto;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.guide-head {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
h3 {
margin-bottom: 0.4rem;
}
p {
line-height: 1.5;
font-size: 0.9rem;
}
code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.85em;
background: #11151d;
border: 1px solid var(--line);
border-radius: 4px;
padding: 0.05rem 0.3rem;
}
pre {
margin: 0.5rem 0 0;
padding: 0.65rem 0.8rem;
background: #11151d;
border: 1px solid var(--line);
border-radius: 6px;
overflow-x: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.82rem;
line-height: 1.5;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.85rem;
}
th,
td {
border-bottom: 1px solid var(--line);
padding: 0.35rem 0.5rem;
text-align: left;
vertical-align: top;
}
th {
white-space: nowrap;
color: var(--muted);
font-weight: 600;
}
tbody th {
width: 7rem;
}
@media (max-width: 800px) {
tbody th {
width: auto;
}
}
</style>

View File

@@ -1,9 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import CardGraphEditor from '../components/CardGraphEditor.vue' import SourceGuide from '../components/SourceGuide.vue'
import PseudoGuide from '../components/PseudoGuide.vue'
type Status = 'supported' | 'partial' | 'unsupported' type Status = 'supported' | 'partial' | 'unsupported'
const statusLabels: Record<Status, string> = {
supported: 'Supported',
partial: 'Partial',
unsupported: 'Unsupported',
}
interface CardSummary { interface CardSummary {
oracle_id: string oracle_id: string
name: string name: string
@@ -87,7 +92,6 @@ const rarityOptions = ['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus
const cmcOptions = ['0', '1', '2', '3', '4', '5', '6', '7+'] const cmcOptions = ['0', '1', '2', '3', '4', '5', '6', '7+']
const view = ref<'editor' | 'guide'>('editor') const view = ref<'editor' | 'guide'>('editor')
const editorMode = ref<'text' | 'visual'>('text')
const search = ref('') const search = ref('')
const statusFilter = ref('needs-work') const statusFilter = ref('needs-work')
const formatFilter = ref('') const formatFilter = ref('')
@@ -217,7 +221,7 @@ async function translate() {
async function reset() { async function reset() {
if (!detail.value || saving.value) return if (!detail.value || saving.value) return
if (!window.confirm('Delete the manual implementation and restore the generated one?')) return if (!window.confirm('Delete the verified implementation and restore the generated one?')) return
saving.value = true saving.value = true
editorError.value = '' editorError.value = ''
try { try {
@@ -269,7 +273,7 @@ onMounted(() => {
{{ stats.supported.toLocaleString() }} supported · {{ stats.supported.toLocaleString() }} supported ·
{{ stats.partial.toLocaleString() }} partial · {{ stats.partial.toLocaleString() }} partial ·
{{ stats.unsupported.toLocaleString() }} unsupported · {{ stats.unsupported.toLocaleString() }} unsupported ·
{{ stats.manual.toLocaleString() }} manual {{ stats.manual.toLocaleString() }} verified
</template> </template>
<template v-else>Loading stats…</template> <template v-else>Loading stats…</template>
</p> </p>
@@ -292,7 +296,7 @@ onMounted(() => {
<option value="unsupported">Not implemented</option> <option value="unsupported">Not implemented</option>
<option value="partial">Partial</option> <option value="partial">Partial</option>
<option value="supported">Supported</option> <option value="supported">Supported</option>
<option value="manual">Manual</option> <option value="manual">Verified</option>
<option value="all">All cards</option> <option value="all">All cards</option>
</select> </select>
<button type="submit">Search</button> <button type="submit">Search</button>
@@ -353,8 +357,16 @@ onMounted(() => {
v-if="card.implementation" v-if="card.implementation"
class="badge" class="badge"
:class="card.implementation.status" :class="card.implementation.status"
>{{ card.implementation.status }}</span> :title="statusLabels[card.implementation.status]"
<span v-if="card.implementation?.manual" class="badge manual">manual</span> :aria-label="statusLabels[card.implementation.status]"
>{{ card.implementation.status[0] }}</span>
<span
v-if="card.implementation"
class="badge"
:class="card.implementation.manual ? 'verified' : 'generated'"
:title="card.implementation.manual ? 'Verified' : 'Generated'"
:aria-label="card.implementation.manual ? 'Verified' : 'Generated'"
>{{ card.implementation.manual ? 'V' : 'G' }}</span>
</span> </span>
</button> </button>
</CardHover> </CardHover>
@@ -381,8 +393,18 @@ onMounted(() => {
</p> </p>
</div> </div>
<div class="badges"> <div class="badges">
<span class="badge" :class="detail.compiled.status">{{ detail.compiled.status }}</span> <span
<span v-if="detail.manual" class="badge manual">manual</span> class="badge"
:class="detail.compiled.status"
:title="statusLabels[detail.compiled.status]"
:aria-label="statusLabels[detail.compiled.status]"
>{{ detail.compiled.status[0] }}</span>
<span
class="badge"
:class="detail.manual ? 'verified' : 'generated'"
:title="detail.manual ? 'Verified' : 'Generated'"
:aria-label="detail.manual ? 'Verified' : 'Generated'"
>{{ detail.manual ? 'V' : 'G' }}</span>
</div> </div>
</div> </div>
@@ -402,23 +424,15 @@ onMounted(() => {
</p> </p>
<p v-else-if="editorError" class="error">{{ editorError }}</p> <p v-else-if="editorError" class="error">{{ editorError }}</p>
<div class="row"> <span class="muted">Card source</span>
<div class="tabs">
<button type="button" :class="{ active: editorMode === 'text' }" @click="editorMode = 'text'">Text</button>
<button type="button" :class="{ active: editorMode === 'visual' }" @click="editorMode = 'visual'">Visual</button>
</div>
<span class="muted grow">{{ editorMode === 'text' ? 'Pseudocode' : 'Node graph' }}</span>
</div>
<textarea <textarea
v-if="editorMode === 'text'"
v-model="source" v-model="source"
spellcheck="false" spellcheck="false"
aria-label="Card implementation" aria-label="Card implementation"
@keydown.ctrl.s.prevent="save" @keydown.ctrl.s.prevent="save"
@keydown.meta.s.prevent="save" @keydown.meta.s.prevent="save"
/> />
<CardGraphEditor v-else :key="detail.card.oracle_id" v-model="source" />
<div class="actions"> <div class="actions">
<button type="button" class="primary" :disabled="saving || !dirty" @click="save"> <button type="button" class="primary" :disabled="saving || !dirty" @click="save">
@@ -439,7 +453,7 @@ onMounted(() => {
</section> </section>
</div> </div>
<PseudoGuide v-else /> <SourceGuide v-else />
</main> </main>
</template> </template>

View File

@@ -74,6 +74,7 @@ interface MatchView {
priority: string priority: string
status: string status: string
winner?: string winner?: string
mulligans?: { player: string; count: number; kept: boolean; bottom: number }[]
stack: { id: string; kind: string; label: string; controller: string }[] stack: { id: string; kind: string; label: string; controller: string }[]
log: string[] log: string[]
hand: CardView[] hand: CardView[]
@@ -83,6 +84,7 @@ interface MatchView {
what: string what: string
sourceId: string sourceId: string
sourceName: string sourceName: string
amount?: number
options: string[] options: string[]
} }
pendingSearch?: { pendingSearch?: {
@@ -206,6 +208,15 @@ const myPlaymat = computed(() => {
: { kind: 'upload' as const, url: `${apiBase}/playmats/${encodeURIComponent(playmat.id)}` } : { kind: 'upload' as const, url: `${apiBase}/playmats/${encodeURIComponent(playmat.id)}` }
}) })
const viewerId = computed(() => state.value?.viewerId ?? '') const viewerId = computed(() => state.value?.viewerId ?? '')
const mulligan = computed(() => game.value?.status === 'mulligan'
? game.value.mulligans?.find(entry => entry.player === viewerId.value)
: undefined)
const mulliganBottom = computed(() => mulligan.value?.bottom ?? 0)
const mulliganWaiting = computed(() => (game.value?.mulligans ?? [])
.filter(entry => !entry.kept
&& !state.value?.players.find(player => player.id === entry.player)?.lost)
.map(entry => playerName(entry.player))
.join(', '))
const isHost = computed(() => state.value?.hostId === viewerId.value) const isHost = computed(() => state.value?.hostId === viewerId.value)
const emptySeats = computed(() => state.value ? state.value.maxPlayers - state.value.players.length : 0) const emptySeats = computed(() => state.value ? state.value.maxPlayers - state.value.players.length : 0)
const opponents = computed(() => (state.value?.players ?? []).filter(player => player.id !== viewerId.value && !player.lost)) const opponents = computed(() => (state.value?.players ?? []).filter(player => player.id !== viewerId.value && !player.lost))
@@ -262,6 +273,9 @@ const filteredSearchLibrary = computed(() => {
: searchLibrary.value : searchLibrary.value
}) })
const pendingChoice = computed(() => game.value?.pendingChoice) const pendingChoice = computed(() => game.value?.pendingChoice)
const pendingCostLabel = computed(() => pendingChoice.value?.amount === undefined
? 'the cost'
: `${pendingChoice.value.amount} life`)
const choiceFilter = ref('') const choiceFilter = ref('')
const choiceInput = ref<HTMLInputElement | null>(null) const choiceInput = ref<HTMLInputElement | null>(null)
const filteredChoiceOptions = computed(() => { const filteredChoiceOptions = computed(() => {
@@ -601,13 +615,26 @@ async function playLand(card: CardView) {
await act({ type: 'play_land', cardId: card.id }) await act({ type: 'play_land', cardId: card.id })
} }
async function keepHand() {
await act({ type: 'keep_hand' })
}
async function takeMulligan() {
await act({ type: 'mulligan' })
}
/** Cards with choices need the cast panel; everything else plays on click. */ /** Cards with choices need the cast panel; everything else plays on click. */
function needsCastOptions(card: CardView): boolean { function needsCastOptions(card: CardView): boolean {
return Boolean(card.manaCost?.includes('X') || /\btarget|choose (one|two|three)/i.test(card.oracleText ?? '')) return Boolean(card.manaCost?.includes('X') || /\btarget|choose (one|two|three)/i.test(card.oracleText ?? ''))
} }
async function playCard(card: CardView) { async function playCard(card: CardView) {
if (busy.value || !card.playable) return if (busy.value) return
if (mulliganBottom.value > 0) {
await act({ type: 'mulligan_bottom', cardId: card.id })
return
}
if (!card.playable) return
cancelCast() cancelCast()
if (isLand(card)) { if (isLand(card)) {
await playLand(card) await playLand(card)
@@ -826,6 +853,11 @@ async function chooseCreatureType(type: string) {
await act({ type: 'choose_type', choice: type }) await act({ type: 'choose_type', choice: type })
} }
async function chooseCost(pay: boolean) {
if (busy.value) return
await act({ type: 'choose_cost', pay })
}
async function attack() { async function attack() {
const attackers = selectedAttackers.value const attackers = selectedAttackers.value
.filter(attackerId => attackTargets[attackerId]) .filter(attackerId => attackTargets[attackerId])
@@ -1026,7 +1058,8 @@ onUnmounted(() => {
<header class="game-head"> <header class="game-head">
<div> <div>
<h1>{{ summary ? `${summary.hostName}'s game` : 'Commander game' }}</h1> <h1>{{ summary ? `${summary.hostName}'s game` : 'Commander game' }}</h1>
<p v-if="game" class="muted"> <p v-if="game?.status === 'mulligan'" class="muted">Opening hands · keep or mulligan</p>
<p v-else-if="game" class="muted">
Turn {{ game.turn }} · {{ phaseLabel }} · priority: {{ priorityName }} Turn {{ game.turn }} · {{ phaseLabel }} · priority: {{ priorityName }}
</p> </p>
<p v-else class="muted">{{ state?.status ?? summary?.status ?? 'Loading…' }}</p> <p v-else class="muted">{{ state?.status ?? summary?.status ?? 'Loading…' }}</p>
@@ -1360,7 +1393,22 @@ onUnmounted(() => {
</TransitionGroup> </TransitionGroup>
</section> </section>
<section class="hand-panel"> <div v-if="game.status === 'mulligan'" class="mulligan-backdrop" aria-hidden="true" />
<section class="hand-panel" :class="{ 'mulligan-mode': game.status === 'mulligan' }">
<div v-if="mulligan" class="mulligan-bar">
<template v-if="mulligan.kept">
<span class="muted">Hand kept. Waiting for {{ mulliganWaiting || 'the other players' }}.</span>
</template>
<template v-else-if="mulligan.bottom">
<span>Click {{ mulligan.bottom }} card{{ mulligan.bottom === 1 ? '' : 's' }} in your hand to put
{{ mulligan.bottom === 1 ? 'it' : 'them' }} on the bottom of your library.</span>
</template>
<template v-else>
<span>Mulligans: {{ mulligan.count }}.</span>
<button type="button" class="primary" :disabled="busy" @click="keepHand">Keep hand</button>
<button type="button" :disabled="busy" @click="takeMulligan">Mulligan</button>
</template>
</div>
<div class="row wrap hand-head"> <div class="row wrap hand-head">
<h2>Your hand</h2> <h2>Your hand</h2>
<span class="tag">{{ game.hand.length }}</span> <span class="tag">{{ game.hand.length }}</span>
@@ -1385,14 +1433,16 @@ onUnmounted(() => {
v-for="(card, index) in game.hand" v-for="(card, index) in game.hand"
:key="card.id" :key="card.id"
class="hand-card" class="hand-card"
:class="{ playable: card.playable, unplayable: !card.playable }" :class="{ playable: card.playable || mulliganBottom > 0 }"
:style="fanStyle(index, game.hand.length)" :style="fanStyle(index, game.hand.length)"
:title="card.playable :title="mulliganBottom > 0
? `Put ${card.name} on the bottom of your library`
: card.playable
? `Click to ${isLand(card) ? 'play' : 'cast'} ${card.name}` ? `Click to ${isLand(card) ? 'play' : 'cast'} ${card.name}`
: card.oracleText" : card.oracleText"
role="button" role="button"
:tabindex="card.playable ? 0 : -1" :tabindex="card.playable || mulliganBottom > 0 ? 0 : -1"
:aria-disabled="!card.playable" :aria-disabled="!card.playable && !mulliganBottom"
@click="playCard(card)" @click="playCard(card)"
@keydown.enter.prevent="playCard(card)" @keydown.enter.prevent="playCard(card)"
@keydown.space.prevent="playCard(card)" @keydown.space.prevent="playCard(card)"
@@ -1450,9 +1500,12 @@ onUnmounted(() => {
</section> </section>
<section v-if="pendingChoice && pendingChoice.player !== viewerId" class="panel side search-panel"> <section v-if="pendingChoice && pendingChoice.player !== viewerId" class="panel side search-panel">
<h2>Choose a type</h2> <h2>{{ pendingChoice.what === 'pay_cost' ? 'Pay a cost' : 'Choose a type' }}</h2>
<p class="muted"> <p class="muted">
{{ playerName(pendingChoice.player) }} is choosing a creature type for {{ pendingChoice.sourceName }}. {{ playerName(pendingChoice.player) }}
{{ pendingChoice.what === 'pay_cost'
? `is deciding whether to pay ${pendingCostLabel} for ${pendingChoice.sourceName}.`
: `is choosing a creature type for ${pendingChoice.sourceName}.` }}
</p> </p>
</section> </section>
@@ -1535,7 +1588,7 @@ onUnmounted(() => {
</template> </template>
</template> </template>
<div v-if="state?.status === 'active' && game" class="turn-actions"> <div v-if="state?.status === 'active' && game?.status === 'active'" class="turn-actions">
<button <button
type="button" type="button"
class="turn-button" class="turn-button"
@@ -1555,11 +1608,29 @@ onUnmounted(() => {
<section class="search-modal" role="dialog" aria-modal="true" aria-labelledby="choice-title"> <section class="search-modal" role="dialog" aria-modal="true" aria-labelledby="choice-title">
<header class="search-head"> <header class="search-head">
<div class="grow"> <div class="grow">
<h2 id="choice-title">Choose a creature type</h2> <h2 id="choice-title">{{ pendingChoice.what === 'pay_cost' ? `Pay ${pendingCostLabel}?` : 'Choose a creature type' }}</h2>
<p class="muted">{{ pendingChoice.sourceName }} enters.</p> <p class="muted">{{ pendingChoice.sourceName }} enters.</p>
</div> </div>
<span class="tag">{{ filteredChoiceOptions.length }} types</span> <span v-if="pendingChoice.what !== 'pay_cost'" class="tag">{{ filteredChoiceOptions.length }} types</span>
</header> </header>
<template v-if="pendingChoice.what === 'pay_cost'">
<p class="muted">If you don't, it enters tapped.</p>
<div class="choice-grid">
<button
type="button"
class="choice-option"
:disabled="busy || (pendingChoice.amount !== undefined && (me?.life ?? 0) < pendingChoice.amount)"
@click="chooseCost(true)"
>Pay {{ pendingCostLabel }}</button>
<button
type="button"
class="choice-option"
:disabled="busy"
@click="chooseCost(false)"
>Enter tapped</button>
</div>
</template>
<template v-else>
<input <input
ref="choiceInput" ref="choiceInput"
v-model="choiceFilter" v-model="choiceFilter"
@@ -1579,6 +1650,7 @@ onUnmounted(() => {
@click="chooseCreatureType(type)" @click="chooseCreatureType(type)"
>{{ type }}</button> >{{ type }}</button>
</div> </div>
</template>
</section> </section>
</div> </div>
</Teleport> </Teleport>
@@ -2593,6 +2665,13 @@ onUnmounted(() => {
font-size: 0.85rem; font-size: 0.85rem;
} }
.mulligan-backdrop {
position: fixed;
inset: 0;
z-index: 65;
background: rgb(0 0 0 / 82%);
}
.hand-panel { .hand-panel {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
@@ -2608,12 +2687,37 @@ onUnmounted(() => {
transform: translateX(-50%); transform: translateX(-50%);
} }
.hand-panel.mulligan-mode {
position: fixed;
top: 50%;
bottom: auto;
z-index: 66;
width: min(100%, 60rem);
padding: 0 0.5rem;
transform: translate(-50%, -50%);
}
.hand-head { .hand-head {
justify-content: center; justify-content: center;
padding: 0 0.25rem; padding: 0 0.25rem;
pointer-events: auto; pointer-events: auto;
} }
.mulligan-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin: 0 0.5rem;
padding: 0.45rem 0.7rem;
border: 1px solid var(--line);
border-radius: 0.5rem;
background: var(--panel);
font-size: 0.9rem;
pointer-events: auto;
}
.hand-head h2 { .hand-head h2 {
font-size: 0.95rem; font-size: 0.95rem;
white-space: nowrap; white-space: nowrap;
@@ -2675,6 +2779,12 @@ onUnmounted(() => {
cursor: pointer; cursor: pointer;
} }
.hand-card.playable .hand-lift {
outline: 2px solid #58a6ff;
outline-offset: 2px;
border-radius: 8px;
}
.hand-card:hover, .hand-card:hover,
.hand-card:focus-within { .hand-card:focus-within {
z-index: 30; z-index: 30;
@@ -2694,18 +2804,6 @@ onUnmounted(() => {
filter: drop-shadow(0 14px 22px rgb(0 0 0 / 55%)); filter: drop-shadow(0 14px 22px rgb(0 0 0 / 55%));
} }
.hand-card.playable:hover .hand-lift,
.hand-card.playable:focus-within .hand-lift {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 8px;
}
.hand-card.unplayable {
filter: grayscale(1);
opacity: 0.45;
}
.hand-options { .hand-options {
position: absolute; position: absolute;
bottom: 0.4em; bottom: 0.4em;

View File

@@ -1,846 +0,0 @@
// Line-level model behind the visual card editor. It mirrors the canonical
// formatter output (abilities at column 0, nested calls indented two spaces) so
// editing a node and serializing it back keeps the pseudocode valid.
export interface GraphNode {
id: number
text: string
kind: 'ability' | 'effect' | 'raw'
children: GraphNode[]
}
let nextId = 1
export function nextNodeId(): number {
return nextId++
}
export function makeNode(text: string, kind: GraphNode['kind'], children: GraphNode[] = []): GraphNode {
return { id: nextNodeId(), text, kind, children }
}
export function parseGraph(source: string): GraphNode[] {
const roots: GraphNode[] = []
const stack: Array<{ indent: number; node: GraphNode }> = []
for (const raw of source.split('\n')) {
if (!raw.trim()) continue
const indent = (raw.match(/^[ \t]*/)?.[0] ?? '').replace(/\t/g, ' ').length
const text = raw.trim()
const kind: GraphNode['kind'] =
text.startsWith('#') || text === '(no abilities)' ? 'raw' : indent === 0 ? 'ability' : 'effect'
const node = makeNode(text, kind)
while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()
if (stack.length) stack[stack.length - 1].node.children.push(node)
else roots.push(node)
stack.push({ indent, node })
}
return roots
}
export function serializeGraph(list: GraphNode[], depth = 0): string {
return list
.map(node => {
const line = ' '.repeat(depth) + node.text
return node.children.length ? `${line}\n${serializeGraph(node.children, depth + 1)}` : line
})
.join('\n')
}
/** Inserted at the top level by the visual editor's "Add ability" menu. */
export const ABILITY_PALETTE = [
{
group: 'Triggered',
items: [
{ label: 'Enters the battlefield', value: 'on enters(this):' },
{ label: 'Dies', value: 'on dies(this):' },
{ label: 'Attacks', value: 'on attacks(this):' },
{ label: 'Upkeep', value: 'on upkeep(you):' },
{ label: 'Cast a spell', value: 'on cast(you, any spell):' },
{ label: 'Deals damage', value: 'on deals_damage(this, any):' },
],
},
{
group: 'Other',
items: [
{ label: 'Activated {T}', value: 'activate {T}:' },
{ label: 'Activated {2}, {T}', value: 'activate {2}, {T}:' },
{ label: 'Static', value: 'static:' },
{ label: 'Static if a condition', value: 'static if it is your turn:' },
{ label: 'Spell effect', value: 'spell:' },
{ label: 'Keyword: Flying', value: 'keyword Flying' },
],
},
]
/** Appended below an ability or nested block. Keep every value parseable. */
export const EFFECT_PALETTE = [
{
group: 'Removal',
items: [
{ label: 'Damage', value: 'damage(target creature, 3)' },
{ label: 'Destroy', value: 'destroy(target creature)' },
{ label: 'Exile', value: 'exile(target permanent)' },
{ label: 'Tap', value: 'tap(target creature)' },
{ label: 'Counter spell', value: 'counter(spell, target spell)' },
{ label: 'Sacrifice', value: 'sacrifice(you, target creature)' },
],
},
{
group: 'Cards and life',
items: [
{ label: 'Draw', value: 'draw(you, 1)' },
{ label: 'Discard', value: 'discard(you, 1)' },
{ label: 'Mill', value: 'mill(you, 1)' },
{ label: 'Scry', value: 'scry(you, 2)' },
{ label: 'Surveil', value: 'surveil(you, 1)' },
{ label: 'Search library', value: 'search(you, creature, 1, to hand, shuffle)' },
{ label: 'Look at top', value: 'look_top(you, 3)' },
{ label: 'Gain life', value: 'gain_life(you, 2)' },
{ label: 'Lose life', value: 'lose_life(opponent, 2)' },
{ label: 'Energy', value: 'energy(you, 2)' },
],
},
{
group: 'Board',
items: [
{ label: 'Create token', value: 'create_token(you, 1, 1/1 white soldier creature)' },
{ label: 'Create copy token', value: 'create_token(you, 1, copy of the triggering object, not legendary)' },
{ label: 'Put counters', value: 'put_counters(target creature, +1/+1, 1)' },
{ label: 'Pump', value: 'pump(target creature, 2/2, until end of turn)' },
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
{ label: 'Untap', value: 'untap(target permanent you control)' },
{ label: 'Return to hand', value: 'return_to_hand(target creature)' },
{ label: 'Add mana', value: 'add_mana(you, {G})' },
],
},
{
group: 'Flow',
items: [
{ label: 'If condition', value: 'if you control at least 3 artifacts:' },
],
},
]
/** Static abilities accept a different effect vocabulary than triggered/spell ones. */
export const STATIC_EFFECT_PALETTE = [
{
group: 'Static effects',
items: [
{ label: 'Pump', value: 'pump(each creature you control, 1/1)' },
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
{ label: 'Enters tapped', value: 'enters_tapped(this)' },
{ label: 'Enters with counters', value: 'enters_with_counters(this, +1/+1, 1)' },
{ label: 'Restrict', value: 'restrict(target creature, cant_attack)' },
{ label: 'Set base P/T', value: 'set_pt(target creature, base, 1/1)' },
],
},
]
/** Value nodes that can be wired into argument sockets. */
export const VALUE_PALETTE = [
{
group: 'Players',
items: [
{ label: 'A player', value: 'target player' },
{ label: 'Each opponent', value: 'each opponent' },
{ label: 'Each player', value: 'each player' },
{ label: 'You', value: 'you' },
{ label: 'That player', value: 'that player' },
{ label: 'Its controller', value: 'its controller' },
],
},
{
group: 'Targets',
items: [
{ label: 'A creature', value: 'target creature' },
{ label: 'A permanent', value: 'target permanent' },
{ label: 'An artifact', value: 'target artifact' },
{ label: 'A land', value: 'target land' },
{ label: 'A spell', value: 'target spell' },
{ label: 'An ability', value: 'target ability' },
{ label: 'Any target', value: 'any target' },
{ label: 'This', value: 'this' },
{ label: 'The triggering object', value: 'the triggering object' },
{ label: 'Each creature you control', value: 'each creature you control' },
{ label: 'Each creature an opponent controls', value: 'each creature an opponent controls' },
],
},
{
group: 'Selectors',
items: [
{ label: 'Creature', value: 'creature' },
{ label: 'Artifact', value: 'artifact' },
{ label: 'Enchantment', value: 'enchantment' },
{ label: 'Land', value: 'land' },
{ label: 'Red', value: 'red' },
{ label: 'Creature you control', value: 'creature you control' },
{ label: 'Artifact you control', value: 'artifact you control' },
{ label: 'Tapped creature', value: 'tapped creature' },
{ label: 'Power 4 or greater', value: 'creature with power 4 or greater' },
{ label: 'Nontoken Dragon', value: 'each other nontoken dragon creature you control' },
{ label: 'Nontoken Angel', value: "each nontoken angel you don't control" },
{ label: 'Selector builder', value: '__selector__' },
],
},
{
group: 'Tokens',
items: [
{ label: '1/1 white Soldier', value: '1/1 white soldier creature' },
{ label: '1/1 red Goblin', value: '1/1 red goblin creature' },
{ label: 'Copy of the triggering object', value: 'copy of the triggering object' },
{ label: 'Copy, not legendary', value: 'copy of the triggering object, not legendary' },
],
},
{
group: 'Values',
items: [
{ label: '1', value: '1' },
{ label: '2', value: '2' },
{ label: '3', value: '3' },
{ label: 'X', value: 'X' },
{ label: 'That much', value: 'that much' },
{ label: 'Its power', value: 'its power' },
{ label: 'Its toughness', value: 'its toughness' },
{ label: 'Count creatures you control', value: 'count(creature you control)' },
{ label: 'Cards in your hand', value: 'cards in your hand' },
],
},
{
group: 'Costs',
items: [
{ label: 'Tap', value: '{T}' },
{ label: 'Mana {2}', value: '{2}' },
{ label: 'Pay 2 life', value: 'pay 2 life' },
{ label: 'Sacrifice this', value: 'sacrifice this' },
{ label: 'Discard 1 card(s)', value: 'discard 1 card(s)' },
{ label: 'Mill 1 card(s)', value: 'mill 1 card(s)' },
{ label: 'Remove 1 +1/+1 counter(s)', value: 'remove 1 +1/+1 counter(s) from this' },
],
},
{
group: 'Conditions',
items: [
{ label: 'It is your turn', value: 'it is your turn' },
{ label: 'This is tapped', value: 'this is tapped' },
{ label: 'You control at least 3 artifacts', value: 'you control at least 3 artifacts' },
{ label: 'You have at least 10 life', value: 'you have at least 10 life' },
],
},
{
group: 'Durations',
items: [
{ label: 'Until end of turn', value: 'until end of turn' },
{ label: 'Until your next turn', value: 'until your next turn' },
{ label: 'Until the end of your next turn', value: 'until the end of your next turn' },
{ label: 'While this remains', value: 'for as long as this remains on the battlefield' },
],
},
{
group: 'Logic',
items: [
{ label: 'Selector OR', value: '__or__' },
{ label: 'Selector AND', value: '__and__' },
],
},
]
/** Human labels for effect/ability argument sockets. */
export const ARG_HINTS: Record<string, string[]> = {
damage: ['target', 'amount', 'source'],
damage_divided: ['amount', 'target'],
draw: ['player', 'amount'],
discard: ['player', 'amount'],
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', 'duration'],
put_counters: ['target', 'counter', 'amount'],
remove_counters: ['target', 'counter', 'amount'],
create_token: ['player', 'amount', 'token', 'options'],
destroy: ['target'],
exile: ['target'],
tap: ['target'],
untap: ['target'],
regenerate: ['target'],
return_to_hand: ['target'],
put_on_top: ['target'],
sacrifice: ['player', 'target'],
counter: ['spell|ability', 'target'],
return_to_battlefield: ['target', 'options'],
scry: ['player', 'amount'],
surveil: ['player', 'amount'],
search: ['player', 'selector', 'amount', 'destination', 'options'],
add_mana: ['player', 'mana'],
fight: ['target', 'target'],
energy: ['player', 'amount'],
attach: ['target'],
restrict: ['target', 'rule'],
prevent_damage: ['target', 'amount', 'duration'],
gain_control: ['target', 'duration'],
look_top: ['player', 'amount', 'options'],
pay: ['cost'],
transform: ['target'],
}
/** Human labels for trigger event arguments. */
const TRIGGER_ARG_HINTS: Record<string, string[]> = {
enters: ['subject'],
dies: ['subject'],
attacks: ['subject'],
blocks: ['subject'],
attacks_or_blocks: ['subject'],
enters_or_attacks: ['subject'],
enters_or_dies: ['subject'],
leaves_battlefield: ['subject'],
deals_damage: ['subject', 'recipient'],
deals_combat_damage: ['subject', 'recipient'],
upkeep: ['player'],
end_step: ['player'],
begin_combat: ['player'],
first_main_phase: ['player'],
postcombat_main_phase: ['player'],
cast: ['player', 'spell'],
becomes_level: ['level'],
draw: ['player'],
counter_placed: ['subject', 'counter'],
becomes_target: ['subject'],
gain_life: ['player'],
lose_life: ['player'],
}
const TRIGGER_SUBJECT_OPTIONS = [
'this',
'each other creature',
'each creature you control',
'each other nontoken dragon creature you control',
"each nontoken angel you don't control",
]
const PLAYER_OPTIONS = ['you', 'target player', 'each opponent', 'each player', 'that player', 'its controller']
const AMOUNT_OPTIONS = ['1', '2', '3', '4', '5', 'X', 'that much', 'count(creature you control)']
const TOKEN_OPTIONS = [
'1/1 white soldier creature',
'1/1 red goblin creature',
'copy of the triggering object',
]
/** Argument slots with fixed choices become dropdowns in the visual editor. */
export const SLOT_OPTIONS: Record<string, string[][]> = {
enters: [TRIGGER_SUBJECT_OPTIONS],
create_token: [PLAYER_OPTIONS, AMOUNT_OPTIONS, TOKEN_OPTIONS, ['not legendary']],
}
/** Splits on `separator` outside parentheses, brackets, braces and quotes. */
export function splitTopLevel(text: string, separator: string): string[] {
const parts: string[] = []
let depth = 0
let quote = false
let escape = false
let start = 0
for (let index = 0; index < text.length; index++) {
const char = text[index]
if (quote) {
if (escape) escape = false
else if (char === '\\') escape = true
else if (char === '"') quote = false
continue
}
if (char === '"') {
quote = true
continue
}
if (char === '(' || char === '[' || char === '{') depth++
else if (char === ')' || char === ']' || char === '}') depth--
else if (depth === 0 && text.startsWith(separator, index)) {
parts.push(text.slice(start, index))
index += separator.length - 1
start = index + 1
}
}
parts.push(text.slice(start))
return parts
}
export function blockOf(text: string): { kind: 'if' | 'choose' | 'schedule'; value: string } | undefined {
const ifMatch = text.match(/^if (.+):$/)
if (ifMatch) return { kind: 'if', value: ifMatch[1] }
const chooseMatch = text.match(/^choose (\d+(?:-\d+)?):$/)
if (chooseMatch) return { kind: 'choose', value: chooseMatch[1] }
const scheduleMatch = text.match(/^schedule\((next_upkeep|next_end_step)\):$/)
if (scheduleMatch) return { kind: 'schedule', value: scheduleMatch[1] }
return undefined
}
/** True for nodes that carry an indented body. Mode lines can nest too. */
export function isBlockText(text: string): boolean {
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) || /^\d+\.\s/.test(text)
}
/** Blocks that are invalid without at least one nested effect. */
function requiresBody(text: string): boolean {
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text)
}
export function abilityRequiresEffects(text: string): boolean {
return /^(?:on |activate |static|spell|chapter )/.test(text)
}
/** Reads a `name(arg, arg)` prefix, leaving any suffix after the closing paren. */
export function readCallPrefix(text: string): { name: string; args: string[]; end: number } | undefined {
const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/)
if (!match) return undefined
const open = match[0].length - 1
let depth = 0
let quote = false
let escape = false
for (let index = open; index < text.length; index++) {
const char = text[index]
if (quote) {
if (escape) escape = false
else if (char === '\\') escape = true
else if (char === '"') quote = false
continue
}
if (char === '"') {
quote = true
continue
}
if (char === '(') depth++
else if (char === ')') {
depth--
if (depth === 0) {
const inner = text.slice(open + 1, index).trim()
return {
name: match[1],
args: inner ? splitTopLevel(inner, ',').map(arg => arg.trim()) : [],
end: index + 1,
}
}
}
}
return undefined
}
/** Reads a complete `name(arg, arg)` call; returns undefined for block headers. */
export function parseCall(text: string): { name: string; args: string[] } | undefined {
const trimmed = text.trim()
const call = readCallPrefix(trimmed)
return call && call.end === trimmed.length ? { name: call.name, args: call.args } : undefined
}
/**
* Splits a supported line into fixed text plus argument slots. Unsupported
* lines return undefined and stay as free text.
*/
export function shapeFromText(text: string): NodeShape | undefined {
if (text.startsWith('on ') && text.endsWith(':')) {
const inner = text.slice(3, -1)
const call = readCallPrefix(inner)
if (call) {
const suffix = inner.slice(call.end)
return {
name: `on ${call.name}`,
head: `on ${call.name}(`,
tail: `)${suffix}:`,
separator: ', ',
slots: call.args.map((arg, index) => {
const options = SLOT_OPTIONS[call.name]?.[index]
return {
label: TRIGGER_ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
text: arg,
...(options ? { options } : {}),
}
}),
}
}
}
if (text.startsWith('activate ') && text.endsWith(':')) {
return {
head: 'activate ',
tail: ':',
separator: ', ',
slots: [{ label: 'cost', text: text.slice('activate '.length, -1) }],
}
}
if (text.startsWith('static if ') && text.endsWith(':')) {
return {
head: 'static if ',
tail: ':',
separator: ', ',
slots: [{ label: 'condition', text: text.slice('static if '.length, -1) }],
}
}
const block = blockOf(text)
if (block) {
if (block.kind === 'if') {
return { head: 'if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: block.value }] }
}
if (block.kind === 'choose') {
return { head: 'choose ', tail: ':', separator: ', ', slots: [{ label: 'modes', text: block.value }] }
}
return { head: 'schedule(', tail: '):', separator: ', ', slots: [{ label: 'when', text: block.value }] }
}
const call = parseCall(text)
if (call) {
return {
head: `${call.name}(`,
tail: ')',
separator: ', ',
slots: call.args.map((arg, index) => {
const options = SLOT_OPTIONS[call.name]?.[index]
return {
label: ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
text: arg,
...(options ? { options } : {}),
}
}),
}
}
return undefined
}
/**
* Rebuilds every shaped line from its slots and connected value nodes. Value
* nodes are evaluated recursively, so `or`/`and` combinators can nest.
*/
export function syncTexts(model: GraphModel): void {
const byId = new Map(model.nodes.map(node => [node.id, node]))
const valueEdges = new Map<string, number>()
for (const edge of model.edges) {
if (edge.port === 'value' && edge.slot !== undefined) {
valueEdges.set(`${edge.to}:${edge.slot}`, edge.from)
}
}
function renderSlot(node: CanvasNode, index: number, stack: Set<number>): string {
const childId = valueEdges.get(`${node.id}:${index}`)
const child = childId !== undefined ? byId.get(childId) : undefined
return child ? render(child, stack) : node.shape?.slots[index]?.text ?? ''
}
function render(node: CanvasNode | undefined, stack: Set<number>): string {
if (!node) return ''
if (stack.has(node.id)) return node.kind === 'value' ? node.literal ?? '' : ''
stack.add(node.id)
let text: string
if (node.kind === 'value' && node.combine) {
text = `${renderSlot(node, 0, stack)} ${node.combine} ${renderSlot(node, 1, stack)}`
} else if (node.shape) {
text = node.shape.head
+ node.shape.slots.map((_, index) => renderSlot(node, index, stack)).join(node.shape.separator)
+ node.shape.tail
} else if (node.kind === 'value') {
text = node.literal ?? node.text
} else {
text = node.text
}
stack.delete(node.id)
node.text = text
return text
}
for (const node of model.nodes) render(node, new Set())
}
// ---------------------------------------------------------------------------
// Node canvas. The tree above is converted into flat nodes with explicit
// `next` (sibling) and `body` (indented) links. Source is regenerated by
// following those links, so the canvas and the pseudocode stay in sync.
// ---------------------------------------------------------------------------
export interface NodeSlot {
label: string
text: string
/** Fixed choices rendered as a dropdown instead of a free-text input. */
options?: string[]
}
/** A line split into a fixed shell and the slots a value node can fill. */
export interface NodeShape {
name?: string
head: string
tail: string
separator: string
slots: NodeSlot[]
}
export interface CanvasNode {
id: number
text: string
kind: 'ability' | 'effect' | 'raw' | 'value'
x: number
y: number
shape?: NodeShape
/** Value nodes: literal source text. */
literal?: string
/** Value nodes: combines its two slots instead of using a literal. */
combine?: 'or' | 'and'
valueLabel?: string
}
export type GraphPort = 'next' | 'body' | 'value'
export interface GraphEdge {
id: number
from: number
port: GraphPort
to: number
/** Target argument index when port is 'value'. */
slot?: number
}
export interface GraphModel {
nodes: CanvasNode[]
edges: GraphEdge[]
}
export interface GraphSource {
source: string
unlinked: number
problems: string[]
}
export const NODE_WIDTH = 230
const CHAIN_GAP = 70
const BODY_INDENT = NODE_WIDTH + 20
const BODY_GAP = 70
const ROOT_GAP = 70
let nextEdgeId = 1
export function estimateNodeHeight(text: string, slots?: number, hasName?: boolean): number {
const count = slots ?? parseCall(text)?.args.length ?? 0
if (!count) return hasName ? 84 : 74
return 64 + count * 48 + (hasName ? 24 : 0)
}
export function hasBodyPort(model: GraphModel, node: CanvasNode): boolean {
return node.kind === 'effect'
&& (isBlockText(node.text) || model.edges.some(edge => edge.from === node.id && edge.port === 'body'))
}
/** Converts pseudocode into nodes and links, laid out roughly left to right. */
export function graphFromSource(source: string): GraphModel {
const model: GraphModel = { nodes: [], edges: [] }
let y = 40
for (const root of parseGraph(source)) {
if (root.kind === 'raw') {
model.nodes.push({ id: root.id, text: root.text, kind: 'raw', x: 40, y })
y += 64
continue
}
const bounds = layoutTreeChain(model, [root], 40, y, 0)
y += bounds.height + ROOT_GAP
}
return model
}
function layoutTreeChain(
model: GraphModel,
list: GraphNode[],
x: number,
y: number,
depth: number,
): { width: number; height: number } {
let cursorX = x
let maxHeight = 0
let previous: number | undefined
for (const treeNode of list) {
const kind: CanvasNode['kind'] = depth === 0 ? treeNode.kind : 'effect'
const node: CanvasNode = {
id: treeNode.id,
text: treeNode.text,
kind,
x: cursorX,
y,
shape: shapeFromText(treeNode.text),
}
model.nodes.push(node)
if (previous !== undefined) {
model.edges.push({ id: nextEdgeId++, from: previous, port: 'next', to: node.id })
}
previous = node.id
const height = estimateNodeHeight(node.text, node.shape?.slots.length, Boolean(node.shape?.name))
let totalHeight = height
let advance = NODE_WIDTH
if (treeNode.children.length) {
if (depth === 0) {
// An ability's output is its effect chain, laid out to the right.
const chain = layoutTreeChain(model, treeNode.children, cursorX + NODE_WIDTH + CHAIN_GAP, y, 1)
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'next', to: treeNode.children[0].id })
totalHeight = Math.max(totalHeight, chain.height)
advance = NODE_WIDTH + CHAIN_GAP + chain.width
} else {
// Blocks own an indented body below and just right of their socket.
const body = layoutTreeChain(model, treeNode.children, cursorX + BODY_INDENT, y + height + BODY_GAP, depth + 1)
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'body', to: treeNode.children[0].id })
totalHeight = Math.max(totalHeight, height + BODY_GAP + body.height)
}
}
maxHeight = Math.max(maxHeight, totalHeight)
cursorX += advance + CHAIN_GAP
}
return { width: cursorX - x, height: maxHeight }
}
/** Rebuilds pseudocode by walking next/body links from every ability root. */
export function sourceFromGraph(model: GraphModel): GraphSource {
syncTexts(model)
const byId = new Map(model.nodes.map(node => [node.id, node]))
const outgoing = new Map<string, GraphEdge>()
for (const edge of model.edges) {
outgoing.set(`${edge.from}:${edge.port}`, edge)
}
const lines: string[] = []
const visited = new Set<number>()
const problems: string[] = []
const label = (text: string) => (text.length > 52 ? `${text.slice(0, 49)}…` : text)
const checkModes = (startId: number) => {
let mode = byId.get(startId)
let expected = 1
const seenModes = new Set<number>()
while (mode && !seenModes.has(mode.id)) {
seenModes.add(mode.id)
const number = mode.text.match(/^(\d+)\.\s/)
if (!number || Number(number[1]) !== expected) {
problems.push('A choose body must be numbered 1, 2, 3…')
return
}
expected++
const next = outgoing.get(`${mode.id}:next`)
mode = next ? byId.get(next.to) : undefined
}
}
const emitChain = (startId: number, depth: number) => {
let current: number | undefined = startId
while (current !== undefined) {
if (visited.has(current)) {
problems.push(`Cycle at ${label(byId.get(current)?.text ?? 'node')}`)
return
}
const node = byId.get(current)
if (!node) return
visited.add(current)
lines.push(`${' '.repeat(depth)}${node.text}`)
const body = outgoing.get(`${current}:body`)
if (body) {
if (blockOf(node.text)?.kind === 'choose') checkModes(body.to)
emitChain(body.to, depth + 1)
} else if (requiresBody(node.text)) {
problems.push(`"${label(node.text)}" has no body`)
}
current = outgoing.get(`${current}:next`)?.to
}
}
for (const node of model.nodes) {
if (node.kind === 'raw') {
if (!visited.has(node.id)) {
visited.add(node.id)
lines.push(node.text)
}
continue
}
if (node.kind !== 'ability' || visited.has(node.id)) continue
visited.add(node.id)
lines.push(node.text)
const next = outgoing.get(`${node.id}:next`)
if (next) emitChain(next.to, 1)
else if (abilityRequiresEffects(node.text)) problems.push(`"${label(node.text)}" has no effects`)
}
const usedValues = new Set(model.edges.filter(edge => edge.port === 'value').map(edge => edge.from))
const unlinked = model.nodes.filter(node =>
(node.kind === 'effect' && !visited.has(node.id))
|| (node.kind === 'value' && !usedValues.has(node.id)),
).length
if (unlinked) {
problems.push(`${unlinked} unconnected node${unlinked === 1 ? '' : 's'} will be ignored`)
}
return { source: lines.join('\n'), unlinked, problems }
}
function reaches(model: GraphModel, start: number, target: number): boolean {
const stack = [start]
const seen = new Set<number>()
while (stack.length) {
const id = stack.pop()!
if (id === target) return true
if (seen.has(id)) continue
seen.add(id)
for (const edge of model.edges) {
if (edge.from === id) stack.push(edge.to)
}
}
return false
}
/** Links an output socket to a node input or an argument slot. */
export function connectNodes(
model: GraphModel,
from: number,
port: GraphPort,
to: number,
slot?: number,
): boolean {
if (from === to) return false
const source = model.nodes.find(node => node.id === from)
const target = model.nodes.find(node => node.id === to)
if (!source || !target) return false
if (port === 'value') {
if (source.kind !== 'value' || !target.shape || slot === undefined || !target.shape.slots[slot]) {
return false
}
} else {
if (target.kind !== 'effect') return false
if (port === 'body' && !hasBodyPort(model, source)) return false
}
if (reaches(model, to, from)) return false
if (port === 'value') {
model.edges = model.edges.filter(edge =>
!(edge.port === 'value' && edge.to === to && edge.slot === slot)
&& !(edge.from === from && edge.port === 'value'),
)
model.edges.push({ id: nextEdgeId++, from, port, to, slot })
} else {
model.edges = model.edges.filter(edge =>
!((edge.port === 'next' || edge.port === 'body') && edge.to === to)
&& !(edge.from === from && edge.port === port),
)
model.edges.push({ id: nextEdgeId++, from, port, to })
}
return true
}

View File

@@ -1,215 +0,0 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import {
connectNodes,
graphFromSource,
nextNodeId,
parseCall,
parseGraph,
serializeGraph,
shapeFromText,
sourceFromGraph,
syncTexts,
} from '../app/utils/cardGraph.ts'
import type { GraphModel } from '../app/utils/cardGraph.ts'
const SOURCE = `# Soul Warden [supported]
on enters(each other creature):
gain_life(you, 1)
on upkeep(you):
if you control at least 3 artifacts:
draw(you, 1)
create_token(you, 1, 1/1 white soldier creature)`
test('parseGraph builds ability and nested effect nodes', () => {
const roots = parseGraph(SOURCE)
assert.equal(roots.length, 3)
assert.equal(roots[0].kind, 'raw')
assert.equal(roots[1].kind, 'ability')
assert.equal(roots[1].text, 'on enters(each other creature):')
assert.deepEqual(roots[1].children.map(node => node.text), ['gain_life(you, 1)'])
const upkeep = roots[2]
assert.equal(upkeep.children[0].text, 'if you control at least 3 artifacts:')
assert.deepEqual(upkeep.children[0].children.map(node => node.text), ['draw(you, 1)'])
assert.equal(upkeep.children[1].text, 'create_token(you, 1, 1/1 white soldier creature)')
})
test('serializeGraph round-trips formatter output and normalizes indentation', () => {
assert.equal(serializeGraph(parseGraph(SOURCE)), SOURCE.replace('\n\n', '\n'))
assert.equal(
serializeGraph(parseGraph('on dies(this):\n draw(you, 1)')),
'on dies(this):\n draw(you, 1)',
)
})
test('graph conversion round-trips abilities, chains and nested bodies', () => {
const model = graphFromSource(SOURCE)
const result = sourceFromGraph(model)
assert.equal(result.source, SOURCE.replace('\n\n', '\n'))
assert.equal(result.unlinked, 0)
assert.deepEqual(result.problems, [])
})
test('connectNodes replaces an input link and rejects cycles', () => {
const model = graphFromSource(SOURCE)
const ability = model.nodes.find(node => node.kind === 'ability' && node.text.startsWith('on enters'))
const first = model.nodes.find(node => node.text === 'gain_life(you, 1)')
const second = model.nodes.find(node => node.text === 'create_token(you, 1, 1/1 white soldier creature)')
assert.ok(ability && first && second)
assert.equal(connectNodes(model, ability.id, 'next', second.id), true)
assert.equal(sourceFromGraph(model).unlinked, 1)
assert.equal(connectNodes(model, first.id, 'next', second.id), true)
assert.equal(connectNodes(model, second.id, 'next', first.id), false)
})
test('shapeFromText exposes trigger and effect arguments', () => {
const trigger = shapeFromText('on attacks(this):')
assert.equal(trigger?.name, 'on attacks')
assert.deepEqual(trigger?.slots, [{ label: 'subject', text: 'this' }])
const damage = shapeFromText('damage(target creature, 3)')
assert.deepEqual(damage?.slots.map(slot => slot.label), ['target', 'amount'])
})
test('shapeFromText adds dropdown choices for constant slots', () => {
const enters = shapeFromText('on enters(each other nontoken dragon creature you control):')
assert.deepEqual(enters?.slots[0]?.options, [
'this',
'each other creature',
'each creature you control',
'each other nontoken dragon creature you control',
"each nontoken angel you don't control",
])
const copy = shapeFromText("create_token(you, 1, copy of the triggering object, not legendary)")
assert.deepEqual(copy?.slots.map(slot => slot.label), ['player', 'amount', 'token', 'options'])
assert.ok(copy?.slots[2]?.options?.includes('copy of the triggering object'))
assert.deepEqual(copy?.slots[3]?.options, ['not legendary'])
})
test('value nodes fill trigger and effect argument sockets', () => {
const model = graphFromSource(`# Test [supported]
on attacks(this):
damage(target creature, 3)`)
const trigger = model.nodes.find(node => node.kind === 'ability')
const damage = model.nodes.find(node => node.text.startsWith('damage('))
assert.ok(trigger && damage)
const player = {
id: nextNodeId(),
kind: 'value' as const,
text: 'target player',
literal: 'target player',
valueLabel: 'Players',
x: 0,
y: 0,
}
model.nodes.push(player)
assert.equal(connectNodes(model, player.id, 'value', trigger.id, 0), true)
const artifact = {
id: nextNodeId(),
kind: 'value' as const,
text: 'target artifact',
literal: 'target artifact',
valueLabel: 'Targets',
x: 0,
y: 0,
}
model.nodes.push(artifact)
assert.equal(connectNodes(model, artifact.id, 'value', damage.id, 0), true)
assert.equal(sourceFromGraph(model).source, `# Test [supported]
on attacks(target player):
damage(target artifact, 3)`)
})
test('or and and value nodes combine selector slots', () => {
const model = graphFromSource(`# Test [supported]
spell:
search(you, creature, 1, to hand, shuffle)`)
const search = model.nodes.find(node => node.text.startsWith('search('))
assert.ok(search)
const combo: GraphModel['nodes'][number] = {
id: nextNodeId(),
kind: 'value',
text: '',
combine: 'or',
valueLabel: 'Logic',
x: 0,
y: 0,
shape: {
head: '',
tail: '',
separator: ' or ',
slots: [
{ label: 'left', text: 'creature' },
{ label: 'right', text: 'artifact' },
],
},
}
model.nodes.push(combo)
assert.equal(connectNodes(model, combo.id, 'value', search.id, 1), true)
assert.match(sourceFromGraph(model).source, /search\(you, creature or artifact, 1, to hand, shuffle\)/)
syncTexts(model)
assert.equal(combo.text, 'creature or artifact')
combo.combine = 'and'
combo.shape!.slots[0].text = 'red'
combo.shape!.slots[1].text = 'creature'
syncTexts(model)
assert.equal(combo.text, 'red and creature')
})
test('structured selector value nodes render their slots', () => {
const model = graphFromSource(`# Test [supported]
on enters(this):`)
const trigger = model.nodes.find(node => node.kind === 'ability')
assert.ok(trigger)
const selector: GraphModel['nodes'][number] = {
id: nextNodeId(),
kind: 'value',
text: '',
valueLabel: 'Selector',
x: 0,
y: 0,
shape: {
head: '',
tail: '',
separator: ' ',
slots: [
{ label: 'prefix', text: 'each' },
{ label: 'state', text: 'nontoken' },
{ label: 'type', text: 'angel' },
{ label: 'controller', text: "you don't control" },
],
},
}
model.nodes.push(selector)
assert.equal(connectNodes(model, selector.id, 'value', trigger.id, 0), true)
syncTexts(model)
assert.equal(selector.text, "each nontoken angel you don't control")
assert.equal(sourceFromGraph(model).source, `# Test [supported]
on enters(each nontoken angel you don't control):`)
})
test('parseCall splits arguments outside nested groups', () => {
assert.deepEqual(parseCall('draw(you, 1)'), { name: 'draw', args: ['you', '1'] })
assert.deepEqual(parseCall('proliferate()'), { name: 'proliferate', args: [] })
assert.deepEqual(parseCall('damage(divided(any number, creature), 3)'), {
name: 'damage',
args: ['divided(any number, creature)', '3'],
})
assert.equal(parseCall('if you control at least 3 artifacts:'), undefined)
})