diff --git a/AGENTS.md b/AGENTS.md index f38a3e0..0f711d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Online multiplayer Magic: The Gathering (Commander) emulator: Nuxt frontend + Fa ## 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/`. - `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 backend && npm test # all backend tests 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 - 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`. -- 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. - 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. diff --git a/README.md b/README.md index ef50cd2..da4d4a3 100644 --- a/README.md +++ b/README.md @@ -94,23 +94,24 @@ with its original text, never guessed. ```bash 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 ``` -`data/card-effects.pseudo.txt` is the human-readable pseudocode view. The -pseudocode is also an input format: the frontend editor saves one override file -per card under `backend/data/card-overrides/`, and `npm run compile:cards` -validates those files and uses them instead of generated output. See -[backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL, +`data/card-effects.js` is the human-readable card source. The source is also an +input format: the frontend editor saves one override file per card under +`backend/data/card-overrides/`, and `npm run compile:cards` validates those files +and uses them instead of generated output. Card source looks like JavaScript but +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. 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 -OpenRouter model and loads the returned pseudocode into the editor without -saving it. The model is instructed to answer with pseudocode only — no -explanations, Markdown or code fences — and the answer must parse before the API -returns it. Set `OPENROUTER_API_KEY` on the backend to enable the button; +source syntax. **Draft with AI** sends the selected card's oracle text to an +OpenRouter model and loads the returned source into the editor without saving +it. The model is instructed to answer with card source only — no explanations, +Markdown or code fences — and the answer must parse before the API returns it. +Set `OPENROUTER_API_KEY` on the backend to enable the button; `OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. ## 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. - `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and 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 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 | | `PORT` | `4000` | backend | Port the API listens on inside the container | | `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 | 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/ │ ├── 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/images.ts # on-disk cache for Scryfall card art -│ ├── src/effects/ # effect DSL, compiler, formatter, pseudocode parser -│ ├── src/effects/translate.ts # natural language -> pseudocode through OpenRouter +│ ├── src/effects/ # effect DSL, compiler, formatter, source interpreter +│ ├── src/effects/translate.ts # natural language -> card source through OpenRouter │ ├── src/game/ # rules engine, commander rules, match manager │ ├── src/accounts.ts # Mongo models, auth, decks, and preferences │ ├── 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/game-engine.md # engine API, rules coverage, limitations │ ├── 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/utils/auth.ts # login token storage and headers │ ├── 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) │ ├── Dockerfile # dev, build, and production stages │ └── 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?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/: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 | | `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` | `/stats` | Supported, partial, unsupported, and manual counts | | `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` | diff --git a/backend/.gitignore b/backend/.gitignore index 0685ba7..0fafd64 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -3,7 +3,7 @@ dist .env data/cards.json data/card-effects.json -data/card-effects.pseudo.txt +data/card-effects.js data/images/ data/playmats/ data/*.tmp diff --git a/backend/data/card-overrides/27b047e3-0d41-45e2-98e9-9391d7923a1e.js b/backend/data/card-overrides/27b047e3-0d41-45e2-98e9-9391d7923a1e.js new file mode 100644 index 0000000..05c1044 --- /dev/null +++ b/backend/data/card-overrides/27b047e3-0d41-45e2-98e9-9391d7923a1e.js @@ -0,0 +1,5 @@ +export default [ + activated([tapCost()], [ + addMana(you, anyColor(1, { restriction: 'a land an opponent controls could produce' })), + ]), +] diff --git a/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.js b/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.js new file mode 100644 index 0000000..c7b0334 --- /dev/null +++ b/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.js @@ -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 })), + ), +] diff --git a/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt b/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt deleted file mode 100644 index df2a213..0000000 --- a/backend/data/card-overrides/880fcf86-e6a9-482c-b91d-750f293127b2.pseudo.txt +++ /dev/null @@ -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) diff --git a/backend/docs/card-effects.md b/backend/docs/card-effects.md index c8c04cc..473d278 100644 --- a/backend/docs/card-effects.md +++ b/backend/docs/card-effects.md @@ -3,9 +3,9 @@ The card database from Scryfall is English prose. The game engine cannot execute prose, so `backend/src/effects/` compiles every oracle-text line into a small JSON AST. The AST is the canonical form for the engine. A pretty-printer renders -the same AST as readable pseudocode, and a matching parser reads that pseudocode -back, so a human can replace the generated implementation of a card without -touching JSON. +the same AST as readable card source, and a matching interpreter reads that +source back, so a human can replace the generated implementation of a card +without touching JSON. This is deliberately **not** a rules engine. It answers "what does the card say?" in machine-readable form. "What happens when it resolves?" belongs to the @@ -18,10 +18,10 @@ Scryfall oracle text -> normalize (card name, "this creature", contractions, reminder text) -> classify (keyword / triggered / activated / static / spell effect) -> parse targets, values, costs, conditions, durations - -> JSON AST + pseudocode rendering + -> JSON AST + card-source rendering -data/card-overrides/.pseudo.txt - -> pseudocode parser +data/card-overrides/.js + -> safe source interpreter -> JSON AST used instead of the generated one ``` @@ -34,16 +34,16 @@ a guessed effect. A wrong effect is worse than a missing one. From `backend/`: ```bash -npm run compile:cards # writes data/card-effects.json and .pseudo.txt -npm test # compiler, pseudocode parser, and engine tests +npm run compile:cards # writes data/card-effects.json and data/card-effects.js +npm test # compiler, source interpreter, and engine tests npm run dev # API for the frontend editor ``` Current output over the imported Commander pool (32,116 cards): ```text -Cards: 14,141 supported, 10,119 partial, 7,856 unsupported -Ability lines: 37,983/60,470 parsed (62.8%) +Cards: 14,239 supported, 10,088 partial, 7,789 unsupported +Ability lines: 38,132/60,470 parsed (63.1%) ``` - **supported** — every ability line parsed. @@ -58,40 +58,200 @@ patterns updates the numbers. | File | Contents | | ---- | -------- | | `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card | -| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode | -| `data/card-overrides/.pseudo.txt` | Human-authored implementations, one file per card | +| `data/card-effects.js` | The same cards rendered as card source | +| `data/card-overrides/.js` | Human-authored implementations, one file per card | The two generated files are git-ignored. Overrides are ordinary source files and should be committed. -## Pseudocode +Compiled cards carry the Scryfall `typeLine`, and the game catalog uses it. +An override can declare its own type line with `card(...)`; that value wins when +the card is loaded into a game. -```text -# Soul Warden [supported] -on enters(each other creature): - gain_life(you, 1) +## Card source -# Llanowar Elves [supported] -activate {T}: - add_mana(you, {G}) +Card source looks like a JavaScript module, but it is **not executed as +JavaScript**. `src/effects/source.ts` tokenizes and evaluates a deliberately +small expression subset against a fixed builder API. There is no `eval`, no +`new Function`, no imports, no property writes and no access to globals: an +unrecognized name or method is a parse error. This matters because +`PUT /cards/:oracleId/implementation` is unauthenticated. -# Krenko, Mob Boss [supported] -activate {T}: - create_token(you, count(creature goblin you control), 1/1 red goblin creature) +A card exports its type line and an array of abilities: + +```js +export default card('Creature — Human Cleric', [ + keywords('Flying', 'Ward {2}'), + triggered(when.enters(each(permanents.other().withType('creature'))), [ + gainLife(you, 1), + ]), + activated([tapCost()], [ + addMana(you, mana('{G}')), + ]), +]) ``` -Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads -it back into the same AST the compiler produces. Blocks are indented two spaces. -A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a -new section for a multi-face card. Use `(no abilities)` when a face has none. +Plain `export default [...]` is still accepted and uses the Scryfall type line. +Multi-face cards export `faces(face('Name', 'Type line', [...]), ...)` in card order: + +```js +export default faces( + face('Front', 'Instant', [spell([draw(you, 2)])]), + face('Back', 'Creature — Human', [keyword('Flying')]), +) +``` + +Every effect list also accepts a callback. A single expression is one effect; a +block is several effects, separated by newlines, `;` or `,`: + +```js +export default card('Creature — Human Cleric', [ + triggered(when.enters(self), () => draw(you, 1)), + activated([tapCost()], () => { + gainLife(you, 1) + draw(you, 1) + }), +]) +``` + +Arrays stay valid and are still used for costs, `modal` modes, ability lists, +`card`, `faces` and `face`. The formatter emits callbacks for effect lists and +`card(typeLine, abilities)` at the top level. + +The formatter writes the same shape, so a generated implementation can be +copied, edited and saved as an override. `formatCard` and `parseCardSource` +round-trip: comments are ignored, a leading `// Card [status]` line is optional, +and `const` declarations are allowed for reuse: + +```js +const dragons = permanents.withType('creature').withSubtype('dragon').youControl() + +export default card('Creature — Human Cleric', [ + staticAbility([staticPump(each(dragons), 1, 1)]), +]) +``` + +### Abilities + +| Call | Meaning | +| ---- | ------- | +| `keyword(name, value)` | One keyword, optionally parameterized | +| `keywords(...names)` | Several keywords from one oracle line | +| `triggered(event, effects, options)` | `When`/`Whenever`/`At` ability | +| `activated(costs, effects, options)` | Cost `:` effect, including loyalty | +| `staticAbility(effects, options)` | Continuous effect or restriction | +| `spell(effects, options)` | Effect line of an instant or sorcery | +| `additionalCost(costs, options)` | Additional cost | +| `alternativeCost(costs, options)` | Alternative cast, possibly free | +| `overload(cost)` | Overload alternate cost | +| `chapter(chapters, effects, options)` | Saga chapter ability | +| `levelBand(min, max, power, toughness)` | Level band | +| `levelPt(power, toughness)` | Level P/T line | +| `unsupported(reason, text)` | Preserved text plus a reason | + +`options` accepts `condition` and `optional`; activated abilities also accept +`timing: 'sorcery'` and `activationsPerTurn`. + +### Selectors and targets + +Selectors start from `permanents`, `cards` or `creatures` and chain filters: + +```js +permanents.withType('creature').withSubtype('dragon').withColor('red') + .other().tapped().youControl().powerAtLeast(4) +``` + +Available filters include `withType`, `withSubtype`, `withSupertype`, +`withColor`, `withKeyword`, `withoutKeyword`, `withoutType`, `other`, `tapped`, +`untapped`, `attacking`, `token`, `nontoken`, `equipped`, `enchanted`, +`youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`, +`inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`, +`toughnessAtLeast`/`toughnessAtMost`, `manaValueAtLeast`/`manaValueAtMost` +and `matchingAny`. + +Targets wrap a selector or player: + +```js +target(permanents.withType('creature')) +each(creatures.withColor('red')) +pick(cards.withType('land'), { upTo: 2 }) +divided(3, creatures.attacking()) +targetSpell(permanents.withType('instant')) +targetAbility() +``` + +Fixed targets are `self`, `triggerSubject`, `previousTarget`, `anyTarget` and +`targetPlayerOrPlaneswalker`. Players are `you`, `opponent`, `eachOpponent`, +`eachPlayer`, `targetPlayer`, `thatPlayer`, `itsController` and `itsOwner`. + +Values are numbers, `X`, `itsPower`, `itsToughness`, `count(selector)`, +`cardsInHand(player)`, `maxCardsInHand()`, `maxOpponentCount(selector)`, +`totalManaValue(selector)`, `totalPower(selector)`, `anyNumber()` and +`eventAmount()`. + +### Effects, costs and statics + +Effects are camelCase builders, one array entry or callback statement each: + +```js +damage(target(permanents.withType('creature')), 3) +draw(you, 2) +gainLife(you, 1) +createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 })) +putCounters(target(permanents.withType('creature')), '+1/+1', 2) +destroy(target(permanents.withType('creature'))) +addMana(you, mana('{G}{G}')) +search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true }) +pump(each(creatures.youControl()), 1, 1, untilEndOfTurn) +``` + +Costs are distinct from effects: `manaCost('{2}{U}')`, `tapCost()`, +`untapCost()`, `sacrificeSelf()`, `payLife(3)`, `discardCost(1)`, +`removeCountersCost('+1/+1', 1)`, `exileSelf()`, `choice([...])` and the rest of +the cost builders in `source.ts`. + +Static effects are also distinct, so their AST shape is unambiguous: +`staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`, +`entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`, +`costReduction`, `costIncrease`, `searchRestriction` and +`exileInsteadOfGraveyard`. `entersTapped` takes an optional `unlessCost` builder +for "you may pay N life; if you don't, it enters tapped": +`entersTapped(self, { unlessCost: payLife(2) })`. + +Durations are `permanent` (default), `untilEndOfTurn`, `untilYourNextTurn`, +`untilEndOfYourNextTurn`, `untilEndOfCombat`, +`untilControllersNextUntapStep` and `whileSourceOnBattlefield`. + +Triggers live under `when`: `when.enters`, `when.dies`, `when.attacks`, +`when.blocks`, `when.attacksOrBlocks`, `when.entersOrAttacks`, +`when.entersOrDies`, `when.leavesBattlefield`, `when.dealsDamage`, +`when.upkeep`, `when.endStep`, `when.beginCombat`, `when.firstMainPhase`, +`when.postcombatMainPhase`, `when.cast`, `when.becomesLevel`, `when.draw`, +`when.counterPlaced`, `when.becomesTarget`, `when.lifeGained` and +`when.lifeLost`. + +Conditions are top-level calls such as `yourTurn()`, `youControl(selector, n)`, +`opponentControls(selector)`, `lifeAtLeast(player, n)`, `wasKicked()`, +`ifYouDo()`, `ifYouDont()` and `otherwise()`. The full list is the set of +condition builders in `source.ts`. + +Nested structures are effect lists (array or callback) or `ifThen`/`modal`: + +```js +triggered(when.upkeep(you), [ + ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]), +]) + +spell([ + modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]]), +]) +``` ## Manual implementations The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a -card, edit its pseudocode, and save. The editor toggles between the text view and a -node canvas where sockets are wired to define effect order and nested bodies; both -edit the same source. The API validates the source before writing it, so a typo -never replaces a working file. Overrides take precedence during +card, edit its source, and save. The API validates the source before writing it, +so a typo never replaces a working file. Overrides take precedence during `npm run compile:cards`; invalid override files stop the compile with the line number. @@ -100,7 +260,7 @@ number. | `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag | | `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` | | `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output | -| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text | +| `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for card source from the card's oracle text | | `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent | | `GET` | `/stats` | Supported, partial, unsupported, and manual counts | @@ -110,21 +270,20 @@ number. The editor's **Draft with AI** button calls `POST /cards/:oracleId/translate`. The backend sends the card's oracle text to -an [OpenRouter](https://openrouter.ai/) model and returns pseudocode, without +an [OpenRouter](https://openrouter.ai/) model and returns card source, without saving it. The response is parsed before it reaches the browser, so prose or a non-parseable guess is reported as an error instead of replacing the editor. Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. -The system prompt contains the syntax reference and a strict output contract: -pseudocode only, no explanations, Markdown, code fences or card header, and no -invented operations. Output is capped at 700 tokens. A fenced answer is +The system prompt contains the source reference and a strict output contract: +card source only, no explanations, Markdown, code fences or card header, and no +invented operations. Output is capped at 1,200 tokens. A fenced answer is unwrapped defensively, but an invalid answer is not retried (that would spend more tokens). The translator uses the default model only; there is no per-request model picker. - ## AST The types live in `src/effects/types.ts`. A card contains one or more abilities: @@ -133,6 +292,7 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities: { "oracle_id": "...", "name": "Soul Warden", + "typeLine": "Creature — Human Cleric", "status": "supported", "abilities": [ { @@ -239,7 +399,7 @@ ambiguous pronouns stay unsupported. ## Adding support -For a single card, open the frontend editor, edit the pseudocode, and save; no +For a single card, open the frontend editor, edit the source, and save; no compiler change is needed. For a whole class of cards: 1. Run `npm run compile:cards` and pick a frequent unsupported pattern. diff --git a/backend/docs/game-engine.md b/backend/docs/game-engine.md index 7e46257..eb14bcc 100644 --- a/backend/docs/game-engine.md +++ b/backend/docs/game-engine.md @@ -18,6 +18,7 @@ const game = new Game({ startingLife: 40, startingHandSize: 7, commander: true, + mulligans: true, players: [ { id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 }, { id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 }, @@ -32,7 +33,9 @@ in `commander.ts` checks size, singleton, color identity, and the commander type `catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds intrinsic mana abilities for basic lands, because Scryfall's oracle text only has -reminder text for them and the compiler produces no ability. +reminder text for them and the compiler produces no ability. When a compiled card +declares a `typeLine`, that value is used instead of Scryfall's; the generated +card source carries the type line and an override can change it. For tests or hand-authored cards, build a `CardDefinition` yourself: @@ -56,7 +59,10 @@ const bolt: CardDefinition = { | Method | Purpose | | ------ | ------- | -| `start()` | Shuffles libraries, draws opening hands, begins turn 1. | +| `start()` | Shuffles libraries and draws opening hands. With `mulligans: true`, turn 1 waits until every player keeps. | +| `keepHand(playerId)` | Keeps the opening hand; begins turn 1 once every living player has kept. | +| `mulligan(playerId)` | Shuffles the hand back, draws a new opening hand, and queues bottom-of-library choices (one more each time). | +| `putOnBottom(playerId, cardId)` | Puts one chosen card from a mulliganed opening hand on the bottom of its owner's library. | | `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. | | `castSpell(playerId, cardId, { targets, x, mode, overload })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone, adds commander tax, and can pay the overload cost instead. | | `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. | @@ -87,6 +93,10 @@ the permanent, and the match API refuses other priority actions until `chooseCre (the `choose_type` action) receives one of the creature types in `CREATURE_TYPES`. The chosen type is stored on the object and cleared when it leaves the battlefield. +With mulligans enabled, the game starts in the `mulligan` status. A mulligan shuffles +the hand back and draws seven; the second mulligan puts one card on the bottom, the +third two, and so on (London rule). Turn 1 begins when every living player has kept. + ## Turn structure ```text @@ -132,8 +142,8 @@ shown to players who can actually do something. lifelink, vigilance, haste, indestructible. Regeneration shields replace destruction. - State-based actions: life at or below zero, ten poison counters, 21 commander - damage from one commander, lethal or deathtouch damage, zero toughness, and - drawing from an empty library. + damage from one commander, lethal or deathtouch damage, zero toughness, the + legend rule, and drawing from an empty library. ## Known limitations @@ -144,11 +154,13 @@ shown to players who can actually do something. - Commander support covers single commanders. Partner, backgrounds, companions, and "choose a commander" variants are not modelled. The engine always takes the command-zone replacement instead of asking. -- The legend rule, planeswalker loyalty abilities, attacking planeswalkers, and +- Planeswalker loyalty abilities, attacking planeswalkers, and protection/menace/defender are not implemented unless expressed as a compiled - restriction. + restriction. When the legend rule applies, the engine keeps the first copy it + finds and moves the rest to the graveyard instead of asking the controller. - Modal spells choose a mode by index (`options.mode`); optional "you may" choices - are not modelled. An optional `pay` is simply not paid when unaffordable. Search + are not modelled, except "pay a cost or enter tapped" which pauses for the + controller. An optional `pay` is simply not paid when unaffordable. Search effects with several matching cards do pause for the player's pick. - "As this enters, choose a creature type" pauses for a pick and stores the type on the permanent, but no effect reads the chosen type yet. The other `choose` kinds @@ -160,7 +172,9 @@ shown to players who can actually do something. - Overload widens only top-level effect targets; a nested modal or conditional target keeps its printed target. Free alternative costs are modelled only for controlling a commander, and search restrictions cap the searching player's own library. -- Opening hands are kept automatically; there is no mulligan flow. +- Opening hands use the London mulligan when `mulligans` is enabled: each mulligan + draws seven, then puts one more card on the bottom than the previous one. The + match API starts with mulligans on. - Replacement/prevention effects, layers, and dependency ordering are simplified. Continuous effects apply in creation order rather than in full rules order. - The engine is synchronous and exposes full state. `rooms.ts` owns the in-memory diff --git a/backend/scripts/compile-cards.ts b/backend/scripts/compile-cards.ts index 769574f..320b083 100644 --- a/backend/scripts/compile-cards.ts +++ b/backend/scripts/compile-cards.ts @@ -4,13 +4,13 @@ import type { Card } from '../src/cards.js' import { compileCard } from '../src/effects/compile.js' import { formatCard } from '../src/effects/format.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' const DATA_DIR = join(process.cwd(), 'data') const CARDS_FILE = join(DATA_DIR, 'cards.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 { return `${(bytes / 1024 / 1024).toFixed(1)} MB` @@ -55,7 +55,7 @@ for (const card of cards) { try { result = source === undefined ? compileCard(card) : compileImplementation(card, source) } catch (error) { - if (error instanceof PseudoParseError) { + if (error instanceof SourceParseError) { console.error(`Invalid manual implementation for ${card.name} (${card.oracle_id}):`) console.error(` ${error.message}`) process.exit(1) @@ -80,9 +80,9 @@ for (const card of cards) { await mkdir(DATA_DIR, { recursive: true }) 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(PSEUDO_FILE, pseudoOutput) +await writeFile(SOURCE_FILE, sourceOutput) console.log(`Compiled ${compiled.length} cards (${manualCount} with manual implementations).`) console.log( @@ -100,4 +100,4 @@ if (samples.length) { for (const sample of samples) console.log(` - ${sample}`) } 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}`) diff --git a/backend/src/effects/compile.ts b/backend/src/effects/compile.ts index c91128e..2372ec4 100644 --- a/backend/src/effects/compile.ts +++ b/backend/src/effects/compile.ts @@ -997,7 +997,13 @@ function parseEffect(text: string): Effect | Effect[] | undefined { match = sentence.match(/^add ((?:\{[^}]+\})(?:,? ?(?:or )?\{[^}]+\})*)$/) if (match) { const symbols = match[1].match(/\{[^}]+\}/g) - if (symbols) return { op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols } } + if (symbols) { + return { + op: 'add_mana', + player: 'you', + mana: { kind: 'symbols', symbols, ...(/\bor\b/i.test(match[1]) ? { oneOf: true } : {}) }, + } + } } match = sentence.match(/^add (one|two|three|four|five|x) mana of any (one )?color( in your commander's color identity)?$/) @@ -2068,6 +2074,11 @@ function parseStaticEffects(text: string): StaticEffect[] | undefined { if (sentence === 'this enters tapped') { return [{ op: 'enters_tapped', target: { kind: 'self' } }] } + match = sentence.match(/^as this enters, you may pay (\w+) life\. if you don't, it enters tapped$/) + if (match) { + const amount = parseValue(match[1]) + if (amount) return [{ op: 'enters_tapped', target: { kind: 'self' }, unlessCost: { kind: 'pay_life', amount } }] + } const entersTappedUnless = sentence.match(/^this enters tapped unless (.+)$/) if (entersTappedUnless) { const unless = parseCondition(entersTappedUnless[1]) @@ -2475,7 +2486,7 @@ function compileFace(face: CardFace | { name: string; oracle_text?: string; type const ability = compileLine(line, face.name, known, isSpell) if (!(ability.kind === 'unsupported' && ability.reason === 'empty')) abilities.push(ability) } - return { name: face.name, status: statusOf(abilities), abilities } + return { name: face.name, typeLine: face.type_line, status: statusOf(abilities), abilities } } export function compileCard(card: Card): CompiledCard { @@ -2485,7 +2496,7 @@ export function compileCard(card: Card): CompiledCard { const status: Status = statuses.includes('unsupported') ? statuses.every(value => value === 'unsupported') ? 'unsupported' : 'partial' : statuses.includes('partial') ? 'partial' : 'supported' - return { oracle_id: card.oracle_id, name: card.name, status, abilities: [], faces } + return { oracle_id: card.oracle_id, name: card.name, typeLine: card.type_line, status, abilities: [], faces } } const face = compileFace( @@ -2495,6 +2506,7 @@ export function compileCard(card: Card): CompiledCard { return { oracle_id: card.oracle_id, name: card.name, + typeLine: card.type_line, status: face.status, abilities: face.abilities, } diff --git a/backend/src/effects/format.ts b/backend/src/effects/format.ts index 69a5131..bc7ab82 100644 --- a/backend/src/effects/format.ts +++ b/backend/src/effects/format.ts @@ -7,6 +7,7 @@ import type { Effect, ManaSpec, ObjectSelector, + PlayerRef, StaticEffect, Target, TokenSpec, @@ -16,6 +17,61 @@ import type { const COLOR_NAMES: Record = { W: 'white', U: 'blue', B: 'black', R: 'red', G: 'green', C: 'colorless' } +const PLAYER_NAMES: Record = { + you: 'you', + opponent: 'opponent', + each_opponent: 'eachOpponent', + each_player: 'eachPlayer', + target_player: 'targetPlayer', + that_player: 'thatPlayer', + its_controller: 'itsController', + its_owner: 'itsOwner', +} + +const DURATION_NAMES: Record = { + permanent: 'permanent', + until_end_of_turn: 'untilEndOfTurn', + until_your_next_turn: 'untilYourNextTurn', + until_end_of_your_next_turn: 'untilEndOfYourNextTurn', + until_end_of_combat: 'untilEndOfCombat', + until_controllers_next_untap_step: 'untilControllersNextUntapStep', + while_source_on_battlefield: 'whileSourceOnBattlefield', +} + +function quote(text: string): string { + return `'${text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n').replace(/\r/g, '\\r')}'` +} + +function indent(text: string, spaces = 2): string { + const pad = ' '.repeat(spaces) + return text.split('\n').map(line => `${pad}${line}`).join('\n') +} + +function list(items: string[]): string { + if (!items.length) return '[]' + return `[\n${items.map(item => indent(item)).join(',\n')},\n]` +} + +function callback(items: string[]): string { + if (!items.length) return '() => {}' + if (items.length === 1) return `() => ${items[0]}` + return `() => {\n${items.map(item => indent(item)).join('\n')}\n}` +} + +function options(entries: Array<[string, string | undefined]>): string | undefined { + const parts = entries.filter(([, value]) => value !== undefined).map(([key, value]) => `${key}: ${value}`) + return parts.length ? `{ ${parts.join(', ')} }` : undefined +} + +function optionArg(entries: Array<[string, string | undefined]>): string { + const value = options(entries) + return value ? `, ${value}` : '' +} + +function formatPlayer(player: PlayerRef): string { + return PLAYER_NAMES[player] +} + function formatValue(value: Value): string { switch (value.kind) { case 'number': @@ -25,608 +81,640 @@ function formatValue(value: Value): string { case 'count': return `count(${formatSelector(value.selector)})` case 'source_power': - return 'its power' + return 'itsPower' case 'source_toughness': - return 'its toughness' + return 'itsToughness' case 'cards_in_hand': - return `cards in ${value.player === 'you' ? 'your' : "that player's"} hand` + return `cardsInHand(${formatPlayer(value.player)})` case 'max_cards_in_hand': - return 'cards in the hand of the opponent with the most cards' + return 'maxCardsInHand()' case 'max_opponent_count': - return `greatest number of ${formatSelector(value.selector)} an opponent controls` + return `maxOpponentCount(${formatSelector(value.selector)})` case 'total_mana_value': - return `total mana value of ${formatSelector(value.selector)}` + return `totalManaValue(${formatSelector(value.selector)})` case 'total_power': - return `total power of ${formatSelector(value.selector)}` + return `totalPower(${formatSelector(value.selector)})` case 'any_number': - return 'any number' + return 'anyNumber()' case 'event_amount': - return 'that much' + return 'eventAmount()' } } +function formatSelector(selector: ObjectSelector): string { + let text = 'permanents' + + if (selector.other) text += '.other()' + if (selector.tapped === true) text += '.tapped()' + if (selector.tapped === false) text += '.untapped()' + if (selector.attacking) text += '.attacking()' + if (selector.token === true) text += '.token()' + if (selector.token === false) text += '.nontoken()' + if (selector.attached === 'equipped') text += '.equipped()' + if (selector.attached === 'enchanted') text += '.enchanted()' + + if (selector.colors?.length) { + text += `.withColor(${selector.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')})` + } + if (selector.supertypes?.length) { + text += `.withSupertype(${selector.supertypes.map(quote).join(', ')})` + } + if (selector.subtypes?.length) { + text += `.withSubtype(${selector.subtypes.map(quote).join(', ')})` + } + if (selector.types?.length) { + text += `.withType(${selector.types.map(quote).join(', ')})` + } + if (selector.excludeTypes?.length) { + text += `.withoutType(${selector.excludeTypes.map(quote).join(', ')})` + } + if (selector.counters) { + text += `.withCounter(${quote(selector.counters.counter)}, ${selector.counters.atLeast})` + } + if (selector.keywords?.length) { + text += `.withKeyword(${selector.keywords.map(quote).join(', ')})` + } + if (selector.excludeKeywords?.length) { + text += `.withoutKeyword(${selector.excludeKeywords.map(quote).join(', ')})` + } + if (selector.power?.atLeast !== undefined) text += `.powerAtLeast(${selector.power.atLeast})` + if (selector.power?.atMost !== undefined) text += `.powerAtMost(${selector.power.atMost})` + if (selector.toughness?.atLeast !== undefined) text += `.toughnessAtLeast(${selector.toughness.atLeast})` + if (selector.toughness?.atMost !== undefined) text += `.toughnessAtMost(${selector.toughness.atMost})` + if (selector.manaValue?.atLeast !== undefined) text += `.manaValueAtLeast(${selector.manaValue.atLeast})` + if (selector.manaValue?.atMost !== undefined) text += `.manaValueAtMost(${selector.manaValue.atMost})` + if (selector.name) text += `.named(${quote(selector.name)})` + if (selector.controller === 'you') text += '.youControl()' + else if (selector.controller === 'opponent') text += '.opponentControls()' + else if (selector.controller === 'any') text += `.controlledBy('any')` + if (selector.owner === 'you') text += `.ownedBy('you')` + else if (selector.owner === 'opponent') text += `.ownedBy('opponent')` + if (selector.zone) text += `.inZone(${quote(selector.zone)})` + if (selector.match === 'any') text += '.matchingAny()' + + return text +} + function isBareSelector(selector: ObjectSelector): boolean { return selector.types?.length === 0 && Object.keys(selector).every(key => key === 'types') } -function formatSelector(selector: ObjectSelector): string { - const parts: string[] = [] - if (selector.other) parts.push('other') - if (selector.tapped === true) parts.push('tapped') - if (selector.tapped === false) parts.push('untapped') - if (selector.attacking) parts.push('attacking') - if (selector.token) parts.push('token') - if (selector.token === false) parts.push('nontoken') - if (selector.attached) parts.push(selector.attached) - const joiner = selector.match === 'any' ? ' or ' : ' and ' - if (selector.colors?.length) { - parts.push(selector.colors.map(color => COLOR_NAMES[color] ?? color).join(joiner)) - } - if (selector.supertypes?.length) parts.push(selector.supertypes.join(joiner)) - if (selector.subtypes?.length) parts.push(selector.subtypes.join(joiner)) - if (selector.types?.length) { - parts.push(selector.types.join(selector.match === 'any' ? ' or ' : ' ')) - } - if (selector.excludeTypes?.length) parts.push(`non-${selector.excludeTypes.join('/')}`) - if (selector.counters) parts.push(`with ${selector.counters.atLeast}+ ${selector.counters.counter} counters`) - if (selector.keywords?.length) parts.push(`with ${selector.keywords.join(' and ')}`) - if (selector.excludeKeywords?.length) parts.push(`without ${selector.excludeKeywords.join(' and ')}`) - if (selector.power?.atLeast !== undefined) parts.push(`power ${selector.power.atLeast}+`) - if (selector.power?.atMost !== undefined) parts.push(`power ${selector.power.atMost} or less`) - if (selector.toughness?.atLeast !== undefined) parts.push(`toughness ${selector.toughness.atLeast}+`) - if (selector.toughness?.atMost !== undefined) parts.push(`toughness ${selector.toughness.atMost} or less`) - if (selector.manaValue?.atLeast !== undefined) parts.push(`mana value ${selector.manaValue.atLeast}+`) - if (selector.manaValue?.atMost !== undefined) parts.push(`mana value ${selector.manaValue.atMost} or less`) - if (selector.name) parts.push(`named ${selector.name}`) - - let text = parts.filter(Boolean).join(' ') - if (selector.controller === 'you') text += ' you control' - else if (selector.controller === 'opponent') text += ' an opponent controls' - if (selector.owner === 'you') text += ' you own' - else if (selector.owner === 'opponent') text += " you don't own" - - if (!text) text = 'card' - - if (selector.zone === 'graveyard') text += ' from a graveyard' - else if (selector.zone === 'library') text += ' from a library' - else if (selector.zone === 'hand') text += ' from a hand' - else if (selector.zone === 'exile') text += ' in exile' - - return text +function formatTargetOptions(target: Extract): string { + return optionArg([ + ['count', target.count !== undefined ? String(target.count) : undefined], + ['upTo', target.upTo ? 'true' : undefined], + ['includeSelf', target.includeSelf ? 'true' : undefined], + ]).replace(/^, /, '') } export function formatTarget(target: Target): string { switch (target.kind) { case 'self': - return 'this' + return 'self' case 'trigger_subject': - return 'the triggering object' + return 'triggerSubject' case 'previous_target': - return 'the chosen target' + return 'previousTarget' case 'any': - return 'any target' - case 'player': - if (target.mode === 'each') { - if (target.who === 'each_opponent') return 'each opponent' - if (target.who === 'each_player') return 'each player' - } - if (target.who === 'you') return 'you' - if (target.who === 'target_player') return 'target player' - if (target.who === 'that_player') return 'that player' - if (target.who === 'opponent') return 'target opponent' - if (target.who === 'its_controller') return 'its controller' - if (target.who === 'its_owner') return 'its owner' - return target.who + return 'anyTarget' case 'player_or_planeswalker': - return 'target player or planeswalker' + return 'targetPlayerOrPlaneswalker' + case 'player': + return target.mode === 'each' + ? `each(${formatPlayer(target.who)})` + : `target(${formatPlayer(target.who)})` case 'object': { - const prefix = target.mode === 'target' ? 'target ' : target.mode === 'each' ? 'each ' : '' - const count = target.count ? `${target.upTo ? 'up to ' : ''}${target.count} ` : '' - const includeSelf = target.includeSelf ? 'this or ' : '' - return `${prefix}${count}${includeSelf}${formatSelector(target.selector)}` + const name = target.mode === 'target' ? 'target' : target.mode === 'each' ? 'each' : 'pick' + const extra = formatTargetOptions(target) + return `${name}(${formatSelector(target.selector)}${extra ? `, ${extra}` : ''})` } case 'spell': - return isBareSelector(target.selector) ? 'target spell' : `target ${formatSelector(target.selector)} spell` + return isBareSelector(target.selector) ? 'targetSpell()' : `targetSpell(${formatSelector(target.selector)})` case 'ability': - return 'target ability' + return target.selector ? `targetAbility(${formatSelector(target.selector)})` : 'targetAbility()' case 'divided': - return `divided(${target.max === 'any' ? 'any number' : target.max}${target.selector ? `, ${formatSelector(target.selector)}` : ''})` + return `divided(${target.max === 'any' ? quote('any') : target.max}${target.selector ? `, ${formatSelector(target.selector)}` : ''})` } } function formatMana(mana: ManaSpec): string { if (mana.kind === 'symbols') { - return `${mana.symbols.join('')}${mana.restriction ? ` (only ${mana.restriction})` : ''}` + return `mana(${quote(mana.symbols.join(''))}${optionArg([ + ['oneOf', mana.oneOf ? 'true' : undefined], + ['restriction', mana.restriction ? quote(mana.restriction) : undefined], + ])})` } - return `${formatValue(mana.amount)} mana of any${mana.oneColor ? ' one' : ''} color${mana.restriction ? ` (only ${mana.restriction})` : ''}` + return `anyColor(${formatValue(mana.amount)}${optionArg([ + ['oneColor', mana.oneColor ? 'true' : undefined], + ['restriction', mana.restriction ? quote(mana.restriction) : undefined], + ])})` } function formatCost(cost: Cost): string { switch (cost.kind) { case 'mana': - return cost.symbols + return `manaCost(${quote(cost.symbols)})` case 'tap': - return '{T}' + return 'tapCost()' case 'untap': - return '{Q}' + return 'untapCost()' case 'tap_other': - return `tap ${formatSelector(cost.selector)}` + return `tapOther(${formatSelector(cost.selector)})` case 'energy': - return `{E} x${cost.amount}` + return `energyCost(${cost.amount})` case 'loyalty': - return `${cost.amount > 0 ? '+' : ''}${cost.amount} loyalty` + return `loyalty(${cost.amount})` case 'pay_life': - return `pay ${formatValue(cost.amount)} life` + return `payLife(${formatValue(cost.amount)})` case 'discard': - if (cost.amount.kind === 'cards_in_hand' && cost.amount.player === 'you') { - return `discard your hand${cost.random ? ' at random' : ''}` - } - return `discard ${formatValue(cost.amount)} card(s)${cost.random ? ' at random' : ''}` + return `discardCost(${formatValue(cost.amount)}${optionArg([ + ['player', cost.player === 'you' ? undefined : formatPlayer(cost.player)], + ['random', cost.random ? 'true' : undefined], + ])})` case 'sacrifice': - return `sacrifice ${formatSelector(cost.selector)}` + return `sacrificeCost(${formatSelector(cost.selector)})` case 'sacrifice_self': - return 'sacrifice this' + return 'sacrificeSelf()' case 'exile_self': - return 'exile this from a graveyard' + return 'exileSelf()' case 'exile_from_graveyard': - return `exile ${cost.amount ? `${formatValue(cost.amount)} ` : ''}${formatSelector(cost.selector)} from your graveyard` + return `exileFromGraveyard(${formatSelector(cost.selector)}${cost.amount ? `, ${formatValue(cost.amount)}` : ''})` case 'reveal': - return `reveal ${formatSelector(cost.selector)} from your hand` + return `reveal(${formatSelector(cost.selector)})` case 'choice': - return `(${cost.options.map(option => option.map(formatCost).join(' + ')).join(' or ')})` + return `choice([${cost.options.map(option => `[${option.map(formatCost).join(', ')}]`).join(', ')}])` case 'return_to_hand': - return `return ${formatSelector(cost.selector)} to its owner's hand` + return `returnToHandCost(${formatSelector(cost.selector)})` case 'behold': - return `behold ${formatSelector(cost.selector)}` + return `behold(${formatSelector(cost.selector)})` case 'waterbend': - return `waterbend ${formatValue(cost.amount)}` + return `waterbend(${formatValue(cost.amount)})` case 'blight': - return `blight ${formatValue(cost.amount)}` + return `blight(${formatValue(cost.amount)})` case 'choose': - return `choose ${cost.what}` + return `chooseCost(${quote(cost.what)})` case 'put_counter': - return `put ${cost.counter} counter on ${formatSelector(cost.selector)}` + return `putCounterCost(${quote(cost.counter)}, ${formatSelector(cost.selector)})` case 'remove_counters': - return `remove ${formatValue(cost.amount)} ${cost.counter} counter(s) from ${cost.selector ? formatSelector(cost.selector) : 'this'}` + return `removeCountersCost(${quote(cost.counter)}, ${formatValue(cost.amount)}${cost.selector ? `, ${formatSelector(cost.selector)}` : ''})` case 'forage': - return 'forage' + return 'forage()' case 'collect_evidence': - return `collect evidence ${cost.amount}` + return `collectEvidence(${cost.amount})` case 'mill': - return `mill ${formatValue(cost.amount)} card(s)` + return `millCost(${formatValue(cost.amount)})` } } -function formatDuration(duration: Duration): string { - switch (duration) { - case 'permanent': - return '' - case 'until_end_of_turn': - return ', until end of turn' - case 'until_your_next_turn': - return ', until your next turn' - case 'until_end_of_your_next_turn': - return ', until the end of your next turn' - case 'until_end_of_combat': - return ', until end of combat' - case 'until_controllers_next_untap_step': - return ", until its controller's next untap step" - case 'while_source_on_battlefield': - return ', for as long as this remains on the battlefield' - } +function formatDuration(duration: Duration): string | undefined { + return duration === 'permanent' ? undefined : DURATION_NAMES[duration] } function formatToken(token: TokenSpec): string { - const parts: string[] = [] - if (token.tapped) parts.push('tapped') - if (token.power && token.toughness) parts.push(`${formatValue(token.power)}/${formatValue(token.toughness)}`) - if (token.colors?.length) parts.push(token.colors.map(color => COLOR_NAMES[color] ?? color).join(' and ')) - if (token.subtypes.length) parts.push(...token.subtypes) - if (token.types.length) parts.push(...token.types) - if (token.keywords?.length) parts.push(`with ${token.keywords.join(', ')}`) - return parts.join(' ') + return `token(${options([ + ['name', token.name ? quote(token.name) : undefined], + ['types', token.types.length ? `[${token.types.map(quote).join(', ')}]` : undefined], + ['subtypes', token.subtypes.length ? `[${token.subtypes.map(quote).join(', ')}]` : undefined], + ['colors', token.colors.length ? `[${token.colors.map(color => quote(COLOR_NAMES[color] ?? color)).join(', ')}]` : undefined], + ['power', token.power ? formatValue(token.power) : undefined], + ['toughness', token.toughness ? formatValue(token.toughness) : undefined], + ['keywords', token.keywords?.length ? `[${token.keywords.map(quote).join(', ')}]` : undefined], + ['tapped', token.tapped ? 'true' : undefined], + ])})` +} + +function formatEffectList(effects: Effect[]): string { + return callback(effects.map(formatEffect)) } export function formatEffect(effect: Effect): string { switch (effect.op) { case 'damage': - return `damage(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.source ? `, from ${formatTarget(effect.source)}` : ''})` + return `damage(${formatTarget(effect.target)}, ${formatValue(effect.amount)}${effect.source ? `, ${formatTarget(effect.source)}` : ''})` case 'draw': - return `draw(${effect.player}, ${formatValue(effect.amount)})` + return `draw(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'discard': - return `discard(${effect.player}, ${formatValue(effect.amount)}${effect.random ? ', at random' : ''})` + return `discard(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([['random', effect.random ? 'true' : undefined]])})` case 'mill': - return `mill(${effect.player}, ${formatValue(effect.amount)})` + return `mill(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'life': - return `${effect.mode === 'gain' ? 'gain_life' : 'lose_life'}(${effect.player}, ${formatValue(effect.amount)})` + return `${effect.mode === 'gain' ? 'gainLife' : 'loseLife'}(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'pump': - return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})` + return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'grant': - return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''}${formatDuration(effect.duration)})` + return `grant(${formatTarget(effect.target)}, ${quote(effect.keyword)}${optionArg([ + ['value', effect.value ? quote(effect.value) : undefined], + ['duration', formatDuration(effect.duration)], + ])})` case 'put_counters': - return `put_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})` + return `putCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'remove_counters': - return `remove_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})` + return `removeCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'proliferate': return 'proliferate()' case 'create_token': return effect.copyOf - ? `create_token(${effect.player}, ${formatValue(effect.amount)}, copy of ${formatTarget(effect.copyOf)}${effect.notLegendary ? ', not legendary' : ''})` - : `create_token(${effect.player}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})` + ? `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, copyOf(${formatTarget(effect.copyOf)}${effect.notLegendary ? ', { notLegendary: true }' : ''}))` + : `createToken(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}, ${formatToken(effect.token)})` case 'destroy': return `destroy(${formatTarget(effect.target)})` case 'exile': return `exile(${formatTarget(effect.target)})` case 'sacrifice': - return `sacrifice(${effect.player}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})` + return `sacrifice(${formatPlayer(effect.player)}, ${formatTarget(effect.target)}${effect.unless ? `, ${formatCost(effect.unless)}` : ''})` case 'counter': - return `counter(${effect.what}, ${formatTarget(effect.target)}${effect.unless ? ` unless ${formatCost(effect.unless)}` : ''})` + return `counter(${quote(effect.what)}, ${formatTarget(effect.target)}${effect.unless ? `, ${formatCost(effect.unless)}` : ''})` case 'return_to_hand': - return `return_to_hand(${formatTarget(effect.target)})` - case 'return_to_battlefield': { - const counters = effect.counters - ? `, ${effect.counters.amount.kind === 'number' ? effect.counters.amount.value : formatValue(effect.counters.amount)} ${effect.counters.counter} counters` - : '' - return `return_to_battlefield(${formatTarget(effect.target)}${effect.tapped ? ', tapped' : ''}${effect.transformed ? ', transformed' : ''}${counters})` - } + return `returnToHand(${formatTarget(effect.target)})` + case 'return_to_battlefield': + return `returnToBattlefield(${formatTarget(effect.target)}${optionArg([ + ['tapped', effect.tapped ? 'true' : undefined], + ['transformed', effect.transformed ? 'true' : undefined], + ['counters', effect.counters ? `{ counter: ${quote(effect.counters.counter)}, amount: ${formatValue(effect.counters.amount)} }` : undefined], + ])})` case 'set_pt': - return `set_pt(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)}${formatDuration(effect.duration)})` + return `setPt(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)}${optionArg([['duration', formatDuration(effect.duration)]])})` case 'put_on_top': - return `put_on_top(${formatTarget(effect.target)})` + return `putOnTop(${formatTarget(effect.target)})` case 'tap': return `tap(${formatTarget(effect.target)})` case 'untap': return `untap(${formatTarget(effect.target)})` case 'scry': - return `scry(${effect.player}, ${formatValue(effect.amount)})` + return `scry(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'surveil': - return `surveil(${effect.player}, ${formatValue(effect.amount)})` + return `surveil(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'search': - return `search(${effect.player}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}, to ${effect.destination}${effect.zones?.length === 2 ? ', library+graveyard' : ''}${effect.tapped ? ', tapped' : ''}${effect.split ? `, then ${effect.split.destination}${effect.split.tapped ? ' tapped' : ''}` : ''}${effect.shuffle ? ', shuffle' : ''})` + return `search(${formatPlayer(effect.player)}, ${formatSelector(effect.selector)}, ${formatValue(effect.amount)}${optionArg([ + ['destination', quote(effect.destination)], + ['tapped', effect.tapped ? 'true' : undefined], + ['shuffle', effect.shuffle ? 'true' : undefined], + ['zones', effect.zones?.length ? `[${effect.zones.map(quote).join(', ')}]` : undefined], + ['split', effect.split ? `{ destination: ${quote(effect.split.destination)}, tapped: ${effect.split.tapped ? 'true' : 'false'} }` : undefined], + ])})` case 'shuffle': - return `shuffle(${effect.player})` + return `shuffle(${formatPlayer(effect.player)})` case 'add_mana': - return `add_mana(${effect.player}, ${formatMana(effect.mana)})` + return `addMana(${formatPlayer(effect.player)}, ${formatMana(effect.mana)})` case 'fight': return `fight(${formatTarget(effect.a)}, ${formatTarget(effect.b)})` case 'regenerate': return `regenerate(${formatTarget(effect.target)})` case 'energy': - return `energy(${effect.player}, ${formatValue(effect.amount)})` + return `energy(${formatPlayer(effect.player)}, ${formatValue(effect.amount)})` case 'attach': - return `attach(this, ${formatTarget(effect.target)})` + return `attach(${formatTarget(effect.target)})` case 'restriction': - return `restrict(${formatTarget(effect.target)}, ${effect.rule}${formatDuration(effect.duration)})` + return `restrict(${formatTarget(effect.target)}, ${quote(effect.rule)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'keyword_action': - return `${effect.action.replace(/ /g, '_')}(${effect.target ? formatTarget(effect.target) : ''}${effect.amount ? `${effect.target ? ', ' : ''}${formatValue(effect.amount)}` : ''}${effect.detail ? `, ${effect.detail}` : ''})` - case 'level_up': - return `level_up(${effect.level})` - case 'put_from_among': - return `put_from_among(${formatValue(effect.amount)}${effect.selector ? `, ${formatSelector(effect.selector)}` : ''}, to ${effect.destination})` - case 'dig': - return `dig(${formatValue(effect.amount)}, ${effect.upTo ? 'up to ' : ''}${formatValue(effect.pick)}${effect.pickSelector ? ` ${formatSelector(effect.pickSelector)}` : ''} to ${effect.to}${effect.tapped ? ' tapped' : ''}, rest ${effect.rest}${effect.order ? ` ${effect.order}` : ''}${effect.optional ? ', optional' : ''})` + return `keywordAction(${quote(effect.action)}${optionArg([ + ['target', effect.target ? formatTarget(effect.target) : undefined], + ['amount', effect.amount ? formatValue(effect.amount) : undefined], + ['detail', effect.detail ? quote(effect.detail) : undefined], + ])})` case 'prevent_damage': - return `prevent_${effect.combatOnly ? 'combat_' : ''}damage(${formatTarget(effect.target)}, ${effect.amount === 'all' ? 'all' : formatValue(effect.amount)}${formatDuration(effect.duration)})` + return `preventDamage(${formatTarget(effect.target)}, ${effect.amount === 'all' ? quote('all') : formatValue(effect.amount)}${optionArg([ + ['combatOnly', effect.combatOnly ? 'true' : undefined], + ['duration', formatDuration(effect.duration)], + ])})` case 'gain_control': - return `gain_control(${formatTarget(effect.target)}${formatDuration(effect.duration)})` + return `gainControl(${formatTarget(effect.target)}${formatDuration(effect.duration) ? `, ${formatDuration(effect.duration)}` : ''})` case 'emblem': - return `emblem("${effect.text}")` + return `emblem(${quote(effect.text)})` case 'transform': return `transform(${formatTarget(effect.target)})` case 'pay': - return `pay(${effect.costs.map(formatCost).join(', ')})` + return `pay([${effect.costs.map(formatCost).join(', ')}])` case 'conditional': - return `if ${formatCondition(effect.condition)}:\n${indent(effect.effects.map(formatEffect).join('\n'))}` - case 'modal': { - const choose = effect.min === effect.max ? String(effect.min) : `${effect.min}-${effect.max}` - const body = effect.modes - .map((mode, index) => `${index + 1}. ${mode.map(formatEffect).join('; ')}`) - .join('\n') - return `choose ${choose}:\n${indent(body)}` - } + return `ifThen(${formatCondition(effect.condition)}, ${formatEffectList(effect.effects)})` + case 'modal': + return `modal(${effect.min}, ${effect.max}, ${list(effect.modes.map(mode => formatEffectList(mode)))})` case 'look_top': - return `look_top(${effect.player}, ${formatValue(effect.amount)}${effect.reorder ? ', reorder' : ''})` + return `lookTop(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([['reorder', effect.reorder ? 'true' : undefined]])})` case 'schedule': - return `schedule(${effect.when}):\n${indent(effect.effects.map(formatEffect).join('\n'))}` + return `schedule(${quote(effect.when)}, ${formatEffectList(effect.effects)})` + case 'level_up': + return `levelUp(${effect.level})` + case 'put_from_among': + return `putFromAmong(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([ + ['selector', effect.selector ? formatSelector(effect.selector) : undefined], + ['destination', quote(effect.destination)], + ])})` + case 'dig': + return `dig(${formatPlayer(effect.player)}, ${formatValue(effect.amount)}${optionArg([ + ['pick', formatValue(effect.pick)], + ['upTo', effect.upTo ? 'true' : undefined], + ['pickSelector', effect.pickSelector ? formatSelector(effect.pickSelector) : undefined], + ['to', quote(effect.to)], + ['rest', quote(effect.rest)], + ['order', effect.order ? quote(effect.order) : undefined], + ['optional', effect.optional ? 'true' : undefined], + ['tapped', effect.tapped ? 'true' : undefined], + ])})` case 'damage_divided': - return `damage_divided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})` + return `damageDivided(${formatValue(effect.amount)}, ${formatTarget(effect.target)})` case 'exile_graveyards': - return 'exile_graveyards()' + return 'exileGraveyards()' case 'hideaway': return `hideaway(${formatValue(effect.amount)})` case 'play_exiled': - return `play_exiled(${effect.player}${effect.free ? ', free' : ''})` + return `playExiled(${formatPlayer(effect.player)}${optionArg([['free', effect.free ? 'true' : undefined]])})` } } function formatCondition(condition: Condition): string { switch (condition.kind) { case 'you_control': - return `you control ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}${formatSelector(condition.selector)}` + return `youControl(${formatSelector(condition.selector)}${condition.atLeast !== undefined ? `, ${condition.atLeast}` : ''})` case 'opponent_controls': - return `an opponent controls ${formatSelector(condition.selector)}` + return `opponentControls(${formatSelector(condition.selector)}${condition.atLeast !== undefined ? `, ${condition.atLeast}` : ''})` case 'your_turn': - return 'it is your turn' + return 'yourTurn()' case 'not_your_turn': - return "it isn't your turn" + return 'notYourTurn()' case 'source_tapped': - return 'this is tapped' - case 'life_at_least': - return `${condition.player} has at least ${condition.amount} life` - case 'life_at_most': - return `${condition.player} has at most ${condition.amount} life` - case 'cards_in_graveyard': - return `${condition.player} has ${condition.atLeast}+ cards in their graveyard` + return 'sourceTapped()' case 'source_untapped': - return 'this is untapped' + return 'sourceUntapped()' case 'source_attacking': - return 'this is attacking' + return 'sourceAttacking()' + case 'life_at_least': + return `lifeAtLeast(${formatPlayer(condition.player)}, ${condition.amount})` + case 'life_at_most': + return `lifeAtMost(${formatPlayer(condition.player)}, ${condition.amount})` case 'life_above_starting': - return `${condition.player} has at least ${condition.amount} life more than their starting life total` + return `lifeAboveStarting(${formatPlayer(condition.player)}, ${condition.amount})` + case 'cards_in_graveyard': + return `cardsInGraveyard(${formatPlayer(condition.player)}, ${condition.atLeast})` case 'hand_empty': - return `${condition.player} has no cards in hand` + return `handEmpty(${formatPlayer(condition.player)})` case 'creature_died_this_turn': - return `${condition.controller === 'you' ? 'a creature you control' : condition.controller === 'opponent' ? 'a creature an opponent controls' : 'a creature'} died this turn` + return `creatureDiedThisTurn(${condition.controller ? quote(condition.controller) : ''})` case 'you_gained_life_this_turn': - return `you gained ${condition.atLeast ? `at least ${condition.atLeast} ` : ''}life this turn` + return `youGainedLifeThisTurn(${condition.atLeast !== undefined ? condition.atLeast : ''})` case 'you_drew_cards_this_turn': - return `you drew ${condition.atLeast ? `${condition.atLeast}+ ` : 'a '}cards this turn` + return `youDrewCardsThisTurn(${condition.atLeast !== undefined ? condition.atLeast : ''})` case 'spells_cast_last_turn': - return `${condition.who} cast ${condition.atLeast}+ spells last turn` + return `spellsCastLastTurn(${quote(condition.who)}, ${condition.atLeast})` case 'no_spells_last_turn': - return 'no spells were cast last turn' + return 'noSpellsLastTurn()' case 'attacked_this_turn': - return 'this attacked this turn' + return 'attackedThisTurn()' case 'you_attacked_this_turn': - return 'you attacked this turn' + return 'youAttackedThisTurn()' case 'defending_player_controls': - return `defending player controls ${formatSelector(condition.selector)}` + return `defendingPlayerControls(${formatSelector(condition.selector)})` case 'targets': - return `it targets ${formatSelector(condition.selector)}` + return `targets(${formatSelector(condition.selector)})` case 'was_kicked': - return 'this was kicked' + return 'wasKicked()' case 'cast': - return condition.fromHand ? 'you cast it from your hand' : 'you cast it' + return `youCastIt(${condition.fromHand ? `{ fromHand: true }` : ''})` case 'in_graveyard': - return 'this is in your graveyard' + return 'inGraveyard()' case 'on_battlefield': - return 'this is on the battlefield' + return 'onBattlefield()' case 'monarch': - return "you're the monarch" + return 'monarch()' case 'initiative': - return 'you have the initiative' + return 'initiative()' case 'citys_blessing': - return "you have the city's blessing" + return 'citysBlessing()' case 'suspended': - return 'this is suspended' + return 'suspended()' case 'bargained': - return 'it was bargained' + return 'bargained()' case 'was_creature': - return 'it was a creature' + return 'wasCreature()' case 'opponent_lost_life_this_turn': - return 'an opponent lost life this turn' + return 'opponentLostLifeThisTurn()' case 'life_changed_this_turn': - return 'you gained or lost life this turn' + return 'lifeChangedThisTurn()' case 'descended_this_turn': - return 'you descended this turn' + return 'descendedThisTurn()' case 'permanent_left_battlefield_this_turn': - return 'a permanent you controlled left the battlefield this turn' + return 'permanentLeftBattlefieldThisTurn()' case 'nonland_permanents_entered_this_turn': - return `${condition.atLeast}+ nonland permanents entered the battlefield under your control this turn` + return `nonlandPermanentsEnteredThisTurn(${condition.atLeast})` case 'attacked_with_total_power': - return `you attacked with total power ${condition.atLeast}+ this combat` + return `attackedWithTotalPower(${condition.atLeast})` case 'total_power': - return `creatures you control have total power ${condition.atLeast}+` + return `yourCreaturesTotalPower(${condition.atLeast})` case 'opponent_controls_more_lands': - return 'an opponent controls more lands than you' + return 'opponentControlsMoreLands()' case 'distinct_powers': - return `you control ${condition.atLeast}+ creatures with different powers` + return `distinctPowers(${condition.atLeast})` case 'graveyard_card_types': - return `there are ${condition.atLeast}+ card types in your graveyard` + return `graveyardCardTypes(${condition.atLeast})` case 'no_objects': - return `no ${formatSelector(condition.selector)} on the battlefield` + return `noObjects(${formatSelector(condition.selector)})` case 'cards_in_hand_at_most': - return `${condition.who} has ${condition.atMost} or fewer cards in hand` + return `cardsInHandAtMost(${formatPlayer(condition.who)}, ${condition.atMost})` case 'not_their_turn': - return 'it is not their turn' + return 'notTheirTurn()' case 'no_attackers': - return 'no creatures attacked this turn' + return 'noAttackers()' case 'opponent_poison': - return `an opponent has ${condition.atLeast}+ poison counters` + return `opponentPoison(${condition.atLeast})` case 'tribute_not_paid': - return "tribute wasn't paid" + return 'tributeNotPaid()' case 'had_counters': - return condition.counter ? `it had a ${condition.counter} counter on it` : 'it had counters on it' + return `hadCounters(${condition.counter ? quote(condition.counter) : ''})` case 'mana_from_treasure': - return 'mana from a Treasure was spent to cast it' + return 'manaFromTreasure()' case 'mana_spent': - return `at least ${condition.atLeast} mana was spent to cast it` + return `manaSpent(${condition.atLeast})` case 'no_mana_spent': - return 'no mana was spent to cast it' + return 'noManaSpent()' case 'mana_symbol_spent': - return `${condition.symbols} was spent to cast it` + return `manaSymbolSpent(${quote(condition.symbols)})` case 'kicked_with': - return `it was kicked with ${condition.cost}` + return `kickedWith(${quote(condition.cost)})` case 'more_cards_than_each_opponent': - return 'you have more cards in hand than each opponent' + return 'moreCardsThanEachOpponent()' case 'first_combat_phase': - return 'it is the first combat phase of the turn' + return 'firstCombatPhase()' case 'not_token': - return 'it is not a token' + return 'notToken()' case 'cast_spell_this_turn': - return `you've cast ${condition.noncreature ? 'a noncreature ' : 'a '}spell this turn` + return `castSpellThisTurn(${condition.noncreature ? `{ noncreature: true }` : ''})` case 'full_party': - return 'you have a full party' + return 'fullParty()' case 'graveyard_count': - return `there are ${condition.atLeast}+ ${formatSelector(condition.selector)} in your graveyard` + return `graveyardCount(${formatSelector(condition.selector)}, ${condition.atLeast})` case 'creature_power_greater_than_base': - return `you control a creature with ${condition.stat} greater than its base ${condition.stat}` + return `creaturePowerGreaterThanBase(${quote(condition.stat)})` case 'if_you_do': - return 'you do' + return 'ifYouDo()' case 'if_you_dont': - return "you don't" + return 'ifYouDont()' case 'otherwise': - return 'otherwise' + return 'otherwise()' case 'you_control_commander': - return 'you control a commander' + return 'youControlCommander()' case 'distinct_names': - return `you control ${condition.atLeast}+ ${formatSelector(condition.selector)} with different names` + return `distinctNames(${formatSelector(condition.selector)}, ${condition.atLeast})` case 'opponent_damaged_this_turn': - return `an opponent was dealt ${condition.atLeast}+ damage this turn` + return `opponentDamagedThisTurn(${condition.atLeast})` case 'attacked_with_creatures': - return `you attacked with ${condition.atLeast}+ creatures this turn` + return `attackedWithCreatures(${condition.atLeast})` case 'library_at_most': - return `a library has ${condition.atMost} or fewer cards in it` + return `libraryAtMost(${condition.atMost})` } } function formatTrigger(event: TriggerEvent): string { switch (event.kind) { case 'enters': - return `enters(${formatTarget(event.subject)})` + return `when.enters(${formatTarget(event.subject)})` case 'dies': - return `dies(${formatTarget(event.subject)})` + return `when.dies(${formatTarget(event.subject)})` case 'attacks': - return `attacks(${formatTarget(event.subject)})` + return `when.attacks(${formatTarget(event.subject)})` case 'blocks': - return `blocks(${formatTarget(event.subject)})` + return `when.blocks(${formatTarget(event.subject)})` case 'attacks_or_blocks': - return `attacks_or_blocks(${formatTarget(event.subject)})` + return `when.attacksOrBlocks(${formatTarget(event.subject)})` case 'enters_or_attacks': - return `enters_or_attacks(${formatTarget(event.subject)})` + return `when.entersOrAttacks(${formatTarget(event.subject)})` case 'enters_or_dies': - return `enters_or_dies(${formatTarget(event.subject)})` + return `when.entersOrDies(${formatTarget(event.subject)})` case 'leaves_battlefield': - return `leaves_battlefield(${formatTarget(event.subject)})` + return `when.leavesBattlefield(${formatTarget(event.subject)})` case 'deals_damage': - return `deals_${event.combat ? 'combat_' : ''}damage(${formatTarget(event.subject)}, ${event.recipient})` + return `when.dealsDamage(${formatTarget(event.subject)}, ${quote(event.recipient)}${optionArg([['combat', event.combat ? 'true' : undefined]])})` case 'upkeep': - return `upkeep(${event.who})` + return `when.upkeep(${formatPlayer(event.who)})` case 'end_step': - return `end_step(${event.who})` + return `when.endStep(${formatPlayer(event.who)})` case 'begin_combat': - return `begin_combat(${event.who})` + return `when.beginCombat(${formatPlayer(event.who)})` case 'main_phase': - return `${event.phase}_main_phase(${event.who})` + return `when.${event.phase === 'first' ? 'firstMainPhase' : 'postcombatMainPhase'}(${formatPlayer(event.who)})` case 'cast': - return `cast(${event.who}, ${isBareSelector(event.spell) ? 'any spell' : formatSelector(event.spell)}${event.targetsSelf ? ', targets this' : ''}${event.orCopy ? ', or copy' : ''}${event.ordinal ? `, #${event.ordinal} each turn` : ''})` + return `when.cast(${formatPlayer(event.who)}${isBareSelector(event.spell) ? '' : `, ${formatSelector(event.spell)}`}${optionArg([ + ['targetsSelf', event.targetsSelf ? 'true' : undefined], + ['orCopy', event.orCopy ? 'true' : undefined], + ['ordinal', event.ordinal !== undefined ? String(event.ordinal) : undefined], + ])})` case 'becomes_level': - return `becomes_level(${event.level})` + return `when.becomesLevel(${event.level})` case 'draw': - return `draw(${event.who}${event.ordinal ? `, #${event.ordinal} each turn` : ''})` + return `when.draw(${formatPlayer(event.who)}${event.ordinal !== undefined ? `, ${event.ordinal}` : ''})` case 'counter_placed': - return `counter_placed(${formatTarget(event.subject)}${event.counter ? `, ${event.counter}` : ''})` + return `when.counterPlaced(${formatTarget(event.subject)}${event.counter ? `, ${quote(event.counter)}` : ''})` case 'becomes_target': - return `becomes_target(${formatTarget(event.subject)})` + return `when.becomesTarget(${formatTarget(event.subject)})` case 'life': - return `${event.mode}_life(${event.who})` + return `when.${event.mode === 'gain' ? 'lifeGained' : 'lifeLost'}(${formatPlayer(event.who)})` } } function formatStaticEffect(effect: StaticEffect): string { switch (effect.op) { case 'pump': - return `pump(${formatTarget(effect.target)}, ${formatValue(effect.power)}/${formatValue(effect.toughness)})` + return `staticPump(${formatTarget(effect.target)}, ${formatValue(effect.power)}, ${formatValue(effect.toughness)})` case 'grant': - return `grant(${formatTarget(effect.target)}, ${effect.keyword}${effect.value ? ` ${effect.value}` : ''})` - case 'restriction': { - const extra = [ - effect.value ? formatValue(effect.value) : '', - effect.comparison ? effect.comparison.replace(/_/g, ' ') : '', - effect.detail ?? '', - effect.condition ? `if ${formatCondition(effect.condition)}` : '', - ].filter(Boolean).join(' ') - return `restrict(${formatTarget(effect.target)}, ${effect.rule}${extra ? ` ${extra}` : ''})` - } - case 'enters_tapped': - return `enters_tapped(${formatTarget(effect.target)}${effect.unless ? `, unless ${formatCondition(effect.unless)}` : ''})` - case 'enters_with_counters': - return `enters_with_counters(${formatTarget(effect.target)}, ${effect.counter}, ${formatValue(effect.amount)})` + return `staticGrant(${formatTarget(effect.target)}, ${quote(effect.keyword)}${optionArg([['value', effect.value ? quote(effect.value) : undefined]])})` case 'grant_ability': - return `grant_ability(${formatTarget(effect.target)}):\n${indent(formatAbility(effect.ability))}` + return `grantAbility(${formatTarget(effect.target)}, ${formatAbility(effect.ability)})` + case 'restriction': + return `staticRestrict(${formatTarget(effect.target)}, ${quote(effect.rule)}${optionArg([ + ['value', effect.value ? formatValue(effect.value) : undefined], + ['comparison', effect.comparison ? quote(effect.comparison) : undefined], + ['detail', effect.detail ? quote(effect.detail) : undefined], + ['condition', effect.condition ? formatCondition(effect.condition) : undefined], + ])})` + case 'enters_tapped': + return `entersTapped(${formatTarget(effect.target)}${optionArg([ + ['unless', effect.unless ? formatCondition(effect.unless) : undefined], + ['unlessCost', effect.unlessCost ? formatCost(effect.unlessCost) : undefined], + ])})` + case 'enters_with_counters': + return `entersWithCounters(${formatTarget(effect.target)}, ${quote(effect.counter)}, ${formatValue(effect.amount)})` case 'set_pt': - return `set_pt(${formatTarget(effect.target)}${effect.base ? ', base' : ''}, ${effect.power ? formatValue(effect.power) : '?'}/${effect.toughness ? formatValue(effect.toughness) : '?'})` + return `staticSetPt(${formatTarget(effect.target)}, ${effect.power ? formatValue(effect.power) : 'null'}, ${effect.toughness ? formatValue(effect.toughness) : 'null'}${optionArg([['base', effect.base ? 'true' : undefined]])})` case 'control': return `control(${formatTarget(effect.target)})` case 'choose': - return `choose(${effect.what})` + return `choose(${quote(effect.what)})` case 'replacement': - return `replace(${effect.what}${effect.target ? `, ${formatTarget(effect.target)}` : ''}, instead ${effect.instead})` + return `replace(${quote(effect.what)}${optionArg([ + ['target', effect.target ? formatTarget(effect.target) : undefined], + ['instead', quote(effect.instead)], + ])})` case 'cost_reduction': - return `cost_reduction(${formatTarget(effect.target)}, ${effect.symbols ?? (effect.amount ? formatValue(effect.amount) : '0')}${effect.condition ? `, if ${formatCondition(effect.condition)}` : ''})` + return `costReduction(${formatTarget(effect.target)}, ${effect.symbols ? quote(effect.symbols) : effect.amount ? formatValue(effect.amount) : '0'}${optionArg([['condition', effect.condition ? formatCondition(effect.condition) : undefined]])})` case 'cost_increase': - return `cost_increase(${formatValue(effect.amount)}${effect.spellType ? `, ${effect.spellType}` : ''})` + return `costIncrease(${formatValue(effect.amount)}${optionArg([['spellType', effect.spellType ? quote(effect.spellType) : undefined]])})` case 'search_restriction': - return `search_restriction(${effect.who}, ${formatValue(effect.amount)})` + return `searchRestriction(${quote(effect.who)}, ${formatValue(effect.amount)})` case 'exile_instead_of_graveyard': - return `exile_instead_of_graveyard(${effect.owner ?? ''})` + return `exileInsteadOfGraveyard(${effect.owner ? quote(effect.owner) : ''})` } } -function indent(text: string, spaces = 2): string { - const pad = ' '.repeat(spaces) - return text - .split('\n') - .map(line => `${pad}${line}`) - .join('\n') +function formatStaticEffectList(effects: StaticEffect[]): string { + return callback(effects.map(formatStaticEffect)) } export function formatAbility(ability: Ability): string { switch (ability.kind) { case 'keyword': - return `keyword ${ability.keyword}${ability.value ? ` ${ability.value}` : ''}` + return `keyword(${quote(ability.keyword)}${ability.value ? `, ${quote(ability.value)}` : ''})` case 'keywords': - return `keywords ${ability.keywords.map(keyword => `${keyword.keyword}${keyword.value ? ` ${keyword.value}` : ''}`).join(', ')}` - case 'triggered': { - const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : '' - const body = ability.effects.map(formatEffect).join('\n') - return `on ${formatTrigger(ability.event)}${condition}${ability.optional ? ' (may)' : ''}:\n${indent(body)}` - } - case 'activated': { - const costs = ability.costs.map(formatCost).join(', ') - const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : '' - const limit = ability.activationsPerTurn ? ` (${ability.activationsPerTurn}/turn)` : '' - const timing = ability.timing === 'sorcery' ? ' (sorcery speed)' : '' - const body = ability.effects.map(formatEffect).join('\n') - return `activate ${costs}${condition}${limit}${timing}${ability.optional ? ' (may)' : ''}:\n${indent(body)}` - } - case 'static': { - const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : '' - return `static${condition}:\n${indent(ability.effects.map(formatStaticEffect).join('\n'))}` - } + return `keywords(${ability.keywords.map(keyword => quote(`${keyword.keyword}${keyword.value ? ` ${keyword.value}` : ''}`)).join(', ')})` + case 'triggered': + return `triggered(${formatTrigger(ability.event)}, ${formatEffectList(ability.effects)}${optionArg([ + ['condition', ability.condition ? formatCondition(ability.condition) : undefined], + ['optional', ability.optional ? 'true' : undefined], + ])})` + case 'activated': + return `activated([${ability.costs.map(formatCost).join(', ')}], ${formatEffectList(ability.effects)}${optionArg([ + ['condition', ability.condition ? formatCondition(ability.condition) : undefined], + ['timing', ability.timing ? quote(ability.timing) : undefined], + ['activationsPerTurn', ability.activationsPerTurn !== undefined ? String(ability.activationsPerTurn) : undefined], + ['optional', ability.optional ? 'true' : undefined], + ])})` + case 'static': + return `staticAbility(${formatStaticEffectList(ability.effects)}${optionArg([ + ['condition', ability.condition ? formatCondition(ability.condition) : undefined], + ])})` case 'spell': - return `spell${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}` + return `spell(${formatEffectList(ability.effects)}${optionArg([['optional', ability.optional ? 'true' : undefined]])})` case 'additional_cost': - return `additional cost${ability.optional ? ' (may)' : ''}: ${ability.costs.map(formatCost).join(', ')}` - case 'alternative_cost': { - const condition = ability.condition ? ` if ${formatCondition(ability.condition)}` : '' - return `alternative cost${condition}: ${ability.costs.length ? ability.costs.map(formatCost).join(', ') : 'free'}` - } + return `additionalCost([${ability.costs.map(formatCost).join(', ')}]${optionArg([['optional', ability.optional ? 'true' : undefined]])})` + case 'alternative_cost': + return `alternativeCost([${ability.costs.map(formatCost).join(', ')}]${optionArg([ + ['condition', ability.condition ? formatCondition(ability.condition) : undefined], + ])})` case 'overload': - return `overload ${ability.cost}` + return `overload(${quote(ability.cost)})` case 'chapter': - return `chapter ${ability.chapters.join(', ')}${ability.optional ? ' (may)' : ''}:\n${indent(ability.effects.map(formatEffect).join('\n'))}` - case 'level_band': { - const band = ability.max !== undefined ? `${ability.min}-${ability.max}` : `${ability.min}+` - const pt = ability.power ? `: ${formatValue(ability.power)}/${formatValue(ability.toughness!)}` : '' - return `level ${band}${pt}` - } + return `chapter([${ability.chapters.map(quote).join(', ')}], ${formatEffectList(ability.effects)}${optionArg([['optional', ability.optional ? 'true' : undefined]])})` + case 'level_band': + return `levelBand(${ability.min}, ${ability.max !== undefined ? ability.max : 'null'}${ability.power ? `, ${formatValue(ability.power)}, ${formatValue(ability.toughness!)}` : ''})` case 'level_pt': - return `level_pt(${formatValue(ability.power)}/${formatValue(ability.toughness)})` + return `levelPt(${formatValue(ability.power)}, ${formatValue(ability.toughness)})` case 'unsupported': - return `unsupported (${ability.reason}): ${ability.text.replace(/\n/g, '\n ')}` + return `unsupported(${quote(ability.reason)}, ${quote(ability.text)})` } } -export function formatCard(card: CompiledCard): string { - const lines = [`# ${card.name} [${card.status}]`] - if (card.faces?.length) { - for (const face of card.faces) { - lines.push('', `## ${face.name} [${face.status}]`) - lines.push(face.abilities.map(formatAbility).join('\n') || '(no abilities)') - } - } else { - lines.push(card.abilities.map(formatAbility).join('\n') || '(no abilities)') - } - return lines.join('\n') +function formatAbilityList(abilities: Ability[]): string { + return list(abilities.map(formatAbility)) +} + +export function formatCard(card: CompiledCard): string { + const header = `// ${card.name} [${card.status}]` + if (card.faces?.length) { + const faces = card.faces.map(face => { + const typeLine = face.typeLine ? `${quote(face.typeLine)}, ` : '' + return `face(${quote(face.name)}, ${typeLine}${formatAbilityList(face.abilities)})` + }) + return `${header}\nexport default faces(\n${faces.map(face => indent(face)).join(',\n')},\n)` + } + const abilities = formatAbilityList(card.abilities) + const body = card.typeLine ? `card(${quote(card.typeLine)}, ${abilities})` : abilities + return `${header}\nexport default ${body}` } diff --git a/backend/src/effects/implementations.ts b/backend/src/effects/implementations.ts index 28e0c6e..01ea299 100644 --- a/backend/src/effects/implementations.ts +++ b/backend/src/effects/implementations.ts @@ -1,5 +1,5 @@ -// Human-authored card implementations live in one plain-text file per oracle -// id under data/card-overrides/. The file is pseudocode in the same syntax the +// Human-authored card implementations live in one JavaScript file per oracle +// id under data/card-overrides/. The file uses the same builder API the // formatter prints, so it stays readable and can be re-compiled by the engine. import { readFileSync, statSync } from 'node:fs' @@ -9,8 +9,8 @@ import { allCards } from '../cards.js' import type { Card } from '../cards.js' import { compileCard, statusOf } from './compile.js' import { formatCard } from './format.js' -import { parsePseudoCard, PseudoParseError } from './pseudo.js' -import type { CompiledCard, CompiledFace } from './types.js' +import { parseCardSource, SourceParseError } from './source.js' +import type { Ability, CompiledCard, CompiledFace } from './types.js' export type ImplementationStatus = 'supported' | 'partial' | 'unsupported' @@ -37,7 +37,7 @@ export function overridesDir(): string { function overrideFile(oracleId: string): string { if (!ORACLE_ID.test(oracleId)) throw new Error(`Invalid oracle id: ${oracleId}`) - return join(overridesDir(), `${oracleId}.pseudo.txt`) + return join(overridesDir(), `${oracleId}.js`) } function isMissing(error: unknown): boolean { @@ -67,7 +67,7 @@ export async function readAllOverrides(): Promise> { } for (const name of names) { - const oracleId = name.replace(/\.pseudo\.txt$/, '') + const oracleId = name.replace(/\.js$/, '') if (name === oracleId || !ORACLE_ID.test(oracleId)) continue const override = await readOverride(oracleId) if (override) result.set(oracleId, override.source) @@ -99,31 +99,45 @@ function facesStatus(faces: CompiledFace[]): ImplementationStatus { return faces.some(face => face.status === 'partial') ? 'partial' : 'supported' } -/** Parses manual pseudocode and turns it into the same AST the compiler emits. */ +/** Copies the oracle label onto manual abilities so the stack log stays readable. */ +function fillAbilityText(abilities: Ability[], generated: Ability[] | undefined): void { + abilities.forEach((ability, index) => { + const source = generated?.[index] + if (source && 'text' in source && source.text) { + (ability as Ability & { text?: string }).text = source.text + } + }) +} + +/** Parses manual JavaScript and turns it into the same AST the compiler emits. */ export function compileImplementation(card: Card, source: string): CompiledCard { - const parsed = parsePseudoCard(source) + const parsed = parseCardSource(source) if (card.card_faces?.length) { if (!parsed.faces?.length) { - throw new PseudoParseError( - `this card has ${card.card_faces.length} faces; add "## " sections`, + throw new SourceParseError( + `this card has ${card.card_faces.length} faces; export faces(face(...), ...)`, 1, ) } if (parsed.faces.length !== card.card_faces.length) { - throw new PseudoParseError( + throw new SourceParseError( `expected ${card.card_faces.length} faces, found ${parsed.faces.length}`, 1, ) } + const generated = compileCard(card) const faces: CompiledFace[] = card.card_faces.map((face, index) => { const manualFace = parsed.faces![index] if (manualFace.name.toLowerCase() !== face.name.toLowerCase()) { - throw new PseudoParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1) + throw new SourceParseError(`expected face "${face.name}", found "${manualFace.name}"`, 1) } + const generatedFace = generated.faces?.find(entry => entry.name.toLowerCase() === face.name.toLowerCase()) + fillAbilityText(manualFace.abilities, generatedFace?.abilities) return { name: face.name, + typeLine: manualFace.typeLine ?? face.type_line, status: statusOf(manualFace.abilities), abilities: manualFace.abilities, } @@ -132,6 +146,7 @@ export function compileImplementation(card: Card, source: string): CompiledCard return { oracle_id: card.oracle_id, name: card.name, + typeLine: card.type_line, status: facesStatus(faces), abilities: [], faces, @@ -140,12 +155,14 @@ export function compileImplementation(card: Card, source: string): CompiledCard } if (parsed.faces?.length) { - throw new PseudoParseError('this card has no faces; remove the "##" sections', 1) + throw new SourceParseError('this card has no faces; export card(...) instead of faces(...)', 1) } + fillAbilityText(parsed.abilities, compileCard(card).abilities) return { oracle_id: card.oracle_id, name: card.name, + typeLine: parsed.typeLine ?? card.type_line, status: statusOf(parsed.abilities), abilities: parsed.abilities, manual: true, diff --git a/backend/src/effects/pseudo.ts b/backend/src/effects/pseudo.ts deleted file mode 100644 index 211bb01..0000000 --- a/backend/src/effects/pseudo.ts +++ /dev/null @@ -1,1886 +0,0 @@ -// Two-way card pseudocode. `format.ts` renders this syntax and this module reads -// it back, so a human can edit an implementation without touching JSON. -// -// The syntax is exactly the formatter output: one ability per unindented block, -// effects indented below it. Headers such as `# Card [status]` are ignored, and -// `## Face` starts a new face section. - -import { SIMPLE_KEYWORDS } from './compile.js' -import { parseNumber, parsePlayerRef, parseValue, singularize } from './parse.js' -import type { - Ability, - Condition, - Cost, - Duration, - Effect, - KeywordAbility, - ManaSpec, - ObjectSelector, - PlayerRef, - StaticEffect, - Target, - TokenSpec, - TriggerEvent, - Value, - Zone, -} from './types.js' - -export class PseudoParseError extends Error { - readonly line: number - - constructor(message: string, line: number) { - super(`line ${line}: ${message}`) - this.name = 'PseudoParseError' - this.line = line - } -} - -export interface ParsedFacePseudo { - name: string - abilities: Ability[] -} - -export interface ParsedCardPseudo { - abilities: Ability[] - faces?: ParsedFacePseudo[] -} - -interface SourceLine { - text: string - indent: number - line: number -} - -interface Block { - header: SourceLine - body: SourceLine[] -} - -const PLAYERS = new Set([ - 'you', - 'opponent', - 'each_opponent', - 'each_player', - 'target_player', - 'that_player', - 'its_controller', - 'its_owner', -]) - -const TYPE_WORDS = new Set([ - 'artifact', - 'battle', - 'creature', - 'enchantment', - 'instant', - 'land', - 'permanent', - 'planeswalker', - 'sorcery', -]) - -const SUPERTYPES = new Set(['basic', 'legendary', 'snow', 'world', 'ongoing', 'commander']) - -const COLOR_WORDS: Record = { - white: 'W', - blue: 'U', - black: 'B', - red: 'R', - green: 'G', - colorless: 'C', -} - -const DURATIONS = new Map([ - ['until end of turn', 'until_end_of_turn'], - ['until your next turn', 'until_your_next_turn'], - ['until the end of your next turn', 'until_end_of_your_next_turn'], - ['until end of combat', 'until_end_of_combat'], - ["until its controller's next untap step", 'until_controllers_next_untap_step'], - ['for as long as this remains on the battlefield', 'while_source_on_battlefield'], -]) - -function fail(line: SourceLine, message: string): never { - throw new PseudoParseError(message, line.line) -} - -function countIndent(text: string): number { - const match = text.match(/^[ \t]*/) - return match?.[0].replace(/\t/g, ' ').length ?? 0 -} - -/** Splits on `separator` at the top level of parentheses, brackets, and quotes. */ -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 -} - -function splitPowerToughness(text: string): [string, string] | undefined { - const index = firstTopLevelIndex(text, '/') - if (index < 0) return undefined - return [text.slice(0, index).trim(), text.slice(index + 1).trim()] -} - -function lastTopLevelIndex(text: string, separator: string): number { - let found = -1 - for (let index = firstTopLevelIndex(text, separator); index >= 0; index = firstTopLevelIndex(text, separator, index + 1)) { - found = index - } - return found -} - -function firstTopLevelIndex(text: string, separator: string, from = 0): number { - let depth = 0 - let quote = false - let escape = false - - 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 && index >= from && text.startsWith(separator, index)) return index - } - return -1 -} - -interface Call { - name: string - args: string[] - end: number -} - -function readCallPrefix(text: string): Call | 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) { - return { - name: match[1], - args: splitTopLevel(text.slice(open + 1, index), ',').map(arg => arg.trim()), - end: index + 1, - } - } - } - } - return undefined -} - -function parseCall(text: string): Call | undefined { - const call = readCallPrefix(text.trim()) - return call && call.end === text.trim().length ? call : undefined -} - -function arg(args: string[], index: number, line: SourceLine): string { - const value = args[index] - if (value === undefined) fail(line, 'missing argument') - return value.trim() -} - -function parsePlayer(text: string, line: SourceLine): PlayerRef { - const trimmed = text.trim() - if (PLAYERS.has(trimmed as PlayerRef)) return trimmed as PlayerRef - const parsed = parsePlayerRef(trimmed) - if (parsed) return parsed - return fail(line, `unknown player "${trimmed}"`) -} - -function parsePlayerOrThrow(text: string, line: SourceLine, allowed: readonly T[]): T { - const player = parsePlayer(text, line) - if (!allowed.includes(player as T)) fail(line, `player "${player}" is not allowed here`) - return player as T -} - -function parseValueText(text: string, line: SourceLine): Value { - const trimmed = text.trim() - if (trimmed === 'all') return fail(line, '"all" is not a numeric value') - - const call = parseCall(trimmed) - if (call?.name === 'count' && call.args.length === 1) { - return { kind: 'count', selector: parseSelector(call.args[0], line) } - } - - let match = trimmed.match(/^greatest number of (.+) an opponent controls$/) - if (match) return { kind: 'max_opponent_count', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^total mana value of (.+)$/) - if (match) return { kind: 'total_mana_value', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^total power of (.+)$/) - if (match) return { kind: 'total_power', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^cards in (your|that player's|an opponent's|target player's) hand$/) - if (match) { - return { - kind: 'cards_in_hand', - player: match[1] === 'your' ? 'you' : match[1] === 'that player\'s' ? 'that_player' : match[1] === 'target player\'s' ? 'target_player' : 'opponent', - } - } - - if (trimmed === 'cards in the hand of the opponent with the most cards') { - return { kind: 'max_cards_in_hand' } - } - if (trimmed === 'any number') return { kind: 'any_number' } - if (trimmed === 'X' || trimmed === 'x') return { kind: 'x' } - if (trimmed === 'its power') return { kind: 'source_power' } - if (trimmed === 'its toughness') return { kind: 'source_toughness' } - - const parsed = parseValue(trimmed) - if (parsed) return parsed - return fail(line, `cannot read value "${trimmed}"`) -} - -function parseValuePrefix(text: string): { value: Value; rest: string } | undefined { - const trimmed = text.trim() - let match = trimmed.match(/^(greatest number of .+? an opponent controls)(?:\s+(.+))?$/) - if (match) return { value: { kind: 'max_opponent_count', selector: { types: [] } }, rest: match[2] ?? '' } - - const call = readCallPrefix(trimmed) - if (call?.name === 'count') { - return { value: { kind: 'count', selector: { types: [] } }, rest: trimmed.slice(call.end).trim() } - } - - match = trimmed.match(/^(total mana value of .+|total power of .+|cards in (?:your|that player's|an opponent's|target player's) hand|its power|its toughness|any number|that much|X|x|-?\d+)(?:\s+(.+))?$/) - if (!match) return undefined - const valueText = match[1] - const staticValue = parseValue(valueText === 'X' ? 'x' : valueText) - if (!staticValue && valueText !== 'any number') return undefined - return { value: staticValue ?? { kind: 'any_number' }, rest: match[2] ?? '' } -} - -function parseSelector(text: string, line: SourceLine): ObjectSelector { - const selector = parseSelectorText(text) - if (!selector) return fail(line, `cannot read selector "${text.trim()}"`) - return selector -} - -function parseSelectorText(text: string): ObjectSelector | undefined { - let rest = text.trim() - if (!rest) return undefined - - if (rest === 'card' || rest === 'cards') return { types: [] } - - const selector: ObjectSelector = {} - - const zoneSuffixes: Array<[string, Zone]> = [ - [' from a graveyard', 'graveyard'], - [' from a library', 'library'], - [' from a hand', 'hand'], - [' in exile', 'exile'], - [' on the battlefield', 'battlefield'], - [' on the stack', 'stack'], - ] - for (const [suffix, zone] of zoneSuffixes) { - if (rest.endsWith(suffix)) { - selector.zone = zone - rest = rest.slice(0, -suffix.length).trim() - break - } - } - - if (rest.endsWith(" you don't own")) { - selector.owner = 'opponent' - rest = rest.slice(0, -' you don\'t own'.length).trim() - } else if (rest.endsWith(' you own')) { - selector.owner = 'you' - rest = rest.slice(0, -' you own'.length).trim() - } - - if (rest.endsWith(' an opponent controls')) { - selector.controller = 'opponent' - rest = rest.slice(0, -' an opponent controls'.length).trim() - } else if (rest.endsWith(' you control')) { - selector.controller = 'you' - rest = rest.slice(0, -' you control'.length).trim() - } - - const named = rest.match(/^(.*?)\bnamed (.+)$/) - if (named) { - selector.name = named[2].trim() - rest = named[1].trim() - } - - let match = rest.match(/^(.*?) mana value (\d+) or (greater|less)$/) - if (match) { - selector.manaValue = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } - rest = match[1].trim() - } - match = rest.match(/^(.*?) power (\d+) or (greater|less)$/) - if (match) { - selector.power = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } - rest = match[1].trim() - } - match = rest.match(/^(.*?) toughness (\d+) or (greater|less)$/) - if (match) { - selector.toughness = match[3] === 'greater' ? { atLeast: Number(match[2]) } : { atMost: Number(match[2]) } - rest = match[1].trim() - } - match = rest.match(/^(.*?) power (\d+)\+$/) - if (match) { - selector.power = { atLeast: Number(match[2]) } - rest = match[1].trim() - } - match = rest.match(/^(.*?) toughness (\d+)\+$/) - if (match) { - selector.toughness = { atLeast: Number(match[2]) } - rest = match[1].trim() - } - match = rest.match(/^(.*?) mana value (\d+)\+$/) - if (match) { - selector.manaValue = { atLeast: Number(match[2]) } - rest = match[1].trim() - } - - match = rest.match(/^(.*?) without (.+)$/) - if (match) { - selector.excludeKeywords = match[2].split(' and ').map(value => value.trim()).filter(Boolean) - rest = match[1].trim() - } - - match = rest.match(/^(.*?) with (\d+)\+ (.+?) counters(?: with (.+))?$/) - if (match) { - selector.counters = { counter: match[3], atLeast: Number(match[2]) } - if (match[4]) selector.keywords = match[4].split(' and ').map(value => value.trim()).filter(Boolean) - rest = match[1].trim() - } else { - match = rest.match(/^(.*?) with (.+)$/) - if (match) { - selector.keywords = match[2].split(' and ').map(value => value.trim()).filter(Boolean) - rest = match[1].trim() - } - } - - let changed = true - while (changed && rest) { - changed = false - for (const [word, key] of [ - ['other', 'other'], - ['tapped', 'tapped'], - ['untapped', 'untapped'], - ['attacking', 'attacking'], - ['token', 'token'], - ['nontoken', 'nontoken'], - ['equipped', 'equipped'], - ['enchanted', 'enchanted'], - ] as const) { - if (rest === word || rest.startsWith(`${word} `)) { - if (key === 'other') selector.other = true - else if (key === 'tapped') selector.tapped = true - else if (key === 'untapped') selector.tapped = false - else if (key === 'attacking') selector.attacking = true - else if (key === 'token') selector.token = true - else if (key === 'nontoken') selector.token = false - else if (key === 'equipped') selector.attached = 'equipped' - else if (key === 'enchanted') selector.attached = 'enchanted' - rest = rest.slice(word.length).trim() - changed = true - break - } - } - } - - const colors: string[] = [] - while (rest) { - const color = rest.match(/^(white|blue|black|red|green|colorless)(?: and )?(.*)$/) - if (!color) break - colors.push(COLOR_WORDS[color[1]]) - rest = color[2].trim() - } - if (colors.length) selector.colors = colors - - const types: string[] = [] - const supertypes: string[] = [] - const subtypes: string[] = [] - const excludeTypes: string[] = [] - let matchAny = false - - for (const rawWord of rest.split(/\s+/).filter(Boolean)) { - if (rawWord === 'and') continue - if (rawWord === 'or') { - matchAny = true - continue - } - if (rawWord.startsWith('non-')) { - const types = rawWord.slice(4).split('/') - if (types.every(type => TYPE_WORDS.has(singularize(type)))) { - for (const type of types) excludeTypes.push(singularize(type)) - continue - } - subtypes.push(singularize(rawWord)) - continue - } - const word = singularize(rawWord) - if (SUPERTYPES.has(word)) { - supertypes.push(word) - continue - } - if (TYPE_WORDS.has(word)) { - types.push(word) - continue - } - if (/^[a-z][a-z'-]*$/.test(word)) { - subtypes.push(word) - continue - } - return undefined - } - - if (types.length) selector.types = types - if (matchAny) selector.match = 'any' - if (excludeTypes.length) selector.excludeTypes = excludeTypes - if (supertypes.length) selector.supertypes = supertypes - if (subtypes.length) selector.subtypes = subtypes - - return selector -} - -function parseTarget(text: string, line: SourceLine): Target { - const trimmed = text.trim() - if (!trimmed) fail(line, 'missing target') - - if (trimmed === 'this') return { kind: 'self' } - if (trimmed === 'the triggering object') return { kind: 'trigger_subject' } - if (trimmed === 'the chosen target' || trimmed === 'the previous target') return { kind: 'previous_target' } - if (trimmed === 'any target') return { kind: 'any' } - if (trimmed === 'target player or planeswalker') return { kind: 'player_or_planeswalker', mode: 'target' } - if (trimmed === 'target ability') return { kind: 'ability', mode: 'target' } - if (trimmed === 'target spell') return { kind: 'spell', selector: { types: [] }, mode: 'target' } - - const spell = trimmed.match(/^target (.+) spell$/) - if (spell) return { kind: 'spell', selector: parseSelector(spell[1], line), mode: 'target' } - - if (trimmed.startsWith('divided(')) { - const call = parseCall(trimmed) - if (call?.name === 'divided') { - const maxText = arg(call.args, 0, line) - const max = maxText === 'any number' ? 'any' : Number(maxText) - if (max !== 'any' && !Number.isFinite(max)) fail(line, `bad divided target count "${maxText}"`) - return { - kind: 'divided', - max, - selector: call.args[1] ? parseSelector(call.args[1], line) : undefined, - } - } - } - - if (PLAYERS.has(trimmed as PlayerRef) || parsePlayerRef(trimmed)) { - const who = parsePlayer(trimmed, line) - return { kind: 'player', who, mode: trimmed.startsWith('each ') ? 'each' : 'target' } - } - - let rest = trimmed - let mode: 'target' | 'each' | 'choose' = 'choose' - let includeSelf = false - let upTo = false - let count: number | undefined - - const upToBefore = rest.match(/^up to (\w+) target (.+)$/) - if (upToBefore) { - upTo = true - count = parseNumber(upToBefore[1]) - rest = `target ${upToBefore[2]}` - } - - if (rest.startsWith('target ')) { - mode = 'target' - rest = rest.slice(7).trim() - } else if (rest.startsWith('each ')) { - mode = 'each' - rest = rest.slice(5).trim() - } - - const quantity = rest.match(/^(up to )?(\w+) (.+)$/) - if ( - quantity - && parseNumber(quantity[2]) !== undefined - && quantity[2] !== 'a' - && quantity[2] !== 'an' - ) { - upTo = Boolean(quantity[1]) - count = parseNumber(quantity[2]) - rest = quantity[3].trim() - } - - if (rest.startsWith('this or ')) { - includeSelf = true - rest = rest.slice(8).trim() - } - - return { - kind: 'object', - selector: parseSelector(rest, line), - mode, - ...(count !== undefined ? { count } : {}), - ...(upTo ? { upTo: true } : {}), - ...(includeSelf ? { includeSelf: true } : {}), - } -} - -function parseDurationText(text: string, line: SourceLine): Duration { - const trimmed = text.trim() - if (!trimmed || trimmed === 'permanent') return 'permanent' - const duration = DURATIONS.get(trimmed) - if (!duration) fail(line, `cannot read duration "${trimmed}"`) - return duration -} - -function parseKeyword(text: string): KeywordAbility { - const trimmed = text.trim() - const lower = trimmed.toLowerCase() - const simple = [...SIMPLE_KEYWORDS.entries()].sort((a, b) => b[0].length - a[0].length) - for (const [key, keyword] of simple) { - if (lower === key) return { kind: 'keyword', keyword: trimmed } - if (lower.startsWith(`${key} `)) return { kind: 'keyword', keyword, value: trimmed.slice(key.length + 1) } - } - - const match = trimmed.match(/^(\S+)(?: (.+))?$/) - if (!match) return { kind: 'keyword', keyword: trimmed } - return { - kind: 'keyword', - keyword: match[1].charAt(0).toUpperCase() + match[1].slice(1), - value: match[2], - } -} - -function parseKeywordList(text: string): KeywordAbility[] { - return splitTopLevel(text, ',').map(part => parseKeyword(part.trim())).filter(Boolean) -} - -function parseCosts(text: string, line: SourceLine): Cost[] { - const trimmed = text.trim() - if (!trimmed) fail(line, 'missing cost') - const parts = splitTopLevel(trimmed, ',').map(part => part.trim()).filter(Boolean) - const costs: Cost[] = [] - for (const part of parts) costs.push(parseCost(part, line)) - return costs -} - -function tryCostOption(text: string, line: SourceLine): Cost[] | undefined { - try { - return splitTopLevel(text, ' + ').map(part => parseCost(part, line)) - } catch { - return undefined - } -} - -function parseCost(text: string, line: SourceLine): Cost { - const trimmed = text.trim() - - if (trimmed.startsWith('(') && trimmed.endsWith(')')) { - const inner = trimmed.slice(1, -1) - const parts = splitTopLevel(inner, ' or ') - for (let split = 1; split < parts.length; split++) { - const left = tryCostOption(parts.slice(0, split).join(' or '), line) - const right = tryCostOption(parts.slice(split).join(' or '), line) - if (left && right) return { kind: 'choice', options: [left, right] } - } - const options = parts.map(option => - splitTopLevel(option, ' + ').map(part => parseCost(part, line)), - ) - if (options.length > 1) return { kind: 'choice', options } - } - - const energy = trimmed.match(/^\{E\} x(\d+)$/) - if (energy) return { kind: 'energy', amount: Number(energy[1]) } - - if (/^(?:\{[^}]+\})+$/.test(trimmed)) { - const symbols = trimmed.match(/\{[^}]+\}/g) ?? [] - const costs: Cost[] = [] - const mana: string[] = [] - for (const symbol of symbols) { - const lower = symbol.toLowerCase() - if (lower === '{t}') costs.push({ kind: 'tap' }) - else if (lower === '{q}') costs.push({ kind: 'untap' }) - else if (lower === '{e}') { - const last = costs[costs.length - 1] - if (last?.kind === 'energy') last.amount += 1 - else costs.push({ kind: 'energy', amount: 1 }) - } else mana.push(symbol) - } - if (mana.length) costs.push({ kind: 'mana', symbols: mana.join('') }) - return costs.length === 1 ? costs[0] : { kind: 'choice', options: costs.map(cost => [cost]) } - } - - let match = trimmed.match(/^([+-]?\d+) loyalty$/) - if (match) return { kind: 'loyalty', amount: Number(match[1]) } - - match = trimmed.match(/^pay (.+) life$/) - if (match) return { kind: 'pay_life', amount: parseValueText(match[1], line) } - - if (trimmed === 'sacrifice this') return { kind: 'sacrifice_self' } - match = trimmed.match(/^sacrifice (.+)$/) - if (match) return { kind: 'sacrifice', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^tap (.+)$/) - if (match) return { kind: 'tap_other', selector: parseSelector(match[1], line) } - - if (trimmed === 'exile this from a graveyard' || trimmed === 'exile this') { - return { kind: 'exile_self' } - } - match = trimmed.match(/^exile (.+?) from your graveyard$/) - if (match) { - const body = match[1].trim() - const prefixed = parseValuePrefix(body) - return { - kind: 'exile_from_graveyard', - selector: parseSelector(prefixed?.rest || body, line), - amount: prefixed?.value, - } - } - - match = trimmed.match(/^reveal (.+) from your hand$/) - if (match) return { kind: 'reveal', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^return (.+) to its owner's hand$/) - if (match) return { kind: 'return_to_hand', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^behold (.+)$/) - if (match) return { kind: 'behold', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^waterbend (.+)$/) - if (match) return { kind: 'waterbend', amount: parseValueText(match[1], line) } - - match = trimmed.match(/^blight (.+)$/) - if (match) return { kind: 'blight', amount: parseValueText(match[1], line) } - - match = trimmed.match(/^choose (.+)$/) - if (match) return { kind: 'choose', what: match[1] } - - match = trimmed.match(/^put (.+?) counters? on (.+)$/) - if (match) return { kind: 'put_counter', counter: match[1], selector: parseSelector(match[2], line) } - - match = trimmed.match(/^remove (.+?) (.+?) counter(?:s|\(s\))? from (.+)$/) - if (match) { - return { - kind: 'remove_counters', - counter: match[2], - amount: parseValueText(match[1], line), - ...(match[3] === 'this' ? {} : { selector: parseSelector(match[3], line) }), - } - } - - if (trimmed === 'forage') return { kind: 'forage' } - - match = trimmed.match(/^collect evidence (\d+)$/) - if (match) return { kind: 'collect_evidence', amount: Number(match[1]) } - - match = trimmed.match(/^mill (.+) card\(s\)$/) - if (match) return { kind: 'mill', amount: parseValueText(match[1], line) } - - if (trimmed === 'discard your hand') { - return { kind: 'discard', amount: { kind: 'cards_in_hand', player: 'you' }, player: 'you' } - } - match = trimmed.match(/^discard (.+?) card\(s\)( at random)?$/) - if (match) { - return { - kind: 'discard', - amount: parseValueText(match[1], line), - player: 'you', - random: Boolean(match[2]) || undefined, - } - } - - return fail(line, `cannot read cost "${trimmed}"`) -} - -function parseEffectExprList(text: string, line: SourceLine): Effect[] { - const parts = splitTopLevel(text, ';').map(part => part.trim()).filter(Boolean) - if (!parts.length) fail(line, 'expected an effect') - return parts.map(part => parseEffectExpr(part, line)) -} - -function parseEffectExpr(text: string, line: SourceLine): Effect { - const call = parseCall(text) - if (!call) fail(line, `expected an effect call, got "${text}"`) - const { name, args } = call - - switch (name) { - case 'damage': { - const source = args[2]?.replace(/^from /, '').trim() - return { - op: 'damage', - target: parseTarget(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - ...(source ? { source: parseTarget(source, line) } : {}), - } - } - case 'damage_divided': - return { - op: 'damage_divided', - amount: parseValueText(arg(args, 0, line), line), - target: parseTarget(arg(args, 1, line), line), - } - case 'draw': - return { op: 'draw', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } - case 'discard': - return { - op: 'discard', - player: parsePlayer(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - random: args[2]?.trim() === 'at random' || undefined, - } - case 'mill': - return { op: 'mill', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } - case 'gain_life': - case 'lose_life': - return { - op: 'life', - player: parsePlayer(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - mode: name === 'gain_life' ? 'gain' : 'lose', - } - case 'pump': - case 'set_pt': { - const pt = splitPowerToughness(arg(args, 1, line)) - if (!pt) fail(line, `expected power/toughness, got "${args[1]}"`) - return { - op: name, - target: parseTarget(arg(args, 0, line), line), - power: parseValueText(pt[0], line), - toughness: parseValueText(pt[1], line), - duration: args[2] ? parseDurationText(args[2], line) : 'permanent', - } - } - case 'grant': { - const last = args[args.length - 1]?.trim() - const hasDuration = args.length > 2 && (DURATIONS.has(last) || last === 'permanent') - const keyword = parseKeyword(args.slice(1, hasDuration ? -1 : undefined).join(', ')) - return { - op: 'grant', - target: parseTarget(arg(args, 0, line), line), - keyword: keyword.keyword, - value: keyword.value, - duration: hasDuration ? parseDurationText(last, line) : 'permanent', - } - } - case 'put_counters': - case 'remove_counters': - return { - op: name, - target: parseTarget(arg(args, 0, line), line), - counter: args.slice(1, -1).join(', ').trim(), - amount: parseValueText(arg(args, args.length - 1, line), line), - } - case 'proliferate': - return { op: 'proliferate' } - case 'exile_graveyards': - return { op: 'exile_graveyards' } - case 'hideaway': - return { op: 'hideaway', amount: parseValueText(arg(args, 0, line), line) } - case 'play_exiled': - return { - op: 'play_exiled', - player: parsePlayer(arg(args, 0, line), line), - free: args[1]?.trim() === 'free' || undefined, - } - case 'create_token': { - const rest = args.slice(2).join(', ').trim() - if (rest.startsWith('copy of ')) { - const notLegendary = /, not legendary$/.test(rest) - const targetText = rest.slice(8).replace(/, not legendary$/, '').trim() - return { - op: 'create_token', - player: parsePlayer(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - token: { types: [], subtypes: [], colors: [] }, - copyOf: parseTarget(targetText, line), - ...(notLegendary ? { notLegendary: true } : {}), - } - } - return { - op: 'create_token', - player: parsePlayer(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - token: parseTokenSpec(rest, line), - } - } - case 'destroy': - case 'exile': - case 'tap': - case 'untap': - case 'regenerate': - case 'return_to_hand': - case 'put_on_top': - return { op: name, target: parseTarget(arg(args, 0, line), line) } - case 'sacrifice': { - const rest = arg(args, 1, line) - const unlessIndex = lastTopLevelIndex(rest, ' unless ') - const targetText = unlessIndex >= 0 ? rest.slice(0, unlessIndex).trim() : rest - const unlessText = unlessIndex >= 0 ? rest.slice(unlessIndex + 8).trim() : undefined - return { - op: 'sacrifice', - player: parsePlayer(arg(args, 0, line), line), - target: parseTarget(targetText, line), - ...(unlessText ? { unless: parseCost(unlessText, line) } : {}), - } - } - case 'counter': { - const what = arg(args, 0, line) - if (what !== 'spell' && what !== 'ability') fail(line, `unknown counter kind "${what}"`) - const rest = arg(args, 1, line) - const unlessIndex = lastTopLevelIndex(rest, ' unless ') - const targetText = unlessIndex >= 0 ? rest.slice(0, unlessIndex).trim() : rest - const unlessText = unlessIndex >= 0 ? rest.slice(unlessIndex + 8).trim() : undefined - return { - op: 'counter', - what, - target: parseTarget(targetText, line), - ...(unlessText ? { unless: parseCost(unlessText, line) } : {}), - } - } - case 'return_to_battlefield': { - let tapped = false - let transformed: boolean | undefined - let counters: { counter: string; amount: Value } | undefined - for (const extra of args.slice(1)) { - const trimmed = extra.trim() - if (trimmed === 'tapped') tapped = true - else if (trimmed === 'transformed') transformed = true - else { - const counter = trimmed.match(/^(.+?) (.+) counters$/) - if (!counter) fail(line, `cannot read return_to_battlefield option "${trimmed}"`) - counters = { amount: parseValueText(counter[1], line), counter: counter[2] } - } - } - return { - op: 'return_to_battlefield', - target: parseTarget(arg(args, 0, line), line), - tapped, - transformed, - counters, - } - } - case 'scry': - case 'surveil': - return { op: name, player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } - case 'search': { - const destinationIndex = args.findIndex(value => /^to /.test(value.trim())) - if (destinationIndex < 0) fail(line, 'search needs a destination') - const destination = args[destinationIndex].trim().replace(/^to /, '') - if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(destination)) { - fail(line, `unknown search destination "${destination}"`) - } - const splitIndex = args.findIndex(value => /^then /.test(value.trim())) - let split: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } | undefined - if (splitIndex >= 0) { - const splitText = args[splitIndex].trim().replace(/^then /, '') - const splitTapped = / tapped$/.test(splitText) - const splitDestination = splitText.replace(/ tapped$/, '') - if (!['hand', 'battlefield', 'graveyard', 'top', 'bottom'].includes(splitDestination)) { - fail(line, `unknown search destination "${splitDestination}"`) - } - split = { - destination: splitDestination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', - tapped: splitTapped, - } - } - const before = args.slice(1, destinationIndex) - const amountText = before[before.length - 1] - if (amountText === undefined) fail(line, 'search needs an amount') - return { - op: 'search', - player: parsePlayer(arg(args, 0, line), line), - selector: parseSelector(before.slice(0, -1).join(', '), line), - amount: parseValueText(amountText, line), - destination: destination as 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom', - tapped: args.includes('tapped'), - shuffle: args.includes('shuffle'), - ...(split ? { split } : {}), - ...(args.includes('library+graveyard') ? { zones: ['library', 'graveyard'] as ('library' | 'graveyard')[] } : {}), - } - } - case 'shuffle': - return { op: 'shuffle', player: parsePlayer(arg(args, 0, line), line) } - case 'add_mana': - return { op: 'add_mana', player: parsePlayer(arg(args, 0, line), line), mana: parseMana(arg(args, 1, line), line) } - case 'fight': - return { op: 'fight', a: parseTarget(arg(args, 0, line), line), b: parseTarget(arg(args, 1, line), line) } - case 'energy': - return { op: 'energy', player: parsePlayer(arg(args, 0, line), line), amount: parseValueText(arg(args, 1, line), line) } - case 'attach': - return { op: 'attach', target: parseTarget(arg(args, args.length - 1, line), line) } - case 'restrict': { - const rule = arg(args, 1, line) - if (rule !== 'cant_attack' && rule !== 'cant_block' && rule !== 'doesnt_untap') { - fail(line, `unknown restriction rule "${rule}"`) - } - return { - op: 'restriction', - target: parseTarget(arg(args, 0, line), line), - rule, - duration: args[2] ? parseDurationText(args[2], line) : 'permanent', - } - } - case 'prevent_damage': - case 'prevent_combat_damage': { - const amountText = arg(args, 1, line) - return { - op: 'prevent_damage', - target: parseTarget(arg(args, 0, line), line), - amount: amountText === 'all' ? 'all' : parseValueText(amountText, line), - combatOnly: name === 'prevent_combat_damage' || undefined, - duration: args[2] ? parseDurationText(args[2], line) : 'permanent', - } - } - case 'gain_control': - return { - op: 'gain_control', - target: parseTarget(arg(args, 0, line), line), - duration: args[1] ? parseDurationText(args[1], line) : 'permanent', - } - case 'emblem': - return { op: 'emblem', text: unquote(arg(args, 0, line), line) } - case 'transform': - return { op: 'transform', target: parseTarget(arg(args, 0, line), line) } - case 'pay': - return { op: 'pay', costs: args.map(part => parseCost(part, line)) } - case 'look_top': - return { - op: 'look_top', - player: parsePlayer(arg(args, 0, line), line), - amount: parseValueText(arg(args, 1, line), line), - reorder: args.includes('reorder') || undefined, - } - case 'level_up': - return { op: 'level_up', level: Number(arg(args, 0, line)) } - case 'put_from_among': { - const last = arg(args, args.length - 1, line) - if (!last.startsWith('to ')) fail(line, 'put_from_among needs a destination') - const destination = last.slice(3) - if (!['hand', 'graveyard', 'battlefield', 'top', 'bottom'].includes(destination)) { - fail(line, `unknown destination "${destination}"`) - } - return { - op: 'put_from_among', - player: 'you', - amount: parseValueText(arg(args, 0, line), line), - ...(args.length > 2 ? { selector: parseSelector(args[1], line) } : {}), - destination: destination as 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom', - } - } - case 'dig': - return parseDig(args, line) - default: - return parseKeywordAction(name, args, line) - } -} - -function parseMana(text: string, line: SourceLine): ManaSpec { - const trimmed = text.trim() - if (/^(?:\{[^}]+\})+/.test(trimmed)) { - const symbols = trimmed.match(/\{[^}]+\}/g) ?? [] - const restriction = trimmed.match(/\(only (.+)\)$/)?.[1] - return { kind: 'symbols', symbols, restriction } - } - - const match = trimmed.match(/^(.+) mana of any( one)? color(?: \(only (.+)\))?$/) - if (!match) fail(line, `cannot read mana "${trimmed}"`) - return { - kind: 'any_color', - amount: parseValueText(match[1], line), - oneColor: Boolean(match[2]), - restriction: match[3], - } -} - -function parseDig(args: string[], line: SourceLine): Effect { - const amount = parseValueText(arg(args, 0, line), line) - const first = arg(args, 1, line) - const upTo = first.startsWith('up to ') - const pickMatch = (upTo ? first.slice(6) : first).match(/^(.*?) to (hand|battlefield)( tapped)?$/) - if (!pickMatch) fail(line, `cannot read dig destination in "${first}"`) - - const pickBody = pickMatch[1].trim() - const prefixed = parseValuePrefix(pickBody) - if (!prefixed) fail(line, `cannot read dig card count in "${pickBody}"`) - - let rest = 'bottom' - let order: 'any' | 'random' | undefined - let optional = false - for (const extra of args.slice(2)) { - const trimmed = extra.trim() - if (trimmed === 'optional') optional = true - else if (trimmed.startsWith('rest ')) { - const parts = trimmed.slice(5).split(' ') - rest = parts[0] - if (parts[1] === 'any' || parts[1] === 'random') order = parts[1] - } else fail(line, `cannot read dig option "${trimmed}"`) - } - - if (!['bottom', 'graveyard', 'top'].includes(rest)) fail(line, `unknown dig rest destination "${rest}"`) - return { - op: 'dig', - player: 'you', - amount, - pick: prefixed.value, - ...(prefixed.rest ? { pickSelector: parseSelector(prefixed.rest, line) } : {}), - upTo: upTo || undefined, - to: pickMatch[2] as 'hand' | 'battlefield', - tapped: Boolean(pickMatch[3]) || undefined, - rest: rest as 'bottom' | 'graveyard' | 'top', - order, - optional: optional || undefined, - } -} - -function parseKeywordAction(name: string, args: string[], line: SourceLine): Effect { - const action = name.replace(/_/g, ' ') - let target: Target | undefined - let amount: Value | undefined - let detail: string | undefined - - if (args.length === 1) { - if (args[0].trim()) { - try { - target = parseTarget(args[0], line) - } catch { - amount = parseValueText(args[0], line) - } - } - } else if (args.length >= 2) { - amount = parseValueText(args[0], line) - detail = args.slice(1).join(', ') - } - - return { op: 'keyword_action', action, ...(amount ? { amount } : {}), ...(target ? { target } : {}), ...(detail ? { detail } : {}) } -} - -function unquote(text: string, line: SourceLine): string { - const trimmed = text.trim() - if (!trimmed.startsWith('"') || !trimmed.endsWith('"')) fail(line, 'expected a quoted string') - return trimmed.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\') -} - -function parseTokenSpec(text: string, line: SourceLine): TokenSpec { - let rest = text.trim() - const tapped = rest.startsWith('tapped ') - if (tapped) rest = rest.slice(7) - - let power: Value | undefined - let toughness: Value | undefined - const pt = rest.match(/^(\S+)\/(\S+) /) - if (pt) { - power = parseValueText(pt[1], line) - toughness = parseValueText(pt[2], line) - rest = rest.slice(pt[0].length) - } - - const colors: string[] = [] - while (rest) { - const color = rest.match(/^(white|blue|black|red|green|colorless)(?: and )?(.*)$/) - if (!color) break - colors.push(COLOR_WORDS[color[1]]) - rest = color[2].trim() - } - - let keywords: string[] | undefined - const withMatch = rest.match(/^(.*?) with (.+)$/) - if (withMatch) { - rest = withMatch[1].trim() - keywords = withMatch[2].split(', ').map(value => value.trim()).filter(Boolean) - } - - const types: string[] = [] - const subtypes: string[] = [] - for (const word of rest.split(/\s+/).filter(Boolean)) { - if (word === 'and') continue - const singular = singularize(word) - if (TYPE_WORDS.has(singular)) types.push(singular) - else if (/^[a-z][a-z'-]*$/.test(singular)) subtypes.push(singular) - else fail(line, `cannot read token type "${word}"`) - } - - return { - types: types.length ? types : [power ? 'creature' : 'artifact'], - subtypes, - colors, - power, - toughness, - keywords, - tapped: tapped || undefined, - } -} - -function parseConditionText(text: string, line: SourceLine): Condition { - const trimmed = text.trim() - - if (trimmed === 'it is your turn') return { kind: 'your_turn' } - if (trimmed === "it isn't your turn" || trimmed === 'it is not your turn') return { kind: 'not_your_turn' } - if (trimmed === 'this is tapped') return { kind: 'source_tapped' } - if (trimmed === 'this is untapped') return { kind: 'source_untapped' } - if (trimmed === 'this is attacking') return { kind: 'source_attacking' } - if (trimmed === 'this was kicked') return { kind: 'was_kicked' } - if (trimmed === 'this attacked this turn') return { kind: 'attacked_this_turn' } - if (trimmed === 'you attacked this turn') return { kind: 'you_attacked_this_turn' } - if (trimmed === 'you cast it') return { kind: 'cast' } - if (trimmed === 'you cast it from your hand') return { kind: 'cast', fromHand: true } - if (trimmed === 'this is in your graveyard') return { kind: 'in_graveyard' } - if (trimmed === 'this is on the battlefield') return { kind: 'on_battlefield' } - if (trimmed === "you're the monarch") return { kind: 'monarch' } - if (trimmed === 'you have the initiative') return { kind: 'initiative' } - if (trimmed === "you have the city's blessing") return { kind: 'citys_blessing' } - if (trimmed === 'this is suspended') return { kind: 'suspended' } - if (trimmed === 'it was bargained') return { kind: 'bargained' } - if (trimmed === 'it was a creature') return { kind: 'was_creature' } - if (trimmed === 'an opponent lost life this turn') return { kind: 'opponent_lost_life_this_turn' } - if (trimmed === 'you gained or lost life this turn') return { kind: 'life_changed_this_turn' } - if (trimmed === 'you descended this turn') return { kind: 'descended_this_turn' } - if (trimmed === 'a permanent you controlled left the battlefield this turn') { - return { kind: 'permanent_left_battlefield_this_turn', controller: 'you' } - } - if (trimmed === 'you have more cards in hand than each opponent') return { kind: 'more_cards_than_each_opponent' } - if (trimmed === 'it is the first combat phase of the turn') return { kind: 'first_combat_phase' } - if (trimmed === 'it is not a token') return { kind: 'not_token' } - if (trimmed === "you've cast a spell this turn") return { kind: 'cast_spell_this_turn' } - if (trimmed === "you've cast a noncreature spell this turn") { - return { kind: 'cast_spell_this_turn', noncreature: true } - } - if (trimmed === 'you have a full party') return { kind: 'full_party' } - if (trimmed === 'you control a commander') return { kind: 'you_control_commander' } - if (trimmed === 'no spells were cast last turn') return { kind: 'no_spells_last_turn' } - if (trimmed === 'no creatures attacked this turn') return { kind: 'no_attackers' } - if (trimmed === "tribute wasn't paid") return { kind: 'tribute_not_paid' } - if (trimmed === 'mana from a Treasure was spent to cast it') return { kind: 'mana_from_treasure' } - if (trimmed === 'no mana was spent to cast it') return { kind: 'no_mana_spent' } - if (trimmed === 'you gained life this turn') return { kind: 'you_gained_life_this_turn' } - if (trimmed === 'you drew a card this turn') return { kind: 'you_drew_cards_this_turn', atLeast: 1 } - if (trimmed === 'you have no cards in hand') return { kind: 'hand_empty', player: 'you' } - if (trimmed === 'an opponent has no cards in hand') return { kind: 'hand_empty', player: 'opponent' } - if (trimmed === 'a creature died this turn') return { kind: 'creature_died_this_turn' } - if (trimmed === 'a creature you control died this turn') { - return { kind: 'creature_died_this_turn', controller: 'you' } - } - if (trimmed === 'a creature an opponent controls died this turn') { - return { kind: 'creature_died_this_turn', controller: 'opponent' } - } - if (trimmed === 'an opponent controls more lands than you') return { kind: 'opponent_controls_more_lands' } - if (trimmed === 'it is not their turn') return { kind: 'not_their_turn' } - if (trimmed === 'it had counters on it') return { kind: 'had_counters' } - if (trimmed === 'you do') return { kind: 'if_you_do' } - if (trimmed === "you don't") return { kind: 'if_you_dont' } - if (trimmed === 'otherwise') return { kind: 'otherwise' } - if (trimmed === 'defending player controls') return fail(line, 'missing defending-player selector') - - let match = trimmed.match(/^an opponent was dealt (\d+)\+ damage this turn$/) - if (match) return { kind: 'opponent_damaged_this_turn', atLeast: Number(match[1]) } - match = trimmed.match(/^you attacked with (\d+)\+ creatures this turn$/) - if (match) return { kind: 'attacked_with_creatures', atLeast: Number(match[1]) } - match = trimmed.match(/^a library has (\d+) or fewer cards in it$/) - if (match) return { kind: 'library_at_most', atMost: Number(match[1]) } - - match = trimmed.match(/^you control (\d+)\+ creatures with different powers$/) - if (match) return { kind: 'distinct_powers', atLeast: Number(match[1]) } - match = trimmed.match(/^you control (\d+)\+ (.+?) with different names$/) - if (match) return { kind: 'distinct_names', selector: parseSelector(match[2], line), atLeast: Number(match[1]) } - match = trimmed.match(/^you control a creature with (power|toughness) greater than its base (?:power|toughness)$/) - if (match) { - return { kind: 'creature_power_greater_than_base', controller: 'you', stat: match[1] as 'power' | 'toughness' } - } - match = trimmed.match(/^you control at least (\d+) (.+)$/) - if (match) return { kind: 'you_control', selector: parseSelector(match[2], line), atLeast: Number(match[1]) } - match = trimmed.match(/^you control (.+)$/) - if (match) return { kind: 'you_control', selector: parseSelector(match[1], line) } - match = trimmed.match(/^an opponent controls (.+)$/) - if (match) return { kind: 'opponent_controls', selector: parseSelector(match[1], line) } - - match = trimmed.match(/^(.+) has at least (\d+) life more than their starting life total$/) - if (match) { - return { kind: 'life_above_starting', player: parsePlayer(match[1], line), amount: Number(match[2]) } - } - match = trimmed.match(/^(.+) has at least (\d+) life$/) - if (match) return { kind: 'life_at_least', player: parsePlayer(match[1], line), amount: Number(match[2]) } - match = trimmed.match(/^(.+) has at most (\d+) life$/) - if (match) return { kind: 'life_at_most', player: parsePlayer(match[1], line), amount: Number(match[2]) } - - match = trimmed.match(/^(.+) has (\d+)\+ cards in their graveyard$/) - if (match) return { kind: 'cards_in_graveyard', player: parsePlayer(match[1], line), atLeast: Number(match[2]) } - match = trimmed.match(/^(.+) has no cards in hand$/) - if (match) return { kind: 'hand_empty', player: parsePlayer(match[1], line) } - match = trimmed.match(/^(.+) has (\d+) or fewer cards in hand$/) - if (match) return { kind: 'cards_in_hand_at_most', who: parsePlayer(match[1], line), atMost: Number(match[2]) } - - match = trimmed.match(/^you gained at least (\d+) life this turn$/) - if (match) return { kind: 'you_gained_life_this_turn', atLeast: Number(match[1]) } - match = trimmed.match(/^you drew (\d+)\+ cards this turn$/) - if (match) return { kind: 'you_drew_cards_this_turn', atLeast: Number(match[1]) } - match = trimmed.match(/^(.+) cast (\d+)\+ spells last turn$/) - if (match) { - const who = match[1] - if (who !== 'you' && who !== 'opponent' && who !== 'each_player' && who !== 'a_player') { - fail(line, `unknown spell caster "${who}"`) - } - return { kind: 'spells_cast_last_turn', who, atLeast: Number(match[2]) } - } - - match = trimmed.match(/^(\d+)\+ nonland permanents entered the battlefield under your control this turn$/) - if (match) return { kind: 'nonland_permanents_entered_this_turn', atLeast: Number(match[1]) } - match = trimmed.match(/^you attacked with total power (\d+)\+ this combat$/) - if (match) return { kind: 'attacked_with_total_power', atLeast: Number(match[1]) } - match = trimmed.match(/^creatures you control have total power (\d+)\+$/) - if (match) return { kind: 'total_power', controller: 'you', atLeast: Number(match[1]) } - match = trimmed.match(/^there are (\d+)\+ card types among cards in your graveyard$/) - if (match) return { kind: 'graveyard_card_types', atLeast: Number(match[1]) } - match = trimmed.match(/^there are (\d+)\+ (.+?) in your graveyard$/) - if (match) return { kind: 'graveyard_count', selector: parseSelector(match[2], line), atLeast: Number(match[1]) } - match = trimmed.match(/^no (.+) on the battlefield$/) - if (match) return { kind: 'no_objects', selector: parseSelector(match[1], line) } - match = trimmed.match(/^an opponent has (\d+)\+ poison counters$/) - if (match) return { kind: 'opponent_poison', atLeast: Number(match[1]) } - match = trimmed.match(/^it had a (.+) counter on it$/) - if (match) return { kind: 'had_counters', counter: match[1] } - match = trimmed.match(/^at least (\d+) mana was spent to cast it$/) - if (match) return { kind: 'mana_spent', atLeast: Number(match[1]) } - match = trimmed.match(/^((?:\{[^}]+\})+) was spent to cast it$/) - if (match) return { kind: 'mana_symbol_spent', symbols: match[1] } - match = trimmed.match(/^((?:\{[^}]+\})+)$/) - if (match) return { kind: 'mana_symbol_spent', symbols: match[1] } - match = trimmed.match(/^it was kicked with ((?:\{[^}]+\})+)$/) - if (match) return { kind: 'kicked_with', cost: match[1] } - match = trimmed.match(/^defending player controls (.+)$/) - if (match) return { kind: 'defending_player_controls', selector: parseSelector(match[1], line) } - match = trimmed.match(/^it targets (.+)$/) - if (match) return { kind: 'targets', selector: parseSelector(match[1], line) } - - return fail(line, `cannot read condition "${trimmed}"`) -} - -function parseTrigger(text: string, line: SourceLine): TriggerEvent { - const call = parseCall(text) - if (!call) fail(line, `cannot read trigger "${text}"`) - const { name, args } = call - - switch (name) { - case 'enters': - case 'dies': - case 'attacks': - case 'blocks': - case 'attacks_or_blocks': - case 'enters_or_attacks': - case 'enters_or_dies': - case 'leaves_battlefield': - return { kind: name, subject: parseTarget(arg(args, 0, line), line) } - case 'deals_damage': - case 'deals_combat_damage': { - const recipient = arg(args, 1, line) - if (!['player', 'creature', 'permanent', 'any'].includes(recipient)) { - fail(line, `unknown damage recipient "${recipient}"`) - } - return { - kind: 'deals_damage', - subject: parseTarget(arg(args, 0, line), line), - recipient: recipient as 'player' | 'creature' | 'permanent' | 'any', - combat: name === 'deals_combat_damage', - } - } - case 'upkeep': - case 'end_step': - case 'begin_combat': - return { - kind: name, - who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), - } - case 'first_main_phase': - case 'postcombat_main_phase': - return { - kind: 'main_phase', - who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), - phase: name === 'first_main_phase' ? 'first' : 'postcombat', - } - case 'cast': { - const spellText = arg(args, 1, line) - const spell: ObjectSelector = spellText === 'any spell' - ? { types: [] } - : parseSelector(spellText.replace(/ spells?$/, ''), line) - const ordinalText = args.find(value => /^#\d+ each turn$/.test(value.trim())) - return { - kind: 'cast', - who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), - spell, - targetsSelf: args.includes('targets this') || undefined, - orCopy: args.includes('or copy') || undefined, - ordinal: ordinalText ? Number(ordinalText.trim().match(/\d+/)?.[0]) : undefined, - } - } - case 'becomes_level': - return { kind: 'becomes_level', level: Number(arg(args, 0, line)) } - case 'draw': { - const ordinalText = args[1]?.trim() - return { - kind: 'draw', - who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), - ...(ordinalText ? { ordinal: Number(ordinalText.match(/\d+/)?.[0]) } : {}), - } - } - case 'counter_placed': - return { - kind: 'counter_placed', - subject: parseTarget(arg(args, 0, line), line), - ...(args[1] ? { counter: args[1].trim() } : {}), - } - case 'becomes_target': - return { kind: 'becomes_target', subject: parseTarget(arg(args, 0, line), line) } - case 'gain_life': - case 'lose_life': - return { - kind: 'life', - who: parsePlayerOrThrow(arg(args, 0, line), line, ['you', 'opponent', 'each_player']), - mode: name === 'gain_life' ? 'gain' : 'lose', - } - default: - return fail(line, `cannot read trigger "${text}"`) - } -} - -function parseEffects(lines: SourceLine[]): Effect[] { - if (!lines.length) fail(lines[0] ?? { text: '', indent: 0, line: 1 }, 'expected an effect') - const base = Math.min(...lines.map(line => line.indent)) - return parseEffectSequence(lines, 0, base).effects -} - -function parseEffectSequence( - lines: SourceLine[], - start: number, - base: number, -): { effects: Effect[]; next: number } { - const effects: Effect[] = [] - let index = start - - while (index < lines.length) { - const line = lines[index] - if (line.indent < base) break - if (line.indent > base) fail(line, 'unexpected indentation') - - const text = line.text.trim() - - let match = text.match(/^if (.+):$/) - if (match) { - const nested = collectIndented(lines, index + 1, base) - if (!nested.lines.length) fail(line, 'if needs an indented body') - effects.push({ op: 'conditional', condition: parseConditionText(match[1], line), effects: parseEffects(nested.lines) }) - index = nested.next - continue - } - - match = text.match(/^choose (\d+)(?:-(\d+))?:$/) - if (match) { - const nested = collectIndented(lines, index + 1, base) - if (!nested.lines.length) fail(line, 'choose needs an indented body') - const modeIndent = nested.lines[0].indent - const modes: Effect[][] = [] - let modeIndex = 0 - while (modeIndex < nested.lines.length) { - const modeLine = nested.lines[modeIndex] - const mode = modeLine.text.trim().match(/^(\d+)\.\s*(.*)$/) - if (!mode || modeLine.indent !== modeIndent) fail(modeLine, 'choose modes must be numbered') - const modeLines: SourceLine[] = splitTopLevel(mode[2], ';') - .map(part => part.trim()) - .filter(Boolean) - .map(part => ({ text: part, indent: 0, line: modeLine.line })) - let next = modeIndex + 1 - while (next < nested.lines.length && nested.lines[next].indent > modeIndent) { - modeLines.push({ ...nested.lines[next], indent: nested.lines[next].indent - modeIndent }) - next++ - } - modes[Number(mode[1]) - 1] = parseEffectSequence(modeLines, 0, 0).effects - modeIndex = next - } - if (!modes.length || modes.some(mode => !mode)) fail(line, 'choose modes must be numbered from 1') - const min = Number(match[1]) - const max = match[2] ? Number(match[2]) : min - effects.push({ op: 'modal', min, max, modes }) - index = nested.next - continue - } - - match = text.match(/^schedule\((next_upkeep|next_end_step)\):$/) - if (match) { - const nested = collectIndented(lines, index + 1, base) - if (!nested.lines.length) fail(line, 'schedule needs an indented body') - effects.push({ op: 'schedule', when: match[1] as 'next_upkeep' | 'next_end_step', effects: parseEffects(nested.lines) }) - index = nested.next - continue - } - - effects.push(...parseEffectExprList(text, line)) - index++ - } - - return { effects, next: index } -} - -function collectIndented(lines: SourceLine[], start: number, base: number): { lines: SourceLine[]; next: number } { - let index = start - while (index < lines.length && lines[index].indent > base) index++ - return { lines: lines.slice(start, index), next: index } -} - -function parseStaticEffects(lines: SourceLine[]): StaticEffect[] { - if (!lines.length) fail(lines[0] ?? { text: '', indent: 0, line: 1 }, 'expected a static effect') - const base = Math.min(...lines.map(line => line.indent)) - const effects: StaticEffect[] = [] - let index = 0 - - while (index < lines.length) { - const line = lines[index] - if (line.indent !== base) fail(line, 'unexpected indentation') - const text = line.text.trim() - - if (text.startsWith('grant_ability(') && text.endsWith('):')) { - const call = parseCall(text.slice(0, -1)) - if (!call || call.name !== 'grant_ability') fail(line, `cannot read static effect "${text}"`) - const nested = collectIndented(lines, index + 1, base) - if (!nested.lines.length) fail(line, 'grant_ability needs an indented ability') - const abilities = parseBlocks(nested.lines) - if (abilities.length !== 1) fail(line, 'grant_ability needs exactly one ability') - effects.push({ - op: 'grant_ability', - target: parseTarget(arg(call.args, 0, line), line), - ability: abilities[0], - }) - index = nested.next - continue - } - - effects.push(parseStaticEffect(text, line)) - index++ - } - - return effects -} - -function parseStaticEffect(text: string, line: SourceLine): StaticEffect { - const call = parseCall(text) - if (!call) fail(line, `expected a static effect, got "${text}"`) - const { name, args } = call - - switch (name) { - case 'pump': { - const pt = splitPowerToughness(arg(args, 1, line)) - if (!pt) fail(line, `expected power/toughness, got "${args[1]}"`) - return { - op: 'pump', - target: parseTarget(arg(args, 0, line), line), - power: parseValueText(pt[0], line), - toughness: parseValueText(pt[1], line), - } - } - case 'grant': { - const keyword = parseKeyword(args.slice(1).join(', ')) - return { - op: 'grant', - target: parseTarget(arg(args, 0, line), line), - keyword: keyword.keyword, - value: keyword.value, - } - } - case 'grant_ability': { - let abilityText = arg(args, 1, line).trim() - if (abilityText.startsWith('(') && abilityText.endsWith(')')) abilityText = abilityText.slice(1, -1) - return { - op: 'grant_ability', - target: parseTarget(arg(args, 0, line), line), - ability: parseInlineAbility(abilityText, line), - } - } - case 'restrict': { - const target = parseTarget(arg(args, 0, line), line) - const rest = args.slice(1).join(', ').trim() - const ifIndex = lastTopLevelIndex(rest, ' if ') - const before = ifIndex >= 0 ? rest.slice(0, ifIndex).trim() : rest - const condition = ifIndex >= 0 ? parseConditionText(rest.slice(ifIndex + 4), line) : undefined - const rule = before.split(/\s+/)[0] - const detail = before.slice(rule.length).trim() - return { - op: 'restriction', - target, - rule, - ...(detail ? { detail } : {}), - ...(condition ? { condition } : {}), - } - } - case 'enters_tapped': { - const unlessIndex = lastTopLevelIndex(text, ', unless ') - const targetText = unlessIndex >= 0 ? arg(args, 0, line) : arg(args, 0, line) - const unlessArg = args.length > 1 ? args.slice(1).join(', ').replace(/^unless /, '') : undefined - return { - op: 'enters_tapped', - target: parseTarget(targetText, line), - ...(unlessArg ? { unless: parseConditionText(unlessArg, line) } : {}), - } - } - case 'enters_with_counters': - return { - op: 'enters_with_counters', - target: parseTarget(arg(args, 0, line), line), - counter: args.slice(1, -1).join(', ').trim(), - amount: parseValueText(arg(args, args.length - 1, line), line), - } - case 'set_pt': { - const base = args[1]?.trim() === 'base' - const ptText = arg(args, base ? 2 : 1, line) - const pt = splitPowerToughness(ptText) - if (!pt) fail(line, `expected power/toughness, got "${ptText}"`) - return { - op: 'set_pt', - target: parseTarget(arg(args, 0, line), line), - power: pt[0] === '?' ? undefined : parseValueText(pt[0], line), - toughness: pt[1] === '?' ? undefined : parseValueText(pt[1], line), - base: base || undefined, - } - } - case 'control': - return { op: 'control', target: parseTarget(arg(args, 0, line), line) } - case 'choose': { - const what = arg(args, 0, line) - if (!['creature_type', 'color', 'card_name', 'player', 'opponent', 'number'].includes(what)) { - fail(line, `unknown choice "${what}"`) - } - return { op: 'choose', what: what as 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' } - } - case 'replace': { - const what = arg(args, 0, line) - if (!['dies', 'leaves_battlefield', 'discard', 'draw'].includes(what)) fail(line, `unknown replacement "${what}"`) - const targetText = args.length > 2 ? args[1] : undefined - const instead = arg(args, args.length - 1, line).replace(/^instead /, '') - if (!['exile', 'return_to_hand', 'return_to_library', 'prevent'].includes(instead)) { - fail(line, `unknown replacement result "${instead}"`) - } - return { - op: 'replacement', - what: what as 'dies' | 'leaves_battlefield' | 'discard' | 'draw', - instead: instead as 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent', - ...(targetText ? { target: parseTarget(targetText, line) } : {}), - } - } - case 'cost_reduction': { - const rest = args[2]?.trim() - const value = arg(args, 1, line).trim() - return { - op: 'cost_reduction', - target: parseTarget(arg(args, 0, line), line), - ...(/^(?:\{[^}]+\})+$/.test(value) - ? { symbols: value } - : { amount: parseValueText(value, line) }), - ...(rest?.startsWith('if ') ? { condition: parseConditionText(rest.slice(3), line) } : {}), - } - } - case 'cost_increase': { - const spellType = args[1]?.trim() - if (spellType && spellType !== 'noncreature' && spellType !== 'creature') { - fail(line, `unknown spell type "${spellType}"`) - } - return { - op: 'cost_increase', - amount: parseValueText(arg(args, 0, line), line), - ...(spellType ? { spellType: spellType as 'noncreature' | 'creature' } : {}), - } - } - case 'search_restriction': { - const who = arg(args, 0, line) - if (who !== 'opponent' && who !== 'you') fail(line, `unknown search restriction player "${who}"`) - return { op: 'search_restriction', who, amount: parseValueText(arg(args, 1, line), line) } - } - case 'exile_instead_of_graveyard': { - const owner = args[0]?.trim() - if (owner && owner !== 'opponent' && owner !== 'you') { - fail(line, `unknown replacement owner "${owner}"`) - } - return { op: 'exile_instead_of_graveyard', ...(owner ? { owner: owner as 'opponent' | 'you' } : {}) } - } - case 'unsupported': - return fail(line, 'unsupported is an ability, not a static effect') - default: - return fail(line, `cannot read static effect "${text}"`) - } -} - -function parseInlineAbility(text: string, line: SourceLine): Ability { - const trimmed = text.trim() - const colon = firstTopLevelIndex(trimmed, ':') - if (colon < 0) return parseAbilityBlock({ header: { text: trimmed, indent: 0, line: line.line }, body: [] }) - - const header = trimmed.slice(0, colon + 1) - const bodyText = trimmed.slice(colon + 1).trim() - const body = bodyText - ? splitTopLevel(bodyText, ';').map(effect => ({ text: ` ${effect.trim()}`, indent: 2, line: line.line })) - : [] - return parseAbilityBlock({ header: { text: header, indent: 0, line: line.line }, body }) -} - -function parseAbilityBlock(block: Block): Ability { - const header = block.header.text.trim() - const body = block.body - - const unsupported = header.match(/^unsupported \(([^)]*)\): ?(.*)$/) - if (unsupported) { - const text = [unsupported[2], ...body.map(line => line.text.trim())].filter(Boolean).join('\n') - return { kind: 'unsupported', reason: unsupported[1], text } - } - - let match = header.match(/^keyword (.+)$/) - if (match) return parseKeyword(match[1]) - - match = header.match(/^keywords (.+)$/) - if (match) return { kind: 'keywords', keywords: parseKeywordList(match[1]) } - - match = header.match(/^level_pt\((.+)\/(.+)\)$/) - if (match) { - return { - kind: 'level_pt', - power: parseValueText(match[1], block.header), - toughness: parseValueText(match[2], block.header), - text: header, - } - } - - match = header.match(/^level (\d+)(?:-(\d+)|\+)(?:: (.+)\/(.+))?$/) - if (match) { - return { - kind: 'level_band', - min: Number(match[1]), - max: match[2] ? Number(match[2]) : undefined, - power: match[3] ? parseValueText(match[3], block.header) : undefined, - toughness: match[4] ? parseValueText(match[4], block.header) : undefined, - text: header, - } - } - - match = header.match(/^additional cost( \(may\))?: ?(.*)$/) - if (match) { - const costsText = [match[2], ...body.map(line => line.text.trim())].filter(Boolean).join(', ') - return { kind: 'additional_cost', costs: parseCosts(costsText, block.header), optional: Boolean(match[1]), text: header } - } - - match = header.match(/^alternative cost(?: if (.+?))?: ?(.*)$/) - if (match) { - const costsText = match[2].trim() - return { - kind: 'alternative_cost', - costs: costsText === 'free' ? [] : parseCosts(costsText, block.header), - ...(match[1] ? { condition: parseConditionText(match[1], block.header) } : {}), - text: header, - } - } - - match = header.match(/^overload ((?:\{[^}]+\})+)$/) - if (match) return { kind: 'overload', cost: match[1], text: header } - - if (!header.endsWith(':')) fail(block.header, `expected an ability block, got "${header}"`) - let rest = header.slice(0, -1) - - match = rest.match(/^chapter (.+?)( \(may\))?$/) - if (match) { - return { - kind: 'chapter', - chapters: splitTopLevel(match[1], ',').map(value => value.trim().toUpperCase()), - effects: parseEffects(body), - optional: Boolean(match[2]), - text: header, - } - } - - if (rest === 'spell' || rest === 'spell (may)') { - return { kind: 'spell', effects: parseEffects(body), optional: rest.endsWith('(may)'), text: header } - } - - match = rest.match(/^static(?: if (.+))?$/) - if (match) { - return { kind: 'static', effects: parseStaticEffects(body), ...(match[1] ? { condition: parseConditionText(match[1], block.header) } : {}), text: header } - } - - if (rest.startsWith('on ')) { - let triggerText = rest.slice(3).trim() - const optional = triggerText.endsWith(' (may)') - if (optional) triggerText = triggerText.slice(0, -6).trim() - const call = readCallPrefix(triggerText) - if (!call) fail(block.header, `cannot read trigger "${triggerText}"`) - let tail = triggerText.slice(call.end).trim() - let condition: Condition | undefined - if (tail.startsWith('if ')) { - condition = parseConditionText(tail.slice(3), block.header) - tail = '' - } - if (tail) fail(block.header, `unexpected trigger text "${tail}"`) - return { - kind: 'triggered', - event: parseTrigger(triggerText.slice(0, call.end).trim(), block.header), - condition, - effects: parseEffects(body), - optional, - text: header, - } - } - - if (rest.startsWith('activate ')) { - let costsText = rest.slice(9).trim() - let optional = false - let timing: 'instant' | 'sorcery' | undefined - let activationsPerTurn: number | undefined - - if (costsText.endsWith(' (may)')) { - optional = true - costsText = costsText.slice(0, -6).trim() - } - if (costsText.endsWith(' (sorcery speed)')) { - timing = 'sorcery' - costsText = costsText.slice(0, -16).trim() - } - const perTurn = costsText.match(/ \((\d+)\/turn\)$/) - if (perTurn) { - activationsPerTurn = Number(perTurn[1]) - costsText = costsText.slice(0, perTurn.index).trim() - } - - let condition: Condition | undefined - const ifIndex = lastTopLevelIndex(costsText, ' if ') - if (ifIndex >= 0) { - condition = parseConditionText(costsText.slice(ifIndex + 4), block.header) - costsText = costsText.slice(0, ifIndex).trim() - } - - return { - kind: 'activated', - costs: parseCosts(costsText, block.header), - effects: parseEffects(body), - condition, - timing, - activationsPerTurn, - optional, - text: header, - } - } - - return fail(block.header, `cannot read ability "${header}"`) -} - -interface Section { - name?: string - lines: SourceLine[] - empty: boolean -} - -function splitSections(lines: SourceLine[]): Section[] { - const sections: Section[] = [{ lines: [], empty: false }] - for (const line of lines) { - const trimmed = line.text.trim() - if (!trimmed) continue - if (trimmed.startsWith('##')) { - const name = trimmed.replace(/^##\s*/, '').replace(/\s+\[[^\]]*\]$/, '').trim() - if (!name) fail(line, 'face section needs a name') - sections.push({ name, lines: [], empty: false }) - continue - } - if (trimmed.startsWith('#')) continue - if (trimmed === '(no abilities)') { - sections[sections.length - 1].empty = true - continue - } - sections[sections.length - 1].lines.push(line) - } - return sections -} - -function parseBlocks(lines: SourceLine[]): Ability[] { - if (!lines.length) return [] - const base = Math.min(...lines.map(line => line.indent)) - const blocks: Block[] = [] - - for (const line of lines) { - const indent = line.indent - base - if (indent < 0) fail(line, 'unexpected indentation') - if (indent === 0) { - blocks.push({ header: line, body: [] }) - } else { - const block = blocks[blocks.length - 1] - if (!block) fail(line, 'indented line without an ability') - block.body.push({ ...line, indent }) - } - } - - if (!blocks.length) return [] - return blocks.map(parseAbilityBlock) -} - -function toSourceLines(source: string): SourceLine[] { - const lines: SourceLine[] = [] - source.replace(/\r\n?/g, '\n').split('\n').forEach((raw, index) => { - if (!raw.trim()) return - lines.push({ text: raw, indent: countIndent(raw), line: index + 1 }) - }) - return lines -} - -export function parsePseudoCard(source: string): ParsedCardPseudo { - if (!source.trim()) throw new PseudoParseError('the implementation is empty', 1) - const sections = splitSections(toSourceLines(source)) - const named = sections.filter((section): section is Section & { name: string } => Boolean(section.name)) - - if (named.length) { - const leading = sections[0] - if (leading.lines.length) throw new PseudoParseError('abilities before the first "## face" section', leading.lines[0].line) - const faces = named.map(section => ({ - name: section.name, - abilities: parseBlocks(section.lines), - })) - return { abilities: [], faces } - } - - const abilities = parseBlocks(sections[0]?.lines ?? []) - if (!abilities.length && !sections[0]?.empty) { - throw new PseudoParseError('the implementation has no abilities', 1) - } - return { abilities } -} diff --git a/backend/src/effects/source.ts b/backend/src/effects/source.ts new file mode 100644 index 0000000..d72c81f --- /dev/null +++ b/backend/src/effects/source.ts @@ -0,0 +1,2484 @@ +// Safe JavaScript card source. A card implementation is a module-shaped +// expression that calls the builder API below: +// +// export default [ +// triggered(when.enters(permanents.withType('creature')), () => { +// gainLife(you, 1) +// }), +// ] +// +// The source is tokenized, parsed and evaluated against that API only. It is +// never passed to eval or new Function, so a saved override cannot run code. + +import { SIMPLE_KEYWORDS } from './compile.js' +import { singularize } from './parse.js' +import type { + Ability, + Condition, + Cost, + Duration, + Effect, + KeywordAbility, + ManaSpec, + ObjectSelector, + PlayerRef, + SearchDestination, + StaticEffect, + Target, + TokenSpec, + TriggerEvent, + Value, + Zone, +} from './types.js' + +export class SourceParseError extends Error { + readonly line: number + readonly column: number + + constructor(message: string, line: number, column = 1) { + super(`line ${line}: ${message}`) + this.name = 'SourceParseError' + this.line = line + this.column = column + } +} + +export interface ParsedFaceSource { + name: string + typeLine?: string + abilities: Ability[] +} + +export interface ParsedCardSource { + typeLine?: string + abilities: Ability[] + faces?: ParsedFaceSource[] +} + +// --------------------------------------------------------------------------- +// Tokenizer and safe expression interpreter +// --------------------------------------------------------------------------- + +type TokenKind = 'identifier' | 'number' | 'string' | 'punctuation' | 'eof' + +interface Token { + kind: TokenKind + value: string + line: number + column: number +} + +function isIdentifierStart(char: string | undefined): boolean { + return Boolean(char && /[A-Za-z_$]/.test(char)) +} + +function isIdentifierPart(char: string | undefined): boolean { + return Boolean(char && /[A-Za-z0-9_$]/.test(char)) +} + +function tokenize(source: string): Token[] { + const tokens: Token[] = [] + let index = 0 + let line = 1 + let column = 1 + + const advance = (count = 1): void => { + for (let step = 0; step < count; step++) { + if (source[index] === '\n') { + line++ + column = 1 + } else { + column++ + } + index++ + } + } + + while (index < source.length) { + const char = source[index] + + if (char === ' ' || char === '\t' || char === '\r' || char === '\n') { + advance() + continue + } + + if (char === '/' && source[index + 1] === '/') { + while (index < source.length && source[index] !== '\n') advance() + continue + } + + if (char === '/' && source[index + 1] === '*') { + const startLine = line + const startColumn = column + advance(2) + while (index < source.length && !(source[index] === '*' && source[index + 1] === '/')) advance() + if (index >= source.length) throw new SourceParseError('unterminated block comment', startLine, startColumn) + advance(2) + continue + } + + const startLine = line + const startColumn = column + + if (isIdentifierStart(char)) { + let value = '' + while (isIdentifierPart(source[index])) { + value += source[index] + advance() + } + tokens.push({ kind: 'identifier', value, line: startLine, column: startColumn }) + continue + } + + if (char >= '0' && char <= '9') { + let value = '' + while (source[index] >= '0' && source[index] <= '9') { + value += source[index] + advance() + } + if (source[index] === '.' && source[index + 1] >= '0' && source[index + 1] <= '9') { + value += '.' + advance() + while (source[index] >= '0' && source[index] <= '9') { + value += source[index] + advance() + } + } + tokens.push({ kind: 'number', value, line: startLine, column: startColumn }) + continue + } + + if (char === "'" || char === '"') { + const quote = char + advance() + let value = '' + while (index < source.length && source[index] !== quote) { + if (source[index] === '\\') { + advance() + const escape = source[index] + if (escape === undefined) break + if (escape === 'n') value += '\n' + else if (escape === 'r') value += '\r' + else if (escape === 't') value += '\t' + else if (escape === 'b') value += '\b' + else if (escape === 'f') value += '\f' + else if (escape === 'v') value += '\v' + else if (escape === '0') value += '\0' + else value += escape + advance() + continue + } + value += source[index] + advance() + } + if (source[index] !== quote) { + throw new SourceParseError('unterminated string', startLine, startColumn) + } + advance() + tokens.push({ kind: 'string', value, line: startLine, column: startColumn }) + continue + } + + if (char === '=' && source[index + 1] === '>') { + tokens.push({ kind: 'punctuation', value: '=>', line: startLine, column: startColumn }) + advance(2) + continue + } + + if ('()[]{},.:;=+-'.includes(char)) { + tokens.push({ kind: 'punctuation', value: char, line: startLine, column: startColumn }) + advance() + continue + } + + throw new SourceParseError(`unexpected character "${char}"`, startLine, startColumn) + } + + tokens.push({ kind: 'eof', value: '', line, column }) + return tokens +} + +class Interpreter { + private readonly tokens: Token[] + private index = 0 + private readonly env: Record + + constructor(source: string) { + this.tokens = tokenize(source) + this.env = createApi() + } + + parseProgram(): unknown { + if (this.peek().kind === 'eof') this.fail('the implementation is empty') + + while (this.isWord('const')) { + this.next() + const name = this.expectIdentifier('constant name') + if (name === '__proto__' || name === 'constructor' || name === 'prototype') { + this.fail(`"${name}" is not a valid constant name`) + } + this.expect('=') + this.env[name] = this.parseExpression() + this.match(';') + } + + if (this.isWord('export')) { + this.next() + if (!this.isWord('default')) this.fail('expected "default" after "export"') + this.next() + } + + const value = this.parseExpression() + this.match(';') + if (this.peek().kind !== 'eof') this.fail(`unexpected ${this.describe(this.peek())}`) + return value + } + + private parseExpression(): unknown { + let value = this.parseUnary() + + while (true) { + const token = this.peek() + if (token.kind === 'punctuation' && token.value === '.') { + this.next() + const name = this.expectIdentifier('property name') + value = this.getMember(value, name, token) + continue + } + if (token.kind === 'punctuation' && token.value === '(') { + const args = this.parseArguments() + value = this.call(value, args, token) + continue + } + break + } + + return value + } + + private parseUnary(): unknown { + if (this.match('-')) { + const value = this.parseUnary() + if (typeof value !== 'number') this.fail('unary "-" needs a number') + return -value + } + if (this.match('+')) { + const value = this.parseUnary() + if (typeof value !== 'number') this.fail('unary "+" needs a number') + return value + } + return this.parsePrimary() + } + + private parsePrimary(): unknown { + const token = this.peek() + + if (token.kind === 'number') { + this.next() + return Number(token.value) + } + + if (token.kind === 'string') { + this.next() + return token.value + } + + if (token.kind === 'identifier') { + this.next() + if (token.value === 'true') return true + if (token.value === 'false') return false + if (token.value === 'null') return null + if (token.value === 'undefined') return undefined + if (!(token.value in this.env)) this.failAt(token, `unknown name "${token.value}"`) + return this.env[token.value] + } + + if (this.peek().value === '(' && this.peek(1).value === ')' && this.peek(2).value === '=>') { + return this.parseCallback() + } + + if (this.match('(')) { + const value = this.parseExpression() + this.expect(')') + return value + } + + if (this.peek().value === '[') return this.parseArray() + if (this.peek().value === '{') return this.parseObject() + + this.fail(`expected an expression, got ${this.describe(token)}`) + } + + // Callback bodies are builders, not deferred code, so they are evaluated + // while parsing and the function only hands the result to the caller. + private parseCallback(): unknown { + this.expect('(') + this.expect(')') + this.expect('=>') + if (!this.match('{')) { + const value = this.parseExpression() + return () => value + } + + const values: unknown[] = [] + while (!this.match('}')) { + if (this.match(';') || this.match(',')) continue + values.push(this.parseExpression()) + } + return () => values + } + + private parseArray(): unknown[] { + this.expect('[') + const values: unknown[] = [] + while (true) { + if (this.match(']')) break + values.push(this.parseExpression()) + if (this.match(']')) break + this.expect(',') + } + return values + } + + private parseObject(): Record { + this.expect('{') + const value: Record = Object.create(null) as Record + while (true) { + if (this.match('}')) break + const token = this.peek() + let key: string + if (token.kind === 'identifier' || token.kind === 'string' || token.kind === 'number') { + key = token.value + this.next() + } else { + this.fail('expected an object key') + } + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + this.fail(`"${key}" is not a valid object key`) + } + this.expect(':') + value[key] = this.parseExpression() + if (this.match('}')) break + this.expect(',') + } + return value + } + + private parseArguments(): unknown[] { + this.expect('(') + const args: unknown[] = [] + while (true) { + if (this.match(')')) break + args.push(this.parseExpression()) + if (this.match(')')) break + this.expect(',') + } + return args + } + + private getMember(target: unknown, name: string, token: Token): unknown { + if (name === '__proto__' || name === 'constructor' || name === 'prototype') { + this.failAt(token, `"${name}" is not accessible`) + } + if (target instanceof Selector) { + const method = (target as unknown as Record)[name] + if (typeof method !== 'function') this.failAt(token, `selector has no method "${name}"`) + return method.bind(target) + } + if (target !== null && typeof target === 'object') { + const value = (target as Record)[name] + if (value === undefined) this.failAt(token, `unknown property "${name}"`) + return value + } + this.failAt(token, `cannot read "${name}" from ${this.describeValue(target)}`) + } + + private call(fn: unknown, args: unknown[], token: Token): unknown { + if (typeof fn !== 'function') this.failAt(token, 'value is not callable') + try { + return fn(...args) + } catch (error) { + this.failAt(token, error instanceof Error ? error.message : String(error)) + } + } + + private peek(offset = 0): Token { + return this.tokens[Math.min(this.index + offset, this.tokens.length - 1)] + } + + private next(): Token { + const token = this.peek() + this.index++ + return token + } + + private match(value: string): boolean { + const token = this.peek() + if (token.value !== value) return false + this.index++ + return true + } + + private expect(value: string): Token { + const token = this.peek() + if (token.value !== value) this.fail(`expected "${value}", got ${this.describe(token)}`) + this.index++ + return token + } + + private isWord(value: string): boolean { + const token = this.peek() + return token.kind === 'identifier' && token.value === value + } + + private expectIdentifier(label: string): string { + const token = this.peek() + if (token.kind !== 'identifier') this.fail(`expected ${label}, got ${this.describe(token)}`) + this.index++ + return token.value + } + + private describe(token: Token): string { + if (token.kind === 'eof') return 'end of file' + return `"${token.value}"` + } + + private describeValue(value: unknown): string { + if (value === null) return 'null' + return typeof value + } + + private fail(message: string): never { + this.failAt(this.peek(), message) + } + + private failAt(token: Token, message: string): never { + throw new SourceParseError(message, token.line, token.column) + } +} + +// --------------------------------------------------------------------------- +// Values and validation helpers +// --------------------------------------------------------------------------- + +const PLAYER_REFS = new Set([ + 'you', + 'opponent', + 'each_opponent', + 'each_player', + 'target_player', + 'that_player', + 'its_controller', + 'its_owner', +]) + +const DURATIONS = new Set([ + 'permanent', + 'until_end_of_turn', + 'until_your_next_turn', + 'until_end_of_your_next_turn', + 'until_end_of_combat', + 'until_controllers_next_untap_step', + 'while_source_on_battlefield', +]) + +const ZONES = new Set(['battlefield', 'hand', 'graveyard', 'library', 'exile', 'stack', 'command']) +const SEARCH_DESTINATIONS = new Set(['hand', 'battlefield', 'graveyard', 'top', 'bottom']) + +const COLOR_CODES: Record = { + white: 'W', + blue: 'U', + black: 'B', + red: 'R', + green: 'G', + colorless: 'C', +} + +const CHOICES = new Set(['creature_type', 'color', 'card_name', 'player', 'opponent', 'number']) +const RESTRICTION_RULES = new Set(['cant_attack', 'cant_block', 'doesnt_untap']) +const REPLACEMENT_WHATS = new Set(['dies', 'leaves_battlefield', 'discard', 'draw']) +const REPLACEMENT_RESULTS = new Set(['exile', 'return_to_hand', 'return_to_library', 'prevent']) +const TRIGGER_PLAYERS = new Set(['you', 'opponent', 'each_player']) + +const VALUE_KINDS = new Set([ + 'number', 'x', 'count', 'source_power', 'source_toughness', 'cards_in_hand', + 'max_cards_in_hand', 'max_opponent_count', 'total_mana_value', 'total_power', + 'any_number', 'event_amount', +]) + +const EFFECT_OPS = new Set([ + 'damage', 'draw', 'discard', 'mill', 'life', 'pump', 'set_pt', 'grant', + 'put_counters', 'remove_counters', 'proliferate', 'create_token', 'destroy', + 'exile', 'sacrifice', 'counter', 'return_to_hand', 'return_to_battlefield', + 'put_on_top', 'tap', 'untap', 'scry', 'surveil', 'search', 'shuffle', + 'add_mana', 'fight', 'regenerate', 'energy', 'attach', 'restriction', + 'keyword_action', 'prevent_damage', 'gain_control', 'emblem', 'transform', + 'pay', 'conditional', 'modal', 'look_top', 'schedule', 'level_up', + 'put_from_among', 'dig', 'damage_divided', 'exile_graveyards', 'hideaway', + 'play_exiled', +]) + +const STATIC_OPS = new Set([ + 'pump', 'grant', 'grant_ability', 'restriction', 'enters_tapped', + 'enters_with_counters', 'set_pt', 'control', 'choose', 'replacement', + 'cost_reduction', 'cost_increase', 'search_restriction', + 'exile_instead_of_graveyard', +]) + +const COST_KINDS = new Set([ + 'mana', 'tap', 'untap', 'tap_other', 'energy', 'loyalty', 'pay_life', + 'discard', 'sacrifice', 'sacrifice_self', 'exile_self', 'exile_from_graveyard', + 'reveal', 'choice', 'return_to_hand', 'behold', 'waterbend', 'blight', + 'choose', 'put_counter', 'remove_counters', 'forage', 'collect_evidence', 'mill', +]) + +const CONDITION_KINDS = new Set([ + 'you_control', 'opponent_controls', 'your_turn', 'not_your_turn', + 'source_tapped', 'source_untapped', 'source_attacking', 'life_at_least', + 'life_at_most', 'life_above_starting', 'cards_in_graveyard', 'hand_empty', + 'creature_died_this_turn', 'you_gained_life_this_turn', 'you_drew_cards_this_turn', + 'spells_cast_last_turn', 'no_spells_last_turn', 'attacked_this_turn', + 'you_attacked_this_turn', 'defending_player_controls', 'targets', 'was_kicked', + 'cast', 'in_graveyard', 'on_battlefield', 'monarch', 'initiative', + 'citys_blessing', 'suspended', 'bargained', 'was_creature', + 'opponent_lost_life_this_turn', 'life_changed_this_turn', 'descended_this_turn', + 'permanent_left_battlefield_this_turn', 'nonland_permanents_entered_this_turn', + 'attacked_with_total_power', 'total_power', 'opponent_controls_more_lands', + 'distinct_powers', 'graveyard_card_types', 'no_objects', 'cards_in_hand_at_most', + 'not_their_turn', 'no_attackers', 'opponent_poison', 'tribute_not_paid', + 'had_counters', 'mana_from_treasure', 'mana_spent', 'no_mana_spent', + 'mana_symbol_spent', 'kicked_with', 'more_cards_than_each_opponent', + 'first_combat_phase', 'not_token', 'cast_spell_this_turn', 'full_party', + 'graveyard_count', 'creature_power_greater_than_base', 'if_you_do', + 'if_you_dont', 'otherwise', 'you_control_commander', 'distinct_names', + 'opponent_damaged_this_turn', 'attacked_with_creatures', 'library_at_most', +]) + +const TRIGGER_KINDS = new Set([ + 'enters', 'dies', 'attacks', 'blocks', 'attacks_or_blocks', 'enters_or_attacks', + 'enters_or_dies', 'leaves_battlefield', 'deals_damage', 'upkeep', 'end_step', + 'begin_combat', 'main_phase', 'cast', 'becomes_level', 'draw', 'counter_placed', + 'becomes_target', 'life', +]) + +const ABILITY_KINDS = new Set([ + 'keyword', 'keywords', 'triggered', 'activated', 'static', 'spell', + 'additional_cost', 'alternative_cost', 'overload', 'chapter', 'level_band', + 'level_pt', 'unsupported', +]) + +function expectKind(value: unknown, allowed: Set, label: string, key = 'kind'): Record { + if (!isRecord(value) || typeof value[key] !== 'string' || !allowed.has(value[key] as string)) { + throw new Error(`expected ${label}`) + } + return value +} + + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +function asRecord(value: unknown, label: string): Record { + if (!isRecord(value)) throw new Error(`${label} must be an object`) + return value +} + +function asString(value: unknown, label: string): string { + if (typeof value !== 'string') throw new Error(`${label} must be a string`) + return value +} + +function asNumber(value: unknown, label: string): number { + if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be a number`) + return value +} + +function asBoolean(value: unknown, label: string): boolean { + if (typeof value !== 'boolean') throw new Error(`${label} must be true or false`) + return value +} + +function optionalString(value: unknown, label: string): string | undefined { + if (value === undefined || value === null) return undefined + return asString(value, label) +} + +function stringArray(value: unknown, label: string): string[] { + if (value === undefined || value === null) return [] + if (!Array.isArray(value)) throw new Error(`${label} must be an array`) + return value.map(entry => asString(entry, label)) +} + +function asPlayer(value: unknown): PlayerRef { + if (typeof value === 'string' && PLAYER_REFS.has(value as PlayerRef)) return value as PlayerRef + throw new Error(`expected a player, got ${String(value)}`) +} + +function asTriggerPlayer(value: unknown): 'you' | 'opponent' | 'each_player' { + if (typeof value === 'string' && TRIGGER_PLAYERS.has(value)) return value as 'you' | 'opponent' | 'each_player' + throw new Error(`expected you, opponent or eachPlayer, got ${String(value)}`) +} + +function asDuration(value: unknown, fallback: Duration = 'permanent'): Duration { + if (value === undefined || value === null) return fallback + if (typeof value === 'string' && DURATIONS.has(value as Duration)) return value as Duration + throw new Error(`unknown duration "${String(value)}"`) +} + +function asZone(value: unknown): Zone { + if (typeof value === 'string' && ZONES.has(value as Zone)) return value as Zone + throw new Error(`unknown zone "${String(value)}"`) +} + +function asSearchDestination(value: unknown): SearchDestination { + if (typeof value === 'string' && SEARCH_DESTINATIONS.has(value as SearchDestination)) { + return value as SearchDestination + } + throw new Error(`unknown destination "${String(value)}"`) +} + +function asValue(value: unknown): Value { + if (typeof value === 'number') return { kind: 'number', value } + if (isRecord(value) && typeof value.kind === 'string' && VALUE_KINDS.has(value.kind)) { + return value as unknown as Value + } + throw new Error('expected a value (number or value helper)') +} + +function asSelector(value: unknown): ObjectSelector { + if (value instanceof Selector) return { ...value.fields } + if (isRecord(value)) return { ...value } as ObjectSelector + throw new Error('expected a selector') +} + +function isTarget(value: unknown): value is Target { + return isRecord(value) && typeof value.kind === 'string' && [ + 'self', 'trigger_subject', 'previous_target', 'object', 'player', + 'player_or_planeswalker', 'any', 'spell', 'ability', 'divided', + ].includes(value.kind) +} + +function asTarget(value: unknown): Target { + if (isTarget(value)) return value + throw new Error('expected a target') +} + +function asEffects(value: unknown): Effect[] { + const resolved = typeof value === 'function' ? value() : value + if (!Array.isArray(resolved)) return [asEffect(resolved)] + return resolved.map(asEffect) +} + +function asEffect(value: unknown): Effect { + return expectKind(value, EFFECT_OPS, 'an effect', 'op') as unknown as Effect +} + +function asStaticEffects(value: unknown): StaticEffect[] { + const resolved = typeof value === 'function' ? value() : value + if (!Array.isArray(resolved)) return [asStaticEffect(resolved)] + return resolved.map(asStaticEffect) +} + +function asStaticEffect(value: unknown): StaticEffect { + return expectKind(value, STATIC_OPS, 'a static effect', 'op') as unknown as StaticEffect +} + +function asCosts(value: unknown): Cost[] { + if (!Array.isArray(value)) throw new Error('expected an array of costs') + return value.map(asCost) +} + +function asCost(value: unknown): Cost { + return expectKind(value, COST_KINDS, 'a cost') as unknown as Cost +} + +function asCondition(value: unknown): Condition { + return expectKind(value, CONDITION_KINDS, 'a condition') as unknown as Condition +} + +function asTrigger(value: unknown): TriggerEvent { + return expectKind(value, TRIGGER_KINDS, 'a trigger event') as unknown as TriggerEvent +} + +function asAbility(value: unknown): Ability { + return expectKind(value, ABILITY_KINDS, 'an ability') as unknown as Ability +} + +function asAbilityArray(value: unknown): Ability[] { + if (!Array.isArray(value)) throw new Error('the implementation must be an array of abilities') + return value.map(asAbility) +} + +function asOptions(value: unknown): Record { + if (value === undefined || value === null) return Object.create(null) as Record + return asRecord(value, 'options') +} + +// --------------------------------------------------------------------------- +// Selectors +// --------------------------------------------------------------------------- + +class Selector { + readonly fields: ObjectSelector + + constructor(fields: ObjectSelector = {}) { + this.fields = fields + } + + private with(patch: Partial): Selector { + return new Selector({ ...this.fields, ...patch }) + } + + withType(...types: unknown[]): Selector { + return this.with({ + types: [...(this.fields.types ?? []), ...types.map(type => singularize(asString(type, 'type').toLowerCase()))], + }) + } + + withSupertype(...supertypes: unknown[]): Selector { + return this.with({ + supertypes: [ + ...(this.fields.supertypes ?? []), + ...supertypes.map(type => singularize(asString(type, 'supertype').toLowerCase())), + ], + }) + } + + withSubtype(...subtypes: unknown[]): Selector { + return this.with({ + subtypes: [ + ...(this.fields.subtypes ?? []), + ...subtypes.map(type => singularize(asString(type, 'subtype').toLowerCase())), + ], + }) + } + + withColor(...colors: unknown[]): Selector { + return this.with({ + colors: [ + ...(this.fields.colors ?? []), + ...colors.map(color => { + const text = asString(color, 'color').toLowerCase() + return COLOR_CODES[text] ?? text.toUpperCase() + }), + ], + }) + } + + matchingAny(): Selector { + return this.with({ match: 'any' }) + } + + withoutType(...types: unknown[]): Selector { + return this.with({ + excludeTypes: [ + ...(this.fields.excludeTypes ?? []), + ...types.map(type => singularize(asString(type, 'type').toLowerCase())), + ], + }) + } + + controlledBy(who: unknown): Selector { + if (who !== 'you' && who !== 'opponent' && who !== 'any') { + throw new Error('controlledBy() expects "you", "opponent" or "any"') + } + return this.with({ controller: who }) + } + + youControl(): Selector { + return this.with({ controller: 'you' }) + } + + opponentControls(): Selector { + return this.with({ controller: 'opponent' }) + } + + ownedBy(who: unknown): Selector { + if (who !== 'you' && who !== 'opponent') throw new Error('ownedBy() expects "you" or "opponent"') + return this.with({ owner: who }) + } + + other(): Selector { + return this.with({ other: true }) + } + + tapped(): Selector { + return this.with({ tapped: true }) + } + + untapped(): Selector { + return this.with({ tapped: false }) + } + + attacking(): Selector { + return this.with({ attacking: true }) + } + + token(): Selector { + return this.with({ token: true }) + } + + nontoken(): Selector { + return this.with({ token: false }) + } + + equipped(): Selector { + return this.with({ attached: 'equipped' }) + } + + enchanted(): Selector { + return this.with({ attached: 'enchanted' }) + } + + inZone(zone: unknown): Selector { + return this.with({ zone: asZone(zone) }) + } + + named(name: unknown): Selector { + return this.with({ name: asString(name, 'name') }) + } + + withCounter(counter: unknown, atLeast: unknown = 1): Selector { + return this.with({ counters: { counter: asString(counter, 'counter'), atLeast: asNumber(atLeast, 'counter count') } }) + } + + withKeyword(...keywords: unknown[]): Selector { + return this.with({ + keywords: [...(this.fields.keywords ?? []), ...keywords.map(keyword => asString(keyword, 'keyword'))], + }) + } + + withoutKeyword(...keywords: unknown[]): Selector { + return this.with({ + excludeKeywords: [ + ...(this.fields.excludeKeywords ?? []), + ...keywords.map(keyword => asString(keyword, 'keyword')), + ], + }) + } + + powerAtLeast(amount: unknown): Selector { + return this.with({ power: { ...(this.fields.power ?? {}), atLeast: asNumber(amount, 'power') } }) + } + + powerAtMost(amount: unknown): Selector { + return this.with({ power: { ...(this.fields.power ?? {}), atMost: asNumber(amount, 'power') } }) + } + + toughnessAtLeast(amount: unknown): Selector { + return this.with({ toughness: { ...(this.fields.toughness ?? {}), atLeast: asNumber(amount, 'toughness') } }) + } + + toughnessAtMost(amount: unknown): Selector { + return this.with({ toughness: { ...(this.fields.toughness ?? {}), atMost: asNumber(amount, 'toughness') } }) + } + + manaValueAtLeast(amount: unknown): Selector { + return this.with({ manaValue: { ...(this.fields.manaValue ?? {}), atLeast: asNumber(amount, 'mana value') } }) + } + + manaValueAtMost(amount: unknown): Selector { + return this.with({ manaValue: { ...(this.fields.manaValue ?? {}), atMost: asNumber(amount, 'mana value') } }) + } +} + +// --------------------------------------------------------------------------- +// Targets and values +// --------------------------------------------------------------------------- + +const self: Target = { kind: 'self' } +const triggerSubject: Target = { kind: 'trigger_subject' } +const previousTarget: Target = { kind: 'previous_target' } +const anyTarget: Target = { kind: 'any' } +const targetPlayerOrPlaneswalker: Target = { kind: 'player_or_planeswalker', mode: 'target' } + +function targetOptions(value: unknown): Pick, 'count' | 'upTo' | 'includeSelf'> { + const options = asOptions(value) + return { + ...(options.count !== undefined ? { count: asNumber(options.count, 'count') } : {}), + ...(options.upTo !== undefined ? { upTo: asBoolean(options.upTo, 'upTo') } : {}), + ...(options.includeSelf !== undefined ? { includeSelf: asBoolean(options.includeSelf, 'includeSelf') } : {}), + } +} + +function target(value: unknown, options?: unknown): Target { + if (typeof value === 'string' && PLAYER_REFS.has(value as PlayerRef)) { + return { kind: 'player', who: value as PlayerRef, mode: 'target' } + } + if (isTarget(value)) return value + return { kind: 'object', selector: asSelector(value), mode: 'target', ...targetOptions(options) } +} + +function each(value: unknown, options?: unknown): Target { + if (typeof value === 'string' && PLAYER_REFS.has(value as PlayerRef)) { + return { kind: 'player', who: value as PlayerRef, mode: 'each' } + } + if (isTarget(value)) return value + return { kind: 'object', selector: asSelector(value), mode: 'each', ...targetOptions(options) } +} + +function pick(value: unknown, options?: unknown): Target { + return { kind: 'object', selector: asSelector(value), mode: 'choose', ...targetOptions(options) } +} + +function divided(max: unknown, selector?: unknown): Target { + if (max !== 'any' && typeof max !== 'number') throw new Error('divided() expects a number or "any"') + return { + kind: 'divided', + max: max === 'any' ? 'any' : asNumber(max, 'divided count'), + ...(selector !== undefined ? { selector: asSelector(selector) } : {}), + } +} + +function targetSpell(selector?: unknown): Target { + return { kind: 'spell', selector: selector === undefined ? { types: [] } : asSelector(selector), mode: 'target' } +} + +function targetAbility(selector?: unknown): Target { + return { kind: 'ability', mode: 'target', ...(selector !== undefined ? { selector: asSelector(selector) } : {}) } +} + +const X: Value = { kind: 'x' } +const itsPower: Value = { kind: 'source_power' } +const itsToughness: Value = { kind: 'source_toughness' } + +function count(selector: unknown): Value { + return { kind: 'count', selector: asSelector(selector) } +} + +function cardsInHand(player: unknown): Value { + return { kind: 'cards_in_hand', player: asPlayer(player) } +} + +function maxCardsInHand(): Value { + return { kind: 'max_cards_in_hand' } +} + +function maxOpponentCount(selector: unknown): Value { + return { kind: 'max_opponent_count', selector: asSelector(selector) } +} + +function totalManaValue(selector: unknown): Value { + return { kind: 'total_mana_value', selector: asSelector(selector) } +} + +function totalPower(selector: unknown): Value { + return { kind: 'total_power', selector: asSelector(selector) } +} + +function anyNumber(): Value { + return { kind: 'any_number' } +} + +function eventAmount(): Value { + return { kind: 'event_amount' } +} + +// --------------------------------------------------------------------------- +// Mana, tokens and costs +// --------------------------------------------------------------------------- + +function mana(symbols: unknown, options?: unknown): ManaSpec { + const text = asString(symbols, 'mana symbols') + const found = text.match(/\{[^}]+\}/g) + if (!found?.length) throw new Error('mana() expects symbols like "{2}{G}"') + const data = asOptions(options) + const restriction = optionalString(data.restriction, 'restriction') + return { + kind: 'symbols', + symbols: found, + ...(data.oneOf === true ? { oneOf: true } : {}), + ...(restriction ? { restriction } : {}), + } +} + +function anyColor(amount: unknown, options?: unknown): ManaSpec { + const data = asOptions(options) + return { + kind: 'any_color', + amount: asValue(amount), + oneColor: data.oneColor === undefined ? false : asBoolean(data.oneColor, 'oneColor'), + ...(data.restriction !== undefined ? { restriction: asString(data.restriction, 'restriction') } : {}), + } +} + +function asToken(value: unknown): TokenSpec { + const data = asRecord(value, 'token') + const types = stringArray(data.types, 'token types').map(type => singularize(type.toLowerCase())) + const subtypes = stringArray(data.subtypes, 'token subtypes').map(type => singularize(type.toLowerCase())) + const colors = stringArray(data.colors, 'token colors').map(color => COLOR_CODES[color.toLowerCase()] ?? color.toUpperCase()) + return { + ...(data.name !== undefined ? { name: asString(data.name, 'token name') } : {}), + types: types.length ? types : (data.power !== undefined ? ['creature'] : ['artifact']), + subtypes, + colors, + ...(data.power !== undefined ? { power: asValue(data.power) } : {}), + ...(data.toughness !== undefined ? { toughness: asValue(data.toughness) } : {}), + ...(data.keywords !== undefined ? { keywords: stringArray(data.keywords, 'token keywords') } : {}), + ...(data.tapped === undefined ? {} : { tapped: asBoolean(data.tapped, 'tapped') }), + } +} + +class CopyOf { + readonly target: Target + readonly notLegendary: boolean + + constructor(targetValue: unknown, notLegendary: boolean) { + this.target = asTarget(targetValue) + this.notLegendary = notLegendary + } +} + +function copyOf(targetValue: unknown, options?: unknown): CopyOf { + return new CopyOf(targetValue, asOptions(options).notLegendary === true) +} + +function manaCost(symbols: unknown): Cost { + const spec = mana(symbols) + return { kind: 'mana', symbols: spec.kind === 'symbols' ? spec.symbols.join('') : '' } +} + +function tapCost(): Cost { + return { kind: 'tap' } +} + +function untapCost(): Cost { + return { kind: 'untap' } +} + +function tapOther(selector: unknown): Cost { + return { kind: 'tap_other', selector: asSelector(selector) } +} + +function energyCost(amount: unknown): Cost { + return { kind: 'energy', amount: asNumber(amount, 'energy') } +} + +function loyalty(amount: unknown): Cost { + return { kind: 'loyalty', amount: asNumber(amount, 'loyalty') } +} + +function payLife(amount: unknown): Cost { + return { kind: 'pay_life', amount: asValue(amount) } +} + +function discardCost(amount: unknown, options?: unknown): Cost { + const data = asOptions(options) + return { + kind: 'discard', + amount: asValue(amount), + player: data.player === undefined ? 'you' : asPlayer(data.player), + ...(data.random === true ? { random: true } : {}), + } +} + +function sacrificeCost(selector: unknown): Cost { + return { kind: 'sacrifice', selector: asSelector(selector) } +} + +function sacrificeSelf(): Cost { + return { kind: 'sacrifice_self' } +} + +function exileSelf(): Cost { + return { kind: 'exile_self' } +} + +function exileFromGraveyard(selector: unknown, amount?: unknown): Cost { + return { + kind: 'exile_from_graveyard', + selector: asSelector(selector), + ...(amount !== undefined ? { amount: asValue(amount) } : {}), + } +} + +function reveal(selector: unknown): Cost { + return { kind: 'reveal', selector: asSelector(selector) } +} + +function choice(options: unknown): Cost { + if (!Array.isArray(options)) throw new Error('choice() expects an array of cost arrays') + return { + kind: 'choice', + options: options.map(option => { + if (!Array.isArray(option)) throw new Error('choice() expects an array of cost arrays') + return option.map(asCost) + }), + } +} + +function returnToHandCost(selector: unknown): Cost { + return { kind: 'return_to_hand', selector: asSelector(selector) } +} + +function behold(selector: unknown): Cost { + return { kind: 'behold', selector: asSelector(selector) } +} + +function waterbend(amount: unknown): Cost { + return { kind: 'waterbend', amount: asValue(amount) } +} + +function blight(amount: unknown): Cost { + return { kind: 'blight', amount: asValue(amount) } +} + +function chooseCost(what: unknown): Cost { + return { kind: 'choose', what: asString(what, 'choice') } +} + +function putCounterCost(counter: unknown, selector: unknown): Cost { + return { kind: 'put_counter', counter: asString(counter, 'counter'), selector: asSelector(selector) } +} + +function removeCountersCost(counter: unknown, amount: unknown, selector?: unknown): Cost { + return { + kind: 'remove_counters', + counter: asString(counter, 'counter'), + amount: asValue(amount), + ...(selector !== undefined ? { selector: asSelector(selector) } : {}), + } +} + +function forage(): Cost { + return { kind: 'forage' } +} + +function collectEvidence(amount: unknown): Cost { + return { kind: 'collect_evidence', amount: asNumber(amount, 'evidence') } +} + +function millCost(amount: unknown): Cost { + return { kind: 'mill', amount: asValue(amount) } +} + +// --------------------------------------------------------------------------- +// Effects +// --------------------------------------------------------------------------- + +function damage(targetValue: unknown, amount: unknown, source?: unknown): Effect { + return { + op: 'damage', + target: asTarget(targetValue), + amount: asValue(amount), + ...(source !== undefined ? { source: asTarget(source) } : {}), + } +} + +function damageDivided(amount: unknown, targetValue: unknown): Effect { + return { op: 'damage_divided', amount: asValue(amount), target: asTarget(targetValue) } +} + +function draw(player: unknown, amount: unknown): Effect { + return { op: 'draw', player: asPlayer(player), amount: asValue(amount) } +} + +function discard(player: unknown, amount: unknown, options?: unknown): Effect { + return { + op: 'discard', + player: asPlayer(player), + amount: asValue(amount), + ...(asOptions(options).random === true ? { random: true } : {}), + } +} + +function mill(player: unknown, amount: unknown): Effect { + return { op: 'mill', player: asPlayer(player), amount: asValue(amount) } +} + +function gainLife(player: unknown, amount: unknown): Effect { + return { op: 'life', player: asPlayer(player), amount: asValue(amount), mode: 'gain' } +} + +function loseLife(player: unknown, amount: unknown): Effect { + return { op: 'life', player: asPlayer(player), amount: asValue(amount), mode: 'lose' } +} + +function pump(targetValue: unknown, power: unknown, toughness: unknown, duration?: unknown): Effect { + return { + op: 'pump', + target: asTarget(targetValue), + power: asValue(power), + toughness: asValue(toughness), + duration: asDuration(duration), + } +} + +function setPt(targetValue: unknown, power: unknown, toughness: unknown, options?: unknown): Effect { + const data = asOptions(options) + return { + op: 'set_pt', + target: asTarget(targetValue), + power: asValue(power), + toughness: asValue(toughness), + duration: asDuration(data.duration), + } +} + +function grant(targetValue: unknown, keyword: unknown, options?: unknown): Effect { + const data = asOptions(options) + return { + op: 'grant', + target: asTarget(targetValue), + keyword: asString(keyword, 'keyword'), + ...(data.value !== undefined ? { value: asString(data.value, 'keyword value') } : {}), + duration: asDuration(data.duration), + } +} + +function putCounters(targetValue: unknown, counter: unknown, amount: unknown): Effect { + return { + op: 'put_counters', + target: asTarget(targetValue), + counter: asString(counter, 'counter'), + amount: asValue(amount), + } +} + +function removeCounters(targetValue: unknown, counter: unknown, amount: unknown): Effect { + return { + op: 'remove_counters', + target: asTarget(targetValue), + counter: asString(counter, 'counter'), + amount: asValue(amount), + } +} + +function proliferate(): Effect { + return { op: 'proliferate' } +} + +function createToken(player: unknown, amount: unknown, tokenValue: unknown): Effect { + if (tokenValue instanceof CopyOf) { + return { + op: 'create_token', + player: asPlayer(player), + amount: asValue(amount), + token: { types: [], subtypes: [], colors: [] }, + copyOf: tokenValue.target, + ...(tokenValue.notLegendary ? { notLegendary: true } : {}), + } + } + return { op: 'create_token', player: asPlayer(player), amount: asValue(amount), token: asToken(tokenValue) } +} + +function destroy(targetValue: unknown): Effect { + return { op: 'destroy', target: asTarget(targetValue) } +} + +function exile(targetValue: unknown): Effect { + return { op: 'exile', target: asTarget(targetValue) } +} + +function sacrifice(player: unknown, targetValue: unknown, unless?: unknown): Effect { + return { + op: 'sacrifice', + player: asPlayer(player), + target: asTarget(targetValue), + ...(unless !== undefined ? { unless: asCost(unless) } : {}), + } +} + +function counter(what: unknown, targetValue: unknown, unless?: unknown): Effect { + if (what !== 'spell' && what !== 'ability') throw new Error('counter() expects "spell" or "ability"') + return { + op: 'counter', + what, + target: asTarget(targetValue), + ...(unless !== undefined ? { unless: asCost(unless) } : {}), + } +} + +function returnToHand(targetValue: unknown): Effect { + return { op: 'return_to_hand', target: asTarget(targetValue) } +} + +function returnToBattlefield(targetValue: unknown, options?: unknown): Effect { + const data = asOptions(options) + const counters = data.counters === undefined ? undefined : asRecord(data.counters, 'counters') + return { + op: 'return_to_battlefield', + target: asTarget(targetValue), + tapped: data.tapped === true, + ...(data.transformed === true ? { transformed: true } : {}), + ...(counters + ? { counters: { counter: asString(counters.counter, 'counter'), amount: asValue(counters.amount) } } + : {}), + } +} + +function putOnTop(targetValue: unknown): Effect { + return { op: 'put_on_top', target: asTarget(targetValue) } +} + +function tap(targetValue: unknown): Effect { + return { op: 'tap', target: asTarget(targetValue) } +} + +function untap(targetValue: unknown): Effect { + return { op: 'untap', target: asTarget(targetValue) } +} + +function scry(player: unknown, amount: unknown): Effect { + return { op: 'scry', player: asPlayer(player), amount: asValue(amount) } +} + +function surveil(player: unknown, amount: unknown): Effect { + return { op: 'surveil', player: asPlayer(player), amount: asValue(amount) } +} + +function search(player: unknown, selector: unknown, amount: unknown, options?: unknown): Effect { + const data = asOptions(options) + const split = data.split === undefined ? undefined : asRecord(data.split, 'split') + const zones = data.zones === undefined + ? undefined + : stringArray(data.zones, 'zones').map(zone => { + if (zone !== 'library' && zone !== 'graveyard') throw new Error('zones must be library or graveyard') + return zone + }) + return { + op: 'search', + player: asPlayer(player), + selector: asSelector(selector), + amount: asValue(amount), + destination: asSearchDestination(data.destination ?? 'hand'), + tapped: data.tapped === true, + shuffle: data.shuffle === true, + ...(zones ? { zones } : {}), + ...(split + ? { split: { destination: asSearchDestination(split.destination), tapped: split.tapped === true } } + : {}), + } +} + +function shuffle(player: unknown): Effect { + return { op: 'shuffle', player: asPlayer(player) } +} + +function addMana(player: unknown, manaValue: unknown): Effect { + const spec = typeof manaValue === 'string' ? mana(manaValue) : manaValue + if (!isRecord(spec) || (spec.kind !== 'symbols' && spec.kind !== 'any_color')) { + throw new Error('addMana() expects mana(...) or anyColor(...)') + } + return { op: 'add_mana', player: asPlayer(player), mana: spec as unknown as ManaSpec } +} + +function fight(a: unknown, b: unknown): Effect { + return { op: 'fight', a: asTarget(a), b: asTarget(b) } +} + +function regenerate(targetValue: unknown): Effect { + return { op: 'regenerate', target: asTarget(targetValue) } +} + +function energy(player: unknown, amount: unknown): Effect { + return { op: 'energy', player: asPlayer(player), amount: asValue(amount) } +} + +function attach(targetValue: unknown): Effect { + return { op: 'attach', target: asTarget(targetValue) } +} + +function restrict(targetValue: unknown, rule: unknown, duration?: unknown): Effect { + const text = asString(rule, 'restriction rule') + if (!RESTRICTION_RULES.has(text)) throw new Error(`unknown restriction rule "${text}"`) + return { + op: 'restriction', + target: asTarget(targetValue), + rule: text as 'cant_attack' | 'cant_block' | 'doesnt_untap', + duration: asDuration(duration), + } +} + +function keywordAction(action: unknown, options?: unknown): Effect { + const data = asOptions(options) + return { + op: 'keyword_action', + action: asString(action, 'action').replace(/_/g, ' '), + ...(data.target !== undefined ? { target: asTarget(data.target) } : {}), + ...(data.amount !== undefined ? { amount: asValue(data.amount) } : {}), + ...(data.detail !== undefined ? { detail: asString(data.detail, 'detail') } : {}), + } +} + +function preventDamage(targetValue: unknown, amount: unknown, options?: unknown): Effect { + const data = asOptions(options) + return { + op: 'prevent_damage', + target: asTarget(targetValue), + amount: amount === 'all' ? 'all' : asValue(amount), + ...(data.combatOnly === true ? { combatOnly: true } : {}), + duration: asDuration(data.duration), + } +} + +function gainControl(targetValue: unknown, duration?: unknown): Effect { + return { op: 'gain_control', target: asTarget(targetValue), duration: asDuration(duration) } +} + +function emblem(text: unknown): Effect { + return { op: 'emblem', text: asString(text, 'emblem text') } +} + +function transform(targetValue: unknown): Effect { + return { op: 'transform', target: asTarget(targetValue) } +} + +function pay(costs: unknown): Effect { + return { op: 'pay', costs: asCosts(costs) } +} + +function ifThen(condition: unknown, effects: unknown): Effect { + return { op: 'conditional', condition: asCondition(condition), effects: asEffects(effects) } +} + +function modal(min: unknown, max: unknown, modes: unknown): Effect { + if (!Array.isArray(modes)) throw new Error('modal() expects an array of modes') + return { + op: 'modal', + min: asNumber(min, 'minimum modes'), + max: asNumber(max, 'maximum modes'), + modes: modes.map(mode => asEffects(mode)), + } +} + +function lookTop(player: unknown, amount: unknown, options?: unknown): Effect { + return { + op: 'look_top', + player: asPlayer(player), + amount: asValue(amount), + ...(asOptions(options).reorder === true ? { reorder: true } : {}), + } +} + +function schedule(when: unknown, effects: unknown): Effect { + if (when !== 'next_upkeep' && when !== 'next_end_step') { + throw new Error('schedule() expects "next_upkeep" or "next_end_step"') + } + return { op: 'schedule', when, effects: asEffects(effects) } +} + +function levelUp(level: unknown): Effect { + return { op: 'level_up', level: asNumber(level, 'level') } +} + +function putFromAmong(player: unknown, amount: unknown, options?: unknown): Effect { + const data = asOptions(options) + return { + op: 'put_from_among', + player: asPlayer(player), + amount: asValue(amount), + ...(data.selector !== undefined ? { selector: asSelector(data.selector) } : {}), + destination: asSearchDestination(data.destination ?? 'hand'), + } +} + +function dig(player: unknown, amount: unknown, options?: unknown): Effect { + const data = asOptions(options) + const to = data.to ?? 'hand' + const rest = data.rest ?? 'bottom' + if (to !== 'hand' && to !== 'battlefield') throw new Error('dig() to must be hand or battlefield') + if (rest !== 'bottom' && rest !== 'graveyard' && rest !== 'top') { + throw new Error('dig() rest must be bottom, graveyard or top') + } + return { + op: 'dig', + player: asPlayer(player), + amount: asValue(amount), + pick: asValue(data.pick ?? 1), + ...(data.upTo === true ? { upTo: true } : {}), + ...(data.pickSelector !== undefined ? { pickSelector: asSelector(data.pickSelector) } : {}), + to, + rest, + ...(data.order === 'any' || data.order === 'random' ? { order: data.order } : {}), + ...(data.optional === true ? { optional: true } : {}), + ...(data.tapped === true ? { tapped: true } : {}), + } +} + +function exileGraveyards(): Effect { + return { op: 'exile_graveyards' } +} + +function hideaway(amount: unknown): Effect { + return { op: 'hideaway', amount: asValue(amount) } +} + +function playExiled(player: unknown, options?: unknown): Effect { + return { + op: 'play_exiled', + player: asPlayer(player), + ...(asOptions(options).free === true ? { free: true } : {}), + } +} + +// --------------------------------------------------------------------------- +// Static effects +// --------------------------------------------------------------------------- + +function staticPump(targetValue: unknown, power: unknown, toughness: unknown): StaticEffect { + return { op: 'pump', target: asTarget(targetValue), power: asValue(power), toughness: asValue(toughness) } +} + +function staticGrant(targetValue: unknown, keyword: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + return { + op: 'grant', + target: asTarget(targetValue), + keyword: asString(keyword, 'keyword'), + ...(data.value !== undefined ? { value: asString(data.value, 'keyword value') } : {}), + } +} + +function staticRestrict(targetValue: unknown, rule: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + const text = asString(rule, 'restriction rule') + return { + op: 'restriction', + target: asTarget(targetValue), + rule: text, + ...(data.value !== undefined ? { value: asValue(data.value) } : {}), + ...(data.comparison === 'or_greater' || data.comparison === 'or_less' ? { comparison: data.comparison } : {}), + ...(data.detail !== undefined ? { detail: asString(data.detail, 'detail') } : {}), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + } +} + +function staticSetPt(targetValue: unknown, power: unknown, toughness: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + return { + op: 'set_pt', + target: asTarget(targetValue), + ...(power !== null && power !== undefined ? { power: asValue(power) } : {}), + ...(toughness !== null && toughness !== undefined ? { toughness: asValue(toughness) } : {}), + ...(data.base === true ? { base: true } : {}), + } +} + +function grantAbility(targetValue: unknown, ability: unknown): StaticEffect { + return { op: 'grant_ability', target: asTarget(targetValue), ability: asAbility(ability) } +} + +function entersTapped(targetValue: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + return { + op: 'enters_tapped', + target: asTarget(targetValue), + ...(data.unless !== undefined ? { unless: asCondition(data.unless) } : {}), + ...(data.unlessCost !== undefined ? { unlessCost: asCost(data.unlessCost) } : {}), + } +} + +function entersWithCounters(targetValue: unknown, counter: unknown, amount: unknown): StaticEffect { + return { + op: 'enters_with_counters', + target: asTarget(targetValue), + counter: asString(counter, 'counter'), + amount: asValue(amount), + } +} + +function control(targetValue: unknown): StaticEffect { + return { op: 'control', target: asTarget(targetValue) } +} + +function choose(what: unknown): StaticEffect { + const text = asString(what, 'choice') + if (!CHOICES.has(text)) throw new Error(`unknown choice "${text}"`) + return { op: 'choose', what: text as 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' } +} + +function replace(what: unknown, options?: unknown): StaticEffect { + const text = asString(what, 'replacement') + if (!REPLACEMENT_WHATS.has(text)) throw new Error(`unknown replacement "${text}"`) + const data = asOptions(options) + const instead = asString(data.instead, 'replacement result') + if (!REPLACEMENT_RESULTS.has(instead)) throw new Error(`unknown replacement result "${instead}"`) + return { + op: 'replacement', + what: text as 'dies' | 'leaves_battlefield' | 'discard' | 'draw', + instead: instead as 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent', + ...(data.target !== undefined ? { target: asTarget(data.target) } : {}), + } +} + +function costReduction(targetValue: unknown, amount: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + return { + op: 'cost_reduction', + target: asTarget(targetValue), + ...(typeof amount === 'string' && /^(?:\{[^}]+\})+$/.test(amount) + ? { symbols: amount } + : { amount: asValue(amount) }), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + } +} + +function costIncrease(amount: unknown, options?: unknown): StaticEffect { + const data = asOptions(options) + const spellType = data.spellType + if (spellType !== undefined && spellType !== 'noncreature' && spellType !== 'creature') { + throw new Error('spellType must be noncreature or creature') + } + return { + op: 'cost_increase', + amount: asValue(amount), + ...(spellType ? { spellType } : {}), + } +} + +function searchRestriction(who: unknown, amount: unknown): StaticEffect { + if (who !== 'opponent' && who !== 'you') throw new Error('searchRestriction() expects you or opponent') + return { op: 'search_restriction', who, amount: asValue(amount) } +} + +function exileInsteadOfGraveyard(owner?: unknown): StaticEffect { + if (owner !== undefined && owner !== 'opponent' && owner !== 'you') { + throw new Error('exileInsteadOfGraveyard() expects you or opponent') + } + return { op: 'exile_instead_of_graveyard', ...(owner ? { owner } : {}) } +} + +// --------------------------------------------------------------------------- +// Triggers +// --------------------------------------------------------------------------- + +function trigger(kind: T['kind'], fields: Omit): T { + return { kind, ...fields } as T +} + +function createWhen(): Record { + return Object.assign(Object.create(null), { + enters: (subject: unknown) => trigger('enters', { subject: asTarget(subject) }), + dies: (subject: unknown) => trigger('dies', { subject: asTarget(subject) }), + attacks: (subject: unknown) => trigger('attacks', { subject: asTarget(subject) }), + blocks: (subject: unknown) => trigger('blocks', { subject: asTarget(subject) }), + attacksOrBlocks: (subject: unknown) => trigger('attacks_or_blocks', { subject: asTarget(subject) }), + entersOrAttacks: (subject: unknown) => trigger('enters_or_attacks', { subject: asTarget(subject) }), + entersOrDies: (subject: unknown) => trigger('enters_or_dies', { subject: asTarget(subject) }), + leavesBattlefield: (subject: unknown) => trigger('leaves_battlefield', { subject: asTarget(subject) }), + dealsDamage: (subject: unknown, recipient: unknown, options?: unknown) => { + if (recipient !== 'player' && recipient !== 'creature' && recipient !== 'permanent' && recipient !== 'any') { + throw new Error('dealsDamage() recipient must be player, creature, permanent or any') + } + return trigger('deals_damage', { + subject: asTarget(subject), + recipient, + combat: asOptions(options).combat === true, + }) + }, + upkeep: (who: unknown) => trigger('upkeep', { who: asTriggerPlayer(who) }), + endStep: (who: unknown) => trigger('end_step', { who: asTriggerPlayer(who) }), + beginCombat: (who: unknown) => trigger('begin_combat', { who: asTriggerPlayer(who) }), + firstMainPhase: (who: unknown) => trigger('main_phase', { who: asTriggerPlayer(who), phase: 'first' }), + postcombatMainPhase: (who: unknown) => trigger('main_phase', { who: asTriggerPlayer(who), phase: 'postcombat' }), + cast: (who: unknown, spell?: unknown, options?: unknown) => { + let selector: ObjectSelector = { types: [] } + let data: Record = Object.create(null) as Record + if (spell instanceof Selector) { + selector = asSelector(spell) + } else if (isRecord(spell) && !('targetsSelf' in spell) && !('orCopy' in spell) && !('ordinal' in spell)) { + selector = asSelector(spell) + } else if (spell !== undefined) { + data = asOptions(spell) + } + data = { ...data, ...asOptions(options) } + return trigger('cast', { + who: asTriggerPlayer(who), + spell: selector, + ...(data.targetsSelf === true ? { targetsSelf: true } : {}), + ...(data.orCopy === true ? { orCopy: true } : {}), + ...(data.ordinal !== undefined ? { ordinal: asNumber(data.ordinal, 'ordinal') } : {}), + }) + }, + becomesLevel: (level: unknown) => trigger('becomes_level', { level: asNumber(level, 'level') }), + draw: (who: unknown, ordinal?: unknown) => trigger('draw', { + who: asTriggerPlayer(who), + ...(ordinal !== undefined ? { ordinal: asNumber(ordinal, 'ordinal') } : {}), + }), + counterPlaced: (subject: unknown, counter?: unknown) => trigger('counter_placed', { + subject: asTarget(subject), + ...(counter !== undefined ? { counter: asString(counter, 'counter') } : {}), + }), + becomesTarget: (subject: unknown) => trigger('becomes_target', { subject: asTarget(subject) }), + lifeGained: (who: unknown) => trigger('life', { who: asTriggerPlayer(who), mode: 'gain' }), + lifeLost: (who: unknown) => trigger('life', { who: asTriggerPlayer(who), mode: 'lose' }), + }) +} + +// --------------------------------------------------------------------------- +// Conditions +// --------------------------------------------------------------------------- + +function condition(kind: T['kind'], fields: Omit = {} as Omit): T { + return { kind, ...fields } as T +} + +function youControl(selector: unknown, atLeast?: unknown): Condition { + return condition('you_control', { + selector: asSelector(selector), + ...(atLeast !== undefined ? { atLeast: asNumber(atLeast, 'count') } : {}), + }) +} + +function opponentControls(selector: unknown, atLeast?: unknown): Condition { + return condition('opponent_controls', { + selector: asSelector(selector), + ...(atLeast !== undefined ? { atLeast: asNumber(atLeast, 'count') } : {}), + }) +} + +function yourTurn(): Condition { + return condition('your_turn') +} + +function notYourTurn(): Condition { + return condition('not_your_turn') +} + +function sourceTapped(): Condition { + return condition('source_tapped') +} + +function sourceUntapped(): Condition { + return condition('source_untapped') +} + +function sourceAttacking(): Condition { + return condition('source_attacking') +} + +function lifeAtLeast(player: unknown, amount: unknown): Condition { + return condition('life_at_least', { player: asPlayer(player), amount: asNumber(amount, 'life') }) +} + +function lifeAtMost(player: unknown, amount: unknown): Condition { + return condition('life_at_most', { player: asPlayer(player), amount: asNumber(amount, 'life') }) +} + +function lifeAboveStarting(player: unknown, amount: unknown): Condition { + return condition('life_above_starting', { player: asPlayer(player), amount: asNumber(amount, 'life') }) +} + +function cardsInGraveyard(player: unknown, atLeast: unknown): Condition { + return condition('cards_in_graveyard', { player: asPlayer(player), atLeast: asNumber(atLeast, 'count') }) +} + +function handEmpty(player: unknown): Condition { + return condition('hand_empty', { player: asPlayer(player) }) +} + +function creatureDiedThisTurn(controller?: unknown): Condition { + if (controller !== undefined && controller !== 'you' && controller !== 'opponent') { + throw new Error('creatureDiedThisTurn() expects you or opponent') + } + return condition('creature_died_this_turn', controller ? { controller } : {}) +} + +function youGainedLifeThisTurn(atLeast?: unknown): Condition { + return condition('you_gained_life_this_turn', atLeast === undefined ? {} : { atLeast: asNumber(atLeast, 'life') }) +} + +function youDrewCardsThisTurn(atLeast?: unknown): Condition { + return condition('you_drew_cards_this_turn', atLeast === undefined ? {} : { atLeast: asNumber(atLeast, 'count') }) +} + +function spellsCastLastTurn(who: unknown, atLeast: unknown): Condition { + if (who !== 'you' && who !== 'opponent' && who !== 'each_player' && who !== 'a_player') { + throw new Error('spellsCastLastTurn() expects a spell caster') + } + return condition('spells_cast_last_turn', { who, atLeast: asNumber(atLeast, 'count') }) +} + +function noSpellsLastTurn(): Condition { + return condition('no_spells_last_turn') +} + +function attackedThisTurn(): Condition { + return condition('attacked_this_turn') +} + +function youAttackedThisTurn(): Condition { + return condition('you_attacked_this_turn') +} + +function defendingPlayerControls(selector: unknown): Condition { + return condition('defending_player_controls', { selector: asSelector(selector) }) +} + +function targets(selector: unknown): Condition { + return condition('targets', { selector: asSelector(selector) }) +} + +function wasKicked(): Condition { + return condition('was_kicked') +} + +function youCastIt(options?: unknown): Condition { + return condition('cast', asOptions(options).fromHand === true ? { fromHand: true } : {}) +} + +function inGraveyard(): Condition { + return condition('in_graveyard') +} + +function onBattlefield(): Condition { + return condition('on_battlefield') +} + +function monarch(): Condition { + return condition('monarch') +} + +function initiative(): Condition { + return condition('initiative') +} + +function citysBlessing(): Condition { + return condition('citys_blessing') +} + +function suspended(): Condition { + return condition('suspended') +} + +function bargained(): Condition { + return condition('bargained') +} + +function wasCreature(): Condition { + return condition('was_creature') +} + +function opponentLostLifeThisTurn(): Condition { + return condition('opponent_lost_life_this_turn') +} + +function lifeChangedThisTurn(): Condition { + return condition('life_changed_this_turn') +} + +function descendedThisTurn(): Condition { + return condition('descended_this_turn') +} + +function permanentLeftBattlefieldThisTurn(): Condition { + return condition('permanent_left_battlefield_this_turn', { controller: 'you' }) +} + +function nonlandPermanentsEnteredThisTurn(atLeast: unknown): Condition { + return condition('nonland_permanents_entered_this_turn', { atLeast: asNumber(atLeast, 'count') }) +} + +function attackedWithTotalPower(atLeast: unknown): Condition { + return condition('attacked_with_total_power', { atLeast: asNumber(atLeast, 'power') }) +} + +function yourCreaturesTotalPower(atLeast: unknown): Condition { + return condition('total_power', { controller: 'you', atLeast: asNumber(atLeast, 'power') }) +} + +function opponentControlsMoreLands(): Condition { + return condition('opponent_controls_more_lands') +} + +function distinctPowers(atLeast: unknown): Condition { + return condition('distinct_powers', { atLeast: asNumber(atLeast, 'count') }) +} + +function graveyardCardTypes(atLeast: unknown): Condition { + return condition('graveyard_card_types', { atLeast: asNumber(atLeast, 'count') }) +} + +function noObjects(selector: unknown): Condition { + return condition('no_objects', { selector: asSelector(selector) }) +} + +function cardsInHandAtMost(who: unknown, atMost: unknown): Condition { + return condition('cards_in_hand_at_most', { who: asPlayer(who), atMost: asNumber(atMost, 'count') }) +} + +function notTheirTurn(): Condition { + return condition('not_their_turn') +} + +function noAttackers(): Condition { + return condition('no_attackers') +} + +function opponentPoison(atLeast: unknown): Condition { + return condition('opponent_poison', { atLeast: asNumber(atLeast, 'poison') }) +} + +function tributeNotPaid(): Condition { + return condition('tribute_not_paid') +} + +function hadCounters(counter?: unknown): Condition { + return condition('had_counters', counter === undefined ? {} : { counter: asString(counter, 'counter') }) +} + +function manaFromTreasure(): Condition { + return condition('mana_from_treasure') +} + +function manaSpent(atLeast: unknown): Condition { + return condition('mana_spent', { atLeast: asNumber(atLeast, 'mana') }) +} + +function noManaSpent(): Condition { + return condition('no_mana_spent') +} + +function manaSymbolSpent(symbols: unknown): Condition { + return condition('mana_symbol_spent', { symbols: asString(symbols, 'mana symbols') }) +} + +function kickedWith(cost: unknown): Condition { + return condition('kicked_with', { cost: asString(cost, 'kicker cost') }) +} + +function moreCardsThanEachOpponent(): Condition { + return condition('more_cards_than_each_opponent') +} + +function firstCombatPhase(): Condition { + return condition('first_combat_phase') +} + +function notToken(): Condition { + return condition('not_token') +} + +function castSpellThisTurn(options?: unknown): Condition { + return condition('cast_spell_this_turn', asOptions(options).noncreature === true ? { noncreature: true } : {}) +} + +function fullParty(): Condition { + return condition('full_party') +} + +function graveyardCount(selector: unknown, atLeast: unknown): Condition { + return condition('graveyard_count', { selector: asSelector(selector), atLeast: asNumber(atLeast, 'count') }) +} + +function creaturePowerGreaterThanBase(stat: unknown): Condition { + if (stat !== 'power' && stat !== 'toughness') throw new Error('creaturePowerGreaterThanBase() expects power or toughness') + return condition('creature_power_greater_than_base', { controller: 'you', stat }) +} + +function ifYouDo(): Condition { + return condition('if_you_do') +} + +function ifYouDont(): Condition { + return condition('if_you_dont') +} + +function otherwise(): Condition { + return condition('otherwise') +} + +function youControlCommander(): Condition { + return condition('you_control_commander') +} + +function distinctNames(selector: unknown, atLeast: unknown): Condition { + return condition('distinct_names', { selector: asSelector(selector), atLeast: asNumber(atLeast, 'count') }) +} + +function opponentDamagedThisTurn(atLeast: unknown): Condition { + return condition('opponent_damaged_this_turn', { atLeast: asNumber(atLeast, 'damage') }) +} + +function attackedWithCreatures(atLeast: unknown): Condition { + return condition('attacked_with_creatures', { atLeast: asNumber(atLeast, 'count') }) +} + +function libraryAtMost(atMost: unknown): Condition { + return condition('library_at_most', { atMost: asNumber(atMost, 'cards') }) +} + +// --------------------------------------------------------------------------- +// Abilities and card sections +// --------------------------------------------------------------------------- + +function parseKeywordText(text: string): KeywordAbility { + const trimmed = text.trim() + const lower = trimmed.toLowerCase() + const simple = [...SIMPLE_KEYWORDS.entries()].sort((a, b) => b[0].length - a[0].length) + for (const [key, keyword] of simple) { + if (lower === key) return { kind: 'keyword', keyword: trimmed } + if (lower.startsWith(`${key} `)) return { kind: 'keyword', keyword, value: trimmed.slice(key.length + 1) } + } + const match = trimmed.match(/^(\S+)(?: (.+))?$/) + if (!match) return { kind: 'keyword', keyword: trimmed } + return { + kind: 'keyword', + keyword: match[1].charAt(0).toUpperCase() + match[1].slice(1), + ...(match[2] ? { value: match[2] } : {}), + } +} + +function keyword(name: unknown, value?: unknown): Ability { + return { + kind: 'keyword', + keyword: asString(name, 'keyword'), + ...(value !== undefined ? { value: asString(value, 'keyword value') } : {}), + } +} + +function keywords(...items: unknown[]): Ability { + return { + kind: 'keywords', + keywords: items.map(item => { + if (isRecord(item) && item.kind === 'keyword') return item as unknown as KeywordAbility + return parseKeywordText(asString(item, 'keyword')) + }), + } +} + +function triggered(event: unknown, effects: unknown, options?: unknown): Ability { + const data = asOptions(options) + return { + kind: 'triggered', + event: asTrigger(event), + effects: asEffects(effects), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + optional: data.optional === true, + text: 'Triggered ability', + } +} + +function activated(costs: unknown, effects: unknown, options?: unknown): Ability { + const data = asOptions(options) + const timing = data.timing + if (timing !== undefined && timing !== 'instant' && timing !== 'sorcery') { + throw new Error('timing must be instant or sorcery') + } + return { + kind: 'activated', + costs: asCosts(costs), + effects: asEffects(effects), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + ...(timing ? { timing } : {}), + ...(data.activationsPerTurn !== undefined + ? { activationsPerTurn: asNumber(data.activationsPerTurn, 'activations per turn') } + : {}), + optional: data.optional === true, + text: 'Activated ability', + } +} + +function staticAbility(effects: unknown, options?: unknown): Ability { + const data = asOptions(options) + return { + kind: 'static', + effects: asStaticEffects(effects), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + text: 'Static ability', + } +} + +function spell(effects: unknown, options?: unknown): Ability { + return { + kind: 'spell', + effects: asEffects(effects), + optional: asOptions(options).optional === true, + text: 'Spell effect', + } +} + +function additionalCost(costs: unknown, options?: unknown): Ability { + return { + kind: 'additional_cost', + costs: asCosts(costs), + optional: asOptions(options).optional === true, + text: 'Additional cost', + } +} + +function alternativeCost(costs: unknown, options?: unknown): Ability { + const data = asOptions(options) + return { + kind: 'alternative_cost', + costs: asCosts(costs), + ...(data.condition !== undefined ? { condition: asCondition(data.condition) } : {}), + text: 'Alternative cost', + } +} + +function overload(cost: unknown): Ability { + return { kind: 'overload', cost: asString(cost, 'overload cost'), text: 'Overload' } +} + +function chapter(chapters: unknown, effects: unknown, options?: unknown): Ability { + if (!Array.isArray(chapters)) throw new Error('chapter() expects an array of chapter numbers') + return { + kind: 'chapter', + chapters: chapters.map(entry => asString(entry, 'chapter').toUpperCase()), + effects: asEffects(effects), + optional: asOptions(options).optional === true, + text: 'Chapter ability', + } +} + +function levelBand(min: unknown, max: unknown, power?: unknown, toughness?: unknown): Ability { + return { + kind: 'level_band', + min: asNumber(min, 'minimum level'), + ...(max !== null && max !== undefined ? { max: asNumber(max, 'maximum level') } : {}), + ...(power !== undefined ? { power: asValue(power) } : {}), + ...(toughness !== undefined ? { toughness: asValue(toughness) } : {}), + text: 'Level band', + } +} + +function levelPt(power: unknown, toughness: unknown): Ability { + return { kind: 'level_pt', power: asValue(power), toughness: asValue(toughness), text: 'Level P/T' } +} + +function unsupported(reason: unknown, text: unknown): Ability { + return { kind: 'unsupported', reason: asString(reason, 'reason'), text: asString(text, 'text') } +} + +class CardSection { + readonly typeLine?: string + readonly abilities: Ability[] + + constructor(typeLineOrAbilities: unknown, abilities?: unknown) { + if (abilities === undefined) { + this.abilities = asAbilityArray(typeLineOrAbilities) + } else { + this.typeLine = asString(typeLineOrAbilities, 'card type line') + this.abilities = asAbilityArray(abilities) + } + } +} + +class Face { + readonly name: string + readonly typeLine?: string + readonly abilities: Ability[] + + constructor(name: unknown, typeLineOrAbilities: unknown, abilities?: unknown) { + this.name = asString(name, 'face name') + if (abilities === undefined) { + this.abilities = asAbilityArray(typeLineOrAbilities) + } else { + this.typeLine = asString(typeLineOrAbilities, 'face type line') + this.abilities = asAbilityArray(abilities) + } + } +} + +class Faces { + readonly faces: Face[] + + constructor(faces: unknown[]) { + this.faces = faces.map(face => { + if (!(face instanceof Face)) throw new Error('faces() expects face(...) entries') + return face + }) + } +} + +/** Top-level card section: card('Creature — Human', [...abilities]). */ +function card(typeLineOrAbilities: unknown, abilities?: unknown): CardSection { + return new CardSection(typeLineOrAbilities, abilities) +} + +function face(name: unknown, typeLineOrAbilities: unknown, abilities?: unknown): Face { + return new Face(name, typeLineOrAbilities, abilities) +} + +function faces(...entries: unknown[]): Faces { + return new Faces(entries) +} + +// --------------------------------------------------------------------------- +// API and entry point +// --------------------------------------------------------------------------- + +function createApi(): Record { + return Object.assign(Object.create(null), { + // players + you: 'you', + opponent: 'opponent', + eachOpponent: 'each_opponent', + eachPlayer: 'each_player', + targetPlayer: 'target_player', + thatPlayer: 'that_player', + itsController: 'its_controller', + itsOwner: 'its_owner', + + // selectors + permanents: new Selector(), + cards: new Selector(), + creatures: new Selector({ types: ['creature'] }), + + // targets + self, + triggerSubject, + previousTarget, + anyTarget, + targetPlayerOrPlaneswalker, + target, + each, + pick, + divided, + targetSpell, + targetAbility, + + // values + X, + itsPower, + itsToughness, + count, + cardsInHand, + maxCardsInHand, + maxOpponentCount, + totalManaValue, + totalPower, + anyNumber, + eventAmount, + + // durations + permanent: 'permanent', + untilEndOfTurn: 'until_end_of_turn', + untilYourNextTurn: 'until_your_next_turn', + untilEndOfYourNextTurn: 'until_end_of_your_next_turn', + untilEndOfCombat: 'until_end_of_combat', + untilControllersNextUntapStep: 'until_controllers_next_untap_step', + whileSourceOnBattlefield: 'while_source_on_battlefield', + + // mana and tokens + mana, + anyColor, + token: asToken, + copyOf, + + // costs + manaCost, + tapCost, + untapCost, + tapOther, + energyCost, + loyalty, + payLife, + discardCost, + sacrificeCost, + sacrificeSelf, + exileSelf, + exileFromGraveyard, + reveal, + choice, + returnToHandCost, + behold, + waterbend, + blight, + chooseCost, + putCounterCost, + removeCountersCost, + forage, + collectEvidence, + millCost, + + // effects + damage, + damageDivided, + draw, + discard, + mill, + gainLife, + loseLife, + pump, + setPt, + grant, + putCounters, + removeCounters, + proliferate, + createToken, + destroy, + exile, + sacrifice, + counter, + returnToHand, + returnToBattlefield, + putOnTop, + tap, + untap, + scry, + surveil, + search, + shuffle, + addMana, + fight, + regenerate, + energy, + attach, + restrict, + keywordAction, + preventDamage, + gainControl, + emblem, + transform, + pay, + ifThen, + modal, + lookTop, + schedule, + levelUp, + putFromAmong, + dig, + exileGraveyards, + hideaway, + playExiled, + + // static effects + staticPump, + staticGrant, + staticRestrict, + staticSetPt, + grantAbility, + entersTapped, + entersWithCounters, + control, + choose, + replace, + costReduction, + costIncrease, + searchRestriction, + exileInsteadOfGraveyard, + + // abilities + keyword, + keywords, + triggered, + activated, + staticAbility, + spell, + additionalCost, + alternativeCost, + overload, + chapter, + levelBand, + levelPt, + unsupported, + + // triggers + when: createWhen(), + + // conditions + youControl, + opponentControls, + yourTurn, + notYourTurn, + sourceTapped, + sourceUntapped, + sourceAttacking, + lifeAtLeast, + lifeAtMost, + lifeAboveStarting, + cardsInGraveyard, + handEmpty, + creatureDiedThisTurn, + youGainedLifeThisTurn, + youDrewCardsThisTurn, + spellsCastLastTurn, + noSpellsLastTurn, + attackedThisTurn, + youAttackedThisTurn, + defendingPlayerControls, + targets, + wasKicked, + youCastIt, + inGraveyard, + onBattlefield, + monarch, + initiative, + citysBlessing, + suspended, + bargained, + wasCreature, + opponentLostLifeThisTurn, + lifeChangedThisTurn, + descendedThisTurn, + permanentLeftBattlefieldThisTurn, + nonlandPermanentsEnteredThisTurn, + attackedWithTotalPower, + yourCreaturesTotalPower, + opponentControlsMoreLands, + distinctPowers, + graveyardCardTypes, + noObjects, + cardsInHandAtMost, + notTheirTurn, + noAttackers, + opponentPoison, + tributeNotPaid, + hadCounters, + manaFromTreasure, + manaSpent, + noManaSpent, + manaSymbolSpent, + kickedWith, + moreCardsThanEachOpponent, + firstCombatPhase, + notToken, + castSpellThisTurn, + fullParty, + graveyardCount, + creaturePowerGreaterThanBase, + ifYouDo, + ifYouDont, + otherwise, + youControlCommander, + distinctNames, + opponentDamagedThisTurn, + attackedWithCreatures, + libraryAtMost, + + // card sections + card, + face, + faces, + }) +} + +export function parseCardSource(source: string): ParsedCardSource { + if (!source.trim()) throw new SourceParseError('the implementation is empty', 1) + + try { + const value = new Interpreter(source).parseProgram() + + if (value instanceof Faces) { + if (!value.faces.length) throw new SourceParseError('faces() needs at least one face', 1) + return { + abilities: [], + faces: value.faces.map(section => ({ + name: section.name, + ...(section.typeLine !== undefined ? { typeLine: section.typeLine } : {}), + abilities: section.abilities, + })), + } + } + + if (value instanceof CardSection) { + return { + ...(value.typeLine !== undefined ? { typeLine: value.typeLine } : {}), + abilities: value.abilities, + } + } + + if (Array.isArray(value)) { + return { abilities: asAbilityArray(value) } + } + + throw new SourceParseError('the implementation must export an array of abilities or card(...)', 1) + } catch (error) { + if (error instanceof SourceParseError) throw error + throw new SourceParseError(error instanceof Error ? error.message : String(error), 1) + } +} diff --git a/backend/src/effects/translate.ts b/backend/src/effects/translate.ts index 6c7ff62..fc08167 100644 --- a/backend/src/effects/translate.ts +++ b/backend/src/effects/translate.ts @@ -1,13 +1,14 @@ -// Natural language -> card pseudocode through an OpenRouter-hosted model. -// The model is told to emit pseudocode only, and the answer is parsed before -// it reaches the editor, so prose or a guess never becomes an implementation. +// Natural language -> card source through an OpenRouter-hosted model. +// The model is told to emit the JavaScript card DSL only, and the answer is +// parsed before it reaches the editor, so prose or a guess never becomes an +// implementation. import type { Card } from '../cards.js' import { compileImplementation } from './implementations.js' export const DEFAULT_MODEL = 'google/gemini-2.5-flash-lite' const ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions' -const MAX_TOKENS = 700 +const MAX_TOKENS = 1200 export class TranslationError extends Error { readonly status: number @@ -22,160 +23,164 @@ export class TranslationError extends Error { // Kept compact: it is both the model's only context and the format contract. // Anything not listed here is rejected by the parser, so the model must not // invent operations. -export const PSEUDO_GUIDE = `Pseudocode is line-oriented. Ability headers sit at column 0 and end with a colon. Their effects are indented two spaces, one call per line. Semicolons separate multiple effects on one line. +export const SOURCE_GUIDE = `The source is a JavaScript expression evaluated by a safe interpreter. It is never run as JavaScript: only the names listed here exist. -Multi-face cards use "## " lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed. +A card exports its type line and an array of abilities: -Ability headers: - on [ if ][ (may)]: - activate [, ...][ if ][ (N/turn)][ (sorcery speed)][ (may)]: - static[ if ]: - spell[(may)]: - keyword [ value] - keywords , - additional cost[(may)]: - chapter , [(may)]: - level -[: /] - level +[: /] - level_pt(/) + export default card('Creature — Human Cleric', [ + triggered(when.enters(self), [gainLife(you, 1)]), + activated([tapCost()], [addMana(you, mana('{G}'))]), + ]) -Triggers: - enters(target), dies(target), attacks(target), blocks(target), attacks_or_blocks(target), - enters_or_attacks(target), enters_or_dies(target), leaves_battlefield(target), - deals_damage(target, player|creature|permanent|any), deals_combat_damage(...), - upkeep(you|opponent|each_player), end_step(...), begin_combat(...), - first_main_phase(...), postcombat_main_phase(...), becomes_level(N), - cast(you|opponent|each_player, |any spell[, targets this][, or copy][, #N each turn]), - draw(you|opponent|each_player[, #N each turn]), counter_placed(target[, counter]), - becomes_target(target), gain_life(you|opponent|each_player), lose_life(...) +Multi-face cards export face sections in card order: + + export default faces( + face('Front', 'Instant', [ ...abilities ]), + face('Back', 'Creature — Human', [ ...abilities ]), + ) + +Abilities: + keyword('Flying') one keyword + keyword('Ward', '{2}') keyword with a value + keywords('Flying', 'Trample') several simple keywords + triggered(event, [effects], { condition, optional }) + activated([costs], [effects], { condition, timing: 'sorcery', activationsPerTurn, optional }) + staticAbility([staticEffects], { condition }) + spell([effects], { optional }) + additionalCost([costs], { optional }) + alternativeCost([costs], { condition }) + overload('{6}{U}') + chapter(['I', 'II'], [effects], { optional }) + levelBand(min, max, power, toughness) max may be null + levelPt(power, toughness) + unsupported('short reason', 'original oracle text') + +Any effect list (triggered, activated, staticAbility, spell, chapter, ifThen, +schedule and each modal mode) takes an array or a callback: () => effect, or +() => { effect; effect }. + +Triggers (when.*): + enters(target), dies(target), attacks(target), blocks(target), attacksOrBlocks(target), + entersOrAttacks(target), entersOrDies(target), leavesBattlefield(target), + dealsDamage(target, 'player'|'creature'|'permanent'|'any', { combat }), + upkeep(who), endStep(who), beginCombat(who), firstMainPhase(who), postcombatMainPhase(who), + cast(who, spellSelector, { targetsSelf, orCopy, ordinal }), becomesLevel(N), + draw(who, ordinal), counterPlaced(target, counter), becomesTarget(target), + lifeGained(who), lifeLost(who) + who is you, opponent or eachPlayer. + +Selectors (chainable): + permanents, cards, creatures + .withType('land'), .withSubtype('dragon'), .withSupertype('legendary') + .withColor('white'|'blue'|'black'|'red'|'green'|'colorless') + .withoutType('creature'), .withKeyword('flying'), .withoutKeyword('flying') + .other(), .tapped(), .untapped(), .attacking(), .token(), .nontoken() + .equipped(), .enchanted(), .youControl(), .opponentControls(), .controlledBy('you'|'opponent'|'any') + .ownedBy('you'|'opponent'), .named('Name'), .inZone('battlefield'|'hand'|'graveyard'|'library'|'exile'|'stack'|'command') + .withCounter('+1/+1', 1), .powerAtLeast(N), .powerAtMost(N), .toughnessAtLeast(N), + .toughnessAtMost(N), .manaValueAtLeast(N), .manaValueAtMost(N), .matchingAny() Targets: - this, the triggering object, the chosen target, any target, target player, - target opponent, each opponent, each player, target player or planeswalker, - target spell, target ability, target , each , - up to N target , N , this or , divided([, ]) + self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker + target(selector, { count, upTo, includeSelf }) one target + each(selector) every matching object + pick(selector, { count, upTo }) choose without targeting + divided(N, selector) or divided('any', selector) damage divided among targets + targetSpell(selector), targetAbility(selector) + target(you|opponent|eachOpponent|eachPlayer|targetPlayer|thatPlayer|itsController|itsOwner) -Selectors begin with optional state words: other, tapped, untapped, attacking, token, -equipped, enchanted. Then optional colors (white blue black red green colorless), -supertypes, subtypes, and types. Suffixes: "you control", "an opponent controls", -"you own", "you don't own", "with ", "without ", -"power N+" / "power N or less", "toughness N+" / "toughness N or less", -"mana value N+" / "mana value N or less", "named ", -"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack". +Values: a number, X, itsPower, itsToughness, count(selector), cardsInHand(player), +maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector), +totalPower(selector), anyNumber(), eventAmount() -Values: a number, X, count(), its power, its toughness, -cards in your hand, cards in that player's hand, total power of , -total mana value of , greatest number of an opponent controls, -that much, any number. +Costs: + manaCost('{2}{G}'), tapCost(), untapCost(), tapOther(selector), energyCost(N), + loyalty(N), payLife(value), discardCost(value, { player, random }), sacrificeCost(selector), + sacrificeSelf(), exileSelf(), exileFromGraveyard(selector, amount), reveal(selector), + choice([[cost, ...], [cost, ...]]), returnToHandCost(selector), behold(selector), + waterbend(value), blight(value), chooseCost('text'), putCounterCost(counter, selector), + removeCountersCost(counter, amount, selector), forage(), collectEvidence(N), millCost(value) -Costs: {T}, {Q}, {2}{G}, {E} xN, +1 loyalty, -2 loyalty, pay N life, -discard N card(s)[ at random], discard your hand, sacrifice this, sacrifice , -tap , exile this from a graveyard, exile N from your graveyard, -reveal from your hand, return to its owner's hand, -behold , waterbend , blight , choose , -put counter on , forage, collect evidence N, mill N card(s). -A choice is written (cost or cost) or (cost + cost). - -Effects, one call per line: - damage(target, amount[, from source]) - damage_divided(amount, target) - draw(player, amount) - discard(player, amount[, at random]) - mill(player, amount) - gain_life(player, amount) - lose_life(player, amount) - pump(target, power/toughness[, duration]) - set_pt(target, power/toughness[, duration]) - grant(target, Keyword[ value][, duration]) - put_counters(target, counter, amount) - remove_counters(target, counter, amount) - proliferate() - create_token(player, amount, [tapped ]power/toughness colors subtypes types[ with keyword, keyword]) - destroy(target), exile(target), tap(target), untap(target), regenerate(target) - sacrifice(player, target[, unless cost]) - counter(spell|ability, target[, unless cost]) - return_to_hand(target), put_on_top(target) - return_to_battlefield(target[, tapped][, transformed][, amount counter counters]) - scry(player, amount), surveil(player, amount) - search(player, selector, amount, to hand|battlefield|graveyard|top|bottom[, tapped][, shuffle]) - shuffle(player) - add_mana(player, {G}{G} | amount mana of any color) - fight(a, b) - energy(player, amount) - attach(this, target) - restrict(target, cant_attack|cant_block|doesnt_untap[, duration]) - prevent_damage(target, amount|all[, duration]) - prevent_combat_damage(target, amount|all[, duration]) - gain_control(target[, duration]) - emblem("text") - transform(target) - pay(cost) - look_top(player, amount[, reorder]) - level_up(N) - put_from_among(amount[, selector], to hand|graveyard|battlefield|top|bottom) - dig(amount, up to? pick [selector] to hand|battlefield[ tapped], rest bottom|graveyard|top[ any|random][, optional]) - Other keyword actions: action_name(target) or action_name(amount, detail) - -Nested blocks: - if : - - choose [-]: - 1. - 2. - schedule(next_upkeep|next_end_step): - +Effects: + damage(target, amount, fromSource), damageDivided(amount, target) + draw(player, amount), discard(player, amount, { random }), mill(player, amount) + gainLife(player, amount), loseLife(player, amount) + pump(target, power, toughness, duration), setPt(target, power, toughness, { duration }) + grant(target, keyword, { value, duration }), putCounters(target, counter, amount) + removeCounters(target, counter, amount), proliferate() + createToken(player, amount, token({ types, subtypes, colors, power, toughness, keywords, tapped })) + createToken(player, amount, copyOf(target, { notLegendary })) + destroy(target), exile(target), sacrifice(player, target, unlessCost) + counter('spell'|'ability', target, unlessCost), returnToHand(target) + returnToBattlefield(target, { tapped, transformed, counters: { counter, amount } }) + putOnTop(target), tap(target), untap(target), scry(player, amount), surveil(player, amount) + search(player, selector, amount, { destination, tapped, shuffle, zones, split }) + shuffle(player), addMana(player, mana('{G}{G}') | anyColor(value, { oneColor, restriction })) + fight(a, b), regenerate(target), energy(player, amount), attach(target) + restrict(target, 'cant_attack'|'cant_block'|'doesnt_untap', duration) + keywordAction('action name', { target, amount, detail }) + preventDamage(target, amount | 'all', { combatOnly, duration }) + gainControl(target, duration), emblem('text'), transform(target) + pay([costs]), ifThen(condition, [effects]), modal(min, max, [[effects], [effects]]) + lookTop(player, amount, { reorder }), schedule('next_upkeep'|'next_end_step', [effects]) + levelUp(N), putFromAmong(player, amount, { selector, destination }), dig(player, amount, { ... }) + exileGraveyards(), hideaway(amount), playExiled(player, { free }) Static effects: - pump(target, power/toughness) - grant(target, Keyword[ value]) - restrict(target, rule[ detail][ if ]) - enters_tapped(target[, unless ]) - enters_with_counters(target, counter, amount) - grant_ability(target): - - set_pt(target[, base], power/toughness|?) - control(target) - choose(creature_type|color|card_name|player|opponent|number) - replace(dies|leaves_battlefield|discard|draw[, target], instead exile|return_to_hand|return_to_library|prevent) - cost_reduction(target, amount|{R}{G}[, if ]) + staticPump(target, power, toughness), staticGrant(target, keyword, { value }) + grantAbility(target, ability), staticRestrict(target, rule, { value, comparison, detail, condition }) + entersTapped(target, { unless }), entersWithCounters(target, counter, amount) + staticSetPt(target, power, toughness, { base }), control(target) + choose('creature_type'|'color'|'card_name'|'player'|'opponent'|'number') + replace(what, { target, instead }), costReduction(target, amount | '{R}{G}', { condition }) + costIncrease(amount, { spellType }), searchRestriction('you'|'opponent', amount), + exileInsteadOfGraveyard('you'|'opponent') -Common conditions: you control , you control at least N , -an opponent controls , it is your turn, it isn't your turn, -this is tapped, this is untapped, this is attacking, has at least N life, - has at most N life, has N+ cards in their graveyard, - has no cards in hand, a creature died this turn, -you gained at least N life this turn, you drew N+ cards this turn, -you cast it from your hand, this is in your graveyard, this is on the battlefield, -you're the monarch, you have the initiative, it was kicked, -you've cast a spell this turn, you've cast a noncreature spell this turn, -no creatures attacked this turn, you do, you don't, otherwise. +Conditions: + youControl(selector, atLeast), opponentControls(selector, atLeast), yourTurn(), + notYourTurn(), sourceTapped(), sourceUntapped(), sourceAttacking(), + lifeAtLeast(player, N), lifeAtMost(player, N), lifeAboveStarting(player, N), + cardsInGraveyard(player, N), handEmpty(player), creatureDiedThisTurn('you'|'opponent'), + youGainedLifeThisTurn(N), youDrewCardsThisTurn(N), spellsCastLastTurn(who, N), + noSpellsLastTurn(), attackedThisTurn(), youAttackedThisTurn(), + defendingPlayerControls(selector), targets(selector), wasKicked(), youCastIt({ fromHand }), + inGraveyard(), onBattlefield(), monarch(), initiative(), citysBlessing(), suspended(), + bargained(), wasCreature(), opponentLostLifeThisTurn(), lifeChangedThisTurn(), + descendedThisTurn(), permanentLeftBattlefieldThisTurn(), nonlandPermanentsEnteredThisTurn(N), + attackedWithTotalPower(N), yourCreaturesTotalPower(N), opponentControlsMoreLands(), + distinctPowers(N), graveyardCardTypes(N), noObjects(selector), cardsInHandAtMost(who, N), + notTheirTurn(), noAttackers(), opponentPoison(N), tributeNotPaid(), hadCounters(counter), + manaFromTreasure(), manaSpent(N), noManaSpent(), manaSymbolSpent('{G}'), kickedWith('{2}'), + moreCardsThanEachOpponent(), firstCombatPhase(), notToken(), castSpellThisTurn({ noncreature }), + fullParty(), graveyardCount(selector, N), creaturePowerGreaterThanBase('power'|'toughness'), + ifYouDo(), ifYouDont(), otherwise(), youControlCommander(), distinctNames(selector, N), + opponentDamagedThisTurn(N), attackedWithCreatures(N), libraryAtMost(N) -Durations: permanent (default), until end of turn, until your next turn, -until end of combat, until its controller's next untap step, -for as long as this remains on the battlefield. +Durations: permanent (default), untilEndOfTurn, untilYourNextTurn, +untilEndOfYourNextTurn, untilEndOfCombat, untilControllersNextUntapStep, +whileSourceOnBattlefield. -Players: you, opponent, each_opponent, each_player, target_player, that_player, -its_controller, its_owner. +Players: you, opponent, eachOpponent, eachPlayer, targetPlayer, thatPlayer, +itsController, itsOwner. Example: -on enters(this): - gain_life(you, 1) -activate {T}: - add_mana(you, {G}) + export default card('Creature — Human Cleric', [ + triggered(when.enters(self), [gainLife(you, 1)]), + activated([tapCost()], [addMana(you, mana('{G}'))]), + spell([draw(you, 2)]), + ])` -spell: - draw(you, 2)` - -const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the card pseudocode language below. +const SYSTEM_PROMPT = `You translate Magic: The Gathering card text into the JavaScript card source language below. Output rules: -- Answer with pseudocode only. No explanation, no code fences, no card header, no comments. -- Use only the syntax below. Never invent an operation or a keyword argument. -- If an ability cannot be expressed, use: unsupported (): -- For multi-face cards, output only the "## " sections in the given order. +- Answer with card source only. No explanation, no code fences, no comments. +- Start with card('Type line', [...]) using the exact type line given for the card. +- Use only the names and shapes below. Never invent an operation or a keyword argument. +- If an ability cannot be expressed, use: unsupported('short reason', 'original oracle text') +- For multi-face cards, output only the faces(...) sections in the given order. -${PSEUDO_GUIDE}` +${SOURCE_GUIDE}` function describeCard(card: Card): string { if (card.card_faces?.length) { @@ -226,7 +231,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}): headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', - 'X-Title': 'Commander card pseudocode translator', + 'X-Title': 'Commander card source translator', }, body: JSON.stringify({ model: options.model ?? process.env.OPENROUTER_MODEL ?? DEFAULT_MODEL, @@ -261,7 +266,7 @@ export async function translateCard(card: Card, options: TranslateOptions = {}): compileImplementation(card, source) } catch (error) { throw new TranslationError( - `The model did not return valid pseudocode: ${error instanceof Error ? error.message : String(error)}`, + `The model did not return valid card source: ${error instanceof Error ? error.message : String(error)}`, ) } diff --git a/backend/src/effects/types.ts b/backend/src/effects/types.ts index aab189e..2ba78fa 100644 --- a/backend/src/effects/types.ts +++ b/backend/src/effects/types.ts @@ -67,7 +67,7 @@ export type Value = | { kind: 'event_amount' } export type ManaSpec = - | { kind: 'symbols'; symbols: string[]; restriction?: string } + | { kind: 'symbols'; symbols: string[]; oneOf?: boolean; restriction?: string } | { kind: 'any_color'; amount: Value; oneColor: boolean; restriction?: string } export interface TokenSpec { @@ -268,7 +268,7 @@ export type StaticEffect = | { op: 'grant'; target: Target; keyword: string; value?: string } | { op: 'grant_ability'; target: Target; ability: Ability } | { op: 'restriction'; target: Target; rule: string; value?: Value; comparison?: 'or_greater' | 'or_less'; detail?: string; condition?: Condition } - | { op: 'enters_tapped'; target: Target; unless?: Condition } + | { op: 'enters_tapped'; target: Target; unless?: Condition; unlessCost?: Cost } | { op: 'enters_with_counters'; target: Target; counter: string; amount: Value } | { op: 'set_pt'; target: Target; power?: Value; toughness?: Value; base?: boolean } | { op: 'control'; target: Target } @@ -345,6 +345,8 @@ export type Ability = export interface CompiledFace { name: string + /** Scryfall type line, or the type line declared in card source. */ + typeLine?: string status: 'supported' | 'partial' | 'unsupported' abilities: Ability[] } @@ -352,6 +354,8 @@ export interface CompiledFace { export interface CompiledCard { oracle_id: string name: string + /** Scryfall type line, or the type line declared in card source. */ + typeLine?: string status: 'supported' | 'partial' | 'unsupported' abilities: Ability[] faces?: CompiledFace[] diff --git a/backend/src/game/catalog.ts b/backend/src/game/catalog.ts index e9a3052..0f7e7c8 100644 --- a/backend/src/game/catalog.ts +++ b/backend/src/game/catalog.ts @@ -25,16 +25,22 @@ function numberOrUndefined(value: string | undefined): number | undefined { } function basicLandAbility(typeLine: string): Ability[] { - if (!/basic land/i.test(typeLine)) return [] - const subtype = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/)[0] ?? '' - const color = BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined) - if (!color) return [] + if (!/\bland\b/i.test(typeLine)) return [] + const subtypes = typeLine.toLowerCase().split('—').pop()?.trim().split(/\s+/) ?? [] + const colors = [...new Set(subtypes.map(subtype => BASIC_MANA[subtype] ?? (subtype === 'wastes' ? 'C' : undefined)) + .filter((color): color is string => Boolean(color)))] + if (!colors.length) return [] + const symbols = colors.map(color => `{${color}}`) return [{ kind: 'activated', costs: [{ kind: 'tap' }], - effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }], + effects: [{ + op: 'add_mana', + player: 'you', + mana: { kind: 'symbols', symbols, ...(symbols.length > 1 ? { oneOf: true } : {}) }, + }], optional: false, - text: `{T}: Add {${color}}.`, + text: `{T}: Add ${symbols.join(' or ')}.`, }] } @@ -43,8 +49,9 @@ function definitionFrom( compiled: CompiledCard | undefined, face?: CardFace, faceAbilities?: Ability[], + typeLineOverride?: string, ): CardDefinition { - const typeLine = face?.type_line ?? card.type_line + const typeLine = typeLineOverride ?? compiled?.typeLine ?? face?.type_line ?? card.type_line return { oracleId: card.oracle_id, name: face?.name ?? card.name, @@ -64,7 +71,7 @@ function definitionFrom( export function cardDefinitionFromCard(card: Card, compiled?: CompiledCard): CardDefinition { const face = card.card_faces?.[0] const compiledFace = compiled?.faces?.[0] - return definitionFrom(card, compiled, face, compiledFace?.abilities) + return definitionFrom(card, compiled, face, compiledFace?.abilities, compiledFace?.typeLine) } function load(): Map { diff --git a/backend/src/game/game.ts b/backend/src/game/game.ts index c3edac8..892a267 100644 --- a/backend/src/game/game.ts +++ b/backend/src/game/game.ts @@ -23,6 +23,7 @@ import type { GameConfig, ManaColor, ManaPool, + MulliganState, PendingChoice, PendingSearch, Phase, @@ -195,8 +196,10 @@ export class Game { phase: Phase = 'beginning' step: Step = 'untap' priority = '' - status: 'not_started' | 'active' | 'finished' = 'not_started' + status: 'not_started' | 'mulligan' | 'active' | 'finished' = 'not_started' winner?: string + /** Opening-hand choices, keyed by player id. */ + readonly mulligans = new Map() /** Blocks all other actions until the searching player picks a card. */ pendingSearch?: PendingSearch /** "As this enters, choose..." prompts, in entry order. */ @@ -258,6 +261,9 @@ export class Game { energy: 0, poison: 0, })) + for (const player of this.players) { + this.mulligans.set(player.id, { count: 0, kept: false, bottom: 0 }) + } for (const playerConfig of config.players) { for (const definition of playerConfig.deck) { @@ -290,7 +296,10 @@ export class Game { return object } - /** Starts the game, shuffles libraries, draws opening hands, and begins turn 1. */ + /** + * Starts the game, shuffles libraries, and draws opening hands. With mulligans + * enabled, turn 1 waits until every player keeps; otherwise it begins immediately. + */ start(): void { if (this.status !== 'not_started') throw new GameError('Game already started') for (const player of this.players) this.shuffleLibrary(player) @@ -301,8 +310,69 @@ export class Game { } } + if (!this.config.mulligans) { + this.beginGame() + return + } + this.status = 'mulligan' + this.turn = 1 + this.activePlayer = this.firstPlayer + } + + /** Keeps the opening hand; turn 1 begins once every living player has kept. */ + keepHand(playerId: string): void { + const mulligan = this.requireMulligan(playerId) + if (mulligan.kept) throw new GameError('You already kept your hand') + if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first') + mulligan.kept = true + const player = this.getPlayer(playerId) + this.logMessage(`${player.name} keeps their hand${mulligan.count ? ` after ${mulligan.count} mulligan${mulligan.count === 1 ? '' : 's'}` : ''}`) + if (this.players.every(entry => entry.lost || this.mulligans.get(entry.id)?.kept)) this.beginGame() + } + + /** Shuffles the hand back and draws a new one; each mulligan bottoms one more card. */ + mulligan(playerId: string): void { + const mulligan = this.requireMulligan(playerId) + if (mulligan.kept) throw new GameError('You already kept your hand') + if (mulligan.bottom > 0) throw new GameError('Put your cards on the bottom first') + const player = this.getPlayer(playerId) + for (const id of [...player.hand]) this.moveToZone(id, 'library', { silent: true }) + this.shuffleLibrary(player) + for (let i = 0; i < this.startingHandSize; i++) { + if (!player.library.length) break + this.drawCard(player.id, true) + } + mulligan.count++ + mulligan.bottom = Math.min(Math.max(0, mulligan.count - 1), player.hand.length) + this.logMessage(`${player.name} mulligans${mulligan.bottom + ? ` and puts ${mulligan.bottom} card${mulligan.bottom === 1 ? '' : 's'} on the bottom` + : ''}`) + } + + /** Puts one card from a mulliganed opening hand on the bottom of the library. */ + putOnBottom(playerId: string, cardId: string): void { + const mulligan = this.requireMulligan(playerId) + if (mulligan.kept) throw new GameError('You already kept your hand') + if (mulligan.bottom <= 0) throw new GameError('You have no cards to put on the bottom') + const player = this.getPlayer(playerId) + if (!player.hand.includes(cardId)) throw new GameError('Card is not in hand') + this.moveToZone(cardId, 'library', { silent: true }) + mulligan.bottom-- + } + + private requireMulligan(playerId: string): MulliganState { + if (this.status !== 'mulligan') throw new GameError('The game is not in its mulligan step') + const player = this.getPlayer(playerId) + if (player.lost) throw new GameError('You have left the game') + const mulligan = this.mulligans.get(playerId) + if (!mulligan) throw new GameError(`Unknown player: ${playerId}`) + return mulligan + } + + private beginGame(): void { // Leyline-style "begin the game with it on the battlefield" cards. for (const player of this.players) { + if (player.lost) continue for (const id of [...player.hand]) { const object = this.getObject(id) const beginsOnBattlefield = (object.definition.abilities ?? []).some(ability => @@ -773,7 +843,7 @@ export class Game { /** Marks a player as having forfeited. */ concede(playerId: string): void { - if (this.status !== 'active') throw new GameError('Game is not active') + if (this.status !== 'active' && this.status !== 'mulligan') throw new GameError('Game is not active') this.losePlayer(playerId) if (this.priority === playerId) this.priority = this.nextAlivePlayer(playerId) } @@ -783,7 +853,7 @@ export class Game { if (this.phase !== 'combat' || this.step !== 'declare_blockers') throw new GameError('Not in the declare blockers step') if (this.stack.length) throw new GameError('Cannot declare blockers while the stack is not empty') if (this.pendingSearch) throw new GameError('Choose a card from your library first') - if (this.pendingChoice) throw new GameError('Choose a creature type first') + if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (this.priority !== playerId) throw new GameError('You do not have priority') const seen = new Set() @@ -843,7 +913,7 @@ export class Game { pass(playerId?: string): void { if (this.status !== 'active') throw new GameError('Game is not active') if (this.pendingSearch) throw new GameError('Choose a card from your library first') - if (this.pendingChoice) throw new GameError('Choose a creature type first') + if (this.pendingChoice) throw new GameError('Resolve the pending choice first') const actual = playerId ?? this.priority if (this.priority !== actual) throw new GameError('You do not have priority') const alive = this.alivePlayers().length @@ -947,7 +1017,7 @@ export class Game { chooseSearchCard(playerId: string, cardId: string): void { const pending = this.pendingSearch if (!pending) throw new GameError('No search is waiting for a choice') - if (this.pendingChoice) throw new GameError('Choose a creature type first') + if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (pending.playerId !== playerId) throw new GameError('You are not searching your library') const object = this.searchCandidates(playerId).find(candidate => candidate.id === cardId) if (!object) throw new GameError('That card is not a legal choice') @@ -992,7 +1062,7 @@ export class Game { */ chooseCreatureType(playerId: string, type: string): void { const pending = this.pendingChoice - if (!pending) throw new GameError('No choice is waiting') + if (!pending || pending.what !== 'creature_type') throw new GameError('No choice is waiting') if (pending.playerId !== playerId) throw new GameError('You are not choosing this permanent\'s type') const chosen = CREATURE_TYPES.find(entry => entry.toLowerCase() === type.trim().toLowerCase()) if (!chosen) throw new GameError('Choose a creature type') @@ -1003,6 +1073,32 @@ export class Game { this.logMessage(`${this.getPlayer(playerId).name} chooses ${chosen} for ${object.definition.name}`) } + /** + * Answers an "as this enters, you may pay a cost; otherwise it enters tapped" + * replacement. The match API uses the `choose_cost` action. + */ + chooseCostPayment(playerId: string, pay: boolean): void { + const pending = this.pendingChoice + if (!pending || pending.what !== 'pay_cost' || !pending.cost) throw new GameError('No cost payment is waiting') + if (pending.playerId !== playerId) throw new GameError('You are not choosing this payment') + const object = this.objects.get(pending.sourceId) + if (object && object.zone === 'battlefield') { + if (pay) { + const context = this.contextFor(object, playerId, [], 0, 0) + if (!this.tryPayUnless(pending.cost, playerId, object, context)) throw new GameError('Cannot pay the cost') + this.pendingChoices.shift() + const detail = pending.amount === undefined ? 'the cost' : `${pending.amount} life` + this.logMessage(`${this.getPlayer(playerId).name} pays ${detail} for ${object.definition.name}`) + return + } + this.pendingChoices.shift() + object.tapped = true + this.logMessage(`${object.definition.name} enters tapped`) + return + } + this.pendingChoices.shift() + } + /** * Passes priority for players who cannot do anything meaningful. Stops at the * first player who can act, or when the turn ends, so turns never run on. @@ -1289,10 +1385,15 @@ export class Game { const source = this.players .flatMap(entry => entry.battlefield) .map(id => this.objects.get(id)) - .find((object): object is GameObject => Boolean(object && object.zone === 'battlefield' - && object.controller === player.id - && !object.tapped - && this.findFreeManaAbility(object) !== undefined)) + .map(object => { + if (!object || object.zone !== 'battlefield' || object.controller !== player.id || object.tapped) return undefined + const found = this.findFreeManaAbility(object) + if (!found) return undefined + return { object, allowed: this.manaAbilityAllowedColors(object, found.ability) } + }) + .filter((entry): entry is { object: GameObject; allowed: Set | undefined } => Boolean(entry)) + .filter(entry => this.neededColor(player, cost, entry.allowed) !== undefined) + .sort((a, b) => (a.allowed?.size ?? Number.MAX_SAFE_INTEGER) - (b.allowed?.size ?? Number.MAX_SAFE_INTEGER))[0]?.object if (!source) break this.autoManaDepth++ try { @@ -1321,37 +1422,128 @@ export class Game { const found = this.findFreeManaAbility(source) if (!found) return const player = this.getPlayer(source.controller) + const color = this.manaAbilityColor(source, found.ability, player, cost) + if (!color) return for (const entry of found.ability.costs) { if (entry.kind === 'tap') source.tapped = true } - const color = this.neededColor(player, cost) for (const effect of found.ability.effects) { if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color) } } - private neededColor(player: PlayerState, cost: ManaCost): ManaColor { - for (const color of cost.colored) { - if (player.manaPool[color] <= 0) return color - } - const hybridColor = cost.hybrid.flatMap(entry => entry.colors).find(color => player.manaPool[color] <= 0) - return hybridColor ?? 'W' + private manaAbilityColor( + source: GameObject, + ability: Extract, + player: PlayerState, + cost: ManaCost, + ): ManaColor | undefined { + return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability)) } - private addMana(playerId: string, mana: ManaSpec, preferred: ManaColor = 'W'): void { + private manaAbilityAllowedColors( + source: GameObject, + ability: Extract, + ): Set | 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 | undefined { + for (const color of cost.colored) { + if (player.manaPool[color] > 0) continue + return allowed && !allowed.has(color) ? undefined : color + } + for (const hybrid of cost.hybrid) { + if (hybrid.colors.some(color => player.manaPool[color] > 0)) continue + return hybrid.colors.find(color => !allowed || allowed.has(color)) + } + if (allowed) return MANA_COLORS.find(color => allowed.has(color)) + return 'W' + } + + private addMana(playerId: string, mana: ManaSpec, preferred?: ManaColor): void { const player = this.getPlayer(playerId) if (mana.kind === 'symbols') { + if (mana.oneOf) { + const colors = mana.symbols.map(colorOfSymbol) + const color = preferred && colors.includes(preferred) ? preferred : colors[0] + if (color) player.manaPool[color]++ + return + } for (const symbol of mana.symbols) player.manaPool[colorOfSymbol(symbol)]++ - } else { - const amount = this.value(mana.amount, { - source: this.playerSource(playerId), - controller: playerId, - targets: [], - x: 0, - mode: 0, - }) - for (let i = 0; i < amount; i++) player.manaPool[preferred]++ + return } + const amount = this.value(mana.amount, { + source: this.playerSource(playerId), + controller: playerId, + targets: [], + x: 0, + mode: 0, + }) + const allowed = this.anyColorRestrictionColors(mana, playerId) + if (allowed?.size === 0) return + let color: ManaColor = preferred ?? 'W' + if (allowed && !allowed.has(color)) { + color = MANA_COLORS.find(entry => allowed.has(entry)) ?? 'W' + } + for (let i = 0; i < amount; i++) player.manaPool[color]++ + } + + /** + * Colors a land could produce for an "any color that a land ... could + * produce" restriction. Colorless and snow are not colors. + */ + private landManaColors(playerId: string, opponentsOnly: boolean, seen = new Set()): Set { + const colors = new Set() + 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, + ): Set | undefined { + if (mana.kind !== 'any_color') return undefined + if (mana.restriction === 'a land an opponent controls could produce') { + return this.landManaColors(playerId, true, seen) + } + if (mana.restriction === 'a land you control could produce') { + return this.landManaColors(playerId, false, seen) + } + return undefined } private payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void { @@ -1378,7 +1570,7 @@ export class Game { case 'energy': return player.energy >= cost.amount case 'pay_life': - return player.life > this.value(cost.amount, this.staticContext(source)) + return player.life >= this.value(cost.amount, this.staticContext(source)) case 'discard': return player.hand.length >= this.value(cost.amount, this.staticContext(source)) case 'sacrifice': @@ -2497,9 +2689,19 @@ export class Game { for (const effect of staticSource.ability.effects) { if (effect.op === 'enters_tapped') { if (effect.unless && this.checkCondition(effect.unless, staticSource.source)) continue - if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) { - object.tapped = true + if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue + if (effect.unlessCost && !object.tapped) { + const context = this.staticContext(staticSource.source) + this.pendingChoices.push({ + playerId: object.controller, + sourceId: object.id, + what: 'pay_cost', + cost: effect.unlessCost, + amount: effect.unlessCost.kind === 'pay_life' ? this.value(effect.unlessCost.amount, context) : undefined, + }) + continue } + object.tapped = true } else if (effect.op === 'enters_with_counters') { if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue const amount = this.value(effect.amount, this.staticContext(staticSource.source)) @@ -2773,9 +2975,8 @@ export class Game { /** * Affordability check that mirrors auto-tapping without changing the game. - * shortcut: any_color sources are counted as flexible even when they must - * produce one color, so rare "one color only" sources can be overestimated; - * upgrade if a card ever needs an exact color split from such a source. + * shortcut: only land-based any_color restrictions are modelled; mana + * restricted by a commander identity or a spell type is still flexible. */ private canAffordMana(playerId: string, symbols: string, x: number): boolean { if (!symbols) return true @@ -2783,6 +2984,7 @@ export class Game { const cost = parseManaCost(symbols, x) const pool = { ...player.manaPool } let flexible = 0 + const restricted: { colors: Set; amount: number }[] = [] for (const object of this.battlefieldObjects()) { if (object.controller !== playerId) continue const found = this.findFreeManaAbility(object) @@ -2792,23 +2994,32 @@ export class Game { if (effect.mana.kind === 'symbols') { for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++ } else { - flexible += this.value(effect.mana.amount, { + const amount = this.value(effect.mana.amount, { source: object, controller: playerId, targets: [], x: 0, mode: 0, }) + const allowed = this.anyColorRestrictionColors(effect.mana, playerId) + if (!allowed) flexible += amount + else if (allowed.size) restricted.push({ colors: allowed, amount }) } } } let life = player.life + restricted.sort((a, b) => a.colors.size - b.colors.size) const take = (color: ManaColor): boolean => { if (pool[color] > 0) { pool[color]-- return true } + const source = restricted.find(entry => entry.amount > 0 && entry.colors.has(color)) + if (source) { + source.amount-- + return true + } if (flexible > 0) { flexible-- return true @@ -2824,7 +3035,9 @@ export class Game { if (!(hybrid.life > 0 && life >= hybrid.life)) return false life -= hybrid.life } - const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + flexible + const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0) + + flexible + + restricted.reduce((total, entry) => total + entry.amount, 0) return remaining >= cost.generic } @@ -2923,6 +3136,21 @@ export class Game { } changed = true } + for (const player of this.alivePlayers()) { + const legends = new Map() + for (const object of this.battlefieldObjects()) { + if (object.controller !== player.id || !/\blegendary\b/i.test(object.definition.typeLine)) continue + const name = object.definition.name.toLowerCase() + legends.set(name, [...(legends.get(name) ?? []), object]) + } + for (const copies of legends.values()) { + // shortcut: keeps the first copy found, not the player's choice; ask when the API can pause for it + for (const extra of copies.slice(1)) { + this.moveToZone(extra, 'graveyard', { silent: false }) + changed = true + } + } + } } } @@ -3248,7 +3476,7 @@ export class Game { private requirePriority(playerId: string): void { if (this.status !== 'active') throw new GameError('Game is not active') if (this.pendingSearch) throw new GameError('Choose a card from your library first') - if (this.pendingChoice) throw new GameError('Choose a creature type first') + if (this.pendingChoice) throw new GameError('Resolve the pending choice first') if (this.priority !== playerId) throw new GameError('You do not have priority') } diff --git a/backend/src/game/rooms.ts b/backend/src/game/rooms.ts index 8709bbf..3fdab05 100644 --- a/backend/src/game/rooms.ts +++ b/backend/src/game/rooms.ts @@ -28,6 +28,7 @@ export interface ActionPayload { mode?: number overload?: boolean choice?: string + pay?: boolean position?: { x?: unknown; y?: unknown } attackers?: { attackerId: string; defenderId: string }[] blocks?: { blockerId: string; attackerId: string }[] @@ -110,6 +111,8 @@ export interface MatchView { priority: string status: string winner?: string + /** Present during the opening mulligan step. */ + mulligans?: { player: string; count: number; kept: boolean; bottom: number }[] stack: { id: string; kind: string; label: string; controller: string }[] log: string[] hand: CardView[] @@ -129,6 +132,8 @@ export interface MatchView { what: string sourceId: string sourceName: string + /** Life total to display for a `pay_life` cost. */ + amount?: number /** Choices to offer, populated only for the chooser. */ options: string[] } @@ -363,6 +368,7 @@ export function startMatch(matchId: string, token: string | undefined): void { startingHandSize: 7, firstPlayer: match.seats[0].playerId, commander: true, + mulligans: true, players: match.seats.map(entry => ({ id: entry.playerId, name: entry.name, @@ -424,6 +430,15 @@ export function performAction(matchId: string, token: string | undefined, action try { switch (action.type) { + case 'keep_hand': + game.keepHand(seat.playerId) + break + case 'mulligan': + game.mulligan(seat.playerId) + break + case 'mulligan_bottom': + game.putOnBottom(seat.playerId, requireId(action.cardId)) + break case 'play_land': game.playLand(seat.playerId, requireId(action.cardId)) break @@ -446,6 +461,10 @@ export function performAction(matchId: string, token: string | undefined, action if (typeof action.choice !== 'string') throw new MatchError('Missing type choice') game.chooseCreatureType(seat.playerId, action.choice) break + case 'choose_cost': + if (typeof action.pay !== 'boolean') throw new MatchError('Missing cost payment choice') + game.chooseCostPayment(seat.playerId, action.pay) + break case 'attack': if (!Array.isArray(action.attackers)) throw new MatchError('Invalid attackers') game.declareAttackers(seat.playerId, action.attackers.map(entry => ({ @@ -579,6 +598,9 @@ function serialize(match: Match, viewerId: string): MatchView { priority: game.priority, status: game.status, winner: game.winner, + mulligans: game.status === 'mulligan' + ? game.players.map(player => ({ player: player.id, ...game.mulligans.get(player.id)! })) + : undefined, stack: game.stack.map(item => ({ id: item.id, kind: item.kind, @@ -597,7 +619,8 @@ function serialize(match: Match, viewerId: string): MatchView { what: choice.what, sourceId: choice.sourceId, sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent', - options: choice.playerId === viewerId ? [...CREATURE_TYPES] : [], + amount: choice.amount, + options: choice.playerId === viewerId && choice.what === 'creature_type' ? [...CREATURE_TYPES] : [], } : undefined, pendingSearch: search diff --git a/backend/src/game/types.ts b/backend/src/game/types.ts index 368b7b8..4f55067 100644 --- a/backend/src/game/types.ts +++ b/backend/src/game/types.ts @@ -1,6 +1,6 @@ // The runtime game model. Card definitions are immutable input; objects are the // per-game instances that move between zones. -import type { Ability, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js' +import type { Ability, Cost, Effect, ObjectSelector, TokenSpec, Zone } from '../effects/types.js' export type ManaColor = 'W' | 'U' | 'B' | 'R' | 'G' | 'C' export type ManaPool = Record @@ -38,6 +38,17 @@ export interface GameConfig { firstPlayer?: string /** Enables command-zone casting, commander tax, and commander damage. */ commander?: boolean + /** Waits for every player to keep an opening hand before turn 1. */ + mulligans?: boolean +} + +/** One player's opening-hand choice while the game is in its mulligan step. */ +export interface MulliganState { + /** Mulligans taken so far. */ + count: number + kept: boolean + /** Cards still to put on the bottom of the library. */ + bottom: number } export interface PlayerState { @@ -140,11 +151,15 @@ export interface PendingSearch { split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } } -/** An "as this enters, choose..." pause. Blocks all actions until its controller picks. */ +/** An "as this enters..." pause. Blocks all actions until its controller picks. */ export interface PendingChoice { playerId: string sourceId: string - what: 'creature_type' + what: 'creature_type' | 'pay_cost' + /** Cost to pay to avoid entering tapped. */ + cost?: Cost + /** Life total to display for a `pay_life` cost. */ + amount?: number } export interface CombatAttack { diff --git a/backend/src/server.ts b/backend/src/server.ts index f0e79f9..4db0069 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -23,7 +23,7 @@ import { writeOverride, type ImplementationStatus, } from './effects/implementations.js' -import { PseudoParseError } from './effects/pseudo.js' +import { SourceParseError } from './effects/source.js' import { translateCard, TranslationError } from './effects/translate.js' import { importDeckText } from './game/commander.js' import { cardArt, cardImage, playmatImage, scryfallArtUrl, scryfallImageUrl } from './images.js' @@ -89,7 +89,7 @@ app.setErrorHandler((error, request, reply) => { if (error instanceof CardsUnavailableError) { return reply.code(503).send({ error: error.message }) } - if (error instanceof PseudoParseError) { + if (error instanceof SourceParseError) { return reply.code(400).send({ error: error.message, line: error.line }) } if (error instanceof TranslationError || error instanceof MatchError || error instanceof AuthError) { diff --git a/backend/test/cards.test.ts b/backend/test/cards.test.ts index 730fa66..379c1fa 100644 --- a/backend/test/cards.test.ts +++ b/backend/test/cards.test.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import type { Card } from '../src/cards.js' import { matchesCardFilters } from '../src/cards.js' +import { cardDefinitionFromCard } from '../src/game/catalog.js' function card(overrides: Partial = {}): Card { 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, { 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}'] }, + }]) +}) diff --git a/backend/test/effects.test.ts b/backend/test/effects.test.ts index 5ee8c84..163495f 100644 --- a/backend/test/effects.test.ts +++ b/backend/test/effects.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { compileText } from '../src/effects/compile.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' 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', () => { const [ability] = spell('Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.') 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 }) }) -test('formatter renders pseudocode', () => { +test('formatter renders card source', () => { const [ability] = creature('When this creature enters, draw a card.') const text = formatAbility(ability) - assert.match(text, /on enters\(this\)/) + assert.match(text, /triggered\(when\.enters\(self\)/) 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 assert.deepEqual(effect.copyOf, { kind: 'trigger_subject' }) 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', () => { @@ -299,9 +329,9 @@ test('"until the end of your next turn" gets its own duration', () => { if (effect.op !== 'pump') return assert.equal(effect.duration, 'until_end_of_your_next_turn') - const pseudo = formatAbility(ability) - assert.match(pseudo, /until the end of your next turn/) - assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) + const source = formatAbility(ability) + assert.match(source, /untilEndOfYourNextTurn/) + 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' }) }) -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.') assert.equal(self.kind, 'activated') 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 } }, ]) - const pseudo = formatAbility(self) - assert.match(pseudo, /remove 1 \+1\/\+1 counter\(s\) from this/) - assert.equal(formatAbility(parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0]), pseudo) + const source = formatAbility(self) + assert.match(source, /removeCountersCost\('\+1\/\+1', 1\)/) + 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.') 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[] = [ ...spell('If you control a commander, you may cast this without paying its mana cost.'), ...spell('Overload {6}{U}'), @@ -541,9 +571,9 @@ test('new abilities, effects and conditions round-trip through pseudocode', () = ), ] for (const ability of abilities) { - const pseudo = formatAbility(ability) - const reparsed = parsePseudoCard(`# Test [supported]\n${pseudo}`).abilities[0] + const source = formatAbility(ability) + const reparsed = parseCardSource(`export default [${source}]`).abilities[0] assert.ok(reparsed) - assert.equal(formatAbility(reparsed), pseudo) + assert.equal(formatAbility(reparsed), source) } }) diff --git a/backend/test/game.test.ts b/backend/test/game.test.ts index 9a76284..494bc75 100644 --- a/backend/test/game.test.ts +++ b/backend/test/game.test.ts @@ -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 { const game = new Game({ 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) }) +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', () => { const game = setup([{ id: 'p1' }, { id: 'p2' }]) 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) }) +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', () => { const anthem = card('Glorious Anthem', { typeLine: 'Enchantment', @@ -625,6 +761,63 @@ test('static replacement effects make permanents enter tapped with counters', () 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', () => { const game = new Game({ seed: 3, @@ -658,6 +851,43 @@ test('lethal damage to a player ends the game', () => { 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', () => { const game = setup([{ id: 'p1' }, { id: 'p2' }]) game.start() diff --git a/backend/test/pseudo.test.ts b/backend/test/pseudo.test.ts deleted file mode 100644 index 3c743f4..0000000 --- a/backend/test/pseudo.test.ts +++ /dev/null @@ -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) -}) diff --git a/backend/test/rooms.test.ts b/backend/test/rooms.test.ts index d8fc4db..143bf33 100644 --- a/backend/test/rooms.test.ts +++ b/backend/test/rooms.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' 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) { 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.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') +}) diff --git a/backend/test/source.test.ts b/backend/test/source.test.ts new file mode 100644 index 0000000..bb65ace --- /dev/null +++ b/backend/test/source.test.ts @@ -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) +}) diff --git a/backend/test/translate.test.ts b/backend/test/translate.test.ts index 88d8907..798d99e 100644 --- a/backend/test/translate.test.ts +++ b/backend/test/translate.test.ts @@ -46,40 +46,40 @@ function fakeOpenRouter(content: string) { } } -test('translation asks for pseudocode only and validates the answer', async () => { - const fake = fakeOpenRouter('spell:\n draw(you, 2)') +test('translation asks for card source only and validates the answer', async () => { + const fake = fakeOpenRouter('export default [spell([draw(you, 2)])]') const source = await translateCard(CARD, { apiKey: 'test-key', model: 'test/model', 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.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.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[1].content, /Draw two cards\./) }) 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, { apiKey: 'test-key', model: 'test/model', fetch: fake.fetchImpl, }) - assert.equal(source, 'spell:\n draw(you, 2)') - assert.equal(cleanTranslation(' spell:\n draw(you, 2) '), 'spell:\n draw(you, 2)') + assert.equal(source, 'export default [spell([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.') await assert.rejects( 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: [] }, ], } - 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, { apiKey: 'test-key', model: 'test/model', 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, /## Back/) }) diff --git a/frontend/app/assets/main.css b/frontend/app/assets/main.css index 06ebba6..3c8f7b0 100644 --- a/frontend/app/assets/main.css +++ b/frontend/app/assets/main.css @@ -298,11 +298,14 @@ button.danger { } .badge { - font-size: 0.7rem; + flex: none; + font-size: 0.62rem; + line-height: 1.2; text-transform: uppercase; - letter-spacing: 0.03em; + letter-spacing: 0.02em; + white-space: nowrap; border-radius: 99px; - padding: 0.1rem 0.45rem; + padding: 0.04rem 0.35rem; border: 1px solid currentColor; color: var(--muted); } @@ -319,7 +322,7 @@ button.danger { color: var(--bad); } -.badge.manual { +.badge.verified { color: var(--accent); } diff --git a/frontend/app/components/CardGraphEditor.vue b/frontend/app/components/CardGraphEditor.vue deleted file mode 100644 index 46ac072..0000000 --- a/frontend/app/components/CardGraphEditor.vue +++ /dev/null @@ -1,1094 +0,0 @@ - - - - - diff --git a/frontend/app/components/PseudoGuide.vue b/frontend/app/components/PseudoGuide.vue deleted file mode 100644 index 69391cd..0000000 --- a/frontend/app/components/PseudoGuide.vue +++ /dev/null @@ -1,212 +0,0 @@ - - - diff --git a/frontend/app/components/SourceGuide.vue b/frontend/app/components/SourceGuide.vue new file mode 100644 index 0000000..13d478a --- /dev/null +++ b/frontend/app/components/SourceGuide.vue @@ -0,0 +1,227 @@ + + + diff --git a/frontend/app/pages/cards.vue b/frontend/app/pages/cards.vue index 26dd351..ed96e25 100644 --- a/frontend/app/pages/cards.vue +++ b/frontend/app/pages/cards.vue @@ -1,9 +1,14 @@