Compare commits
6 Commits
39b2d72808
...
goal
| Author | SHA1 | Date | |
|---|---|---|---|
| c742d0cfa8 | |||
| 9ec486274f | |||
| bc05b63083 | |||
| bb85881cac | |||
| c962800876 | |||
|
|
a167649327 |
@@ -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.
|
||||
|
||||
43
README.md
43
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 }` |
|
||||
@@ -284,6 +285,8 @@ your public URLs. Both values are applied at runtime in the production image.
|
||||
| `GET` | `/me/decks` | The account's saved decks |
|
||||
| `PUT` | `/me/decks/:id` | Create or replace a saved deck |
|
||||
| `DELETE` | `/me/decks/:id` | Delete a saved deck |
|
||||
| `POST` | `/me/decks/:id/share` | Create (or reuse) a share link token for a saved deck |
|
||||
| `GET` | `/decks/share/:token` | Public read of a shared deck, used to import a copy |
|
||||
| `GET` | `/me/preferences` | Saved playmat and card back |
|
||||
| `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` |
|
||||
| `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` |
|
||||
|
||||
2
backend/.gitignore
vendored
2
backend/.gitignore
vendored
@@ -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
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export default [
|
||||
activated([tapCost()], [
|
||||
addMana(you, anyColor(1, { restriction: 'a land an opponent controls could produce' })),
|
||||
]),
|
||||
]
|
||||
@@ -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 })),
|
||||
),
|
||||
]
|
||||
@@ -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)
|
||||
@@ -3,9 +3,9 @@
|
||||
The card database from Scryfall is English prose. The game engine cannot execute
|
||||
prose, so `backend/src/effects/` compiles every oracle-text line into a small
|
||||
JSON AST. The AST is the canonical form for the engine. A pretty-printer renders
|
||||
the same AST as readable pseudocode, and a matching parser reads that pseudocode
|
||||
back, so a human can replace the generated implementation of a card without
|
||||
touching JSON.
|
||||
the same AST as readable card source, and a matching interpreter reads that
|
||||
source back, so a human can replace the generated implementation of a card
|
||||
without touching JSON.
|
||||
|
||||
This is deliberately **not** a rules engine. It answers "what does the card
|
||||
say?" in machine-readable form. "What happens when it resolves?" belongs to the
|
||||
@@ -18,10 +18,10 @@ Scryfall oracle text
|
||||
-> normalize (card name, "this creature", contractions, reminder text)
|
||||
-> classify (keyword / triggered / activated / static / spell effect)
|
||||
-> parse targets, values, costs, conditions, durations
|
||||
-> JSON AST + pseudocode rendering
|
||||
-> JSON AST + card-source rendering
|
||||
|
||||
data/card-overrides/<oracle_id>.pseudo.txt
|
||||
-> pseudocode parser
|
||||
data/card-overrides/<oracle_id>.js
|
||||
-> safe source interpreter
|
||||
-> JSON AST used instead of the generated one
|
||||
```
|
||||
|
||||
@@ -34,16 +34,16 @@ a guessed effect. A wrong effect is worse than a missing one.
|
||||
From `backend/`:
|
||||
|
||||
```bash
|
||||
npm run compile:cards # writes data/card-effects.json and .pseudo.txt
|
||||
npm test # compiler, pseudocode parser, and engine tests
|
||||
npm run compile:cards # writes data/card-effects.json and data/card-effects.js
|
||||
npm test # compiler, source interpreter, and engine tests
|
||||
npm run dev # API for the frontend editor
|
||||
```
|
||||
|
||||
Current output over the imported Commander pool (32,116 cards):
|
||||
|
||||
```text
|
||||
Cards: 14,141 supported, 10,119 partial, 7,856 unsupported
|
||||
Ability lines: 37,983/60,470 parsed (62.8%)
|
||||
Cards: 14,239 supported, 10,088 partial, 7,789 unsupported
|
||||
Ability lines: 38,132/60,470 parsed (63.1%)
|
||||
```
|
||||
|
||||
- **supported** — every ability line parsed.
|
||||
@@ -58,40 +58,202 @@ patterns updates the numbers.
|
||||
| File | Contents |
|
||||
| ---- | -------- |
|
||||
| `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card |
|
||||
| `data/card-effects.pseudo.txt` | The same cards rendered as pseudocode |
|
||||
| `data/card-overrides/<oracle_id>.pseudo.txt` | Human-authored implementations, one file per card |
|
||||
| `data/card-effects.js` | The same cards rendered as card source |
|
||||
| `data/card-overrides/<oracle_id>.js` | Human-authored implementations, one file per card |
|
||||
|
||||
The two generated files are git-ignored. Overrides are ordinary source files and
|
||||
should be committed.
|
||||
|
||||
## Pseudocode
|
||||
Compiled cards carry the Scryfall `typeLine`, and the game catalog uses it.
|
||||
An override can declare its own type line with `card(...)`; that value wins when
|
||||
the card is loaded into a game.
|
||||
|
||||
```text
|
||||
# Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
## Card source
|
||||
|
||||
# Llanowar Elves [supported]
|
||||
activate {T}:
|
||||
add_mana(you, {G})
|
||||
Card source looks like a JavaScript module, but it is **not executed as
|
||||
JavaScript**. `src/effects/source.ts` tokenizes and evaluates a deliberately
|
||||
small expression subset against a fixed builder API. There is no `eval`, no
|
||||
`new Function`, no imports, no property writes and no access to globals: an
|
||||
unrecognized name or method is a parse error. This matters because
|
||||
`PUT /cards/:oracleId/implementation` is unauthenticated.
|
||||
|
||||
# Krenko, Mob Boss [supported]
|
||||
activate {T}:
|
||||
create_token(you, count(creature goblin you control), 1/1 red goblin creature)
|
||||
A card exports its type line and an array of abilities:
|
||||
|
||||
```js
|
||||
export default card('Creature — Human Cleric', [
|
||||
keywords('Flying', 'Ward {2}'),
|
||||
triggered(when.enters(each(permanents.other().withType('creature'))), [
|
||||
gainLife(you, 1),
|
||||
]),
|
||||
activated([tapCost()], [
|
||||
addMana(you, mana('{G}')),
|
||||
]),
|
||||
])
|
||||
```
|
||||
|
||||
Pseudocode is a two-way format. `formatCard` writes it, `parsePseudoCard` reads
|
||||
it back into the same AST the compiler produces. Blocks are indented two spaces.
|
||||
A leading `# Card [status]` line is ignored, and `## Face Name [status]` starts a
|
||||
new section for a multi-face card. Use `(no abilities)` when a face has none.
|
||||
Plain `export default [...]` is still accepted and uses the Scryfall type line.
|
||||
Multi-face cards export `faces(face('Name', 'Type line', [...]), ...)` in card order:
|
||||
|
||||
```js
|
||||
export default faces(
|
||||
face('Front', 'Instant', [spell([draw(you, 2)])]),
|
||||
face('Back', 'Creature — Human', [keyword('Flying')]),
|
||||
)
|
||||
```
|
||||
|
||||
Every effect list also accepts a callback. A single expression is one effect; a
|
||||
block is several effects, separated by newlines, `;` or `,`:
|
||||
|
||||
```js
|
||||
export default card('Creature — Human Cleric', [
|
||||
triggered(when.enters(self), () => draw(you, 1)),
|
||||
activated([tapCost()], () => {
|
||||
gainLife(you, 1)
|
||||
draw(you, 1)
|
||||
}),
|
||||
])
|
||||
```
|
||||
|
||||
Arrays stay valid and are still used for costs, `modal` modes, ability lists,
|
||||
`card`, `faces` and `face`. The formatter emits callbacks for effect lists and
|
||||
`card(typeLine, abilities)` at the top level.
|
||||
|
||||
The formatter writes the same shape, so a generated implementation can be
|
||||
copied, edited and saved as an override. `formatCard` and `parseCardSource`
|
||||
round-trip: comments are ignored, a leading `// Card [status]` line is optional,
|
||||
and `const` declarations are allowed for reuse:
|
||||
|
||||
```js
|
||||
const dragons = permanents.withType('creature').withSubtype('dragon').youControl()
|
||||
|
||||
export default card('Creature — Human Cleric', [
|
||||
staticAbility([staticPump(each(dragons), 1, 1)]),
|
||||
])
|
||||
```
|
||||
|
||||
### Abilities
|
||||
|
||||
| Call | Meaning |
|
||||
| ---- | ------- |
|
||||
| `keyword(name, value)` | One keyword, optionally parameterized |
|
||||
| `keywords(...names)` | Several keywords from one oracle line |
|
||||
| `triggered(event, effects, options)` | `When`/`Whenever`/`At` ability |
|
||||
| `activated(costs, effects, options)` | Cost `:` effect, including loyalty |
|
||||
| `staticAbility(effects, options)` | Continuous effect or restriction |
|
||||
| `spell(effects, options)` | Effect line of an instant or sorcery |
|
||||
| `additionalCost(costs, options)` | Additional cost |
|
||||
| `alternativeCost(costs, options)` | Alternative cast, possibly free |
|
||||
| `overload(cost)` | Overload alternate cost |
|
||||
| `chapter(chapters, effects, options)` | Saga chapter ability |
|
||||
| `levelBand(min, max, power, toughness)` | Level band |
|
||||
| `levelPt(power, toughness)` | Level P/T line |
|
||||
| `unsupported(reason, text)` | Preserved text plus a reason |
|
||||
|
||||
`options` accepts `condition` and `optional`; activated abilities also accept
|
||||
`timing: 'sorcery'` and `activationsPerTurn`.
|
||||
|
||||
### Selectors and targets
|
||||
|
||||
Selectors start from `permanents`, `cards` or `creatures` and chain filters:
|
||||
|
||||
```js
|
||||
permanents.withType('creature').withSubtype('dragon').withColor('red')
|
||||
.other().tapped().youControl().powerAtLeast(4)
|
||||
```
|
||||
|
||||
Available filters include `withType`, `withSubtype`, `withSupertype`,
|
||||
`withColor`, `withoutColor`, `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 }))
|
||||
createToken(you, 1, token({ name: 'Monster', types: ['enchantment'], subtypes: ['aura', 'role'] }), { attachTo: target(permanents.withType('creature')) })
|
||||
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`,
|
||||
`exileInsteadOfGraveyard` and `tokenMultiplier` (with optional
|
||||
`who: 'each_player'` or `creatureOnly: true`). `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 +262,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 +272,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 +294,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": [
|
||||
{
|
||||
@@ -165,6 +327,8 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
| `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` |
|
||||
| `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` |
|
||||
| `spell` | Effect line of an instant or sorcery | `Draw two cards.` |
|
||||
| `alternative_cost` | Alternative cast with a condition, possibly free | `If you control a commander, you may cast this without paying its mana cost.` |
|
||||
| `overload` | Overload alternate cost; the engine widens the spell's targets | `Overload {6}{U}` |
|
||||
| `unsupported` | Preserved text plus a reason | `Choose one —` |
|
||||
|
||||
### Effects
|
||||
@@ -177,20 +341,30 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
| `pump` | `target`, `power`, `toughness`, `duration` |
|
||||
| `grant` | `target`, `keyword`, optional `value`, `duration` |
|
||||
| `put_counters`, `remove_counters` | `target`, `counter`, `amount` |
|
||||
| `create_token` | `player`, `amount`, `token` |
|
||||
| `create_token` | `player`, `amount`, `token`, optional `attachTo` target |
|
||||
| `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` |
|
||||
| `sacrifice` | `player`, `target`, optional `unless` cost |
|
||||
| `counter` | `what`, `target`, optional `unless` cost |
|
||||
| `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` |
|
||||
| `search`, `shuffle` | player, selector, destination |
|
||||
| `search`, `shuffle` | player, selector, destination, optional `split` destination |
|
||||
| `add_mana` | `player`, `mana` (`symbols` or `any_color`) |
|
||||
| `scry`, `surveil` | `player`, `amount` |
|
||||
| `fight` | two targets |
|
||||
| `energy` | `player`, `amount` |
|
||||
| `attach` | target to attach this/trigger object to |
|
||||
| `restriction` | target, rule, duration |
|
||||
| `keyword_action` | `action`, optional `amount`, `detail`, `target` |
|
||||
| `keyword_action` | `action`, optional `amount`, `detail`, `target`; the engine implements `explore`, `incubate`, and `impulse` |
|
||||
| `proliferate` | no payload |
|
||||
| `hideaway` | `amount`; looks at that many cards and pauses for the controller to exile one face down, linking it to the source |
|
||||
| `play_exiled` | `player`, optional `free`; plays a card linked with `hideaway` |
|
||||
| `exile_graveyards` | no payload; exiles all cards from every graveyard |
|
||||
| `transform` | `target`; swaps the object's front and back faces |
|
||||
|
||||
A created token whose name or subtype matches one of the predefined tokens in
|
||||
comprehensive rules 111.10 gets that token's full characteristics and abilities
|
||||
from `src/game/tokens.ts`. The compiled `token` spec only needs enough information
|
||||
to identify it, for example `token({ subtypes: ['treasure'] })` or
|
||||
`token({ name: 'Monster', subtypes: ['aura', 'role'] })` for a Role.
|
||||
|
||||
### Targets, values, costs
|
||||
|
||||
@@ -202,8 +376,12 @@ The types live in `src/effects/types.ts`. A card contains one or more abilities:
|
||||
`source_toughness`, `cards_in_hand`, or `event_amount`.
|
||||
- **Costs** are mana symbols, tap/untap, tapping another permanent, energy,
|
||||
loyalty, life, discard, sacrifice, self-exile, mill, and removing counters.
|
||||
- **Conditions** cover controlling permanents, turn ownership, tapped source,
|
||||
life totals, and graveyard size.
|
||||
- **Conditions** cover controlling permanents, commander control, turn ownership,
|
||||
tapped source, life totals, graveyard/hand/library size, total power, distinct
|
||||
permanent names, and this-turn attacks and damage.
|
||||
- **Static effects** include pumps, keyword grants, restrictions, enters
|
||||
tapped/with counters, control, choices, replacements, cost reduction/increase,
|
||||
search restriction, and exiling cards instead of putting them into graveyards.
|
||||
- **Durations** cover permanent, end of turn, your next turn, the end of your
|
||||
next turn, end of combat, controller's next untap step, and while the source
|
||||
remains.
|
||||
@@ -230,7 +408,7 @@ ambiguous pronouns stay unsupported.
|
||||
|
||||
## Adding support
|
||||
|
||||
For a single card, open the frontend editor, edit the pseudocode, and save; no
|
||||
For a single card, open the frontend editor, edit the source, and save; no
|
||||
compiler change is needed. For a whole class of cards:
|
||||
|
||||
1. Run `npm run compile:cards` and pick a frequent unsupported pattern.
|
||||
|
||||
@@ -18,6 +18,7 @@ const game = new Game({
|
||||
startingLife: 40,
|
||||
startingHandSize: 7,
|
||||
commander: true,
|
||||
mulligans: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 },
|
||||
{ id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 },
|
||||
@@ -32,7 +33,9 @@ in `commander.ts` checks size, singleton, color identity, and the commander type
|
||||
|
||||
`catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds
|
||||
intrinsic mana abilities for basic lands, because Scryfall's oracle text only has
|
||||
reminder text for them and the compiler produces no ability.
|
||||
reminder text for them and the compiler produces no ability. When a compiled card
|
||||
declares a `typeLine`, that value is used instead of Scryfall's; the generated
|
||||
card source carries the type line and an override can change it.
|
||||
|
||||
For tests or hand-authored cards, build a `CardDefinition` yourself:
|
||||
|
||||
@@ -56,19 +59,25 @@ 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 })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone and adds commander tax. |
|
||||
| `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode })` | Activates an ability on a permanent. Mana abilities resolve immediately. |
|
||||
| `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, manaColor })` | Activates an ability on a permanent. Mana abilities resolve immediately; `manaColor` picks the color when the ability can make several. |
|
||||
| `movePermanent(playerId, cardId, x, y)` | Cosmetic board layout for a permanent you control; coordinates are 0..1 within the battlefield. |
|
||||
| `declareAttackers(playerId, [{ attackerId, defenderId }])` | Starts combat from the precombat main if needed. |
|
||||
| `declareBlockers(playerId, [{ blockerId, attackerId }])` | Declares blocks for one defending player. In multiplayer, combat damage waits until every defending player has declared or passed. |
|
||||
| `resolveCombatDamage()` | Deals combat damage manually; passing priority also does this. |
|
||||
| `pass(playerId?)` | Passes priority; when everyone passes, resolves the top of the stack or advances the phase. |
|
||||
| `chooseSearchCard(playerId, cardId)` | Finishes one pick of a paused library search. |
|
||||
| `chooseHideawayCard(playerId, cardId)` | Exiles one of the cards looked at with hideaway; the rest go to the bottom in a random order. |
|
||||
| `chooseCreatureType(playerId, type)` | Answers an "as this enters, choose a creature type" prompt. |
|
||||
| `resolveStack()` | Convenience for tests/scripts: passes priority until the stack is empty. Does not advance phases. |
|
||||
| `endTurn(playerId)` | Ends the active player's turn, skipping remaining phases. Requires an empty stack. |
|
||||
| `canPlayCard(playerId, cardId)` | Whether a hand or command-zone card can legally be played now, including timing, mana, and targets. |
|
||||
| `legalTargetsForCard(playerId, cardId)`, `legalTargetsForAbility(playerId, sourceId, abilityIndex)` | Legal `TargetChoice`s for a spell or activated ability, so the UI can offer only real targets. |
|
||||
| `autoAdvance()` | Passes priority for players with nothing meaningful to do; stops when someone can act or the turn ends. |
|
||||
| `getPower`, `getToughness`, `hasKeyword` | Current characteristics after static and continuous effects. |
|
||||
| `addCard`, `moveToZone` | Setup helpers for placing cards directly into zones. |
|
||||
@@ -78,7 +87,17 @@ non-flash spells can only be cast in the active player's main phase with an empt
|
||||
stack. Targets may be supplied explicitly; if omitted, the first legal target is
|
||||
chosen automatically, which keeps scripted games short. A search effect that matches
|
||||
several cards pauses instead: other actions are refused until its controller calls
|
||||
`chooseSearchCard` (the match API uses the `choose_search` action).
|
||||
`chooseSearchCard` (the match API uses the `choose_search` action). The match API also
|
||||
sends the chooser the full searched pool (`searchPool`) so the UI can show and filter
|
||||
the library; only `searchCandidates` are legal picks. A permanent with "as this enters,
|
||||
choose a creature type" also pauses play: `pendingChoice` records the controller and
|
||||
the permanent, and the match API refuses other priority actions until `chooseCreatureType`
|
||||
(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
|
||||
|
||||
@@ -88,55 +107,104 @@ untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers
|
||||
-> end step -> cleanup -> next player's turn
|
||||
```
|
||||
|
||||
The starting player skips their first draw. Cleanup discards down to seven cards,
|
||||
clears damage, expires `until_end_of_turn` and `until_end_of_your_next_turn`
|
||||
effects, and empties mana pools. The engine advances phases when every living
|
||||
player passes in turn; it does not stop at every rules-defined priority window.
|
||||
The match manager calls `autoAdvance()` after each action, so priority is only
|
||||
shown to players who can actually do something.
|
||||
The starting player draws on their first turn, as in multiplayer Commander. Cleanup
|
||||
discards down to seven cards, clears damage, expires `until_end_of_turn` and
|
||||
`until_end_of_your_next_turn` effects, and empties mana pools. The engine advances
|
||||
phases when every living player passes in turn; it does not stop at every
|
||||
rules-defined priority window. The match manager calls `autoAdvance()` after each
|
||||
action, so priority is only shown to players who can actually do something.
|
||||
|
||||
## Supported
|
||||
|
||||
- Zones: library, hand, battlefield, graveyard, exile, stack, and command zone. Tokens
|
||||
cease to exist when they leave the battlefield.
|
||||
- Commander: command-zone casting, `{2}` tax per previous cast from the command
|
||||
zone, return to the command zone instead of graveyard/exile/hand/library, and a
|
||||
loss at 21 combat damage from one commander. Deck construction is validated by
|
||||
`validateCommanderDeck`.
|
||||
zone, free alternative costs while you control a commander, return to the command
|
||||
zone instead of graveyard/exile/hand/library, and a loss at 21 combat damage from
|
||||
one commander. Deck construction is validated by `validateCommanderDeck`.
|
||||
- Mana: colored, generic, hybrid, Phyrexian, `{X}`, and `{S}` costs; manual mana
|
||||
abilities plus automatic tapping of untapped mana sources when paying.
|
||||
- Costs: tap, untap, tap another permanent, pay life, discard, sacrifice, exile,
|
||||
putting/removing counters, mill, energy, and choice costs.
|
||||
- Abilities: spell effects, activated abilities, triggered abilities (enters,
|
||||
leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step, combat), static
|
||||
effects, and basic replacement effects for entering tapped/with counters.
|
||||
putting/removing counters, mill, energy, and choice costs. Static cost reductions
|
||||
and increases apply while their source is on the battlefield.
|
||||
- Abilities: spell effects, overload, activated abilities, triggered abilities
|
||||
(enters, leaves, dies, attacks, blocks, cast, draw, life, upkeep, end step,
|
||||
combat), static effects, and basic replacement effects for entering tapped/with
|
||||
counters and exiling cards instead of putting them into graveyards.
|
||||
- Effects: damage, draw, discard, mill, life, pump/set P/T, grant keyword,
|
||||
counters, proliferate, tokens, destroy, exile, sacrifice, counter spell/ability,
|
||||
zone returns, tap/untap, search/shuffle, add mana, fight, regenerate, energy,
|
||||
attach, restrictions, conditional and modal effects, dig, and divided damage.
|
||||
counters, proliferate, tokens, destroy, exile, exile all graveyards, sacrifice,
|
||||
counter spell/ability, zone returns, tap/untap, search/shuffle, add mana, fight,
|
||||
regenerate, energy, attach, restrictions, conditional and modal effects, dig,
|
||||
divided damage, hideaway, and playing a card exiled with hideaway.
|
||||
- Tokens: the predefined tokens from comprehensive rules 111.10 (Treasure, Food,
|
||||
Gold, Walker, Shard, Clue, Blood, Powerstone, Incubator, Map, Junk, Lander,
|
||||
Mutagen, Vibranium, Heartwood, and the seven Role tokens). `tokens.ts` supplies
|
||||
their characteristics and abilities when a created token names that subtype or
|
||||
name. Role tokens can be created already attached to their target. Incubator
|
||||
tokens carry their counters and can transform into a Phyrexian.
|
||||
- Keyword actions: explore, incubate, and impulse. Impulse exiles the top card and
|
||||
marks it playable from exile until the end of the current turn.
|
||||
- Restrictions and conditions: activated abilities can be disabled, opponents can
|
||||
be limited to the top N cards when searching, cards can begin the game on the
|
||||
battlefield from the opening hand, and conditions can count commander control or
|
||||
distinct permanent names.
|
||||
- Combat keywords: flying, reach, first strike, double strike, trample, deathtouch,
|
||||
lifelink, vigilance, haste, indestructible. Regeneration shields replace
|
||||
destruction.
|
||||
- State-based actions: life at or below zero, ten poison counters, 21 commander
|
||||
damage from one commander, lethal or deathtouch damage, zero toughness, and
|
||||
drawing from an empty library.
|
||||
damage from one commander, lethal or deathtouch damage, zero toughness, the
|
||||
legend rule, and drawing from an empty library.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Some effect nodes are accepted but intentionally do nothing yet:
|
||||
`prevent_damage`, `gain_control`, `emblem`, `transform`, `schedule`, `level_up`,
|
||||
`put_from_among`, `look_top`, `scry`, `surveil`, and `keyword_action`.
|
||||
Unsupported oracle lines are already marked by the compiler and never reach here.
|
||||
`prevent_damage`, `gain_control`, `emblem`, `schedule`, `level_up`,
|
||||
`put_from_among`, `look_top`, `scry`, and `surveil`. Scry and surveil are
|
||||
no-ops, so an effect that scries and then draws still draws. `keyword_action`
|
||||
implements explore, incubate, and impulse; any other action is ignored.
|
||||
`transform` only works on an object that has a back face, currently the
|
||||
Incubator token. Unsupported oracle lines are already marked by the compiler
|
||||
and never reach here.
|
||||
- Explore puts a revealed land card into its controller's hand. For a nonland
|
||||
card, the exploring creature gets a +1/+1 counter and the card goes to the
|
||||
graveyard; it does not ask whether to put that card on top instead.
|
||||
- Impulse grants the engine's play-from-exile permission. The web client marks a
|
||||
playable exiled card and offers a Play button in the exile browser; other clients
|
||||
must expose the same cast/play path.
|
||||
- Powerstone and Vibranium mana carries an "artifact spells" restriction that the
|
||||
mana pool does not enforce, so it can currently pay for any spell.
|
||||
- Role and other Aura static abilities use the `attached: enchanted` selector,
|
||||
which matches any creature that has an Aura attached rather than only that
|
||||
Aura's own enchanted creature. With several Auras, a pump can apply more widely
|
||||
than printed.
|
||||
- Ward is recorded as a keyword and shown on the permanent, but targeting does not
|
||||
yet ask for its cost, so Royal Role's ward {1} is not enforced.
|
||||
- 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.
|
||||
- Opening hands are kept automatically; there is no mulligan flow.
|
||||
- "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
|
||||
(color, card name, player, opponent, number) are accepted and ignored. Cavern of
|
||||
Souls' mana is not restricted to the chosen type and does not make the spell
|
||||
uncounterable.
|
||||
- Hideaway pauses for its controller to exile one of the looked-at cards; the
|
||||
rest go to the bottom in a random order. The exiled card stays face down and is
|
||||
shown under its source, hidden from every player's card list. `play_exiled` only
|
||||
supports the free "without paying its mana cost" case.
|
||||
- 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 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
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -69,9 +69,11 @@ const deckSchema = new Schema({
|
||||
commander: { type: deckCardSchema, required: true },
|
||||
cards: { type: [deckCardSchema], default: [] },
|
||||
cardBack: { type: String, default: null },
|
||||
shareToken: String,
|
||||
updatedAt: { type: Number, required: true },
|
||||
})
|
||||
deckSchema.index({ owner: 1, deckId: 1 }, { unique: true })
|
||||
deckSchema.index({ shareToken: 1 }, { unique: true, sparse: true })
|
||||
|
||||
const User = mongoose.models.User ?? mongoose.model('User', userSchema)
|
||||
const Session = mongoose.models.Session ?? mongoose.model('Session', sessionSchema)
|
||||
@@ -83,6 +85,7 @@ interface DeckRow {
|
||||
commander: DeckCardInput
|
||||
cards: DeckCardInput[]
|
||||
cardBack?: string | null
|
||||
shareToken?: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
@@ -305,6 +308,34 @@ export function registerAccountRoutes(app: FastifyInstance): void {
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
// Reuses the deck's token so re-sharing a deck never breaks an existing link.
|
||||
app.post<{ Params: { id: string } }>('/me/decks/:id/share', async (request, reply) => {
|
||||
const user = await authenticate(request)
|
||||
const deckId = request.params.id
|
||||
if (!/^[a-zA-Z0-9_-]{1,100}$/.test(deckId)) {
|
||||
return reply.code(400).send({ error: 'Invalid deck id' })
|
||||
}
|
||||
const created = await Deck.findOneAndUpdate(
|
||||
{ owner: user.id, deckId, shareToken: null },
|
||||
{ $set: { shareToken: randomBytes(16).toString('base64url') } },
|
||||
{ returnDocument: 'after' },
|
||||
).lean<DeckRow>()
|
||||
if (created?.shareToken) return { token: created.shareToken }
|
||||
|
||||
const existing = await Deck.findOne({ owner: user.id, deckId }).lean<DeckRow>()
|
||||
if (!existing?.shareToken) return reply.code(404).send({ error: 'Deck not found' })
|
||||
return { token: existing.shareToken }
|
||||
})
|
||||
|
||||
app.get<{ Params: { token: string } }>('/decks/share/:token', async (request, reply) => {
|
||||
if (!/^[A-Za-z0-9_-]{22}$/.test(request.params.token)) {
|
||||
return reply.code(404).send({ error: 'Shared deck not found' })
|
||||
}
|
||||
const deck = await Deck.findOne({ shareToken: request.params.token }).lean<DeckRow>()
|
||||
if (!deck) return reply.code(404).send({ error: 'Shared deck not found' })
|
||||
return { deck: toDeck(deck, await implementationIndex()) }
|
||||
})
|
||||
|
||||
app.get('/me/preferences', async request => {
|
||||
const user = await authenticate(request)
|
||||
return preferences(user.id)
|
||||
|
||||
558
backend/src/effects/compile-primitives.ts
Normal file
558
backend/src/effects/compile-primitives.ts
Normal file
@@ -0,0 +1,558 @@
|
||||
import type { Card, CardFace } from '../cards.js'
|
||||
import {
|
||||
parseCondition,
|
||||
parseCost,
|
||||
parseDuration,
|
||||
parseNumber,
|
||||
parseSelector,
|
||||
parseTarget,
|
||||
parseValue,
|
||||
ROLE_NAMES,
|
||||
} from './parse.js'
|
||||
import type {
|
||||
Ability,
|
||||
CompiledCard,
|
||||
CompiledFace,
|
||||
Condition,
|
||||
Cost,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
} from './types.js'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
|
||||
export const SIMPLE_KEYWORDS = new Map<string, string>([
|
||||
['flying', 'Flying'],
|
||||
['trample', 'Trample'],
|
||||
['vigilance', 'Vigilance'],
|
||||
['haste', 'Haste'],
|
||||
['flash', 'Flash'],
|
||||
['reach', 'Reach'],
|
||||
['menace', 'Menace'],
|
||||
['lifelink', 'Lifelink'],
|
||||
['deathtouch', 'Deathtouch'],
|
||||
['first strike', 'First strike'],
|
||||
['double strike', 'Double strike'],
|
||||
['defender', 'Defender'],
|
||||
['indestructible', 'Indestructible'],
|
||||
['hexproof', 'Hexproof'],
|
||||
['prowess', 'Prowess'],
|
||||
['convoke', 'Convoke'],
|
||||
['delve', 'Delve'],
|
||||
['shroud', 'Shroud'],
|
||||
['shadow', 'Shadow'],
|
||||
['horsemanship', 'Horsemanship'],
|
||||
['fear', 'Fear'],
|
||||
['intimidate', 'Intimidate'],
|
||||
['skulk', 'Skulk'],
|
||||
['wither', 'Wither'],
|
||||
['infect', 'Infect'],
|
||||
['persist', 'Persist'],
|
||||
['undying', 'Undying'],
|
||||
['exalted', 'Exalted'],
|
||||
['evolve', 'Evolve'],
|
||||
['exploit', 'Exploit'],
|
||||
['riot', 'Riot'],
|
||||
['cascade', 'Cascade'],
|
||||
['banding', 'Banding'],
|
||||
['flanking', 'Flanking'],
|
||||
['storm', 'Storm'],
|
||||
['sunburst', 'Sunburst'],
|
||||
['haunt', 'Haunt'],
|
||||
['living weapon', 'Living weapon'],
|
||||
['battle cry', 'Battle cry'],
|
||||
['dethrone', 'Dethrone'],
|
||||
['melee', 'Melee'],
|
||||
['mentor', 'Mentor'],
|
||||
['aftermath', 'Aftermath'],
|
||||
['ascend', 'Ascend'],
|
||||
['fuse', 'Fuse'],
|
||||
['jump-start', 'Jump-start'],
|
||||
['improvise', 'Improvise'],
|
||||
['undaunted', 'Undaunted'],
|
||||
['spectacle', 'Spectacle'],
|
||||
['escape', 'Escape'],
|
||||
['companion', 'Companion'],
|
||||
['daybound', 'Daybound'],
|
||||
['nightbound', 'Nightbound'],
|
||||
['training', 'Training'],
|
||||
['read ahead', 'Read ahead'],
|
||||
['casualty', 'Casualty'],
|
||||
['enlist', 'Enlist'],
|
||||
['bargain', 'Bargain'],
|
||||
['gift', 'Gift'],
|
||||
['disguise', 'Disguise'],
|
||||
['cloak', 'Cloak'],
|
||||
['saddle', 'Saddle'],
|
||||
['impending', 'Impending'],
|
||||
['harmonize', 'Harmonize'],
|
||||
['start your engines!', 'Start your engines!'],
|
||||
['devoid', 'Devoid'],
|
||||
['changeling', 'Changeling'],
|
||||
['phasing', 'Phasing'],
|
||||
['dredge', 'Dredge'],
|
||||
['bloodthirst', 'Bloodthirst'],
|
||||
['devour', 'Devour'],
|
||||
['graft', 'Graft'],
|
||||
['modular', 'Modular'],
|
||||
['bushido', 'Bushido'],
|
||||
['rampage', 'Rampage'],
|
||||
['absorb', 'Absorb'],
|
||||
['frenzy', 'Frenzy'],
|
||||
['tribute', 'Tribute'],
|
||||
['soulshift', 'Soulshift'],
|
||||
])
|
||||
|
||||
const PARAMETERIZED_KEYWORDS: Array<[RegExp, string]> = [
|
||||
[/^ward\s+(.+)$/, 'Ward'],
|
||||
[/^ward—(.+)$/, 'Ward'],
|
||||
[/^equip\s+(.+)$/, 'Equip'],
|
||||
[/^crew\s+(\d+)$/, 'Crew'],
|
||||
[/^saddle\s+(\d+)$/, 'Saddle'],
|
||||
[/^cycling\s+(.+)$/, 'Cycling'],
|
||||
[/^typecycling\s+(.+)$/, 'Typecycling'],
|
||||
[/^landcycling\s+(.+)$/, 'Landcycling'],
|
||||
[/^basic landcycling\s+(.+)$/, 'Basic landcycling'],
|
||||
[/^flashback(?:\s*[—-]\s*|\s+)(.+)$/, 'Flashback'],
|
||||
[/^kicker(?:\s*[—-]\s*|\s+)(.+)$/, 'Kicker'],
|
||||
[/^entwine\s+(.+)$/, 'Entwine'],
|
||||
[/^fabricate\s+(\d+)$/, 'Fabricate'],
|
||||
[/^madness\s+(.+)$/, 'Madness'],
|
||||
[/^suspend\s+(\d+)\s*[—-]\s*(.+)$/, 'Suspend'],
|
||||
[/^protection from (.+)$/, 'Protection'],
|
||||
[/^enchant (.+)$/, 'Enchant'],
|
||||
[/^annihilator\s+(\d+)$/, 'Annihilator'],
|
||||
[/^afterlife\s+(\d+)$/, 'Afterlife'],
|
||||
[/^afflict\s+(\d+)$/, 'Afflict'],
|
||||
[/^amass\s+(.+)$/, 'Amass'],
|
||||
[/^affinity for (.+)$/, 'Affinity'],
|
||||
[/^bestow\s+(.+)$/, 'Bestow'],
|
||||
[/^emerge\s+(.+)$/, 'Emerge'],
|
||||
[/^mutate\s+(.+)$/, 'Mutate'],
|
||||
[/^morph\s+(.+)$/, 'Morph'],
|
||||
[/^megamorph\s+(.+)$/, 'Megamorph'],
|
||||
[/^manifest\s+(.+)$/, 'Manifest'],
|
||||
[/^disguise\s+(.+)$/, 'Disguise'],
|
||||
[/^cloak\s+(.+)$/, 'Cloak'],
|
||||
[/^escape(?:\s*[—-]\s*|\s+)(.+)$/, 'Escape'],
|
||||
[/^evoke\s+(.+)$/, 'Evoke'],
|
||||
[/^echo\s+(.+)$/, 'Echo'],
|
||||
[/^cumulative upkeep(?:\s*[—-]\s*|\s+)(.+)$/, 'Cumulative upkeep'],
|
||||
[/^fading\s+(\d+)$/, 'Fading'],
|
||||
[/^vanishing\s+(\d+)$/, 'Vanishing'],
|
||||
[/^modular\s+(\d+)$/, 'Modular'],
|
||||
[/^bushido\s+(\d+)$/, 'Bushido'],
|
||||
[/^rampage\s+(\d+)$/, 'Rampage'],
|
||||
[/^absorb\s+(\d+)$/, 'Absorb'],
|
||||
[/^frenzy\s+(\d+)$/, 'Frenzy'],
|
||||
[/^tribute\s+(\d+)$/, 'Tribute'],
|
||||
[/^bloodthirst\s+(\d+)$/, 'Bloodthirst'],
|
||||
[/^devour\s+(\d+)$/, 'Devour'],
|
||||
[/^graft\s+(\d+)$/, 'Graft'],
|
||||
[/^soulshift\s+(\d+)$/, 'Soulshift'],
|
||||
[/^dredge\s+(\d+)$/, 'Dredge'],
|
||||
[/^toxic\s+(\d+)$/, 'Toxic'],
|
||||
[/^backup\s+(\d+)$/, 'Backup'],
|
||||
[/^firebending\s+(\d+)$/, 'Firebending'],
|
||||
[/^renown\s+(\d+)$/, 'Renown'],
|
||||
[/^teamwork\s+(\d+)$/, 'Teamwork'],
|
||||
[/^squad\s+(\d+)$/, 'Squad'],
|
||||
[/^mobilize\s+(\d+)$/, 'Mobilize'],
|
||||
[/^casualty\s+(\d+)$/, 'Casualty'],
|
||||
[/^level up\s+(.+)$/, 'Level up'],
|
||||
[/^plot\s+(.+)$/, 'Plot'],
|
||||
[/^unearth\s+(.+)$/, 'Unearth'],
|
||||
[/^buyback\s+(.+)$/, 'Buyback'],
|
||||
[/^foretell\s+(.+)$/, 'Foretell'],
|
||||
[/^forecast(?:\s*[—-]\s*|\s+)(.+)$/, 'Forecast'],
|
||||
[/^ninjutsu\s+(.+)$/, 'Ninjutsu'],
|
||||
[/^dash\s+(.+)$/, 'Dash'],
|
||||
[/^disturb\s+(.+)$/, 'Disturb'],
|
||||
[/^warp\s+(.+)$/, 'Warp'],
|
||||
[/^blitz\s+(.+)$/, 'Blitz'],
|
||||
[/^encore\s+(.+)$/, 'Encore'],
|
||||
[/^grandeur(?:\s*[—-]\s*|\s+)(.+)$/, 'Grandeur'],
|
||||
[/^scavenge\s+(.+)$/, 'Scavenge'],
|
||||
[/^fortify\s+(.+)$/, 'Fortify'],
|
||||
[/^outlast\s+(.+)$/, 'Outlast'],
|
||||
[/^embalm\s+(.+)$/, 'Embalm'],
|
||||
[/^eternalize\s+(.+)$/, 'Eternalize'],
|
||||
[/^transfigure\s+(.+)$/, 'Transfigure'],
|
||||
[/^transmute\s+(.+)$/, 'Transmute'],
|
||||
[/^reconfigure\s+(.+)$/, 'Reconfigure'],
|
||||
[/^partner with (.+)$/, 'Partner'],
|
||||
[/^partner[—-](.+)$/, 'Partner'],
|
||||
[/^companion\s*[—-]\s*(.+)$/, 'Companion'],
|
||||
[/^(.+?)walk$/, 'Landwalk'],
|
||||
]
|
||||
|
||||
export const STANDALONE_ACTIONS = new Set([
|
||||
'investigate',
|
||||
'proliferate',
|
||||
'populate',
|
||||
'learn',
|
||||
'take the initiative',
|
||||
'venture into the dungeon',
|
||||
'time travel',
|
||||
'open an attraction',
|
||||
'manifest dread',
|
||||
'the ring tempts you',
|
||||
'connive',
|
||||
'explore',
|
||||
])
|
||||
|
||||
/** Removes reminder text. Oracle text only uses parentheses for reminders. */
|
||||
export function stripReminders(text: string): string {
|
||||
let result = text
|
||||
let previous: string
|
||||
do {
|
||||
previous = result
|
||||
result = result.replace(/\s*\([^()]*\)/g, '')
|
||||
} while (result !== previous)
|
||||
return result.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
export function normalize(text: string, cardName: string): string {
|
||||
let result = stripReminders(text)
|
||||
.replace(/\u2019/g, "'")
|
||||
.replace(/\u2212/g, '-')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
|
||||
const names = [cardName]
|
||||
const shortName = cardName.split(',')[0]?.trim()
|
||||
if (shortName && shortName !== cardName) names.push(shortName)
|
||||
|
||||
for (const name of names) {
|
||||
if (!name) continue
|
||||
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
result = result.replace(new RegExp(`\\b${escaped}\\b`, 'gi'), 'this')
|
||||
}
|
||||
|
||||
result = result
|
||||
.replace(/\bthis\s+[a-z]+'s\b/gi, 'its')
|
||||
.replace(/\bthis's\b/gi, 'its')
|
||||
.replace(/\bthis (?:creature|permanent|artifact|enchantment|land|card|spell|token|vehicle|aura|planeswalker|battle|saga|equipment|class|treasure|food|clue|blood|map|gold|powerstone)\b/gi, 'this')
|
||||
.replace(/\b~'s\b/g, 'its')
|
||||
.replace(/~/g, 'this')
|
||||
.replace(/\bit's\b/gi, 'it is')
|
||||
.replace(/\bdoesn't\b/gi, 'does not')
|
||||
.replace(/\bcan't\b/gi, 'cannot')
|
||||
.replace(/\bwon't\b/gi, 'will not')
|
||||
|
||||
return result.replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
export function splitSentences(text: string): string[] {
|
||||
return text
|
||||
.split(/(?<=[.!?])\s+(?=\S)/)
|
||||
.map(part => part.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export const LEADING_DURATION = /^(until end of turn|until your next turn|until the end of your next turn|until end of combat), /i
|
||||
|
||||
/** "Until end of turn, X" is the same effect as "X until end of turn". */
|
||||
export function takeLeadingDuration(text: string): { rest: string; duration?: string } {
|
||||
const match = text.match(LEADING_DURATION)
|
||||
if (!match) return { rest: text }
|
||||
return { rest: text.slice(match[0].length), duration: match[1].toLowerCase() }
|
||||
}
|
||||
|
||||
/** Lowercase oracle text without destroying mana symbol casing ({W} -> {w}). */
|
||||
export function lowerText(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/\{([^}]+)\}/g, (_, symbols: string) => `{${symbols.toUpperCase()}}`)
|
||||
}
|
||||
|
||||
export function parseKeywordToken(part: string, known: Set<string>): KeywordAbility | undefined {
|
||||
const lower = part.trim().toLowerCase()
|
||||
if (!lower) return undefined
|
||||
|
||||
const knownKeyword = [...known].find(keyword => keyword.toLowerCase() === lower)
|
||||
if (knownKeyword) return { kind: 'keyword', keyword: knownKeyword }
|
||||
|
||||
const simple = SIMPLE_KEYWORDS.get(lower)
|
||||
if (simple) return { kind: 'keyword', keyword: simple }
|
||||
|
||||
for (const [pattern, keyword] of PARAMETERIZED_KEYWORDS) {
|
||||
const match = lower.match(pattern)
|
||||
if (match) return { kind: 'keyword', keyword, value: match[1] }
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parseKeywordLine(text: string, known: Set<string>): KeywordAbility[] | undefined {
|
||||
const whole = parseKeywordToken(text, known)
|
||||
if (whole) return [whole]
|
||||
|
||||
const parts = text
|
||||
.split(/,| and /)
|
||||
.map(part => part.trim())
|
||||
.filter(Boolean)
|
||||
if (!parts.length) return undefined
|
||||
|
||||
const keywords: KeywordAbility[] = []
|
||||
for (const part of parts) {
|
||||
const keyword = parseKeywordToken(part, known)
|
||||
if (!keyword) return undefined
|
||||
keywords.push(keyword)
|
||||
}
|
||||
return keywords
|
||||
}
|
||||
|
||||
export function parseGroupTarget(text: string): Target | undefined {
|
||||
const direct = parseTarget(text)
|
||||
if (direct) {
|
||||
if (direct.kind === 'object' && direct.mode === 'choose') return { ...direct, mode: 'each' }
|
||||
return direct
|
||||
}
|
||||
|
||||
const selector = parseSelector(text)
|
||||
if (selector) return { kind: 'object', selector, mode: 'each' }
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parseSubject(text: string): Target | undefined {
|
||||
let subject = text.trim()
|
||||
subject = subject.replace(/^one or more /, '')
|
||||
if (subject === 'this') return { kind: 'self' }
|
||||
|
||||
const orAnother = subject.match(/^this or another (.+)$/)
|
||||
if (orAnother) {
|
||||
const selector = parseSelector(`another ${orAnother[1]}`)
|
||||
if (selector) return { kind: 'object', selector, mode: 'each', includeSelf: true }
|
||||
}
|
||||
|
||||
return parseGroupTarget(subject)
|
||||
}
|
||||
|
||||
export function valueWithSign(text: string): Value | undefined {
|
||||
const sign = text.startsWith('-') ? -1 : 1
|
||||
const raw = text.replace(/^[+-]/, '')
|
||||
const value = parseValue(raw)
|
||||
if (!value) return undefined
|
||||
if (value.kind === 'number') return { kind: 'number', value: sign * value.value }
|
||||
return value
|
||||
}
|
||||
|
||||
export function forEachSelector(text: string): ObjectSelector | undefined {
|
||||
return parseSelector(text.replace(/^each /, ''))
|
||||
}
|
||||
|
||||
export function scaleEffect(effect: Effect, selector: ObjectSelector): Effect | undefined {
|
||||
const count: Value = { kind: 'count', selector }
|
||||
switch (effect.op) {
|
||||
case 'damage':
|
||||
if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined
|
||||
return { ...effect, amount: count }
|
||||
case 'draw':
|
||||
case 'mill':
|
||||
case 'life':
|
||||
if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined
|
||||
return { ...effect, amount: count }
|
||||
case 'put_counters':
|
||||
if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined
|
||||
return { ...effect, amount: count }
|
||||
case 'create_token':
|
||||
if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return undefined
|
||||
return { ...effect, amount: count }
|
||||
case 'pump':
|
||||
if (effect.power.kind !== 'number' || effect.toughness.kind !== 'number') return undefined
|
||||
if (![0, 1].includes(effect.power.value) || ![0, 1].includes(effect.toughness.value)) return undefined
|
||||
if (effect.power.value === 0 && effect.toughness.value === 0) return undefined
|
||||
return {
|
||||
...effect,
|
||||
power: effect.power.value === 1 ? count : effect.power,
|
||||
toughness: effect.toughness.value === 1 ? count : effect.toughness,
|
||||
}
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function parseToken(text: string): TokenSpec | undefined {
|
||||
let rest = text.trim().toLowerCase().replace(/\s+tokens?$/, '')
|
||||
if (rest.startsWith('a ') || rest.startsWith('an ')) rest = rest.replace(/^an? /, '')
|
||||
const tapped = rest.startsWith('tapped ')
|
||||
if (tapped) rest = rest.slice(7)
|
||||
return parseTokenBody(rest, tapped)
|
||||
}
|
||||
|
||||
export function parseTokenBody(text: string, tapped: boolean): TokenSpec | undefined {
|
||||
let rest = text.trim()
|
||||
if (!rest) return undefined
|
||||
if (/\b(copy|named|equal|number of|that's|thats)\b/.test(rest)) return undefined
|
||||
|
||||
const colors: string[] = []
|
||||
for (const [word, code] of Object.entries({ white: 'W', blue: 'U', black: 'B', red: 'R', green: 'G' })) {
|
||||
if (new RegExp(`\\b${word}\\b`).test(rest)) colors.push(code)
|
||||
}
|
||||
if (/\bcolorless\b/.test(rest)) colors.push('C')
|
||||
|
||||
const role = Object.entries(ROLE_NAMES).find(([name]) => rest.endsWith(`${name} role`))
|
||||
if (role) {
|
||||
return { name: role[1], types: ['enchantment'], subtypes: ['aura', 'role'], colors, tapped: tapped || undefined }
|
||||
}
|
||||
|
||||
let power: Value | undefined
|
||||
let toughness: Value | undefined
|
||||
const pt = rest.match(/^(\d+|x)\/(\d+|x)\b/)
|
||||
if (pt) {
|
||||
power = parseValue(pt[1])
|
||||
toughness = parseValue(pt[2])
|
||||
rest = rest.slice(pt[0].length).trim()
|
||||
}
|
||||
|
||||
const keywords: string[] = []
|
||||
const withMatch = rest.match(/\bwith (.+)$/)
|
||||
if (withMatch) {
|
||||
const parsed = parseKeywordLine(withMatch[1], new Set())
|
||||
if (!parsed) return undefined
|
||||
for (const keyword of parsed) {
|
||||
keywords.push(keyword.value ? `${keyword.keyword} ${keyword.value}` : keyword.keyword)
|
||||
}
|
||||
rest = rest.slice(0, withMatch.index).trim()
|
||||
}
|
||||
|
||||
const typeWords = new Set(['artifact', 'creature', 'enchantment', 'instant', 'land', 'planeswalker', 'sorcery', 'battle'])
|
||||
const types: string[] = []
|
||||
const subtypes: string[] = []
|
||||
for (const word of rest.split(/[\s,]+/).filter(Boolean)) {
|
||||
if (word === 'and' || word === 'or') continue
|
||||
if (['white', 'blue', 'black', 'red', 'green', 'colorless', 'tapped'].includes(word)) continue
|
||||
if (typeWords.has(word)) {
|
||||
types.push(word)
|
||||
continue
|
||||
}
|
||||
if (/^[a-z][a-z'-]*$/.test(word)) {
|
||||
subtypes.push(word.length > 3 && word.endsWith('s') && !word.endsWith('ss') ? word.slice(0, -1) : word)
|
||||
continue
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (!types.length) types.push('artifact')
|
||||
if (!subtypes.length && !power) return undefined
|
||||
|
||||
return { types, subtypes, colors, power, toughness, keywords: keywords.length ? keywords : undefined, tapped: tapped || undefined }
|
||||
}
|
||||
|
||||
export function parseDigDestination(text: string): 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' {
|
||||
if (text === 'into your hand') return 'hand'
|
||||
if (text === 'into your graveyard') return 'graveyard'
|
||||
if (text === 'onto the battlefield') return 'battlefield'
|
||||
if (text === 'on top of your library') return 'top'
|
||||
return 'bottom'
|
||||
}
|
||||
|
||||
export function parseSearchDestination(
|
||||
text: string,
|
||||
): { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean } | undefined {
|
||||
switch (text) {
|
||||
case 'into your hand':
|
||||
return { destination: 'hand', tapped: false }
|
||||
case 'onto the battlefield':
|
||||
return { destination: 'battlefield', tapped: false }
|
||||
case 'onto the battlefield tapped':
|
||||
return { destination: 'battlefield', tapped: true }
|
||||
case 'into your graveyard':
|
||||
return { destination: 'graveyard', tapped: false }
|
||||
case 'on top of your library':
|
||||
return { destination: 'top', tapped: false }
|
||||
case 'on the bottom of your library':
|
||||
return { destination: 'bottom', tapped: false }
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
export function parseSearch(text: string): Effect | undefined {
|
||||
const match = text.match(/^search your (library|library and\/or graveyard) for (.+)$/)
|
||||
if (!match) return undefined
|
||||
const zones: ('library' | 'graveyard')[] | undefined =
|
||||
match[1] === 'library' ? undefined : ['library', 'graveyard']
|
||||
const body = match[2].trim()
|
||||
|
||||
// Card names can contain commas, so try every comma as the selector/destination boundary.
|
||||
for (let index = body.indexOf(', '); index !== -1; index = body.indexOf(', ', index + 1)) {
|
||||
const selectorText = body.slice(0, index).trim()
|
||||
const rest = body.slice(index + 2).trim()
|
||||
|
||||
let amount: Value = { kind: 'number', value: 1 }
|
||||
let nameText = selectorText
|
||||
const upTo = nameText.match(/^up to (one|two|three|four|five|\d+) (.+)$/)
|
||||
if (upTo) {
|
||||
amount = parseValue(upTo[1]) ?? amount
|
||||
nameText = upTo[2]
|
||||
} else {
|
||||
nameText = nameText.replace(/^an? /, '')
|
||||
}
|
||||
|
||||
const selector = parseSelector(nameText)
|
||||
if (!selector) continue
|
||||
|
||||
const revealPrefix = /^reveal (?:it|them|that card|those cards),? (?:and )?/
|
||||
let destinationText = rest.replace(revealPrefix, '')
|
||||
let shuffle = false
|
||||
if (/^then shuffle and put (?:it|them|that card|those cards|the card|the chosen card) on top(?: of your library)?$/.test(destinationText)) {
|
||||
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
|
||||
}
|
||||
if (/^shuffle and put (?:it|them|that card|those cards|the card|the chosen card) on top(?: of your library)?$/.test(destinationText)) {
|
||||
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
|
||||
}
|
||||
if (/^put (?:it|them|that card|those cards|the card|the chosen card) on top of your library, then shuffle$/.test(destinationText)) {
|
||||
return { op: 'search', player: 'you', selector, amount, destination: 'top', tapped: false, shuffle: true, ...(zones ? { zones } : {}) }
|
||||
}
|
||||
|
||||
const split = destinationText.match(/^put one (.+?) and the other (.+?)(, then shuffle)?$/)
|
||||
if (split && amount.kind === 'number' && amount.value >= 2) {
|
||||
const first = parseSearchDestination(split[1].trim())
|
||||
const second = parseSearchDestination(split[2].trim())
|
||||
if (first && second) {
|
||||
return {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector,
|
||||
amount,
|
||||
destination: first.destination,
|
||||
tapped: first.tapped,
|
||||
shuffle: Boolean(split[3]),
|
||||
split: second,
|
||||
...(zones ? { zones } : {}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const put = destinationText.match(
|
||||
/^put (?:it|them|that card|those cards|the chosen card) (into your hand|onto the battlefield(?: tapped)?|into your graveyard|on top of your library|on the bottom of your library)(?: under your control)?(?:, then shuffle)?$/,
|
||||
)
|
||||
if (!put) continue
|
||||
|
||||
const parsedDestination = parseSearchDestination(put[1])
|
||||
if (!parsedDestination) continue
|
||||
shuffle = /then shuffle$/.test(destinationText)
|
||||
return {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector,
|
||||
amount,
|
||||
destination: parsedDestination.destination,
|
||||
tapped: parsedDestination.tapped,
|
||||
shuffle,
|
||||
...(zones ? { zones } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
507
backend/src/effects/compile-sentences.ts
Normal file
507
backend/src/effects/compile-sentences.ts
Normal file
@@ -0,0 +1,507 @@
|
||||
import type { Card, CardFace } from '../cards.js'
|
||||
import {
|
||||
parseCondition,
|
||||
parseCost,
|
||||
parseDuration,
|
||||
parseNumber,
|
||||
parseSelector,
|
||||
parseTarget,
|
||||
parseValue,
|
||||
ROLE_NAMES,
|
||||
} from './parse.js'
|
||||
import type {
|
||||
Ability,
|
||||
CompiledCard,
|
||||
CompiledFace,
|
||||
Condition,
|
||||
Cost,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
} from './types.js'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
import { parseEffect } from './compile.js'
|
||||
import { forEachSelector, lowerText, scaleEffect, splitSentences, takeLeadingDuration, valueWithSign } from './compile-primitives.js'
|
||||
|
||||
export function resolvePreviousTarget(text: string, target: Target): string {
|
||||
return text
|
||||
.replace(/\bthat creature\b/gi, 'the chosen target')
|
||||
.replace(/\bthat token\b/gi, 'the chosen target')
|
||||
.replace(/\bit\b(?!['’]s)/gi, 'the chosen target')
|
||||
}
|
||||
|
||||
export function parseEffectSentence(text: string): Effect[] | undefined {
|
||||
const emblem = text.trim().match(/^you get an emblem with "(.+)"$/i)
|
||||
if (emblem) return [{ op: 'emblem', text: emblem[1] }]
|
||||
|
||||
let sentence = lowerText(text).trim().replace(/\.$/, '')
|
||||
sentence = sentence.replace(/^then /, '')
|
||||
|
||||
const exileInstead = sentence.match(
|
||||
/^if (a creature dealt damage this way|that creature(?: or planeswalker)?|it|that permanent) would die this turn, exile it instead$/,
|
||||
)
|
||||
if (exileInstead) {
|
||||
const target: Target = exileInstead[1] === 'a creature dealt damage this way'
|
||||
? { kind: 'damaged' }
|
||||
: { kind: 'previous_target' }
|
||||
return [{ op: 'exile_instead_of_dying', target }]
|
||||
}
|
||||
|
||||
const scaled = sentence.match(/^(.+?) for each (.+)$/)
|
||||
if (scaled) {
|
||||
const selector = forEachSelector(scaled[2])
|
||||
const base = parseEffect(scaled[1])
|
||||
if (selector && base && !Array.isArray(base)) {
|
||||
const effect = scaleEffect(base, selector)
|
||||
if (effect) return [effect]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const whereX = sentence.match(/^(.+?), where x is the number of (.+)$/)
|
||||
if (whereX) {
|
||||
const selector = parseSelector(whereX[2])
|
||||
const base = parseEffect(whereX[1])
|
||||
if (selector && base && !Array.isArray(base)) {
|
||||
return [replaceX(base, { kind: 'count', selector })]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const direct = parseEffect(sentence)
|
||||
if (direct) return Array.isArray(direct) ? direct : [direct]
|
||||
|
||||
if (sentence.includes(' and ')) {
|
||||
const parts = sentence.split(' and ')
|
||||
if (parts.length === 2) {
|
||||
const first = parseEffectSentence(parts[0])
|
||||
if (first) {
|
||||
const target = first.some(effect => effect.op === 'create_token')
|
||||
? ({ kind: 'previous_target' } as Target)
|
||||
: primaryTargetOf(first)
|
||||
const subject = parts[0].match(/^(target player|target opponent|that player|each player|each opponent|you)\b/)?.[1]
|
||||
let second = parseEffectSentence(parts[1])
|
||||
if (!second && target) second = parseEffectSentence(resolvePreviousTarget(parts[1], target))
|
||||
if (!second && subject) {
|
||||
const verb = parts[1].match(/^(\w+)/)?.[1]
|
||||
const text = `${subject} ${subject === 'you' && verb?.endsWith('s') ? verb.slice(0, -1) : verb}${parts[1].slice(verb?.length ?? 0)}`
|
||||
second = parseEffectSentence(text)
|
||||
}
|
||||
if (second) return [...first, ...second]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sentence.includes(', then ')) {
|
||||
const parts = sentence.split(', then ')
|
||||
const effects: Effect[] = []
|
||||
let target: Target | undefined
|
||||
for (const part of parts) {
|
||||
const parsed = parseEffectSentence(target ? resolvePreviousTarget(part, target) : part)
|
||||
?? parseEffectSentence(part)
|
||||
if (!parsed) return undefined
|
||||
effects.push(...parsed)
|
||||
target = parsed.some(effect => effect.op === 'create_token')
|
||||
? { kind: 'previous_target' }
|
||||
: primaryTargetOf(parsed)
|
||||
}
|
||||
return effects
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function replaceX(effect: Effect, value: Value): Effect {
|
||||
const replace = (current: Value): Value => (current.kind === 'x' ? value : current)
|
||||
switch (effect.op) {
|
||||
case 'damage':
|
||||
return { ...effect, amount: replace(effect.amount) }
|
||||
case 'draw':
|
||||
case 'mill':
|
||||
case 'life':
|
||||
return { ...effect, amount: replace(effect.amount) }
|
||||
case 'put_counters':
|
||||
case 'remove_counters':
|
||||
return { ...effect, amount: replace(effect.amount) }
|
||||
case 'create_token':
|
||||
return { ...effect, amount: replace(effect.amount) }
|
||||
case 'pump':
|
||||
return { ...effect, power: replace(effect.power), toughness: replace(effect.toughness) }
|
||||
case 'search':
|
||||
return { ...effect, amount: replace(effect.amount) }
|
||||
default:
|
||||
return effect
|
||||
}
|
||||
}
|
||||
|
||||
export const PRIMARY_TARGET_OPS = new Set([
|
||||
'pump',
|
||||
'grant',
|
||||
'set_pt',
|
||||
'gain_control',
|
||||
'tap',
|
||||
'untap',
|
||||
'destroy',
|
||||
'exile',
|
||||
'return_to_hand',
|
||||
'return_to_battlefield',
|
||||
'sacrifice',
|
||||
'put_counters',
|
||||
'attach',
|
||||
'regenerate',
|
||||
])
|
||||
|
||||
export function primaryTargetOf(effects: Effect[]): Target | undefined {
|
||||
for (const effect of effects) {
|
||||
if (!('target' in effect) || !PRIMARY_TARGET_OPS.has(effect.op)) continue
|
||||
const target = (effect as { target: Target }).target
|
||||
if (
|
||||
target.kind === 'object' ||
|
||||
target.kind === 'self' ||
|
||||
target.kind === 'trigger_subject' ||
|
||||
target.kind === 'previous_target'
|
||||
) {
|
||||
return target
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parsePick(text: string): Value | undefined {
|
||||
if (text === 'any number') return { kind: 'any_number' }
|
||||
return parseValue(text)
|
||||
}
|
||||
|
||||
export function parseDig(text: string): Effect | undefined {
|
||||
const reorder = text.match(
|
||||
/^look at the top (\w+) cards? of (your|target player's) library, then put them back in any order(?:\. you may (?:have that player )?shuffle)?$/,
|
||||
)
|
||||
if (reorder) {
|
||||
const amount = parseValue(reorder[1])
|
||||
if (!amount) return undefined
|
||||
return {
|
||||
op: 'look_top',
|
||||
player: reorder[2] === 'your' ? 'you' : 'target_player',
|
||||
amount,
|
||||
reorder: true,
|
||||
}
|
||||
}
|
||||
|
||||
const prefix = text.match(/^look at the top (\w+) cards? of your library\. (.+)$/)
|
||||
if (!prefix) return undefined
|
||||
const amount = parseValue(prefix[1])
|
||||
if (!amount) return undefined
|
||||
const body = prefix[2].trim().replace(/\.$/, '')
|
||||
|
||||
let match = body.match(
|
||||
/^put (up to )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+|any number) (?:of them|of those cards) into your hand and the (?:other|rest)(?: of those cards)? (on the bottom of your library(?: in (any|a random) order)?|into your graveyard|on top of your library(?: in any order)?)$/,
|
||||
)
|
||||
if (match) {
|
||||
const pick = parsePick(match[2])
|
||||
if (pick) {
|
||||
const destination = match[3]
|
||||
const rest = destination.startsWith('on the bottom')
|
||||
? 'bottom'
|
||||
: destination.startsWith('into your graveyard')
|
||||
? 'graveyard'
|
||||
: 'top'
|
||||
const order = /in a random order$/.test(destination) ? 'random' : 'any'
|
||||
return {
|
||||
op: 'dig',
|
||||
player: 'you',
|
||||
amount,
|
||||
pick,
|
||||
upTo: Boolean(match[1]) || undefined,
|
||||
to: 'hand',
|
||||
rest,
|
||||
order,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = body.match(
|
||||
/^(you may )?reveal (?:up to )?(one|two|three|four|five|\d+)? ?(.+?) from among them and put (?:it|them) into your hand\. put the rest (on the bottom of your library(?: in (any|a random) order)?|into your graveyard)$/,
|
||||
)
|
||||
if (match) {
|
||||
const selector = parseSelector(match[3])
|
||||
const pick = match[2] ? parsePick(match[2]) : ({ kind: 'number', value: 1 } as Value)
|
||||
if (selector && pick) {
|
||||
const destination = match[4]
|
||||
const rest = destination.startsWith('on the bottom') ? 'bottom' : 'graveyard'
|
||||
const order = /in a random order$/.test(destination) ? 'random' : 'any'
|
||||
return {
|
||||
op: 'dig',
|
||||
player: 'you',
|
||||
amount,
|
||||
pick,
|
||||
upTo: /^(?:you may )?reveal up to /.test(body) || undefined,
|
||||
pickSelector: selector,
|
||||
to: 'hand',
|
||||
rest,
|
||||
order,
|
||||
optional: Boolean(match[1]) || undefined,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = body.match(
|
||||
/^put up to (one|two|three|four|five|\d+) (.+?) from among them onto the battlefield( tapped)?(?: and the rest on the bottom of your library(?: in (any|a random) order)?|\. put the rest on the bottom of your library(?: in (any|a random) order)?)$/,
|
||||
)
|
||||
if (match) {
|
||||
const selector = parseSelector(match[2])
|
||||
const pick = parsePick(match[1])
|
||||
if (selector && pick) {
|
||||
return {
|
||||
op: 'dig',
|
||||
player: 'you',
|
||||
amount,
|
||||
pick,
|
||||
upTo: true,
|
||||
pickSelector: selector,
|
||||
to: 'battlefield',
|
||||
tapped: Boolean(match[3]) || undefined,
|
||||
rest: 'bottom',
|
||||
order: /in a random order$/.test(body) ? 'random' : 'any',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = body.match(
|
||||
/^(you may )?put (any number|one|two|three|four|five|\d+) of them into your hand and the rest into your graveyard$/,
|
||||
)
|
||||
if (match) {
|
||||
const pick = parsePick(match[2])
|
||||
if (pick) {
|
||||
return {
|
||||
op: 'dig',
|
||||
player: 'you',
|
||||
amount,
|
||||
pick,
|
||||
to: 'hand',
|
||||
rest: 'graveyard',
|
||||
optional: Boolean(match[1]) || undefined,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parseEffects(text: string, defaultPronoun?: string): { effects: Effect[]; optional: boolean } | undefined {
|
||||
let rest = text.trim().replace(/\.$/, '')
|
||||
let optional = false
|
||||
if (/^you may /i.test(rest)) {
|
||||
optional = true
|
||||
rest = rest.slice(8)
|
||||
}
|
||||
|
||||
const leading = takeLeadingDuration(rest)
|
||||
rest = leading.rest
|
||||
|
||||
const dig = parseDig(rest)
|
||||
if (dig) return { effects: [dig], optional: optional || (dig.op === 'dig' && Boolean(dig.optional)) }
|
||||
|
||||
const sentences = splitSentences(rest)
|
||||
if (!sentences.length) return undefined
|
||||
if (leading.duration) sentences[0] = `${sentences[0].replace(/\.$/, '')} ${leading.duration}`
|
||||
|
||||
const effects: Effect[] = []
|
||||
let previousTarget: Target | undefined
|
||||
for (let sentenceIndex = 0; sentenceIndex < sentences.length; sentenceIndex++) {
|
||||
const rawSentence = sentences[sentenceIndex]
|
||||
let sentence = rawSentence
|
||||
.replace(/^when you do, /i, 'if you do, ')
|
||||
.replace(/^when you don't, /i, "if you don't, ")
|
||||
const leadingIt = /^it\b/i.test(sentence)
|
||||
if (previousTarget && leadingIt) {
|
||||
sentence = `the chosen target${sentence.slice(2)}`
|
||||
}
|
||||
if (previousTarget) {
|
||||
sentence = resolvePreviousTarget(sentence, previousTarget)
|
||||
} else if (defaultPronoun) {
|
||||
sentence = resolveIt(sentence, defaultPronoun)
|
||||
}
|
||||
|
||||
// "Exile the top N ... You may play that card this turn" is one impulse effect.
|
||||
const topCards = sentence.match(/^exile the top (?:(\w+) )?cards? of your library( face down)?\.?$/)
|
||||
if (topCards) {
|
||||
const permission = sentences[sentenceIndex + 1]?.match(
|
||||
/^(?:until end of turn, )?you may (?:play|cast) (?:that card|those cards|it|them)(?: this turn)?\.?$/,
|
||||
)
|
||||
const amount = topCards[1] ? parseValue(topCards[1]) : { kind: 'number' as const, value: 1 }
|
||||
if (permission && amount) {
|
||||
effects.push({ op: 'impulse', player: 'you', amount, faceDown: Boolean(topCards[2]) })
|
||||
sentenceIndex++
|
||||
previousTarget = { kind: 'previous_target' }
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
const spend = sentence.match(/^spend this mana only to (.+)$/i)
|
||||
if (spend) {
|
||||
const last = effects[effects.length - 1]
|
||||
if (last?.op === 'add_mana') {
|
||||
last.mana.restriction = spend[1]
|
||||
continue
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
// The search already shuffles; the sentence only spells out when.
|
||||
if (/^if you search your library this way, shuffle\.?$/i.test(sentence)) {
|
||||
const last = effects[effects.length - 1]
|
||||
if (last?.op !== 'search') return undefined
|
||||
last.shuffle = true
|
||||
continue
|
||||
}
|
||||
|
||||
// "If damage is prevented this way, ..." is a follow-up to the shield.
|
||||
const prevented = sentence.match(/^if damage (?:is|was) prevented this way, (.+)$/i)
|
||||
if (prevented) {
|
||||
const last = effects[effects.length - 1]
|
||||
if (last?.op !== 'prevent_damage') return undefined
|
||||
const inner = parseEffectSentence(prevented[1])
|
||||
if (!inner) return undefined
|
||||
last.then = [...(last.then ?? []), ...inner]
|
||||
continue
|
||||
}
|
||||
|
||||
const perPrevented = sentence.match(/^for each 1 damage prevented this way, (.+)$/i)
|
||||
if (perPrevented) {
|
||||
const last = effects[effects.length - 1]
|
||||
if (last?.op !== 'prevent_damage') return undefined
|
||||
const inner = parseEffectSentence(perPrevented[1])
|
||||
if (!inner) return undefined
|
||||
const scaled = inner.map(effect => {
|
||||
if (!('amount' in effect) || !effect.amount || effect.amount === 'all') return effect
|
||||
if (effect.amount.kind !== 'number' || effect.amount.value !== 1) return effect
|
||||
return { ...effect, amount: { kind: 'event_amount' as const } } as Effect
|
||||
})
|
||||
last.then = [...(last.then ?? []), ...scaled]
|
||||
continue
|
||||
}
|
||||
|
||||
if (/^you gain life equal to the damage prevented this way\.?$/i.test(sentence)) {
|
||||
const last = effects[effects.length - 1]
|
||||
if (last?.op !== 'prevent_damage') return undefined
|
||||
last.then = [...(last.then ?? []), {
|
||||
op: 'life',
|
||||
player: 'you',
|
||||
amount: { kind: 'event_amount' },
|
||||
mode: 'gain',
|
||||
}]
|
||||
continue
|
||||
}
|
||||
|
||||
const exileInstead = sentence.match(
|
||||
/^if (a creature dealt damage this way|that creature(?: or planeswalker)?|it|that permanent) would die this turn, exile it instead\.?$/i,
|
||||
)
|
||||
if (exileInstead) {
|
||||
effects.push({
|
||||
op: 'exile_instead_of_dying',
|
||||
target: exileInstead[1].toLowerCase() === 'a creature dealt damage this way'
|
||||
? { kind: 'damaged' }
|
||||
: { kind: 'previous_target' },
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
const conditional = sentence.match(/^if (.+?), (.+)$/i)
|
||||
if (conditional) {
|
||||
const raw = conditional[1].trim().toLowerCase()
|
||||
const condition: Condition | undefined =
|
||||
raw === 'you do'
|
||||
? { kind: 'if_you_do' }
|
||||
: raw === "you don't" || raw === 'you do not'
|
||||
? { kind: 'if_you_dont' }
|
||||
: parseCondition(conditional[1])
|
||||
if (condition) {
|
||||
let inner = parseEffectSentence(conditional[2])
|
||||
if (!inner && /^you may /i.test(conditional[2])) {
|
||||
inner = parseEffectSentence(conditional[2].slice(8))
|
||||
}
|
||||
if (inner) {
|
||||
effects.push({ op: 'conditional', condition, effects: inner })
|
||||
continue
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const otherwise = sentence.match(/^otherwise, (.+)$/i)
|
||||
if (otherwise) {
|
||||
let inner = parseEffectSentence(otherwise[1])
|
||||
if (!inner && /^you may /i.test(otherwise[1])) {
|
||||
inner = parseEffectSentence(otherwise[1].slice(8))
|
||||
}
|
||||
if (inner) {
|
||||
effects.push({ op: 'conditional', condition: { kind: 'otherwise' }, effects: inner })
|
||||
continue
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const trailingIf = sentence.match(/^(.+?) if (.+)$/i)
|
||||
if (trailingIf) {
|
||||
const condition = parseCondition(trailingIf[2])
|
||||
const inner = condition ? parseEffectSentence(trailingIf[1]) : undefined
|
||||
if (condition && inner) {
|
||||
effects.push({ op: 'conditional', condition, effects: inner })
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
let parsed: Effect[] | undefined
|
||||
if (/, then /i.test(sentence)) {
|
||||
const parts = sentence.split(/,\s+then\s+/i)
|
||||
const combined: Effect[] = []
|
||||
let thenTarget: Target | undefined
|
||||
for (const part of parts) {
|
||||
const inner = parseEffectSentence(thenTarget ? resolvePreviousTarget(part, thenTarget) : part)
|
||||
?? parseEffectSentence(part)
|
||||
if (!inner) {
|
||||
combined.length = 0
|
||||
break
|
||||
}
|
||||
combined.push(...inner)
|
||||
thenTarget = inner.some(effect => effect.op === 'create_token')
|
||||
? { kind: 'previous_target' }
|
||||
: primaryTargetOf(inner)
|
||||
}
|
||||
if (combined.length) parsed = combined
|
||||
}
|
||||
if (!parsed) parsed = parseEffectSentence(sentence)
|
||||
if (!parsed && /^you may /i.test(sentence)) {
|
||||
parsed = parseEffectSentence(sentence.slice(8))
|
||||
if (parsed) optional = true
|
||||
}
|
||||
if (!parsed) return undefined
|
||||
if (!leadingIt) {
|
||||
const prevention = parsed.find(effect => effect.op === 'prevent_damage')
|
||||
const newTarget = prevention?.op === 'prevent_damage' ? prevention.target : primaryTargetOf(parsed)
|
||||
if (newTarget) previousTarget = newTarget
|
||||
}
|
||||
if (parsed.some(effect => effect.op === 'create_token')) previousTarget = { kind: 'previous_target' }
|
||||
effects.push(...parsed)
|
||||
}
|
||||
|
||||
return { effects, optional }
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function resolveIt(text: string, pronoun: string): string {
|
||||
if (/^it\b/i.test(text)) return `${pronoun}${text.slice(2)}`
|
||||
if (/\b(?:target|that|those)\b/.test(text)) return text
|
||||
// A card/token/permanent mentioned in the effect introduces a new referent;
|
||||
// replacing "it" there would guess. Leave it unsupported instead.
|
||||
if (/\b(?:card|cards|token|tokens|permanent|permanents|creature|creatures|spell|spells)\b/.test(text)) return text
|
||||
return text.replace(/\bit\b/g, pronoun)
|
||||
}
|
||||
688
backend/src/effects/compile-static.ts
Normal file
688
backend/src/effects/compile-static.ts
Normal file
@@ -0,0 +1,688 @@
|
||||
import type { Card, CardFace } from '../cards.js'
|
||||
import {
|
||||
parseCondition,
|
||||
parseCost,
|
||||
parseDuration,
|
||||
parseNumber,
|
||||
parseSelector,
|
||||
parseTarget,
|
||||
parseValue,
|
||||
ROLE_NAMES,
|
||||
} from './parse.js'
|
||||
import type {
|
||||
Ability,
|
||||
CompiledCard,
|
||||
CompiledFace,
|
||||
Condition,
|
||||
Cost,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
} from './types.js'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
import { compileLine } from './compile.js'
|
||||
import { forEachSelector, parseKeywordLine, parseToken, takeLeadingDuration, valueWithSign } from './compile-primitives.js'
|
||||
|
||||
export function parseStaticTarget(text: string): Target | undefined {
|
||||
if (text.trim() === 'this' || text.trim() === 'it') return { kind: 'self' }
|
||||
const direct = parseTarget(text)
|
||||
if (direct && direct.kind === 'object') return { ...direct, mode: 'each' }
|
||||
const selector = parseSelector(text)
|
||||
if (selector) return { kind: 'object', selector, mode: 'each' }
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** "Each spell you cast that's X" and "X spells and Y spells" reduce on a union. */
|
||||
export function parseCostReductionTarget(text: string): Target | undefined {
|
||||
const eachSpell = text.match(/^each spell you cast that(?:'s| is) (.+)$/)
|
||||
const normalized = eachSpell
|
||||
? `${eachSpell[1].replace(/^an? /, '')} spells you cast`
|
||||
: text
|
||||
const target = parseStaticTarget(normalized)
|
||||
if (!target || target.kind !== 'object') return target
|
||||
if (!/\band\b|,/.test(normalized)) return target
|
||||
|
||||
target.selector.match = 'any'
|
||||
// parseSelector infers one type from the first subtype; a mixed list has none.
|
||||
if ((target.selector.subtypes?.length ?? 0) > 1) target.selector.types = []
|
||||
return target
|
||||
}
|
||||
|
||||
function tokenSpecByName(name: string): TokenSpec {
|
||||
const clean = name.trim().replace(/^an? /i, '').replace(/ tokens?$/i, '')
|
||||
return {
|
||||
name: clean.charAt(0).toUpperCase() + clean.slice(1),
|
||||
types: ['artifact'],
|
||||
subtypes: [clean.toLowerCase()],
|
||||
colors: [],
|
||||
}
|
||||
}
|
||||
|
||||
function parseReplacementTokens(text: string, from: string[]): TokenSpec[] | undefined {
|
||||
if (/^one of each$/i.test(text.trim())) return from.map(tokenSpecByName)
|
||||
const parts = text.split(/, and |, or | and |, /i).map(part => part.trim()).filter(Boolean)
|
||||
const tokens: TokenSpec[] = []
|
||||
for (const part of parts) {
|
||||
const spec = parseToken(part)
|
||||
if (!spec) return undefined
|
||||
tokens.push(spec)
|
||||
}
|
||||
return tokens.length ? tokens : undefined
|
||||
}
|
||||
|
||||
export function parseStaticEffects(text: string): StaticEffect[] | undefined {
|
||||
const sentence = text
|
||||
.trim()
|
||||
.replace(/\.$/, '')
|
||||
// Clarifies how a colored cost reduction works; our symbols do exactly this.
|
||||
.replace(/\. this effect reduces only the amount of colored mana you pay$/, '')
|
||||
|
||||
let match = sentence.match(/^prevent all (combat )?damage that would be dealt to (.+?)(?: by (.+?))?$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[2])
|
||||
const selector = match[3] ? parseSelector(match[3]) : undefined
|
||||
if (target && (selector || !match[3])) {
|
||||
return [{
|
||||
op: 'prevent_damage',
|
||||
target,
|
||||
amount: 'all',
|
||||
combatOnly: Boolean(match[1]) || undefined,
|
||||
duration: 'permanent',
|
||||
...(selector ? { sourceSelector: selector } : {}),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^prevent all (combat )?damage that would be dealt by (.+?)$/)
|
||||
if (match) {
|
||||
const selector = parseSelector(match[2])
|
||||
if (selector) {
|
||||
return [{
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'any' },
|
||||
amount: 'all',
|
||||
combatOnly: Boolean(match[1]) || undefined,
|
||||
duration: 'permanent',
|
||||
global: true,
|
||||
sourceSelector: selector,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(?:its|this's) (base )?power and toughness are each equal to (.+)$/)
|
||||
if (match) {
|
||||
const value = parseValue(match[2])
|
||||
if (value) {
|
||||
return [{
|
||||
op: 'set_pt',
|
||||
target: { kind: 'self' },
|
||||
power: value,
|
||||
toughness: value,
|
||||
base: Boolean(match[1]) || undefined,
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(?:its|this's) (base )?power is equal to (.+)$/)
|
||||
if (match) {
|
||||
const value = parseValue(match[2])
|
||||
if (value) {
|
||||
return [{ op: 'set_pt', target: { kind: 'self' }, power: value, base: Boolean(match[1]) || undefined }]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(?:its|this's) (base )?toughness is equal to (.+)$/)
|
||||
if (match) {
|
||||
const value = parseValue(match[2])
|
||||
if (value) {
|
||||
return [{ op: 'set_pt', target: { kind: 'self' }, toughness: value, base: Boolean(match[1]) || undefined }]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) for each (.+)$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
const power = valueWithSign(match[2])
|
||||
const toughness = valueWithSign(match[3])
|
||||
const selector = forEachSelector(match[4])
|
||||
if (target && power && toughness && selector) {
|
||||
const count: Value = { kind: 'count', selector }
|
||||
const scaled = (value: Value): Value | undefined => {
|
||||
if (value.kind !== 'number' || (value.value !== 0 && value.value !== 1)) return undefined
|
||||
return value.value === 1 ? count : value
|
||||
}
|
||||
const scaledPower = scaled(power)
|
||||
const scaledToughness = scaled(toughness)
|
||||
if (scaledPower && scaledToughness) {
|
||||
return [{ op: 'pump', target, power: scaledPower, toughness: scaledToughness }]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) and (?:has|have) "(.+)"$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
const power = valueWithSign(match[2])
|
||||
const toughness = valueWithSign(match[3])
|
||||
if (target && power && toughness) {
|
||||
const ability = compileLine(match[4], 'Quoted', new Set(), false)
|
||||
if (ability.kind !== 'unsupported') {
|
||||
return [
|
||||
{ op: 'pump', target, power, toughness },
|
||||
{ op: 'grant_ability', target, ability },
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+) and (?:has|have) (.+)$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
const power = valueWithSign(match[2])
|
||||
const toughness = valueWithSign(match[3])
|
||||
const keywords = parseKeywordLine(match[4], new Set())
|
||||
if (target && power && toughness && keywords) {
|
||||
return [
|
||||
{ op: 'pump', target, power, toughness },
|
||||
...keywords.map(keyword => ({
|
||||
op: 'grant' as const,
|
||||
target,
|
||||
keyword: keyword.keyword,
|
||||
value: keyword.value,
|
||||
})),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:gets|get) ([+-]\w+)\/([+-]\w+)$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
const power = valueWithSign(match[2])
|
||||
const toughness = valueWithSign(match[3])
|
||||
if (target && power && toughness) return [{ op: 'pump', target, power, toughness }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:has|have) "(.+)"$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) {
|
||||
const ability = compileLine(match[2], 'Quoted', new Set(), false)
|
||||
if (ability.kind !== 'unsupported') return [{ op: 'grant_ability', target, ability }]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) (?:has|have) (.+)$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
const keywords = parseKeywordLine(match[2], new Set())
|
||||
if (target && keywords) {
|
||||
return keywords.map(keyword => ({
|
||||
op: 'grant',
|
||||
target,
|
||||
keyword: keyword.keyword,
|
||||
value: keyword.value,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
if (sentence === 'you have no maximum hand size') {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'player', who: 'you', mode: 'target' },
|
||||
rule: 'no_max_hand_size',
|
||||
}]
|
||||
}
|
||||
|
||||
if (sentence === 'you may look at the top card of your library any time') {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'player', who: 'you', mode: 'target' },
|
||||
rule: 'may_look_at_top',
|
||||
}]
|
||||
}
|
||||
|
||||
if (sentence === 'this can be your commander') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'can_be_commander' }]
|
||||
}
|
||||
|
||||
if (sentence === 'you may choose not to untap this during your untap step') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'may_choose_not_to_untap' }]
|
||||
}
|
||||
|
||||
if (sentence === 'this enters prepared') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'enters_prepared' }]
|
||||
}
|
||||
|
||||
if (sentence === 'if this is in your opening hand, you may begin the game with it on the battlefield') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'begin_on_battlefield' }]
|
||||
}
|
||||
|
||||
if (sentence === 'this can block only creatures with flying') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'can_block_only_flying' }]
|
||||
}
|
||||
|
||||
if (sentence === "this cannot be blocked by more than one creature") {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_blocked_by_more_than_one' }]
|
||||
}
|
||||
|
||||
if (sentence === "this can't be blocked by more than one creature") {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_blocked_by_more_than_one' }]
|
||||
}
|
||||
|
||||
if (sentence === 'this cannot attack alone') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_attack_alone' }]
|
||||
}
|
||||
|
||||
if (sentence === 'this cannot block alone') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_block_alone' }]
|
||||
}
|
||||
|
||||
if (sentence === 'this must be blocked if able' || sentence === 'all creatures able to block this do so') {
|
||||
return [{ op: 'restriction', target: { kind: 'self' }, rule: 'must_be_blocked' }]
|
||||
}
|
||||
|
||||
if (sentence === 'you may play an additional land on each of your turns') {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'player', who: 'you', mode: 'target' },
|
||||
rule: 'additional_land_drop',
|
||||
value: { kind: 'number', value: 1 },
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^this cannot be blocked by creatures with power (\w+) or (greater|more|less)$/)
|
||||
if (match) {
|
||||
const value = parseValue(match[1])
|
||||
if (value) {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'self' },
|
||||
rule: 'cant_be_blocked_by_power',
|
||||
value,
|
||||
comparison: match[2] === 'less' ? 'or_less' : 'or_greater',
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^this cannot attack unless defending player controls (.+)$/)
|
||||
if (match) {
|
||||
const selector = parseSelector(match[1])
|
||||
if (selector) {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'self' },
|
||||
rule: 'cant_attack_unless',
|
||||
condition: { kind: 'defending_player_controls', selector },
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
if (sentence === 'you control enchanted creature') {
|
||||
const target = parseStaticTarget('enchanted creature')
|
||||
if (target) return [{ op: 'control', target }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^as this enters, choose (?:a|an) (.+)$/)
|
||||
if (match) {
|
||||
const what =
|
||||
match[1] === 'creature type'
|
||||
? 'creature_type'
|
||||
: match[1] === 'color'
|
||||
? 'color'
|
||||
: match[1] === 'card name'
|
||||
? 'card_name'
|
||||
: match[1] === 'player'
|
||||
? 'player'
|
||||
: match[1] === 'opponent'
|
||||
? 'opponent'
|
||||
: match[1] === 'number'
|
||||
? 'number'
|
||||
: undefined
|
||||
if (what) return [{ op: 'choose', what }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if an effect would create one or more (tokens?|creature tokens?) under your control, it creates (twice|three times) that many of those tokens instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'token_multiplier',
|
||||
multiplier: match[2] === 'twice' ? 2 : 3,
|
||||
who: 'you',
|
||||
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if one or more (tokens?|creature tokens?) would be created( under your control)?, (twice|three times) that many of those tokens are created instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'token_multiplier',
|
||||
multiplier: match[3] === 'twice' ? 2 : 3,
|
||||
who: match[2] ? 'you' : 'each_player',
|
||||
...(match[1] === 'creature tokens' ? { creatureOnly: true } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would create (.+?), instead create one of each$/)
|
||||
if (match) {
|
||||
const from = match[1]
|
||||
.replace(/ tokens?$/i, '')
|
||||
.split(/, and |, or | and |, /i)
|
||||
.map(part => part.trim().replace(/^an? /i, ''))
|
||||
.filter(Boolean)
|
||||
if (from.length) {
|
||||
return [{ op: 'token_replacement', from, tokens: from.map(tokenSpecByName), who: 'you' }]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would create (?:a|an) (.+?) token, instead create (.+)$/)
|
||||
if (match) {
|
||||
const from = [match[1]]
|
||||
const tokens = parseReplacementTokens(match[2], from)
|
||||
if (tokens) return [{ op: 'token_replacement', from, tokens, who: 'you' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would create (?:a|an) (.+?) token, create (.+) instead$/)
|
||||
if (match) {
|
||||
const from = [match[1]]
|
||||
const tokens = parseReplacementTokens(match[2], from)
|
||||
if (tokens) return [{ op: 'token_replacement', from, tokens, who: 'you' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if (?:you|a player) would gain life, (?:you|they) gain (twice|three times|double) that much life(?: plus (\w+))? instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'replacement_amount',
|
||||
what: 'life_gain',
|
||||
multiplier: match[1] === 'three times' ? 3 : 2,
|
||||
...(match[2] ? { add: parseNumber(match[2]) ?? 0 } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would gain life, you gain that much life plus (\w+) instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement_amount', what: 'life_gain', multiplier: 1, add: parseNumber(match[1]) ?? 0 }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would draw a card(?: except the first one you draw in each of your draw steps)?, draw (\w+) cards? instead$/)
|
||||
if (match) {
|
||||
const amount = parseNumber(match[1])
|
||||
if (amount) return [{ op: 'replacement_amount', what: 'draw', multiplier: amount }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if a source you control would deal (noncombat )?damage(?: to a permanent or player)?, it deals (?:double|twice) that damage(?: to that permanent or player)? instead$/)
|
||||
if (match) {
|
||||
return [{
|
||||
op: 'replacement_amount',
|
||||
what: 'damage',
|
||||
multiplier: 2,
|
||||
controller: 'you',
|
||||
...(match[1] ? { noncombatOnly: true } : {}),
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^double all damage that (?:sources|creature sources) you control would deal$/)
|
||||
if (match) return [{ op: 'replacement_amount', what: 'damage', multiplier: 2, controller: 'you' }]
|
||||
|
||||
match = sentence.match(/^if (?:a|another) (white|blue|black|red|green) source( you control)? would deal (noncombat )?damage(?: to a (?:player|permanent or player))?, it deals (?:that much damage plus (\w+)|(?:double|twice) that damage)(?: to that (?:player|permanent or player))? instead$/)
|
||||
if (match) {
|
||||
const color = match[1][0].toUpperCase()
|
||||
const add = match[4] ? parseNumber(match[4]) : undefined
|
||||
return [{
|
||||
op: 'replacement_amount',
|
||||
what: 'damage',
|
||||
multiplier: match[4] ? 1 : 2,
|
||||
...(add !== undefined ? { add } : {}),
|
||||
...(match[2] ? { controller: 'you' as const } : {}),
|
||||
...(match[3] ? { noncombatOnly: true } : {}),
|
||||
sourceColor: color,
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if one or more (.+?) counters? would be put on (.+?), (?:twice|three times|that many plus \w+) that many (?:.+? )?counters? (?:are|is) put on (?:it|that creature|that permanent) instead$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[2])
|
||||
const plus = sentence.match(/that many plus (\w+)/)
|
||||
if (target) {
|
||||
return [{
|
||||
op: 'counter_multiplier',
|
||||
target,
|
||||
counter: match[1],
|
||||
multiplier: /twice/.test(sentence) ? 2 : /three times/.test(sentence) ? 3 : 1,
|
||||
...(plus ? { add: parseNumber(plus[1]) ?? 0 } : {}),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would get one or more \{e\}, you get (twice|three times) that many \{e\} instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement_amount', what: 'energy', multiplier: match[1] === 'three times' ? 3 : 2 }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if you would get one or more \{e\}, you get that many plus (\w+) \{e\} instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement_amount', what: 'energy', multiplier: 1, add: parseNumber(match[1]) ?? 0 }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if this would be put into (?:a|your) graveyard from anywhere, exile it instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement', what: 'dies', instead: 'exile', target: { kind: 'self' } }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if this would leave the battlefield, exile it instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'replacement', what: 'leaves_battlefield', instead: 'exile', target: { kind: 'self' } }]
|
||||
}
|
||||
|
||||
if (sentence === 'if a card or token would be put into a graveyard from anywhere, exile it instead') {
|
||||
return [{ op: 'exile_instead_of_graveyard' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if a card would be put into (an opponent's|your) graveyard from anywhere, exile it instead$/)
|
||||
if (match) {
|
||||
return [{ op: 'exile_instead_of_graveyard', owner: match[1] === 'your' ? 'you' : 'opponent' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^if (an opponent|you) would search (?:a|their) library, that player searches the top (\w+) cards? of that library instead$/)
|
||||
if (match) {
|
||||
const amount = parseValue(match[2])
|
||||
if (amount) return [{ op: 'search_restriction', who: match[1] === 'you' ? 'you' : 'opponent', amount }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^activated abilities of (.+?) cannot be activated$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'cant_activate' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(noncreature|creature) spells cost (\{[^}]+\}) more to cast$/)
|
||||
if (match) {
|
||||
const amount = parseValue(match[2].slice(1, -1))
|
||||
if (amount) return [{ op: 'cost_increase', amount, spellType: match[1] === 'creature' ? 'creature' : 'noncreature' }]
|
||||
}
|
||||
|
||||
let costText = sentence
|
||||
let costCondition: Condition | undefined
|
||||
let costAmount: Value | undefined
|
||||
const costWhereX = costText.match(/^(.+?), where x is (.+)$/)
|
||||
if (costWhereX) {
|
||||
const value = parseValue(costWhereX[2])
|
||||
if (value) {
|
||||
costText = costWhereX[1]
|
||||
costAmount = value
|
||||
}
|
||||
}
|
||||
const costIf = costText.match(/^(.+?) if (.+)$/)
|
||||
if (costIf) {
|
||||
const parsed = parseCondition(costIf[2])
|
||||
if (parsed) {
|
||||
costText = costIf[1]
|
||||
costCondition = parsed
|
||||
}
|
||||
}
|
||||
match = costText.match(/^(.+?) costs? ((?:\{[^}]+\})+) less to cast(?: for each (.+))?$/)
|
||||
if (match) {
|
||||
const target = parseCostReductionTarget(match[1])
|
||||
let amount: Value | undefined = costAmount
|
||||
let symbols: string | undefined
|
||||
if (!amount && match[3]) {
|
||||
const selector = parseSelector(match[3])
|
||||
if (selector) amount = { kind: 'count', selector }
|
||||
} else if (!amount) {
|
||||
const parts = [...match[2].matchAll(/\{([^}]+)\}/g)].map(symbol => symbol[1])
|
||||
if (parts.some(part => /[WUBRGC]/i.test(part))) symbols = match[2].toUpperCase()
|
||||
else if (parts[0]) amount = parseValue(parts[0].toLowerCase())
|
||||
}
|
||||
if (target && (amount || symbols)) {
|
||||
return [{
|
||||
op: 'cost_reduction',
|
||||
target,
|
||||
...(amount ? { amount } : {}),
|
||||
...(symbols ? { symbols } : {}),
|
||||
...(costCondition ? { condition: costCondition } : {}),
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot attack or block$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) {
|
||||
return [
|
||||
{ op: 'restriction', target, rule: 'cant_attack' },
|
||||
{ op: 'restriction', target, rule: 'cant_block' },
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot attack or block, and its activated abilities cannot be activated$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) {
|
||||
return [
|
||||
{ op: 'restriction', target, rule: 'cant_attack' },
|
||||
{ op: 'restriction', target, rule: 'cant_block' },
|
||||
{ op: 'restriction', target, rule: 'cant_activate' },
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if (sentence === 'skip your draw step') {
|
||||
return [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'player', who: 'you', mode: 'target' },
|
||||
rule: 'skip_draw_step',
|
||||
}]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot attack$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'cant_attack' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot block$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'cant_block' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot be blocked$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'cant_be_blocked' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) cannot be countered$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'cant_be_countered' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) does not untap during (?:its controller's|your) untap step$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'doesnt_untap' }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) attacks each combat if able$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
if (target) return [{ op: 'restriction', target, rule: 'must_attack' }]
|
||||
}
|
||||
|
||||
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])
|
||||
if (unless) return [{ op: 'enters_tapped', target: { kind: 'self' }, unless }]
|
||||
}
|
||||
|
||||
match = sentence.match(/^(.+?) enters with (?:(\w+) )?(?:additional )?(.+?) counters? on it(?: for each (.+))?$/)
|
||||
if (match) {
|
||||
const target = parseStaticTarget(match[1])
|
||||
let amount = match[2] ? parseValue(match[2]) : ({ kind: 'number', value: 1 } as Value)
|
||||
if (match[4]) {
|
||||
const selector = parseSelector(match[4])
|
||||
if (selector) amount = { kind: 'count', selector }
|
||||
}
|
||||
if (target && amount) {
|
||||
return [{ op: 'enters_with_counters', target, counter: match[3], amount }]
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parseStaticAbility(text: string): { effects: StaticEffect[]; condition?: Condition } | undefined {
|
||||
let rest = text.trim().replace(/\.$/, '')
|
||||
|
||||
// A leading duration makes this a one-shot effect, not a continuous one.
|
||||
if (takeLeadingDuration(rest).duration) return undefined
|
||||
|
||||
let condition: Condition | undefined
|
||||
const conditionPrefix = rest.match(/^(?:during your turn|as long as it is your turn), (.+)$/)
|
||||
if (conditionPrefix) {
|
||||
condition = { kind: 'your_turn' }
|
||||
rest = conditionPrefix[1]
|
||||
} else {
|
||||
const longAsPrefix = rest.match(/^as long as (.+?), (.+)$/)
|
||||
if (longAsPrefix) {
|
||||
condition = parseCondition(longAsPrefix[1])
|
||||
if (!condition) return undefined
|
||||
rest = longAsPrefix[2]
|
||||
} else {
|
||||
const conditionSuffix = rest.match(/^(.+?) as long as (.+)$/)
|
||||
if (conditionSuffix) {
|
||||
condition = parseCondition(conditionSuffix[2])
|
||||
if (!condition) return undefined
|
||||
rest = conditionSuffix[1]
|
||||
} else {
|
||||
const ifSuffix = rest.match(/^(.+?) if (.+)$/)
|
||||
if (ifSuffix) {
|
||||
const parsed = parseCondition(ifSuffix[2])
|
||||
if (parsed) {
|
||||
condition = parsed
|
||||
rest = ifSuffix[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const effects = parseStaticEffects(rest)
|
||||
return effects ? { effects, condition } : undefined
|
||||
}
|
||||
|
||||
247
backend/src/effects/compile-triggers.ts
Normal file
247
backend/src/effects/compile-triggers.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import type { Card, CardFace } from '../cards.js'
|
||||
import {
|
||||
parseCondition,
|
||||
parseCost,
|
||||
parseDuration,
|
||||
parseNumber,
|
||||
parseSelector,
|
||||
parseTarget,
|
||||
parseValue,
|
||||
ROLE_NAMES,
|
||||
} from './parse.js'
|
||||
import type {
|
||||
Ability,
|
||||
CompiledCard,
|
||||
CompiledFace,
|
||||
Condition,
|
||||
Cost,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
} from './types.js'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
import { parseSubject } from './compile-primitives.js'
|
||||
import { parseEffectSentence, parseEffects } from './compile-sentences.js'
|
||||
|
||||
|
||||
export function stripTriggerFrequency(text: string): { text: string; oncePerTurn: boolean } {
|
||||
const trimmed = text.trim()
|
||||
const match = trimmed.match(/^(.*?)\s*this ability triggers only once( each turn)?\.?$/i)
|
||||
if (!match) return { text: trimmed, oncePerTurn: false }
|
||||
return { text: match[1].replace(/\.$/, '').trim(), oncePerTurn: true }
|
||||
}
|
||||
|
||||
export function parseTriggerPrefix(text: string): { event: TriggerEvent; rest: string } | undefined {
|
||||
let rest = text.trim()
|
||||
|
||||
let match = rest.match(/^when(?:ever)? this (enters|dies|attacks|blocks|leaves the battlefield)(?: the battlefield)?, (.+)$/)
|
||||
if (match) {
|
||||
const kind = match[1] as 'enters' | 'dies' | 'attacks' | 'blocks' | 'leaves the battlefield'
|
||||
const eventKind = kind === 'leaves the battlefield' ? 'leaves_battlefield' : kind
|
||||
return { event: { kind: eventKind, subject: { kind: 'self' } } as TriggerEvent, rest: match[2] }
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? this becomes level (\d+), (.+)$/)
|
||||
if (match) {
|
||||
return { event: { kind: 'becomes_level', level: Number(match[1]) }, rest: match[2] }
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? this enters or attacks, (.+)$/)
|
||||
if (match) return { event: { kind: 'enters_or_attacks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this enters? or attacks?, (.+)$/)
|
||||
if (match) return { event: { kind: 'enters_or_attacks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this enter or attack, (.+)$/)
|
||||
if (match) return { event: { kind: 'enters_or_attacks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this enters or dies, (.+)$/)
|
||||
if (match) return { event: { kind: 'enters_or_dies', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this enters? or dies?, (.+)$/)
|
||||
if (match) return { event: { kind: 'enters_or_dies', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this attacks or blocks, (.+)$/)
|
||||
if (match) return { event: { kind: 'attacks_or_blocks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this attacks? or blocks?, (.+)$/)
|
||||
if (match) return { event: { kind: 'attacks_or_blocks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this blocks or becomes blocked(?: by a creature)?, (.+)$/)
|
||||
if (match) return { event: { kind: 'blocks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this becomes blocked(?: by a creature)?, (.+)$/)
|
||||
if (match) return { event: { kind: 'blocks', subject: { kind: 'self' } }, rest: match[1] }
|
||||
|
||||
match = rest.match(/^when(?:ever)? this deals (combat )?damage to (a player|an opponent|a creature|a planeswalker|one or more players|you), (.+)$/)
|
||||
if (match) {
|
||||
const recipient =
|
||||
match[2] === 'a creature' || match[2] === 'a planeswalker'
|
||||
? 'permanent'
|
||||
: 'player'
|
||||
return {
|
||||
event: {
|
||||
kind: 'deals_damage',
|
||||
subject: { kind: 'self' },
|
||||
recipient,
|
||||
combat: Boolean(match[1]),
|
||||
},
|
||||
rest: match[3],
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? this deals (combat )?damage, (.+)$/)
|
||||
if (match) {
|
||||
return {
|
||||
event: {
|
||||
kind: 'deals_damage',
|
||||
subject: { kind: 'self' },
|
||||
recipient: 'any',
|
||||
combat: Boolean(match[1]),
|
||||
},
|
||||
rest: match[2],
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? this becomes the target of (?:a spell or ability|a spell|an ability)(?: an opponent controls)?, (.+)$/)
|
||||
if (match) {
|
||||
return { event: { kind: 'becomes_target', subject: { kind: 'self' } }, rest: match[1] }
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? this is put into a graveyard from (?:the battlefield|anywhere), (.+)$/)
|
||||
if (match) {
|
||||
return { event: { kind: 'dies', subject: { kind: 'self' } }, rest: match[1] }
|
||||
}
|
||||
|
||||
match = rest.match(/^whenever (you|an opponent|a player) (gains?|loses?) life, (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player'
|
||||
const mode = match[2].startsWith('gain') ? 'gain' : 'lose'
|
||||
return { event: { kind: 'life', who, mode }, rest: match[3] }
|
||||
}
|
||||
|
||||
match = rest.match(/^whenever (you|an opponent|a player) draws? (.+?), (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player'
|
||||
const clause = match[2].trim()
|
||||
let ordinal: number | undefined
|
||||
const ordinalMatch = clause.match(/^(?:your|their) (\w+) card each turn$/)
|
||||
if (ordinalMatch) {
|
||||
ordinal = parseNumber(ordinalMatch[1])
|
||||
if (ordinal === undefined) return undefined
|
||||
} else if (!/^(?:a card|their card|one or more cards|a card this turn)$/.test(clause)) {
|
||||
return undefined
|
||||
}
|
||||
return { event: { kind: 'draw', who, ordinal }, rest: match[3] }
|
||||
}
|
||||
|
||||
match = rest.match(/^at the beginning of (your|each player's|each opponent's|each|the) upkeep, (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'your' ? 'you' : 'each_player'
|
||||
return { event: { kind: 'upkeep', who }, rest: match[2] }
|
||||
}
|
||||
|
||||
match = rest.match(/^at the beginning of (your|each player's|each opponent's|each|the) end step, (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'your' ? 'you' : 'each_player'
|
||||
return { event: { kind: 'end_step', who }, rest: match[2] }
|
||||
}
|
||||
|
||||
match = rest.match(/^at the beginning of combat on (your|each player's|each opponent's) turn, (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'your' ? 'you' : 'each_player'
|
||||
return { event: { kind: 'begin_combat', who }, rest: match[2] }
|
||||
}
|
||||
|
||||
match = rest.match(/^at the beginning of (your|each player's|each opponent's) (first|second|postcombat) main phase, (.+)$/)
|
||||
if (match) {
|
||||
const who = match[1] === 'your' ? 'you' : 'each_player'
|
||||
return {
|
||||
event: {
|
||||
kind: 'main_phase',
|
||||
who,
|
||||
phase: match[2] === 'first' ? 'first' : 'postcombat',
|
||||
},
|
||||
rest: match[3],
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^whenever (you|an opponent|a player) casts?(?: or cop(y|ies))? (.+?), (.+)$/)
|
||||
if (match) {
|
||||
let spellText = match[3].trim()
|
||||
const who = match[1] === 'you' ? 'you' : match[1] === 'an opponent' ? 'opponent' : 'each_player'
|
||||
const orCopy = Boolean(match[2])
|
||||
let ordinal: number | undefined
|
||||
const nth = spellText.match(/^(?:your|their) (\w+) spell each turn$/)
|
||||
if (nth) {
|
||||
ordinal = parseNumber(nth[1])
|
||||
if (ordinal === undefined) return undefined
|
||||
spellText = 'a spell'
|
||||
}
|
||||
let targetsSelf = false
|
||||
if (/ that targets this$/.test(spellText)) {
|
||||
targetsSelf = true
|
||||
spellText = spellText.replace(/ that targets this$/, '')
|
||||
}
|
||||
const spell = spellText === 'a spell' || spellText === 'spell'
|
||||
? { types: [] }
|
||||
: parseSelector(spellText.replace(/ spells?$/, ''))
|
||||
if (spell) {
|
||||
return {
|
||||
event: { kind: 'cast', who, spell, targetsSelf: targetsSelf || undefined, ordinal, orCopy: orCopy || undefined },
|
||||
rest: match[4],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^whenever (?:one or more )?(.+?) counters? are put on (.+?), (.+)$/)
|
||||
if (match) {
|
||||
const subject = parseSubject(match[2])
|
||||
if (subject) {
|
||||
return { event: { kind: 'counter_placed', subject, counter: match[1] }, rest: match[3] }
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^whenever (?:one or more )?(.+?) deals? (combat )?damage to (a player|a player or battle|an opponent|a creature|a planeswalker|you), (.+)$/)
|
||||
if (match) {
|
||||
const subject = parseSubject(match[1])
|
||||
const recipient =
|
||||
match[3] === 'a creature' || match[3] === 'a planeswalker'
|
||||
? 'permanent'
|
||||
: 'player'
|
||||
if (subject) {
|
||||
return {
|
||||
event: { kind: 'deals_damage', subject, recipient, combat: Boolean(match[2]) },
|
||||
rest: match[4],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match = rest.match(/^when(?:ever)? (?:one or more )?(.+?) (enters?|dies?|attacks?|blocks?|leaves? the battlefield), (.+)$/)
|
||||
if (match) {
|
||||
const subject = parseSubject(match[1])
|
||||
if (subject) {
|
||||
const raw = match[2]
|
||||
const kind = raw.startsWith('enter')
|
||||
? 'enters'
|
||||
: raw.startsWith('die')
|
||||
? 'dies'
|
||||
: raw.startsWith('attack')
|
||||
? 'attacks'
|
||||
: raw.startsWith('block')
|
||||
? 'blocks'
|
||||
: 'leaves_battlefield'
|
||||
return { event: { kind, subject } as TriggerEvent, rest: match[3] }
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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<Map<string, string>> {
|
||||
}
|
||||
|
||||
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 "## <face name>" 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,
|
||||
|
||||
@@ -144,6 +144,16 @@ const NON_CREATURE_SUBTYPES: Record<string, string> = {
|
||||
desert: 'land',
|
||||
}
|
||||
|
||||
export const ROLE_NAMES: Record<string, string> = {
|
||||
cursed: 'Cursed',
|
||||
monster: 'Monster',
|
||||
royal: 'Royal',
|
||||
sorcerer: 'Sorcerer',
|
||||
virtuous: 'Virtuous',
|
||||
wicked: 'Wicked',
|
||||
'young hero': 'Young Hero',
|
||||
}
|
||||
|
||||
function typeForSubtype(subtype: string): string {
|
||||
return NON_CREATURE_SUBTYPES[subtype] ?? 'creature'
|
||||
}
|
||||
@@ -168,6 +178,7 @@ export function parseValue(text: string): Value | undefined {
|
||||
|
||||
if (trimmed === 'x') return { kind: 'x' }
|
||||
if (trimmed === 'that much' || trimmed === 'that many') return { kind: 'event_amount' }
|
||||
if (trimmed === 'the damage prevented this way' || trimmed === 'the life lost this way') return { kind: 'event_amount' }
|
||||
if (/^(its|this creature's|this permanent's) power$/.test(trimmed)) return { kind: 'source_power' }
|
||||
if (/^(its|this creature's|this permanent's) toughness$/.test(trimmed)) return { kind: 'source_toughness' }
|
||||
|
||||
@@ -350,6 +361,17 @@ function parseQualifierSuffix(rest: string, selector: ObjectSelector): string {
|
||||
}
|
||||
}
|
||||
|
||||
match = text.match(/^(.+?) with mana value (\w+)$/)
|
||||
if (match) {
|
||||
const amount = parseNumber(match[2])
|
||||
if (amount !== undefined) {
|
||||
selector.manaValue = { atLeast: amount, atMost: amount }
|
||||
text = match[1].trim()
|
||||
changed = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
match = text.match(/^(.+?) with (.+)$/)
|
||||
if (match && SELECTOR_KEYWORDS.has(match[2])) {
|
||||
selector.keywords = [...(selector.keywords ?? []), match[2]]
|
||||
@@ -451,6 +473,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
const supertypes: string[] = []
|
||||
const subtypes: string[] = []
|
||||
const colors: string[] = []
|
||||
const excludeColors: string[] = []
|
||||
let match: ObjectSelector['match']
|
||||
|
||||
for (const rawWord of words) {
|
||||
@@ -495,6 +518,10 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
excludeTypes.push(negative[1])
|
||||
continue
|
||||
}
|
||||
if (negative && COLOR_WORDS[negative[1]]) {
|
||||
excludeColors.push(COLOR_WORDS[negative[1]])
|
||||
continue
|
||||
}
|
||||
|
||||
if (STATE_WORDS.has(word)) {
|
||||
if (word === 'token') selector.token = true
|
||||
@@ -517,7 +544,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
if (!types.length) {
|
||||
if (subtypes.length) {
|
||||
types.push(typeForSubtype(subtypes[0]))
|
||||
} else if (!(excludeTypes.length || colors.length || supertypes.length || selector.name)) {
|
||||
} else if (!(excludeTypes.length || excludeColors.length || colors.length || supertypes.length || selector.name)) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -525,6 +552,7 @@ export function parseSelector(text: string): ObjectSelector | undefined {
|
||||
selector.types = types
|
||||
if (match) selector.match = match
|
||||
if (excludeTypes.length) selector.excludeTypes = excludeTypes
|
||||
if (excludeColors.length) selector.excludeColors = excludeColors
|
||||
if (supertypes.length) selector.supertypes = supertypes
|
||||
if (subtypes.length) selector.subtypes = subtypes
|
||||
if (colors.length) selector.colors = colors
|
||||
@@ -676,6 +704,8 @@ export function parseCondition(text: string): Condition | undefined {
|
||||
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 is equipped') return { kind: 'source_equipped' }
|
||||
if (trimmed === 'this is enchanted') return { kind: 'source_enchanted' }
|
||||
if (trimmed === 'this was kicked' || trimmed === 'it 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' }
|
||||
@@ -805,6 +835,29 @@ export function parseCondition(text: string): Condition | undefined {
|
||||
}
|
||||
if (trimmed === "you've cast a spell this turn") return { kind: 'cast_spell_this_turn' }
|
||||
if (trimmed === 'you have a full party') return { kind: 'full_party' }
|
||||
if (trimmed === 'you control a commander') return { kind: 'you_control_commander' }
|
||||
|
||||
if (trimmed === 'each player has no cards in hand') {
|
||||
return { kind: 'cards_in_hand_at_most', who: 'each_player', atMost: 0 }
|
||||
}
|
||||
|
||||
const opponentDamage = trimmed.match(/^an opponent was dealt (\w+) or more damage this turn$/)
|
||||
if (opponentDamage) {
|
||||
const amount = parseNumber(opponentDamage[1])
|
||||
if (amount !== undefined) return { kind: 'opponent_damaged_this_turn', atLeast: amount }
|
||||
}
|
||||
|
||||
const attackedCreatures = trimmed.match(/^you attacked with (\w+) or more creatures this turn$/)
|
||||
if (attackedCreatures) {
|
||||
const amount = parseNumber(attackedCreatures[1])
|
||||
if (amount !== undefined) return { kind: 'attacked_with_creatures', atLeast: amount }
|
||||
}
|
||||
|
||||
const libraryAtMost = trimmed.match(/^a library has (\w+) or fewer cards in it$/)
|
||||
if (libraryAtMost) {
|
||||
const amount = parseNumber(libraryAtMost[1])
|
||||
if (amount !== undefined) return { kind: 'library_at_most', atMost: amount }
|
||||
}
|
||||
|
||||
const graveyard = trimmed.match(/^there are (\w+) or more cards in (your|an opponent's|target player's) graveyard$/)
|
||||
if (graveyard) {
|
||||
@@ -888,6 +941,13 @@ export function parseCondition(text: string): Condition | undefined {
|
||||
const above = trimmed.match(/^you have at least (\d+) life more than your starting life total$/)
|
||||
if (above) return { kind: 'life_above_starting', player: 'you', amount: Number(above[1]) }
|
||||
|
||||
const distinctNames = trimmed.match(/^you control (\w+) or more (.+?) with different names$/)
|
||||
if (distinctNames) {
|
||||
const amount = parseNumber(distinctNames[1])
|
||||
const selector = parseSelector(distinctNames[2])
|
||||
if (amount !== undefined && selector) return { kind: 'distinct_names', selector, atLeast: amount }
|
||||
}
|
||||
|
||||
const control = trimmed.match(/^you control (?:at least )?(one|two|three|four|five|six|seven|eight|nine|ten|\d+) (?:or more )?(.+)$/)
|
||||
if (control) {
|
||||
const selector = parseSelector(control[2])
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
176
backend/src/effects/source-abilities.ts
Normal file
176
backend/src/effects/source-abilities.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
import { self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker, targetOptions, target, each, pick, divided, targetSpell, targetAbility, X, itsPower, itsToughness, count, cardsInHand, maxCardsInHand, maxOpponentCount, totalManaValue, totalPower, anyNumber, eventAmount, mana, anyColor, asToken, CopyOf, copyOf, manaCost, tapCost, untapCost, tapOther, energyCost, loyalty, payLife, discardCost, sacrificeCost, sacrificeSelf, exileSelf, exileFromGraveyard, reveal, choice, returnToHandCost, behold, waterbend, blight, chooseCost, putCounterCost, removeCountersCost, forage, collectEvidence, millCost } from './source-values.js'
|
||||
|
||||
export 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] } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function keyword(name: unknown, value?: unknown): Ability {
|
||||
return {
|
||||
kind: 'keyword',
|
||||
keyword: asString(name, 'keyword'),
|
||||
...(value !== undefined ? { value: asString(value, 'keyword value') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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'))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export function spell(effects: unknown, options?: unknown): Ability {
|
||||
return {
|
||||
kind: 'spell',
|
||||
effects: asEffects(effects),
|
||||
optional: asOptions(options).optional === true,
|
||||
text: 'Spell effect',
|
||||
}
|
||||
}
|
||||
|
||||
export function additionalCost(costs: unknown, options?: unknown): Ability {
|
||||
return {
|
||||
kind: 'additional_cost',
|
||||
costs: asCosts(costs),
|
||||
optional: asOptions(options).optional === true,
|
||||
text: 'Additional cost',
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export function overload(cost: unknown): Ability {
|
||||
return { kind: 'overload', cost: asString(cost, 'overload cost'), text: 'Overload' }
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export 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',
|
||||
}
|
||||
}
|
||||
|
||||
export function levelPt(power: unknown, toughness: unknown): Ability {
|
||||
return { kind: 'level_pt', power: asValue(power), toughness: asValue(toughness), text: 'Level P/T' }
|
||||
}
|
||||
|
||||
export function unsupported(reason: unknown, text: unknown): Ability {
|
||||
return { kind: 'unsupported', reason: asString(reason, 'reason'), text: asString(text, 'text') }
|
||||
}
|
||||
|
||||
297
backend/src/effects/source-api.ts
Normal file
297
backend/src/effects/source-api.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
import { self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker, targetOptions, target, each, pick, divided, targetSpell, targetAbility, X, itsPower, itsToughness, count, cardsInHand, maxCardsInHand, maxOpponentCount, totalManaValue, totalPower, anyNumber, eventAmount, mana, anyColor, asToken, CopyOf, copyOf, manaCost, tapCost, untapCost, tapOther, energyCost, loyalty, payLife, discardCost, sacrificeCost, sacrificeSelf, exileSelf, exileFromGraveyard, reveal, choice, returnToHandCost, behold, waterbend, blight, chooseCost, putCounterCost, removeCountersCost, forage, collectEvidence, millCost } from './source-values.js'
|
||||
import { damage, damageDivided, draw, discard, mill, gainLife, loseLife, pump, setPt, grant, putCounters, doubleCounters, 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, impulse, exileInsteadOfDying } from './source-effects.js'
|
||||
import { staticPump, staticGrant, staticRestrict, staticSetPt, grantAbility, entersTapped, entersWithCounters, control, choose, replace, replacementAmount, tokenMultiplier, counterMultiplier, tokenReplacement, costReduction, costIncrease, searchRestriction, exileInsteadOfGraveyard } from './source-static.js'
|
||||
import { trigger, createWhen, condition, youControl, opponentControls, yourTurn, notYourTurn, sourceTapped, sourceUntapped, sourceAttacking, sourceEquipped, sourceEnchanted, 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 } from './source-conditions.js'
|
||||
import { parseKeywordText, keyword, keywords, triggered, activated, staticAbility, spell, additionalCost, alternativeCost, overload, chapter, levelBand, levelPt, unsupported } from './source-abilities.js'
|
||||
import { CardSection, Face, Faces, card, face, faces } from './source-card.js'
|
||||
|
||||
export function createApi(): Record<string, unknown> {
|
||||
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,
|
||||
doubleCounters,
|
||||
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,
|
||||
impulse,
|
||||
exileInsteadOfDying,
|
||||
|
||||
// static effects
|
||||
staticPump,
|
||||
staticGrant,
|
||||
staticRestrict,
|
||||
staticSetPt,
|
||||
grantAbility,
|
||||
entersTapped,
|
||||
entersWithCounters,
|
||||
control,
|
||||
choose,
|
||||
replace,
|
||||
costReduction,
|
||||
costIncrease,
|
||||
searchRestriction,
|
||||
exileInsteadOfGraveyard,
|
||||
tokenMultiplier,
|
||||
counterMultiplier,
|
||||
tokenReplacement,
|
||||
replacementAmount,
|
||||
|
||||
// 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,
|
||||
sourceEquipped,
|
||||
sourceEnchanted,
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
94
backend/src/effects/source-card.ts
Normal file
94
backend/src/effects/source-card.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
|
||||
export 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export 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]). */
|
||||
export function card(typeLineOrAbilities: unknown, abilities?: unknown): CardSection {
|
||||
return new CardSection(typeLineOrAbilities, abilities)
|
||||
}
|
||||
|
||||
export function face(name: unknown, typeLineOrAbilities: unknown, abilities?: unknown): Face {
|
||||
return new Face(name, typeLineOrAbilities, abilities)
|
||||
}
|
||||
|
||||
export function faces(...entries: unknown[]): Faces {
|
||||
return new Faces(entries)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API and entry point
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
400
backend/src/effects/source-conditions.ts
Normal file
400
backend/src/effects/source-conditions.ts
Normal file
@@ -0,0 +1,400 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
import { self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker, targetOptions, target, each, pick, divided, targetSpell, targetAbility, X, itsPower, itsToughness, count, cardsInHand, maxCardsInHand, maxOpponentCount, totalManaValue, totalPower, anyNumber, eventAmount, mana, anyColor, asToken, CopyOf, copyOf, manaCost, tapCost, untapCost, tapOther, energyCost, loyalty, payLife, discardCost, sacrificeCost, sacrificeSelf, exileSelf, exileFromGraveyard, reveal, choice, returnToHandCost, behold, waterbend, blight, chooseCost, putCounterCost, removeCountersCost, forage, collectEvidence, millCost } from './source-values.js'
|
||||
|
||||
export function trigger<T extends TriggerEvent>(kind: T['kind'], fields: Omit<T, 'kind'>): T {
|
||||
return { kind, ...fields } as T
|
||||
}
|
||||
|
||||
export function createWhen(): Record<string, unknown> {
|
||||
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<string, unknown> = Object.create(null) as Record<string, unknown>
|
||||
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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function condition<T extends Condition>(kind: T['kind'], fields: Omit<T, 'kind'> = {} as Omit<T, 'kind'>): T {
|
||||
return { kind, ...fields } as T
|
||||
}
|
||||
|
||||
export function youControl(selector: unknown, atLeast?: unknown): Condition {
|
||||
return condition('you_control', {
|
||||
selector: asSelector(selector),
|
||||
...(atLeast !== undefined ? { atLeast: asNumber(atLeast, 'count') } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function opponentControls(selector: unknown, atLeast?: unknown): Condition {
|
||||
return condition('opponent_controls', {
|
||||
selector: asSelector(selector),
|
||||
...(atLeast !== undefined ? { atLeast: asNumber(atLeast, 'count') } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
export function yourTurn(): Condition {
|
||||
return condition('your_turn')
|
||||
}
|
||||
|
||||
export function notYourTurn(): Condition {
|
||||
return condition('not_your_turn')
|
||||
}
|
||||
|
||||
export function sourceTapped(): Condition {
|
||||
return condition('source_tapped')
|
||||
}
|
||||
|
||||
export function sourceUntapped(): Condition {
|
||||
return condition('source_untapped')
|
||||
}
|
||||
|
||||
export function sourceAttacking(): Condition {
|
||||
return condition('source_attacking')
|
||||
}
|
||||
|
||||
export function sourceEquipped(): Condition {
|
||||
return condition('source_equipped')
|
||||
}
|
||||
|
||||
export function sourceEnchanted(): Condition {
|
||||
return condition('source_enchanted')
|
||||
}
|
||||
|
||||
export function lifeAtLeast(player: unknown, amount: unknown): Condition {
|
||||
return condition('life_at_least', { player: asPlayer(player), amount: asNumber(amount, 'life') })
|
||||
}
|
||||
|
||||
export function lifeAtMost(player: unknown, amount: unknown): Condition {
|
||||
return condition('life_at_most', { player: asPlayer(player), amount: asNumber(amount, 'life') })
|
||||
}
|
||||
|
||||
export function lifeAboveStarting(player: unknown, amount: unknown): Condition {
|
||||
return condition('life_above_starting', { player: asPlayer(player), amount: asNumber(amount, 'life') })
|
||||
}
|
||||
|
||||
export function cardsInGraveyard(player: unknown, atLeast: unknown): Condition {
|
||||
return condition('cards_in_graveyard', { player: asPlayer(player), atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function handEmpty(player: unknown): Condition {
|
||||
return condition('hand_empty', { player: asPlayer(player) })
|
||||
}
|
||||
|
||||
export 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 } : {})
|
||||
}
|
||||
|
||||
export function youGainedLifeThisTurn(atLeast?: unknown): Condition {
|
||||
return condition('you_gained_life_this_turn', atLeast === undefined ? {} : { atLeast: asNumber(atLeast, 'life') })
|
||||
}
|
||||
|
||||
export function youDrewCardsThisTurn(atLeast?: unknown): Condition {
|
||||
return condition('you_drew_cards_this_turn', atLeast === undefined ? {} : { atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export 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') })
|
||||
}
|
||||
|
||||
export function noSpellsLastTurn(): Condition {
|
||||
return condition('no_spells_last_turn')
|
||||
}
|
||||
|
||||
export function attackedThisTurn(): Condition {
|
||||
return condition('attacked_this_turn')
|
||||
}
|
||||
|
||||
export function youAttackedThisTurn(): Condition {
|
||||
return condition('you_attacked_this_turn')
|
||||
}
|
||||
|
||||
export function defendingPlayerControls(selector: unknown): Condition {
|
||||
return condition('defending_player_controls', { selector: asSelector(selector) })
|
||||
}
|
||||
|
||||
export function targets(selector: unknown): Condition {
|
||||
return condition('targets', { selector: asSelector(selector) })
|
||||
}
|
||||
|
||||
export function wasKicked(): Condition {
|
||||
return condition('was_kicked')
|
||||
}
|
||||
|
||||
export function youCastIt(options?: unknown): Condition {
|
||||
return condition('cast', asOptions(options).fromHand === true ? { fromHand: true } : {})
|
||||
}
|
||||
|
||||
export function inGraveyard(): Condition {
|
||||
return condition('in_graveyard')
|
||||
}
|
||||
|
||||
export function onBattlefield(): Condition {
|
||||
return condition('on_battlefield')
|
||||
}
|
||||
|
||||
export function monarch(): Condition {
|
||||
return condition('monarch')
|
||||
}
|
||||
|
||||
export function initiative(): Condition {
|
||||
return condition('initiative')
|
||||
}
|
||||
|
||||
export function citysBlessing(): Condition {
|
||||
return condition('citys_blessing')
|
||||
}
|
||||
|
||||
export function suspended(): Condition {
|
||||
return condition('suspended')
|
||||
}
|
||||
|
||||
export function bargained(): Condition {
|
||||
return condition('bargained')
|
||||
}
|
||||
|
||||
export function wasCreature(): Condition {
|
||||
return condition('was_creature')
|
||||
}
|
||||
|
||||
export function opponentLostLifeThisTurn(): Condition {
|
||||
return condition('opponent_lost_life_this_turn')
|
||||
}
|
||||
|
||||
export function lifeChangedThisTurn(): Condition {
|
||||
return condition('life_changed_this_turn')
|
||||
}
|
||||
|
||||
export function descendedThisTurn(): Condition {
|
||||
return condition('descended_this_turn')
|
||||
}
|
||||
|
||||
export function permanentLeftBattlefieldThisTurn(): Condition {
|
||||
return condition('permanent_left_battlefield_this_turn', { controller: 'you' })
|
||||
}
|
||||
|
||||
export function nonlandPermanentsEnteredThisTurn(atLeast: unknown): Condition {
|
||||
return condition('nonland_permanents_entered_this_turn', { atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function attackedWithTotalPower(atLeast: unknown): Condition {
|
||||
return condition('attacked_with_total_power', { atLeast: asNumber(atLeast, 'power') })
|
||||
}
|
||||
|
||||
export function yourCreaturesTotalPower(atLeast: unknown): Condition {
|
||||
return condition('total_power', { controller: 'you', atLeast: asNumber(atLeast, 'power') })
|
||||
}
|
||||
|
||||
export function opponentControlsMoreLands(): Condition {
|
||||
return condition('opponent_controls_more_lands')
|
||||
}
|
||||
|
||||
export function distinctPowers(atLeast: unknown): Condition {
|
||||
return condition('distinct_powers', { atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function graveyardCardTypes(atLeast: unknown): Condition {
|
||||
return condition('graveyard_card_types', { atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function noObjects(selector: unknown): Condition {
|
||||
return condition('no_objects', { selector: asSelector(selector) })
|
||||
}
|
||||
|
||||
export function cardsInHandAtMost(who: unknown, atMost: unknown): Condition {
|
||||
return condition('cards_in_hand_at_most', { who: asPlayer(who), atMost: asNumber(atMost, 'count') })
|
||||
}
|
||||
|
||||
export function notTheirTurn(): Condition {
|
||||
return condition('not_their_turn')
|
||||
}
|
||||
|
||||
export function noAttackers(): Condition {
|
||||
return condition('no_attackers')
|
||||
}
|
||||
|
||||
export function opponentPoison(atLeast: unknown): Condition {
|
||||
return condition('opponent_poison', { atLeast: asNumber(atLeast, 'poison') })
|
||||
}
|
||||
|
||||
export function tributeNotPaid(): Condition {
|
||||
return condition('tribute_not_paid')
|
||||
}
|
||||
|
||||
export function hadCounters(counter?: unknown): Condition {
|
||||
return condition('had_counters', counter === undefined ? {} : { counter: asString(counter, 'counter') })
|
||||
}
|
||||
|
||||
export function manaFromTreasure(): Condition {
|
||||
return condition('mana_from_treasure')
|
||||
}
|
||||
|
||||
export function manaSpent(atLeast: unknown): Condition {
|
||||
return condition('mana_spent', { atLeast: asNumber(atLeast, 'mana') })
|
||||
}
|
||||
|
||||
export function noManaSpent(): Condition {
|
||||
return condition('no_mana_spent')
|
||||
}
|
||||
|
||||
export function manaSymbolSpent(symbols: unknown): Condition {
|
||||
return condition('mana_symbol_spent', { symbols: asString(symbols, 'mana symbols') })
|
||||
}
|
||||
|
||||
export function kickedWith(cost: unknown): Condition {
|
||||
return condition('kicked_with', { cost: asString(cost, 'kicker cost') })
|
||||
}
|
||||
|
||||
export function moreCardsThanEachOpponent(): Condition {
|
||||
return condition('more_cards_than_each_opponent')
|
||||
}
|
||||
|
||||
export function firstCombatPhase(): Condition {
|
||||
return condition('first_combat_phase')
|
||||
}
|
||||
|
||||
export function notToken(): Condition {
|
||||
return condition('not_token')
|
||||
}
|
||||
|
||||
export function castSpellThisTurn(options?: unknown): Condition {
|
||||
return condition('cast_spell_this_turn', asOptions(options).noncreature === true ? { noncreature: true } : {})
|
||||
}
|
||||
|
||||
export function fullParty(): Condition {
|
||||
return condition('full_party')
|
||||
}
|
||||
|
||||
export function graveyardCount(selector: unknown, atLeast: unknown): Condition {
|
||||
return condition('graveyard_count', { selector: asSelector(selector), atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export 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 })
|
||||
}
|
||||
|
||||
export function ifYouDo(): Condition {
|
||||
return condition('if_you_do')
|
||||
}
|
||||
|
||||
export function ifYouDont(): Condition {
|
||||
return condition('if_you_dont')
|
||||
}
|
||||
|
||||
export function otherwise(): Condition {
|
||||
return condition('otherwise')
|
||||
}
|
||||
|
||||
export function youControlCommander(): Condition {
|
||||
return condition('you_control_commander')
|
||||
}
|
||||
|
||||
export function distinctNames(selector: unknown, atLeast: unknown): Condition {
|
||||
return condition('distinct_names', { selector: asSelector(selector), atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function opponentDamagedThisTurn(atLeast: unknown): Condition {
|
||||
return condition('opponent_damaged_this_turn', { atLeast: asNumber(atLeast, 'damage') })
|
||||
}
|
||||
|
||||
export function attackedWithCreatures(atLeast: unknown): Condition {
|
||||
return condition('attacked_with_creatures', { atLeast: asNumber(atLeast, 'count') })
|
||||
}
|
||||
|
||||
export function libraryAtMost(atMost: unknown): Condition {
|
||||
return condition('library_at_most', { atMost: asNumber(atMost, 'cards') })
|
||||
}
|
||||
431
backend/src/effects/source-effects.ts
Normal file
431
backend/src/effects/source-effects.ts
Normal file
@@ -0,0 +1,431 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
import { self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker, targetOptions, target, each, pick, divided, targetSpell, targetAbility, X, itsPower, itsToughness, count, cardsInHand, maxCardsInHand, maxOpponentCount, totalManaValue, totalPower, anyNumber, eventAmount, mana, anyColor, asToken, CopyOf, copyOf, manaCost, tapCost, untapCost, tapOther, energyCost, loyalty, payLife, discardCost, sacrificeCost, sacrificeSelf, exileSelf, exileFromGraveyard, reveal, choice, returnToHandCost, behold, waterbend, blight, chooseCost, putCounterCost, removeCountersCost, forage, collectEvidence, millCost } from './source-values.js'
|
||||
|
||||
export function damage(targetValue: unknown, amount: unknown, source?: unknown): Effect {
|
||||
return {
|
||||
op: 'damage',
|
||||
target: asTarget(targetValue),
|
||||
amount: asValue(amount),
|
||||
...(source !== undefined ? { source: asTarget(source) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function damageDivided(amount: unknown, targetValue: unknown): Effect {
|
||||
return { op: 'damage_divided', amount: asValue(amount), target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function draw(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'draw', player: asPlayer(player), amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function discard(player: unknown, amount: unknown, options?: unknown): Effect {
|
||||
return {
|
||||
op: 'discard',
|
||||
player: asPlayer(player),
|
||||
amount: asValue(amount),
|
||||
...(asOptions(options).random === true ? { random: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function mill(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'mill', player: asPlayer(player), amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function gainLife(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'life', player: asPlayer(player), amount: asValue(amount), mode: 'gain' }
|
||||
}
|
||||
|
||||
export function loseLife(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'life', player: asPlayer(player), amount: asValue(amount), mode: 'lose' }
|
||||
}
|
||||
|
||||
export 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),
|
||||
}
|
||||
}
|
||||
|
||||
export 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),
|
||||
}
|
||||
}
|
||||
|
||||
export 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),
|
||||
}
|
||||
}
|
||||
|
||||
export function putCounters(targetValue: unknown, counter: unknown, amount: unknown): Effect {
|
||||
return {
|
||||
op: 'put_counters',
|
||||
target: asTarget(targetValue),
|
||||
counter: asString(counter, 'counter'),
|
||||
amount: asValue(amount),
|
||||
}
|
||||
}
|
||||
|
||||
export function doubleCounters(targetValue: unknown, counter?: unknown): Effect {
|
||||
return {
|
||||
op: 'double_counters',
|
||||
target: asTarget(targetValue),
|
||||
...(counter !== undefined ? { counter: asString(counter, 'counter') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function removeCounters(targetValue: unknown, counter: unknown, amount: unknown): Effect {
|
||||
return {
|
||||
op: 'remove_counters',
|
||||
target: asTarget(targetValue),
|
||||
counter: asString(counter, 'counter'),
|
||||
amount: asValue(amount),
|
||||
}
|
||||
}
|
||||
|
||||
export function proliferate(): Effect {
|
||||
return { op: 'proliferate' }
|
||||
}
|
||||
|
||||
export function createToken(player: unknown, amount: unknown, tokenValue: unknown, options?: unknown): Effect {
|
||||
const attachTo = options && typeof options === 'object' && 'attachTo' in options
|
||||
? asTarget((options as { attachTo: unknown }).attachTo)
|
||||
: undefined
|
||||
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 } : {}),
|
||||
...(attachTo ? { attachTo } : {}),
|
||||
}
|
||||
}
|
||||
return {
|
||||
op: 'create_token',
|
||||
player: asPlayer(player),
|
||||
amount: asValue(amount),
|
||||
token: asToken(tokenValue),
|
||||
...(attachTo ? { attachTo } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function destroy(targetValue: unknown): Effect {
|
||||
return { op: 'destroy', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function exile(targetValue: unknown): Effect {
|
||||
return { op: 'exile', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function sacrifice(player: unknown, targetValue: unknown, unless?: unknown): Effect {
|
||||
return {
|
||||
op: 'sacrifice',
|
||||
player: asPlayer(player),
|
||||
target: asTarget(targetValue),
|
||||
...(unless !== undefined ? { unless: asCost(unless) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function returnToHand(targetValue: unknown): Effect {
|
||||
return { op: 'return_to_hand', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export 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) } }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function putOnTop(targetValue: unknown): Effect {
|
||||
return { op: 'put_on_top', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function tap(targetValue: unknown): Effect {
|
||||
return { op: 'tap', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function untap(targetValue: unknown): Effect {
|
||||
return { op: 'untap', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function scry(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'scry', player: asPlayer(player), amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function surveil(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'surveil', player: asPlayer(player), amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export 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 } }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function shuffle(player: unknown): Effect {
|
||||
return { op: 'shuffle', player: asPlayer(player) }
|
||||
}
|
||||
|
||||
export 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 }
|
||||
}
|
||||
|
||||
export function fight(a: unknown, b: unknown): Effect {
|
||||
return { op: 'fight', a: asTarget(a), b: asTarget(b) }
|
||||
}
|
||||
|
||||
export function regenerate(targetValue: unknown): Effect {
|
||||
return { op: 'regenerate', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function energy(player: unknown, amount: unknown): Effect {
|
||||
return { op: 'energy', player: asPlayer(player), amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function attach(targetValue: unknown): Effect {
|
||||
return { op: 'attach', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export 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),
|
||||
}
|
||||
}
|
||||
|
||||
export 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') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
...(data.global === true ? { global: true } : {}),
|
||||
...(data.source !== undefined ? { source: asTarget(data.source) } : {}),
|
||||
...(data.sourceSelector !== undefined ? { sourceSelector: asSelector(data.sourceSelector) } : {}),
|
||||
duration: asDuration(data.duration),
|
||||
}
|
||||
}
|
||||
|
||||
export function gainControl(targetValue: unknown, duration?: unknown): Effect {
|
||||
return { op: 'gain_control', target: asTarget(targetValue), duration: asDuration(duration) }
|
||||
}
|
||||
|
||||
export function emblem(text: unknown): Effect {
|
||||
return { op: 'emblem', text: asString(text, 'emblem text') }
|
||||
}
|
||||
|
||||
export function transform(targetValue: unknown): Effect {
|
||||
return { op: 'transform', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function pay(costs: unknown): Effect {
|
||||
return { op: 'pay', costs: asCosts(costs) }
|
||||
}
|
||||
|
||||
export function ifThen(condition: unknown, effects: unknown): Effect {
|
||||
return { op: 'conditional', condition: asCondition(condition), effects: asEffects(effects) }
|
||||
}
|
||||
|
||||
export 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)),
|
||||
}
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) }
|
||||
}
|
||||
|
||||
export function levelUp(level: unknown): Effect {
|
||||
return { op: 'level_up', level: asNumber(level, 'level') }
|
||||
}
|
||||
|
||||
export 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'),
|
||||
}
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function exileGraveyards(): Effect {
|
||||
return { op: 'exile_graveyards' }
|
||||
}
|
||||
|
||||
export function hideaway(amount: unknown): Effect {
|
||||
return { op: 'hideaway', amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function playExiled(player: unknown, options?: unknown): Effect {
|
||||
return {
|
||||
op: 'play_exiled',
|
||||
player: asPlayer(player),
|
||||
...(asOptions(options).free === true ? { free: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function exileInsteadOfDying(targetValue: unknown): Effect {
|
||||
return { op: 'exile_instead_of_dying', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export function impulse(player: unknown, amount: unknown, options?: unknown): Effect {
|
||||
return {
|
||||
op: 'impulse',
|
||||
player: asPlayer(player),
|
||||
amount: asValue(amount),
|
||||
...(asOptions(options).faceDown === true ? { faceDown: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Static effects
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
218
backend/src/effects/source-static.ts
Normal file
218
backend/src/effects/source-static.ts
Normal file
@@ -0,0 +1,218 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
import { self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker, targetOptions, target, each, pick, divided, targetSpell, targetAbility, X, itsPower, itsToughness, count, cardsInHand, maxCardsInHand, maxOpponentCount, totalManaValue, totalPower, anyNumber, eventAmount, mana, anyColor, asToken, CopyOf, copyOf, manaCost, tapCost, untapCost, tapOther, energyCost, loyalty, payLife, discardCost, sacrificeCost, sacrificeSelf, exileSelf, exileFromGraveyard, reveal, choice, returnToHandCost, behold, waterbend, blight, chooseCost, putCounterCost, removeCountersCost, forage, collectEvidence, millCost } from './source-values.js'
|
||||
|
||||
export function staticPump(targetValue: unknown, power: unknown, toughness: unknown): StaticEffect {
|
||||
return { op: 'pump', target: asTarget(targetValue), power: asValue(power), toughness: asValue(toughness) }
|
||||
}
|
||||
|
||||
export 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') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function grantAbility(targetValue: unknown, ability: unknown): StaticEffect {
|
||||
return { op: 'grant_ability', target: asTarget(targetValue), ability: asAbility(ability) }
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function entersWithCounters(targetValue: unknown, counter: unknown, amount: unknown): StaticEffect {
|
||||
return {
|
||||
op: 'enters_with_counters',
|
||||
target: asTarget(targetValue),
|
||||
counter: asString(counter, 'counter'),
|
||||
amount: asValue(amount),
|
||||
}
|
||||
}
|
||||
|
||||
export function control(targetValue: unknown): StaticEffect {
|
||||
return { op: 'control', target: asTarget(targetValue) }
|
||||
}
|
||||
|
||||
export 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' }
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function replacementAmount(what: unknown, multiplier: unknown, options?: unknown): StaticEffect {
|
||||
const text = asString(what, 'replacement amount')
|
||||
if (text !== 'life_gain' && text !== 'damage' && text !== 'draw' && text !== 'energy') {
|
||||
throw new Error(`unknown replacement amount "${text}"`)
|
||||
}
|
||||
const data = asOptions(options)
|
||||
return {
|
||||
op: 'replacement_amount',
|
||||
what: text,
|
||||
multiplier: asNumber(multiplier, 'replacement multiplier'),
|
||||
...(data.add !== undefined ? { add: asNumber(data.add, 'replacement add') } : {}),
|
||||
...(data.combatOnly === true ? { combatOnly: true } : {}),
|
||||
...(data.noncombatOnly === true ? { noncombatOnly: true } : {}),
|
||||
...(data.sourceColor !== undefined ? { sourceColor: asString(data.sourceColor, 'source color') } : {}),
|
||||
...(data.controller === 'you' ? { controller: 'you' as const } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function tokenReplacement(from: unknown, tokens: unknown, options?: unknown): StaticEffect {
|
||||
const data = asOptions(options)
|
||||
const names = Array.isArray(from) ? from.map(entry => asString(entry, 'token name')) : []
|
||||
const specs = Array.isArray(tokens) ? tokens.map(asToken) : []
|
||||
return {
|
||||
op: 'token_replacement',
|
||||
from: names,
|
||||
tokens: specs,
|
||||
...(data.who === 'each_player' ? { who: 'each_player' as const } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function counterMultiplier(targetValue: unknown, multiplier: unknown, options?: unknown): StaticEffect {
|
||||
const data = asOptions(options)
|
||||
return {
|
||||
op: 'counter_multiplier',
|
||||
target: asTarget(targetValue),
|
||||
multiplier: asNumber(multiplier, 'counter multiplier'),
|
||||
...(data.counter !== undefined ? { counter: asString(data.counter, 'counter') } : {}),
|
||||
...(data.add !== undefined ? { add: asNumber(data.add, 'counter add') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function tokenMultiplier(multiplier: unknown, options?: unknown): StaticEffect {
|
||||
const data = asOptions(options)
|
||||
if (data.who !== undefined && data.who !== 'you' && data.who !== 'each_player') {
|
||||
throw new Error("tokenMultiplier() who must be 'you' or 'each_player'")
|
||||
}
|
||||
return {
|
||||
op: 'token_multiplier',
|
||||
multiplier: asNumber(multiplier, 'token multiplier'),
|
||||
who: data.who === 'each_player' ? 'each_player' : 'you',
|
||||
...(data.creatureOnly === true ? { creatureOnly: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) }
|
||||
}
|
||||
|
||||
export 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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
470
backend/src/effects/source-validation.ts
Normal file
470
backend/src/effects/source-validation.ts
Normal file
@@ -0,0 +1,470 @@
|
||||
// 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 { 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 const PLAYER_REFS = new Set<PlayerRef>([
|
||||
'you',
|
||||
'opponent',
|
||||
'each_opponent',
|
||||
'each_player',
|
||||
'target_player',
|
||||
'that_player',
|
||||
'its_controller',
|
||||
'its_owner',
|
||||
])
|
||||
|
||||
export const DURATIONS = new Set<Duration>([
|
||||
'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',
|
||||
])
|
||||
|
||||
export const ZONES = new Set<Zone>(['battlefield', 'hand', 'graveyard', 'library', 'exile', 'stack', 'command'])
|
||||
export const SEARCH_DESTINATIONS = new Set<SearchDestination>(['hand', 'battlefield', 'graveyard', 'top', 'bottom'])
|
||||
|
||||
export const COLOR_CODES: Record<string, string> = {
|
||||
white: 'W',
|
||||
blue: 'U',
|
||||
black: 'B',
|
||||
red: 'R',
|
||||
green: 'G',
|
||||
colorless: 'C',
|
||||
}
|
||||
|
||||
export const CHOICES = new Set(['creature_type', 'color', 'card_name', 'player', 'opponent', 'number'])
|
||||
export const RESTRICTION_RULES = new Set(['cant_attack', 'cant_block', 'doesnt_untap'])
|
||||
export const REPLACEMENT_WHATS = new Set(['dies', 'leaves_battlefield', 'discard', 'draw'])
|
||||
export const REPLACEMENT_RESULTS = new Set(['exile', 'return_to_hand', 'return_to_library', 'prevent'])
|
||||
export const TRIGGER_PLAYERS = new Set(['you', 'opponent', 'each_player'])
|
||||
|
||||
export 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',
|
||||
])
|
||||
|
||||
export const EFFECT_OPS = new Set([
|
||||
'damage', 'draw', 'discard', 'mill', 'life', 'pump', 'set_pt', 'grant',
|
||||
'put_counters', 'remove_counters', 'double_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', 'impulse', 'exile_instead_of_dying',
|
||||
])
|
||||
|
||||
export 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', 'token_multiplier', 'replacement_amount', 'prevent_damage', 'counter_multiplier', 'token_replacement',
|
||||
])
|
||||
|
||||
export 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',
|
||||
])
|
||||
|
||||
export 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',
|
||||
])
|
||||
|
||||
export 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',
|
||||
])
|
||||
|
||||
export const ABILITY_KINDS = new Set([
|
||||
'keyword', 'keywords', 'triggered', 'activated', 'static', 'spell',
|
||||
'additional_cost', 'alternative_cost', 'overload', 'chapter', 'level_band',
|
||||
'level_pt', 'unsupported',
|
||||
])
|
||||
|
||||
export function expectKind(value: unknown, allowed: Set<string>, label: string, key = 'kind'): Record<string, unknown> {
|
||||
if (!isRecord(value) || typeof value[key] !== 'string' || !allowed.has(value[key] as string)) {
|
||||
throw new Error(`expected ${label}`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export function asRecord(value: unknown, label: string): Record<string, unknown> {
|
||||
if (!isRecord(value)) throw new Error(`${label} must be an object`)
|
||||
return value
|
||||
}
|
||||
|
||||
export function asString(value: unknown, label: string): string {
|
||||
if (typeof value !== 'string') throw new Error(`${label} must be a string`)
|
||||
return value
|
||||
}
|
||||
|
||||
export function asNumber(value: unknown, label: string): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be a number`)
|
||||
return value
|
||||
}
|
||||
|
||||
export function asBoolean(value: unknown, label: string): boolean {
|
||||
if (typeof value !== 'boolean') throw new Error(`${label} must be true or false`)
|
||||
return value
|
||||
}
|
||||
|
||||
export function optionalString(value: unknown, label: string): string | undefined {
|
||||
if (value === undefined || value === null) return undefined
|
||||
return asString(value, label)
|
||||
}
|
||||
|
||||
export 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))
|
||||
}
|
||||
|
||||
export 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)}`)
|
||||
}
|
||||
|
||||
export 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)}`)
|
||||
}
|
||||
|
||||
export 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)}"`)
|
||||
}
|
||||
|
||||
export 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)}"`)
|
||||
}
|
||||
|
||||
export 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)}"`)
|
||||
}
|
||||
|
||||
export 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)')
|
||||
}
|
||||
|
||||
export 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')
|
||||
}
|
||||
|
||||
export 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)
|
||||
}
|
||||
|
||||
export function asTarget(value: unknown): Target {
|
||||
if (isTarget(value)) return value
|
||||
throw new Error('expected a target')
|
||||
}
|
||||
|
||||
export function asEffects(value: unknown): Effect[] {
|
||||
const resolved = typeof value === 'function' ? value() : value
|
||||
if (!Array.isArray(resolved)) return [asEffect(resolved)]
|
||||
return resolved.map(asEffect)
|
||||
}
|
||||
|
||||
export function asEffect(value: unknown): Effect {
|
||||
return expectKind(value, EFFECT_OPS, 'an effect', 'op') as unknown as Effect
|
||||
}
|
||||
|
||||
export function asStaticEffects(value: unknown): StaticEffect[] {
|
||||
const resolved = typeof value === 'function' ? value() : value
|
||||
if (!Array.isArray(resolved)) return [asStaticEffect(resolved)]
|
||||
return resolved.map(asStaticEffect)
|
||||
}
|
||||
|
||||
export function asStaticEffect(value: unknown): StaticEffect {
|
||||
return expectKind(value, STATIC_OPS, 'a static effect', 'op') as unknown as StaticEffect
|
||||
}
|
||||
|
||||
export function asCosts(value: unknown): Cost[] {
|
||||
if (!Array.isArray(value)) throw new Error('expected an array of costs')
|
||||
return value.map(asCost)
|
||||
}
|
||||
|
||||
export function asCost(value: unknown): Cost {
|
||||
return expectKind(value, COST_KINDS, 'a cost') as unknown as Cost
|
||||
}
|
||||
|
||||
export function asCondition(value: unknown): Condition {
|
||||
return expectKind(value, CONDITION_KINDS, 'a condition') as unknown as Condition
|
||||
}
|
||||
|
||||
export function asTrigger(value: unknown): TriggerEvent {
|
||||
return expectKind(value, TRIGGER_KINDS, 'a trigger event') as unknown as TriggerEvent
|
||||
}
|
||||
|
||||
export function asAbility(value: unknown): Ability {
|
||||
return expectKind(value, ABILITY_KINDS, 'an ability') as unknown as Ability
|
||||
}
|
||||
|
||||
export function asAbilityArray(value: unknown): Ability[] {
|
||||
if (!Array.isArray(value)) throw new Error('the implementation must be an array of abilities')
|
||||
return value.map(asAbility)
|
||||
}
|
||||
|
||||
export function asOptions(value: unknown): Record<string, unknown> {
|
||||
if (value === undefined || value === null) return Object.create(null) as Record<string, unknown>
|
||||
return asRecord(value, 'options')
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selectors
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export class Selector {
|
||||
readonly fields: ObjectSelector
|
||||
|
||||
constructor(fields: ObjectSelector = {}) {
|
||||
this.fields = fields
|
||||
}
|
||||
|
||||
private with(patch: Partial<ObjectSelector>): 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()
|
||||
}),
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
withoutColor(...colors: unknown[]): Selector {
|
||||
return this.with({
|
||||
excludeColors: [
|
||||
...(this.fields.excludeColors ?? []),
|
||||
...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
|
||||
// ---------------------------------------------------------------------------
|
||||
306
backend/src/effects/source-values.ts
Normal file
306
backend/src/effects/source-values.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
// 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 type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
KeywordAbility,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
SearchDestination,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from './types.js'
|
||||
|
||||
import { SIMPLE_KEYWORDS } from './compile.js'
|
||||
import { singularize } from './parse.js'
|
||||
import { Selector, PLAYER_REFS, DURATIONS, ZONES, SEARCH_DESTINATIONS, COLOR_CODES, CHOICES, RESTRICTION_RULES, REPLACEMENT_WHATS, REPLACEMENT_RESULTS, TRIGGER_PLAYERS, VALUE_KINDS, EFFECT_OPS, STATIC_OPS, COST_KINDS, CONDITION_KINDS, TRIGGER_KINDS, ABILITY_KINDS, expectKind, isRecord, asRecord, asString, asNumber, asBoolean, optionalString, stringArray, asPlayer, asTriggerPlayer, asDuration, asZone, asSearchDestination, asValue, asSelector, isTarget, asTarget, asEffects, asEffect, asStaticEffects, asStaticEffect, asCosts, asCost, asCondition, asTrigger, asAbility, asAbilityArray, asOptions } from './source-validation.js'
|
||||
|
||||
|
||||
export const self: Target = { kind: 'self' }
|
||||
export const triggerSubject: Target = { kind: 'trigger_subject' }
|
||||
export const previousTarget: Target = { kind: 'previous_target' }
|
||||
export const anyTarget: Target = { kind: 'any' }
|
||||
export const targetPlayerOrPlaneswalker: Target = { kind: 'player_or_planeswalker', mode: 'target' }
|
||||
|
||||
export function targetOptions(value: unknown): Pick<Extract<Target, { kind: 'object' }>, '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') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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) }
|
||||
}
|
||||
|
||||
export 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) }
|
||||
}
|
||||
|
||||
export function pick(value: unknown, options?: unknown): Target {
|
||||
return { kind: 'object', selector: asSelector(value), mode: 'choose', ...targetOptions(options) }
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function targetSpell(selector?: unknown): Target {
|
||||
return { kind: 'spell', selector: selector === undefined ? { types: [] } : asSelector(selector), mode: 'target' }
|
||||
}
|
||||
|
||||
export function targetAbility(selector?: unknown): Target {
|
||||
return { kind: 'ability', mode: 'target', ...(selector !== undefined ? { selector: asSelector(selector) } : {}) }
|
||||
}
|
||||
|
||||
export const X: Value = { kind: 'x' }
|
||||
export const itsPower: Value = { kind: 'source_power' }
|
||||
export const itsToughness: Value = { kind: 'source_toughness' }
|
||||
|
||||
export function count(selector: unknown): Value {
|
||||
return { kind: 'count', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function cardsInHand(player: unknown): Value {
|
||||
return { kind: 'cards_in_hand', player: asPlayer(player) }
|
||||
}
|
||||
|
||||
export function maxCardsInHand(): Value {
|
||||
return { kind: 'max_cards_in_hand' }
|
||||
}
|
||||
|
||||
export function maxOpponentCount(selector: unknown): Value {
|
||||
return { kind: 'max_opponent_count', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function totalManaValue(selector: unknown): Value {
|
||||
return { kind: 'total_mana_value', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function totalPower(selector: unknown): Value {
|
||||
return { kind: 'total_power', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function anyNumber(): Value {
|
||||
return { kind: 'any_number' }
|
||||
}
|
||||
|
||||
export function eventAmount(): Value {
|
||||
return { kind: 'event_amount' }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Mana, tokens and costs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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') } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export 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') }),
|
||||
}
|
||||
}
|
||||
|
||||
export class CopyOf {
|
||||
readonly target: Target
|
||||
readonly notLegendary: boolean
|
||||
|
||||
constructor(targetValue: unknown, notLegendary: boolean) {
|
||||
this.target = asTarget(targetValue)
|
||||
this.notLegendary = notLegendary
|
||||
}
|
||||
}
|
||||
|
||||
export function copyOf(targetValue: unknown, options?: unknown): CopyOf {
|
||||
return new CopyOf(targetValue, asOptions(options).notLegendary === true)
|
||||
}
|
||||
|
||||
export function manaCost(symbols: unknown): Cost {
|
||||
const spec = mana(symbols)
|
||||
return { kind: 'mana', symbols: spec.kind === 'symbols' ? spec.symbols.join('') : '' }
|
||||
}
|
||||
|
||||
export function tapCost(): Cost {
|
||||
return { kind: 'tap' }
|
||||
}
|
||||
|
||||
export function untapCost(): Cost {
|
||||
return { kind: 'untap' }
|
||||
}
|
||||
|
||||
export function tapOther(selector: unknown): Cost {
|
||||
return { kind: 'tap_other', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function energyCost(amount: unknown): Cost {
|
||||
return { kind: 'energy', amount: asNumber(amount, 'energy') }
|
||||
}
|
||||
|
||||
export function loyalty(amount: unknown): Cost {
|
||||
return { kind: 'loyalty', amount: asNumber(amount, 'loyalty') }
|
||||
}
|
||||
|
||||
export function payLife(amount: unknown): Cost {
|
||||
return { kind: 'pay_life', amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export 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 } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function sacrificeCost(selector: unknown): Cost {
|
||||
return { kind: 'sacrifice', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function sacrificeSelf(): Cost {
|
||||
return { kind: 'sacrifice_self' }
|
||||
}
|
||||
|
||||
export function exileSelf(): Cost {
|
||||
return { kind: 'exile_self' }
|
||||
}
|
||||
|
||||
export function exileFromGraveyard(selector: unknown, amount?: unknown): Cost {
|
||||
return {
|
||||
kind: 'exile_from_graveyard',
|
||||
selector: asSelector(selector),
|
||||
...(amount !== undefined ? { amount: asValue(amount) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function reveal(selector: unknown): Cost {
|
||||
return { kind: 'reveal', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export 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)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
export function returnToHandCost(selector: unknown): Cost {
|
||||
return { kind: 'return_to_hand', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function behold(selector: unknown): Cost {
|
||||
return { kind: 'behold', selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export function waterbend(amount: unknown): Cost {
|
||||
return { kind: 'waterbend', amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function blight(amount: unknown): Cost {
|
||||
return { kind: 'blight', amount: asValue(amount) }
|
||||
}
|
||||
|
||||
export function chooseCost(what: unknown): Cost {
|
||||
return { kind: 'choose', what: asString(what, 'choice') }
|
||||
}
|
||||
|
||||
export function putCounterCost(counter: unknown, selector: unknown): Cost {
|
||||
return { kind: 'put_counter', counter: asString(counter, 'counter'), selector: asSelector(selector) }
|
||||
}
|
||||
|
||||
export 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) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export function forage(): Cost {
|
||||
return { kind: 'forage' }
|
||||
}
|
||||
|
||||
export function collectEvidence(amount: unknown): Cost {
|
||||
return { kind: 'collect_evidence', amount: asNumber(amount, 'evidence') }
|
||||
}
|
||||
|
||||
export function millCost(amount: unknown): Cost {
|
||||
return { kind: 'mill', amount: asValue(amount) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Effects
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
501
backend/src/effects/source.ts
Normal file
501
backend/src/effects/source.ts
Normal file
@@ -0,0 +1,501 @@
|
||||
// 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 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<string, unknown>
|
||||
|
||||
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<string, unknown> {
|
||||
this.expect('{')
|
||||
const value: Record<string, unknown> = Object.create(null) as Record<string, unknown>
|
||||
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<string, unknown>)[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<string, unknown>)[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
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
import { createApi } from './source-api.js'
|
||||
import { CardSection, Face, Faces } from './source-card.js'
|
||||
import { Selector, asAbilityArray } from './source-validation.js'
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,165 @@ 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 "## <exact face name>" lines, one section per face, in card order. Use "(no abilities)" for a face with none. A leading "# Card [status]" line is optional and not needed.
|
||||
A card exports its type line and an array of abilities:
|
||||
|
||||
Ability headers:
|
||||
on <trigger>[ if <condition>][ (may)]:
|
||||
activate <cost>[, <cost>...][ if <condition>][ (N/turn)][ (sorcery speed)][ (may)]:
|
||||
static[ if <condition>]:
|
||||
spell[(may)]:
|
||||
keyword <Keyword>[ value]
|
||||
keywords <Keyword>, <Keyword>
|
||||
additional cost[(may)]: <cost>
|
||||
chapter <I>, <II>[(may)]:
|
||||
level <min>-<max>[: <power>/<toughness>]
|
||||
level <min>+[: <power>/<toughness>]
|
||||
level_pt(<power>/<toughness>)
|
||||
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, <spell selector>|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')
|
||||
.withoutColor('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 <selector>, each <selector>,
|
||||
up to N target <selector>, N <selector>, this or <selector>, divided(<max>[, <selector>])
|
||||
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 <keyword>", "without <keyword>",
|
||||
"power N+" / "power N or less", "toughness N+" / "toughness N or less",
|
||||
"mana value N+" / "mana value N or less", "named <name>",
|
||||
"from a graveyard", "from a library", "from a hand", "in exile", "on the battlefield", "on the stack".
|
||||
Values: a number, X, itsPower, itsToughness, count(selector), cardsInHand(player),
|
||||
maxCardsInHand(), maxOpponentCount(selector), totalManaValue(selector),
|
||||
totalPower(selector), anyNumber(), eventAmount()
|
||||
|
||||
Values: a number, X, count(<selector>), its power, its toughness,
|
||||
cards in your hand, cards in that player's hand, total power of <selector>,
|
||||
total mana value of <selector>, greatest number of <selector> 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 <selector>,
|
||||
tap <selector>, exile this from a graveyard, exile N <selector> from your graveyard,
|
||||
reveal <selector> from your hand, return <selector> to its owner's hand,
|
||||
behold <selector>, waterbend <value>, blight <value>, choose <text>,
|
||||
put <counter> counter on <selector>, 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 <condition>:
|
||||
<effects>
|
||||
choose <min>[-<max>]:
|
||||
1. <effects separated by ;>
|
||||
2. <effects separated by ;>
|
||||
schedule(next_upkeep|next_end_step):
|
||||
<effects>
|
||||
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 <condition>])
|
||||
enters_tapped(target[, unless <condition>])
|
||||
enters_with_counters(target, counter, amount)
|
||||
grant_ability(target):
|
||||
<one ability block>
|
||||
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[, if <condition>])
|
||||
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 <selector>, you control at least N <selector>,
|
||||
an opponent controls <selector>, it is your turn, it isn't your turn,
|
||||
this is tapped, this is untapped, this is attacking, <player> has at least N life,
|
||||
<player> has at most N life, <player> has N+ cards in their graveyard,
|
||||
<player> 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 (<short reason>): <original oracle text>
|
||||
- For multi-face cards, output only the "## <face name>" 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 +232,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 +267,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)}`,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
export type Zone = 'battlefield' | 'hand' | 'graveyard' | 'library' | 'exile' | 'stack' | 'command'
|
||||
|
||||
export type SearchDestination = 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'
|
||||
|
||||
export type PlayerRef =
|
||||
| 'you'
|
||||
| 'opponent'
|
||||
@@ -23,6 +25,7 @@ export interface ObjectSelector {
|
||||
controller?: 'you' | 'opponent' | 'any'
|
||||
owner?: 'you' | 'opponent'
|
||||
colors?: string[]
|
||||
excludeColors?: string[]
|
||||
other?: boolean
|
||||
attached?: 'equipped' | 'enchanted'
|
||||
zone?: Zone
|
||||
@@ -42,6 +45,7 @@ export type Target =
|
||||
| { kind: 'self' }
|
||||
| { kind: 'trigger_subject' }
|
||||
| { kind: 'previous_target' }
|
||||
| { kind: 'damaged' }
|
||||
| { kind: 'object'; selector: ObjectSelector; mode: 'target' | 'each' | 'choose'; count?: number; upTo?: boolean; includeSelf?: boolean }
|
||||
| { kind: 'player'; who: PlayerRef; mode: 'target' | 'each' }
|
||||
| { kind: 'player_or_planeswalker'; mode: 'target' }
|
||||
@@ -65,7 +69,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 {
|
||||
@@ -128,6 +132,8 @@ export type Condition =
|
||||
| { kind: 'source_tapped' }
|
||||
| { kind: 'source_untapped' }
|
||||
| { kind: 'source_attacking' }
|
||||
| { kind: 'source_equipped' }
|
||||
| { kind: 'source_enchanted' }
|
||||
| { kind: 'life_at_least'; player: PlayerRef; amount: number }
|
||||
| { kind: 'life_at_most'; player: PlayerRef; amount: number }
|
||||
| { kind: 'life_above_starting'; player: PlayerRef; amount: number }
|
||||
@@ -184,6 +190,12 @@ export type Condition =
|
||||
| { kind: 'if_you_do' }
|
||||
| { kind: 'if_you_dont' }
|
||||
| { kind: 'otherwise' }
|
||||
| { kind: 'you_control_commander' }
|
||||
| { kind: 'distinct_names'; selector: ObjectSelector; atLeast: number }
|
||||
| { kind: 'opponent_damaged_this_turn'; atLeast: number }
|
||||
| { kind: 'attacked_with_creatures'; atLeast: number }
|
||||
| { kind: 'library_at_most'; atMost: number }
|
||||
| { kind: 'event_subject_toughness_at_most'; amount: number }
|
||||
|
||||
export type TriggerEvent =
|
||||
| { kind: 'enters'; subject: Target }
|
||||
@@ -217,8 +229,9 @@ export type Effect =
|
||||
| { op: 'grant'; target: Target; keyword: string; value?: string; duration: Duration }
|
||||
| { op: 'put_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'remove_counters'; target: Target; counter: string; amount: Value }
|
||||
| { op: 'double_counters'; target: Target; counter?: string }
|
||||
| { op: 'proliferate' }
|
||||
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean }
|
||||
| { op: 'create_token'; player: PlayerRef; amount: Value; token: TokenSpec; copyOf?: Target; notLegendary?: boolean; attachTo?: Target }
|
||||
| { op: 'destroy'; target: Target }
|
||||
| { op: 'exile'; target: Target }
|
||||
| { op: 'sacrifice'; player: PlayerRef; target: Target; unless?: Cost }
|
||||
@@ -230,7 +243,7 @@ export type Effect =
|
||||
| { op: 'untap'; target: Target }
|
||||
| { op: 'scry'; player: PlayerRef; amount: Value }
|
||||
| { op: 'surveil'; player: PlayerRef; amount: Value }
|
||||
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[] }
|
||||
| { op: 'search'; player: PlayerRef; selector: ObjectSelector; amount: Value; destination: SearchDestination; tapped: boolean; shuffle: boolean; zones?: ('library' | 'graveyard')[]; split?: { destination: SearchDestination; tapped: boolean } }
|
||||
| { op: 'shuffle'; player: PlayerRef }
|
||||
| { op: 'add_mana'; player: PlayerRef; mana: ManaSpec }
|
||||
| { op: 'fight'; a: Target; b: Target }
|
||||
@@ -239,7 +252,7 @@ export type Effect =
|
||||
| { op: 'attach'; target: Target }
|
||||
| { op: 'restriction'; target: Target; rule: 'cant_attack' | 'cant_block' | 'doesnt_untap'; duration: Duration }
|
||||
| { op: 'keyword_action'; action: string; amount?: Value; detail?: string; target?: Target }
|
||||
| { op: 'prevent_damage'; target: Target; amount: Value | 'all'; combatOnly?: boolean; duration: Duration }
|
||||
| { op: 'prevent_damage'; target: Target; amount: Value | 'all'; combatOnly?: boolean; duration: Duration; global?: boolean; then?: Effect[]; source?: Target; sourceSelector?: ObjectSelector }
|
||||
| { op: 'gain_control'; target: Target; duration: Duration }
|
||||
| { op: 'emblem'; text: string }
|
||||
| { op: 'transform'; target: Target }
|
||||
@@ -252,19 +265,32 @@ export type Effect =
|
||||
| { op: 'put_from_among'; player: PlayerRef; selector?: ObjectSelector; amount: Value; destination: 'hand' | 'graveyard' | 'battlefield' | 'top' | 'bottom' }
|
||||
| { op: 'dig'; player: PlayerRef; amount: Value; pick: Value; upTo?: boolean; pickSelector?: ObjectSelector; to: 'hand' | 'battlefield'; rest: 'bottom' | 'graveyard' | 'top'; order?: 'any' | 'random'; optional?: boolean; tapped?: boolean }
|
||||
| { op: 'damage_divided'; amount: Value; target: Target }
|
||||
| { op: 'exile_graveyards' }
|
||||
| { op: 'hideaway'; amount: Value }
|
||||
| { op: 'play_exiled'; player: PlayerRef; free?: boolean }
|
||||
| { op: 'impulse'; player: PlayerRef; amount: Value; faceDown?: boolean }
|
||||
| { op: 'exile_instead_of_dying'; target: Target }
|
||||
|
||||
export type StaticEffect =
|
||||
| { op: 'pump'; target: Target; power: Value; toughness: Value }
|
||||
| { 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 }
|
||||
| { op: 'choose'; what: 'creature_type' | 'color' | 'card_name' | 'player' | 'opponent' | 'number' }
|
||||
| { op: 'replacement'; what: 'dies' | 'leaves_battlefield' | 'discard' | 'draw'; instead: 'exile' | 'return_to_hand' | 'return_to_library' | 'prevent'; target?: Target }
|
||||
| { op: 'cost_reduction'; target: Target; amount: Value; condition?: Condition }
|
||||
| { op: 'replacement_amount'; what: 'life_gain' | 'damage' | 'draw' | 'energy'; multiplier: number; add?: number; combatOnly?: boolean; noncombatOnly?: boolean; sourceColor?: string; controller?: 'you' | 'any' }
|
||||
| { op: 'cost_reduction'; target: Target; amount?: Value; symbols?: string; condition?: Condition }
|
||||
| { op: 'cost_increase'; amount: Value; spellType?: 'noncreature' | 'creature' }
|
||||
| { op: 'search_restriction'; who: 'opponent' | 'you'; amount: Value }
|
||||
| { op: 'exile_instead_of_graveyard'; owner?: 'opponent' | 'you' }
|
||||
| { op: 'token_multiplier'; multiplier: number; who: 'you' | 'each_player'; creatureOnly?: boolean }
|
||||
| { op: 'prevent_damage'; target: Target; amount: Value | 'all'; combatOnly?: boolean; duration: Duration; global?: boolean; sourceSelector?: ObjectSelector }
|
||||
| { op: 'counter_multiplier'; target: Target; counter?: string; multiplier: number; add?: number }
|
||||
| { op: 'token_replacement'; from: string[]; tokens: TokenSpec[]; who?: 'you' | 'each_player' }
|
||||
|
||||
export type Ability =
|
||||
| KeywordAbility
|
||||
@@ -278,6 +304,7 @@ export type Ability =
|
||||
condition?: Condition
|
||||
effects: Effect[]
|
||||
optional: boolean
|
||||
oncePerTurn?: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
@@ -308,6 +335,17 @@ export type Ability =
|
||||
optional: boolean
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'alternative_cost'
|
||||
costs: Cost[]
|
||||
condition?: Condition
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'overload'
|
||||
cost: string
|
||||
text: string
|
||||
}
|
||||
| {
|
||||
kind: 'chapter'
|
||||
chapters: string[]
|
||||
@@ -321,6 +359,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[]
|
||||
}
|
||||
@@ -328,6 +368,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[]
|
||||
|
||||
@@ -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<string, CardDefinition> {
|
||||
|
||||
45
backend/src/game/creature-types.ts
Normal file
45
backend/src/game/creature-types.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
// Scryfall's creature-type catalog (api.scryfall.com/catalog/creature-types).
|
||||
// Update when a set introduces a new type.
|
||||
export const CREATURE_TYPES = [
|
||||
'Advisor', 'Aenar', 'Aetherborn', 'Alien', 'Ally', 'Andorian', 'Android', 'Angel', 'Antelope',
|
||||
'Ape', 'Archer', 'Archon', 'Armadillo', 'Army', 'Artificer', 'Assassin', 'Assembly-Worker',
|
||||
'Astartes', 'Atog', 'Aurochs', 'Automaton', 'Avatar', 'Azra', 'Badger', 'Bajoran', 'Balloon',
|
||||
'Barbarian', 'Bard', 'Basilisk', 'Bat', 'Bear', 'Beast', 'Beaver', 'Beeble', 'Beholder',
|
||||
'Berserker', 'Betazoid', 'Bird', 'Bison', 'Blinkmoth', 'Boar', 'Borg', 'Brainiac', 'Bringer',
|
||||
'Brushwagg', "C'tan", 'Caitian', 'Camarid', 'Camel', 'Capybara', 'Cardassian', 'Caribou',
|
||||
'Carrier', 'Cat', 'Centaur', 'Chicken', 'Child', 'Chimera', 'Citizen', 'Cleric', 'Clown',
|
||||
'Cockatrice', 'Construct', 'Coward', 'Coyote', 'Crab', 'Crocodile', 'Custodes', 'Cyberman',
|
||||
'Cyclops', 'Dalek', 'Dauthi', 'Demigod', 'Demon', 'Denobulan', 'Deserter', 'Detective', 'Devil',
|
||||
'Dinosaur', 'Djinn', 'Doctor', 'Dog', 'Dragon', 'Drake', 'Dreadnought', 'Drix', 'Drone', 'Druid',
|
||||
'Dryad', 'Dwarf', 'Echidna', 'Efreet', 'Egg', 'El-Aurian', 'Elder', 'Eldrazi', 'Elemental',
|
||||
'Elephant', 'Elf', 'Elk', 'Employee', 'Eternal', 'Excalbian', 'Eye', 'Faerie', 'Ferengi',
|
||||
'Ferret', 'Fish', 'Flagbearer', 'Fox', 'Fractal', 'Frog', 'Fungus', 'Gamer', 'Gamma', 'Gargoyle',
|
||||
'Germ', 'Giant', 'Giraffe', 'Gith', 'Glimmer', 'Gnoll', 'Gnome', 'Goat', 'Goblin', 'God',
|
||||
'Golem', 'Gorgon', 'Gorn', 'Graveborn', 'Gremlin', 'Griffin', 'Guest', 'Hag', 'Halfling',
|
||||
'Hamster', 'Harpy', 'Head', 'Hedgehog', 'Hellion', 'Hero', 'Hippo', 'Hippogriff', 'Hirogen',
|
||||
'Homarid', 'Homunculus', 'Horror', 'Horse', 'Human', 'Hydra', 'Hyena', 'Illusion', 'Illyrian',
|
||||
'Imp', 'Incarnation', 'Inhuman', 'Inkling', 'Inquisitor', 'Insect', 'Jackal', 'Jellyfish',
|
||||
'Juggernaut', 'Kangaroo', 'Kavu', 'Kelpien', 'Kirin', 'Kithkin', 'Klingon', 'Knight', 'Kobold',
|
||||
'Kor', 'Kraken', 'Kree', 'Kwejian', 'Lamia', 'Lammasu', 'Lanthanite', 'Leech', 'Lemur',
|
||||
'Leviathan', 'Lhurgoyf', 'Licid', 'Lizard', 'Llama', 'Lobster', 'Manticore', 'Masticore',
|
||||
'Medusan', 'Mercenary', 'Merfolk', 'Metathran', 'Mindless-One', 'Minion', 'Minotaur', 'Mite',
|
||||
'Mole', 'Monger', 'Mongoose', 'Monk', 'Monkey', 'Moogle', 'Moonfolk', 'Mount', 'Mouse', 'Mutant',
|
||||
'Myr', 'Mystic', "Na'kuhl", 'Naga', 'Nautilus', 'Necron', 'Nephilim', 'Nightmare', 'Nightstalker',
|
||||
'Ninja', 'Noble', 'Noggle', 'Nomad', 'Nymph', 'Octopus', 'Officer', 'Ogre', 'Ooze', 'Orb', 'Orc',
|
||||
'Orgg', 'Orion', 'Otter', 'Ouphe', 'Ox', 'Oyster', 'Pangolin', 'Peasant', 'Pegasus', 'Pentavite',
|
||||
'Performer', 'Pest', 'Phelddagrif', 'Phoenix', 'Phyrexian', 'Pilot', 'Pincher', 'Pirate',
|
||||
'Plant', 'Platypus', 'Porcupine', 'Possum', 'Praetor', 'Primarch', 'Prism', 'Processor', 'Q',
|
||||
'Qu', 'Rabbit', 'Raccoon', 'Ranger', 'Rat', 'Rebel', 'Reflection', 'Reveler', 'Rhino', 'Rigger',
|
||||
'Robot', 'Rogue', 'Romulan', 'Rukh', 'Sable', 'Salamander', 'Samurai', 'Sand', 'Saproling',
|
||||
'Satyr', 'Scarecrow', 'Scientist', 'Scion', 'Scorpion', 'Scout', 'Sculpture', 'Seal', 'Serf',
|
||||
'Serpent', 'Servo', 'Shade', 'Shaman', 'Shapeshifter', 'Shark', 'Sheep', "Shi'ar", 'Siren',
|
||||
'Skeleton', 'Skrull', 'Skunk', 'Slith', 'Sliver', 'Sloth', 'Slug', 'Snail', 'Snake', 'Soldier',
|
||||
'Soltari', 'Sorcerer', 'Spawn', 'Specter', 'Spellshaper', 'Sphinx', 'Spider', 'Spike', 'Spirit',
|
||||
'Splinter', 'Sponge', 'Spy', 'Squid', 'Squirrel', 'Starfish', 'Surrakar', 'Survivor', 'Symbiote',
|
||||
'Synth', 'Talosian', 'Teddy', 'Tellarite', 'Tentacle', 'Tetravite', 'Thalakos', 'Tholian',
|
||||
'Thopter', 'Thrull', 'Tiefling', 'Time Lord', 'Tosk', 'Toy', 'Treefolk', 'Tribble', 'Trill',
|
||||
'Trilobite', 'Triskelavite', 'Troll', 'Turtle', 'Tyranid', 'Unicorn', 'Urzan', 'Utrom',
|
||||
'Vampire', 'Varmint', 'Vedalken', 'Villain', 'Volver', 'Vorta', 'Vulcan', 'Wall', 'Walrus',
|
||||
'Warlock', 'Warrior', 'Weasel', 'Weird', 'Werewolf', 'Whale', 'Wizard', 'Wolf', 'Wolverine',
|
||||
'Wombat', 'Worm', 'Wraith', 'Wurm', 'Xindi', 'Yeti', 'Zombie', 'Zubera',
|
||||
]
|
||||
970
backend/src/game/game-actions.ts
Normal file
970
backend/src/game/game-actions.ts
Normal file
@@ -0,0 +1,970 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameEffects } from './game-effects.js'
|
||||
|
||||
export abstract class GameActions extends GameEffects {
|
||||
playLand(playerId: string, cardId: string): GameObject {
|
||||
this.requirePriority(playerId)
|
||||
const player = this.getPlayer(playerId)
|
||||
if (this.activePlayer !== playerId) throw new GameError('Only the active player may play a land')
|
||||
if (this.phase !== 'precombat_main' && this.phase !== 'postcombat_main') {
|
||||
throw new GameError('Lands can only be played during a main phase')
|
||||
}
|
||||
if (this.stack.length) throw new GameError('Cannot play a land while the stack is not empty')
|
||||
if (player.landPlayedThisTurn) throw new GameError('Already played a land this turn')
|
||||
const object = this.getObject(cardId)
|
||||
if (!player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
|
||||
throw new GameError('Card is not in hand')
|
||||
}
|
||||
if (!this.isLand(object)) throw new GameError('That card is not a land')
|
||||
|
||||
player.landPlayedThisTurn = true
|
||||
this.moveToZone(object, 'battlefield', { controller: playerId, silent: false })
|
||||
this.passesInRow = 0
|
||||
this.logMessage(`${player.name} plays ${object.definition.name}`)
|
||||
this.runStateBasedActions()
|
||||
return object
|
||||
}
|
||||
|
||||
castSpell(playerId: string, cardId: string, options: ActionOptions = {}): StackItem {
|
||||
this.requirePriority(playerId)
|
||||
if (this.status !== 'active') throw new GameError('Game is not active')
|
||||
const player = this.getPlayer(playerId)
|
||||
const fromCommand = player.command.includes(cardId)
|
||||
const object = this.getObject(cardId)
|
||||
if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) {
|
||||
throw new GameError('Card is not in hand')
|
||||
}
|
||||
if (fromCommand && !object.isCommander) throw new GameError('That card cannot be cast from the command zone')
|
||||
if (this.isLand(object)) throw new GameError('Land cards are played, not cast')
|
||||
if (!this.canCastAtThisTime(playerId, object)) {
|
||||
throw new GameError('That spell cannot be cast right now')
|
||||
}
|
||||
|
||||
const abilities = object.definition.abilities ?? []
|
||||
const overload = abilities.find((ability): ability is Extract<Ability, { kind: 'overload' }> => ability.kind === 'overload')
|
||||
if (options.overload && !overload) throw new GameError('That spell has no overload')
|
||||
const baseEffects = abilities.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
|
||||
.flatMap(ability => ability.effects)
|
||||
const effects = options.overload ? this.overloadEffects(baseEffects) : baseEffects
|
||||
const targets = this.selectTargets(effects, object, playerId, options.targets ?? [], options.mode ?? 0)
|
||||
const tax = fromCommand ? (player.commanderCasts[object.id] ?? 0) * 2 : 0
|
||||
const taxSymbols = '{2}'.repeat(tax / 2)
|
||||
const extra = this.spellCostIncrease(object)
|
||||
const alternative = this.alternativeCostFor(object)
|
||||
if (options.overload && overload) {
|
||||
this.payMana(playerId, `${this.reducedSpellCost(object, overload.cost)}${taxSymbols}${extra ? `{${extra}}` : ''}`, options.x ?? 0)
|
||||
} else if (alternative) {
|
||||
this.payAlternativeCost(alternative, playerId, object)
|
||||
if (extra) this.payMana(playerId, `{${extra}}`, 0)
|
||||
} else {
|
||||
const cost = this.reducedSpellCost(object, object.definition.manaCost ?? '')
|
||||
this.payMana(playerId, `${cost}${taxSymbols}${extra ? `{${extra}}` : ''}`, options.x ?? 0)
|
||||
}
|
||||
|
||||
this.moveToZone(object, 'stack', { controller: playerId, silent: true })
|
||||
if (fromCommand) player.commanderCasts[object.id] = (player.commanderCasts[object.id] ?? 0) + 1
|
||||
const item: StackItem = {
|
||||
id: this.generateId('stack'),
|
||||
kind: 'spell',
|
||||
source: object,
|
||||
controller: playerId,
|
||||
label: object.definition.name,
|
||||
effects,
|
||||
targets,
|
||||
x: options.x ?? 0,
|
||||
mode: options.mode ?? 0,
|
||||
optional: abilities.some(ability => ability.kind === 'spell' && ability.optional),
|
||||
}
|
||||
this.stack.push(item)
|
||||
player.spellsCastThisTurn++
|
||||
this.passesInRow = 0
|
||||
this.priority = this.nextAlivePlayer(playerId)
|
||||
this.dispatchEvent({ kind: 'cast', player: playerId, subject: object, spell: object, spellItem: item })
|
||||
this.logMessage(`${player.name} casts ${object.definition.name}`)
|
||||
return item
|
||||
}
|
||||
|
||||
protected alternativeCostFor(object: GameObject): Extract<Ability, { kind: 'alternative_cost' }> | undefined {
|
||||
return (object.definition.abilities ?? []).find(ability =>
|
||||
ability.kind === 'alternative_cost'
|
||||
&& (!ability.condition || this.checkCondition(ability.condition, object))) as
|
||||
| Extract<Ability, { kind: 'alternative_cost' }>
|
||||
| undefined
|
||||
}
|
||||
|
||||
protected payAlternativeCost(
|
||||
ability: Extract<Ability, { kind: 'alternative_cost' }>,
|
||||
playerId: string,
|
||||
source: GameObject,
|
||||
): void {
|
||||
if (!ability.costs.length) return
|
||||
this.payCosts(ability.costs, playerId, source, this.contextFor(source, playerId, [], 0, 0))
|
||||
}
|
||||
|
||||
protected spellCostIncrease(object: GameObject): number {
|
||||
let extra = 0
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'cost_increase') continue
|
||||
if (effect.spellType === 'noncreature' && this.isCreature(object)) continue
|
||||
if (effect.spellType === 'creature' && !this.isCreature(object)) continue
|
||||
extra += this.value(effect.amount, this.staticContext(source))
|
||||
}
|
||||
}
|
||||
return extra
|
||||
}
|
||||
|
||||
// shortcut: only static reducers on the battlefield; a card's own "this spell
|
||||
// costs less" text is not applied yet. Upgrade when self-cost cards matter.
|
||||
protected spellCostReduction(object: GameObject): CostReduction {
|
||||
const reduction: CostReduction = { generic: 0, colored: [] }
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'cost_reduction' || effect.target.kind !== 'object') continue
|
||||
if (!this.matchesSelector(object, effect.target.selector, source, object.zone)) continue
|
||||
if (effect.amount) reduction.generic += this.value(effect.amount, this.staticContext(source))
|
||||
if (effect.symbols) {
|
||||
const cost = parseManaCost(effect.symbols)
|
||||
reduction.generic += cost.generic
|
||||
reduction.colored.push(...cost.colored)
|
||||
}
|
||||
}
|
||||
}
|
||||
return reduction
|
||||
}
|
||||
|
||||
protected reducedSpellCost(object: GameObject, symbols: string): string {
|
||||
return reduceManaSymbols(symbols, this.spellCostReduction(object))
|
||||
}
|
||||
|
||||
// shortcut: overload only widens top-level targets; modal/conditional nested
|
||||
// effects keep their original targets. Upgrade when an overload card nests them.
|
||||
protected overloadEffects(effects: Effect[]): Effect[] {
|
||||
return effects.map(effect => ('target' in effect && effect.target
|
||||
? { ...effect, target: this.overloadTarget(effect.target) }
|
||||
: effect))
|
||||
}
|
||||
|
||||
protected overloadTarget(target: Target): Target {
|
||||
if (target.kind === 'object' || target.kind === 'player' || target.kind === 'spell') {
|
||||
return { ...target, mode: 'each' }
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
activateAbility(playerId: string, sourceId: string, abilityIndex: number, options: ActionOptions = {}): StackItem | undefined {
|
||||
this.requirePriority(playerId)
|
||||
const source = this.getObject(sourceId)
|
||||
if (source.zone !== 'battlefield') throw new GameError('Ability source is not on the battlefield')
|
||||
if (source.controller !== playerId) throw new GameError('You do not control that permanent')
|
||||
if (this.hasRestriction(source, 'cant_activate')) throw new GameError('That permanent cannot activate abilities')
|
||||
const ability = (source.definition.abilities ?? [])[abilityIndex]
|
||||
if (!ability || ability.kind !== 'activated') throw new GameError('That is not an activated ability')
|
||||
if (ability.condition && !this.checkCondition(ability.condition, source)) throw new GameError('Ability condition is not met')
|
||||
if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) {
|
||||
throw new GameError('Activate only as a sorcery')
|
||||
}
|
||||
if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source)
|
||||
&& source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) {
|
||||
throw new GameError('That creature has summoning sickness')
|
||||
}
|
||||
const activations = source.activations[abilityIndex] ?? 0
|
||||
if (ability.activationsPerTurn !== undefined && activations >= ability.activationsPerTurn) {
|
||||
throw new GameError('Ability activation limit reached')
|
||||
}
|
||||
if (options.manaColor && !this.manaColorChoices(source, abilityIndex)?.includes(options.manaColor)) {
|
||||
throw new GameError('That ability cannot produce that mana')
|
||||
}
|
||||
|
||||
const targets = this.selectTargets(ability.effects, source, playerId, options.targets ?? [], options.mode ?? 0)
|
||||
const context = this.contextFor(source, playerId, targets, options.x ?? 0, options.mode ?? 0)
|
||||
context.manaColor = options.manaColor
|
||||
this.payCosts(ability.costs, playerId, source, context)
|
||||
source.activations[abilityIndex] = activations + 1
|
||||
|
||||
// Mana abilities bypass the stack, which also makes auto-payment possible.
|
||||
if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) {
|
||||
this.applyEffects(context, ability.effects)
|
||||
this.passesInRow = 0
|
||||
this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`)
|
||||
return undefined
|
||||
}
|
||||
|
||||
const item: StackItem = {
|
||||
id: this.generateId('stack'),
|
||||
kind: 'ability',
|
||||
source,
|
||||
controller: playerId,
|
||||
label: ability.text,
|
||||
effects: ability.effects,
|
||||
targets,
|
||||
x: options.x ?? 0,
|
||||
mode: options.mode ?? 0,
|
||||
optional: ability.optional,
|
||||
}
|
||||
this.stack.push(item)
|
||||
this.passesInRow = 0
|
||||
this.priority = this.nextAlivePlayer(playerId)
|
||||
this.logMessage(`${this.getPlayer(playerId).name} activates ${source.definition.name}`)
|
||||
return item
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the player could legally play a card from hand or the command zone
|
||||
* right now. Used for the client's playable state and for auto-passing.
|
||||
*/
|
||||
canPlayCard(playerId: string, cardId: string): boolean {
|
||||
if (this.status !== 'active' || this.priority !== playerId || this.pendingSearch || this.pendingChoice) return false
|
||||
const player = this.getPlayer(playerId)
|
||||
const fromCommand = player.command.includes(cardId)
|
||||
const object = this.getObject(cardId)
|
||||
if (!fromCommand && !player.hand.includes(cardId) && !this.playableFromExile(playerId, object)) return false
|
||||
if (fromCommand && !object.isCommander) return false
|
||||
|
||||
if (this.isLand(object)) {
|
||||
return this.activePlayer === playerId
|
||||
&& (this.phase === 'precombat_main' || this.phase === 'postcombat_main')
|
||||
&& !this.stack.length
|
||||
&& !player.landPlayedThisTurn
|
||||
}
|
||||
|
||||
if (!this.canCastAtThisTime(playerId, object)) return false
|
||||
const tax = fromCommand ? (player.commanderCasts[cardId] ?? 0) * 2 : 0
|
||||
const extra = this.spellCostIncrease(object)
|
||||
const alternative = this.alternativeCostFor(object)
|
||||
if (alternative) {
|
||||
for (const cost of alternative.costs) {
|
||||
if (cost.kind !== 'mana' || !this.canAffordMana(playerId, cost.symbols, 0)) return false
|
||||
}
|
||||
} else if (!this.canAffordMana(
|
||||
playerId,
|
||||
`${this.reducedSpellCost(object, object.definition.manaCost ?? '')}${'{2}'.repeat(tax / 2)}${extra ? `{${extra}}` : ''}`,
|
||||
0,
|
||||
)) {
|
||||
return false
|
||||
}
|
||||
if (alternative && extra && !this.canAffordMana(playerId, `{${extra}}`, 0)) return false
|
||||
return this.hasLegalTargets(object, playerId)
|
||||
}
|
||||
|
||||
/** Junk and other impulse effects grant a one-turn play permission from exile. */
|
||||
protected playableFromExile(playerId: string, object: GameObject): boolean {
|
||||
return object.zone === 'exile'
|
||||
&& object.owner === playerId
|
||||
&& object.playableFromExileTurn === this.turn
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes one pick of a paused library search. Searches pause when several
|
||||
* cards match so the player chooses instead of taking the first one.
|
||||
*/
|
||||
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('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')
|
||||
|
||||
this.moveSearchedCard(object, playerId, pending.destination, pending.tapped)
|
||||
pending.remaining--
|
||||
if (pending.remaining > 0 && pending.split) {
|
||||
pending.destination = pending.split.destination
|
||||
pending.tapped = pending.split.tapped
|
||||
pending.split = undefined
|
||||
}
|
||||
if (pending.remaining <= 0 || !this.searchCandidates(playerId).length) {
|
||||
this.pendingSearch = undefined
|
||||
if (pending.shuffle) this.shuffleLibrary(this.getPlayer(playerId))
|
||||
this.priority = this.getPlayer(this.activePlayer).lost
|
||||
? this.nextAlivePlayer(this.activePlayer)
|
||||
: this.activePlayer
|
||||
}
|
||||
this.runStateBasedActions()
|
||||
}
|
||||
|
||||
/** Cards the pending search may pick, in library order. Empty for other players. */
|
||||
searchCandidates(playerId: string): GameObject[] {
|
||||
const pending = this.pendingSearch
|
||||
if (!pending || pending.playerId !== playerId) return []
|
||||
return this.findSearchCandidates(playerId, pending.selector, pending.zones)
|
||||
}
|
||||
|
||||
/**
|
||||
* Every card in the zones a pending search can look at, in search order. This
|
||||
* is what the chooser sees while deciding; others get an empty list.
|
||||
*/
|
||||
searchPool(playerId: string): GameObject[] {
|
||||
const pending = this.pendingSearch
|
||||
if (!pending || pending.playerId !== playerId) return []
|
||||
return this.searchableObjects(playerId, pending.zones)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers the hideaway look: exiles the chosen card linked to the source and
|
||||
* puts the rest on the bottom of the library in a random order.
|
||||
*/
|
||||
chooseHideawayCard(playerId: string, cardId: string): void {
|
||||
const pending = this.pendingChoice
|
||||
if (!pending || pending.what !== 'hideaway') throw new GameError('No hideaway choice is waiting')
|
||||
if (pending.playerId !== playerId) throw new GameError('You are not choosing this hideaway card')
|
||||
const looked = (pending.cardIds ?? []).map(id => this.getObject(id))
|
||||
const hidden = looked.find(object => object.id === cardId && object.zone === 'library')
|
||||
if (!hidden) throw new GameError('That card is not a legal choice')
|
||||
|
||||
this.pendingChoices.shift()
|
||||
this.moveToZone(hidden, 'exile', { silent: true })
|
||||
const source = this.objects.get(pending.sourceId)
|
||||
if (hidden.zone === 'exile') {
|
||||
hidden.faceDown = true
|
||||
if (source) source.linkedExile = [...(source.linkedExile ?? []), hidden.id]
|
||||
}
|
||||
|
||||
const rest = looked.filter(object => object.id !== hidden.id)
|
||||
for (let index = rest.length - 1; index > 0; index--) {
|
||||
const swap = Math.floor(this.rng() * (index + 1))
|
||||
const temp = rest[index]
|
||||
rest[index] = rest[swap]
|
||||
rest[swap] = temp
|
||||
}
|
||||
for (const object of rest) this.moveToZone(object, 'library', { silent: true })
|
||||
this.logMessage(`${this.getPlayer(playerId).name} hides away a card`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers an "as this enters, choose a creature type" prompt. The match API
|
||||
* uses the `choose_type` action.
|
||||
*/
|
||||
chooseCreatureType(playerId: string, type: string): void {
|
||||
const pending = this.pendingChoice
|
||||
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')
|
||||
const object = this.objects.get(pending.sourceId)
|
||||
if (!object || object.zone !== 'battlefield') throw new GameError('That permanent is no longer on the battlefield')
|
||||
object.chosenCreatureType = chosen
|
||||
this.pendingChoices.shift()
|
||||
this.logMessage(`${this.getPlayer(playerId).name} chooses ${chosen} for ${object.definition.name}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers an "as this enters, choose a color" prompt. The match API uses the
|
||||
* `choose_color` action.
|
||||
*/
|
||||
chooseColor(playerId: string, color: string): void {
|
||||
const pending = this.pendingChoice
|
||||
if (!pending || pending.what !== 'color') throw new GameError('No color choice is waiting')
|
||||
if (pending.playerId !== playerId) throw new GameError('You are not choosing this permanent\'s color')
|
||||
const chosen = COLOR_NAMES[color.trim().toLowerCase()]
|
||||
if (!chosen) throw new GameError('Choose a color')
|
||||
const object = this.objects.get(pending.sourceId)
|
||||
if (!object || object.zone !== 'battlefield') throw new GameError('That permanent is no longer on the battlefield')
|
||||
object.chosenColor = chosen
|
||||
this.pendingChoices.shift()
|
||||
this.logMessage(`${this.getPlayer(playerId).name} chooses ${color} for ${object.definition.name}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a "you may ..." prompt for the top stack item. The match API uses
|
||||
* the `choose_optional` action.
|
||||
*/
|
||||
chooseOptional(playerId: string, accept: boolean): void {
|
||||
const pending = this.pendingChoice
|
||||
if (!pending || pending.what !== 'optional') throw new GameError('No optional effect is waiting')
|
||||
if (pending.playerId !== playerId) throw new GameError('You are not choosing this optional effect')
|
||||
const item = this.stack[this.stack.length - 1]
|
||||
if (!item) throw new GameError('No effect is waiting')
|
||||
this.pendingChoices.shift()
|
||||
item.optionalAccepted = accept
|
||||
this.resolveTop()
|
||||
}
|
||||
|
||||
/**
|
||||
* 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()
|
||||
}
|
||||
|
||||
protected selectTargets(
|
||||
effects: Effect[],
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
provided: TargetChoice[],
|
||||
mode: number,
|
||||
): TargetChoice[] {
|
||||
const selected: TargetChoice[] = []
|
||||
const queue = [...provided]
|
||||
|
||||
const take = (target: Target, playerOnly: 'opponent' | 'any' | undefined): void => {
|
||||
if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target' || target.kind === 'damaged') return
|
||||
if (target.kind === 'object' && target.mode === 'each') return
|
||||
if (target.kind === 'player' && target.mode === 'each') return
|
||||
const count = target.kind === 'object' ? target.count ?? 1 : 1
|
||||
const upTo = target.kind === 'object' && Boolean(target.upTo)
|
||||
for (let i = 0; i < count; i++) {
|
||||
const explicit = queue.shift()
|
||||
if (explicit) {
|
||||
if (!this.targetChoiceMatches(explicit, target, source, playerOnly)) throw new GameError('Invalid target')
|
||||
selected.push(explicit)
|
||||
continue
|
||||
}
|
||||
const legal = this.legalTargets(target, source, controller, playerOnly)
|
||||
if (!legal.length) {
|
||||
if (upTo) break
|
||||
throw new GameError('No legal target')
|
||||
}
|
||||
selected.push(legal[0])
|
||||
}
|
||||
}
|
||||
|
||||
const walk = (list: Effect[]): void => {
|
||||
for (const effect of list) {
|
||||
if (effect.op === 'conditional') {
|
||||
walk(effect.effects)
|
||||
continue
|
||||
}
|
||||
if (effect.op === 'modal') {
|
||||
const chosen = effect.modes[mode] ?? effect.modes[0] ?? []
|
||||
walk(chosen)
|
||||
continue
|
||||
}
|
||||
if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) {
|
||||
const who = effect.player === 'opponent' ? 'opponent' : 'any'
|
||||
take({ kind: 'player', who: effect.player, mode: 'target' }, who)
|
||||
}
|
||||
if ('target' in effect && effect.target) take(effect.target, undefined)
|
||||
if (effect.op === 'create_token') {
|
||||
if (effect.copyOf) take(effect.copyOf, undefined)
|
||||
if (effect.attachTo) take(effect.attachTo, undefined)
|
||||
}
|
||||
if (effect.op === 'fight') {
|
||||
take(effect.a, undefined)
|
||||
take(effect.b, undefined)
|
||||
}
|
||||
if (effect.op === 'damage_divided') take(effect.target, undefined)
|
||||
}
|
||||
}
|
||||
walk(effects)
|
||||
return selected
|
||||
}
|
||||
|
||||
/** Legal choices for a card's targets, so the UI can offer only real targets. */
|
||||
legalTargetsForCard(playerId: string, cardId: string): TargetChoice[] {
|
||||
const source = this.objects.get(cardId)
|
||||
if (!source) return []
|
||||
const effects = (source.definition.abilities ?? [])
|
||||
.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
|
||||
.flatMap(ability => ability.effects)
|
||||
return this.collectTargets(effects, source, playerId, 0)
|
||||
}
|
||||
|
||||
/** Legal choices for an activated ability's targets. */
|
||||
legalTargetsForAbility(playerId: string, sourceId: string, abilityIndex: number): TargetChoice[] {
|
||||
const source = this.objects.get(sourceId)
|
||||
const ability = source?.definition.abilities?.[abilityIndex]
|
||||
if (!source || !ability || ability.kind !== 'activated') return []
|
||||
return this.collectTargets(ability.effects, source, playerId, 0)
|
||||
}
|
||||
|
||||
protected collectTargets(
|
||||
effects: Effect[],
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
mode: number,
|
||||
): TargetChoice[] {
|
||||
const choices = new Map<string, TargetChoice>()
|
||||
const add = (target: Target, playerOnly?: 'opponent' | 'any'): void => {
|
||||
if (target.kind === 'self' || target.kind === 'trigger_subject' || target.kind === 'previous_target' || target.kind === 'damaged') return
|
||||
if ((target.kind === 'object' || target.kind === 'player') && target.mode === 'each') return
|
||||
for (const choice of this.legalTargets(target, source, controller, playerOnly)) {
|
||||
choices.set(`${choice.kind}:${choice.id}`, choice)
|
||||
}
|
||||
}
|
||||
const walk = (list: Effect[]): void => {
|
||||
for (const effect of list) {
|
||||
if (effect.op === 'conditional') {
|
||||
walk(effect.effects)
|
||||
continue
|
||||
}
|
||||
if (effect.op === 'modal') {
|
||||
walk(effect.modes[mode] ?? effect.modes[0] ?? [])
|
||||
continue
|
||||
}
|
||||
if ('player' in effect && (effect.player === 'target_player' || effect.player === 'opponent')) {
|
||||
add(
|
||||
{ kind: 'player', who: effect.player, mode: 'target' },
|
||||
effect.player === 'opponent' ? 'opponent' : 'any',
|
||||
)
|
||||
}
|
||||
if ('target' in effect && effect.target) add(effect.target)
|
||||
if (effect.op === 'create_token') {
|
||||
if (effect.copyOf) add(effect.copyOf)
|
||||
if (effect.attachTo) add(effect.attachTo)
|
||||
}
|
||||
if (effect.op === 'fight') {
|
||||
add(effect.a)
|
||||
add(effect.b)
|
||||
}
|
||||
if (effect.op === 'damage_divided') add(effect.target)
|
||||
}
|
||||
}
|
||||
walk(effects)
|
||||
return [...choices.values()]
|
||||
}
|
||||
|
||||
protected legalTargets(
|
||||
target: Target,
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
playerOnly: 'opponent' | 'any' | undefined,
|
||||
): TargetChoice[] {
|
||||
switch (target.kind) {
|
||||
case 'object': {
|
||||
return this.objectsMatching(target.selector, source)
|
||||
.map(object => ({ kind: 'object' as const, id: object.id }))
|
||||
}
|
||||
case 'player': {
|
||||
const players = playerOnly === 'opponent' ? this.opponentsOf(controller) : this.alivePlayers().map(player => player.id)
|
||||
return players.map(id => ({ kind: 'player' as const, id }))
|
||||
}
|
||||
case 'player_or_planeswalker': {
|
||||
const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id }))
|
||||
for (const object of this.battlefieldObjects()) {
|
||||
if (this.hasType(object, 'planeswalker')) choices.push({ kind: 'object', id: object.id })
|
||||
}
|
||||
return choices
|
||||
}
|
||||
case 'any': {
|
||||
const choices: TargetChoice[] = this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id }))
|
||||
for (const object of this.battlefieldObjects()) choices.push({ kind: 'object', id: object.id })
|
||||
return choices
|
||||
}
|
||||
case 'spell':
|
||||
return [...this.stack].reverse()
|
||||
.filter(item => item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack'))
|
||||
.map(item => ({ kind: 'spell' as const, id: item.id }))
|
||||
case 'ability':
|
||||
return [...this.stack].reverse()
|
||||
.filter(item => item.kind === 'ability')
|
||||
.map(item => ({ kind: 'spell' as const, id: item.id }))
|
||||
case 'divided':
|
||||
return this.opponentsOf(controller).map(id => ({ kind: 'player' as const, id }))
|
||||
default:
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
protected targetChoiceMatches(
|
||||
choice: TargetChoice,
|
||||
target: Target,
|
||||
source: GameObject,
|
||||
playerOnly: 'opponent' | 'any' | undefined,
|
||||
): boolean {
|
||||
const isOpponent = (id: string): boolean => this.opponentsOf(source.controller).includes(id)
|
||||
if (choice.kind === 'player') {
|
||||
if (target.kind === 'any' || target.kind === 'player' || target.kind === 'player_or_planeswalker') {
|
||||
return playerOnly !== 'opponent' || isOpponent(choice.id)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (choice.kind === 'object') {
|
||||
const object = this.objects.get(choice.id)
|
||||
if (!object) return false
|
||||
if (target.kind === 'any' || target.kind === 'player_or_planeswalker') {
|
||||
return target.kind === 'any' ? object.zone === 'battlefield' : this.hasType(object, 'planeswalker')
|
||||
}
|
||||
if (target.kind !== 'object') return false
|
||||
return this.matchesSelector(object, target.selector, source)
|
||||
}
|
||||
if (choice.kind === 'spell') {
|
||||
const item = this.findStackItem(choice.id)
|
||||
if (!item) return false
|
||||
if (target.kind === 'spell') {
|
||||
return item.kind === 'spell' && this.matchesSelector(item.source, target.selector, source, 'stack')
|
||||
}
|
||||
return target.kind === 'ability' && item.kind === 'ability'
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
protected resolveTargets(context: EffectContext, target: Target): ResolvedTarget[] {
|
||||
let result: ResolvedTarget[] = []
|
||||
switch (target.kind) {
|
||||
case 'self':
|
||||
result = [{ kind: 'object', object: context.source }]
|
||||
break
|
||||
case 'trigger_subject':
|
||||
if (context.triggerSubject) result = [{ kind: 'object', object: context.triggerSubject }]
|
||||
break
|
||||
case 'previous_target':
|
||||
if (context.lastTarget) result = [context.lastTarget]
|
||||
break
|
||||
case 'damaged':
|
||||
result = (context.lastDamaged ?? []).map(object => ({ kind: 'object' as const, object }))
|
||||
break
|
||||
case 'object':
|
||||
if (target.mode === 'each') {
|
||||
result = this.objectsMatching(target.selector, context.source)
|
||||
.map(object => ({ kind: 'object' as const, object }))
|
||||
} else {
|
||||
const count = target.count ?? 1
|
||||
for (let i = 0; i < count; i++) {
|
||||
const choice = context.targets.shift()
|
||||
if (!choice) break
|
||||
if (choice.kind === 'object') {
|
||||
const object = this.objects.get(choice.id)
|
||||
if (object) result.push({ kind: 'object', object })
|
||||
}
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'player':
|
||||
if (target.mode === 'each') {
|
||||
result = this.playersForEffect(target.who, context).map(id => ({ kind: 'player' as const, id }))
|
||||
} else {
|
||||
const choice = context.targets.shift()
|
||||
if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }]
|
||||
else {
|
||||
const id = this.playersForEffect(target.who, context)[0]
|
||||
if (id) result = [{ kind: 'player', id }]
|
||||
}
|
||||
}
|
||||
break
|
||||
case 'player_or_planeswalker':
|
||||
case 'any': {
|
||||
const choice = context.targets.shift()
|
||||
if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }]
|
||||
else if (choice?.kind === 'object') {
|
||||
const object = this.objects.get(choice.id)
|
||||
if (object) result = [{ kind: 'object', object }]
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'spell':
|
||||
case 'ability': {
|
||||
const choice = context.targets.shift()
|
||||
if (choice?.kind === 'spell') {
|
||||
const item = this.findStackItem(choice.id)
|
||||
if (item) result = [{ kind: 'stack', item }]
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'divided': {
|
||||
const choice = context.targets.shift()
|
||||
if (choice?.kind === 'player') result = [{ kind: 'player', id: choice.id }]
|
||||
else if (choice?.kind === 'object') {
|
||||
const object = this.objects.get(choice.id)
|
||||
if (object) result = [{ kind: 'object', object }]
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
if (result.length) context.lastTarget = result[0]
|
||||
return result
|
||||
}
|
||||
|
||||
protected playersForEffect(ref: PlayerRef, context: EffectContext): string[] {
|
||||
const controller = context.source.controller
|
||||
switch (ref) {
|
||||
case 'you':
|
||||
return [controller]
|
||||
case 'opponent': {
|
||||
const choice = context.targets.shift()
|
||||
if (choice?.kind === 'player') return [choice.id]
|
||||
return [this.opponentsOf(controller)[0]].filter(Boolean)
|
||||
}
|
||||
case 'each_opponent':
|
||||
return this.opponentsOf(controller)
|
||||
case 'each_player':
|
||||
return this.alivePlayers().map(player => player.id)
|
||||
case 'target_player': {
|
||||
const choice = context.targets.shift()
|
||||
return [choice?.kind === 'player' ? choice.id : undefined].filter((id): id is string => Boolean(id))
|
||||
}
|
||||
case 'that_player':
|
||||
return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean)
|
||||
case 'its_controller':
|
||||
return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : []
|
||||
case 'its_owner':
|
||||
return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : []
|
||||
}
|
||||
}
|
||||
|
||||
protected playersForValue(ref: PlayerRef, context: EffectContext): string[] {
|
||||
const controller = context.source.controller
|
||||
switch (ref) {
|
||||
case 'you':
|
||||
return [controller]
|
||||
case 'opponent':
|
||||
return [this.opponentsOf(controller)[0]].filter(Boolean)
|
||||
case 'each_opponent':
|
||||
return this.opponentsOf(controller)
|
||||
case 'each_player':
|
||||
return this.alivePlayers().map(player => player.id)
|
||||
case 'target_player':
|
||||
return [context.lastTarget?.kind === 'player' ? context.lastTarget.id : this.opponentsOf(controller)[0]].filter(Boolean)
|
||||
case 'that_player':
|
||||
return [context.eventPlayer ?? this.opponentsOf(controller)[0]].filter(Boolean)
|
||||
case 'its_controller':
|
||||
return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.controller] : []
|
||||
case 'its_owner':
|
||||
return context.lastTarget?.kind === 'object' ? [context.lastTarget.object.owner] : []
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Effects
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void {
|
||||
for (const cost of costs) {
|
||||
if (cost.kind !== 'mana' && !this.canPayNonManaCost(cost, playerId, source)) {
|
||||
throw new GameError('Cannot pay ability cost')
|
||||
}
|
||||
}
|
||||
for (const cost of costs) {
|
||||
if (cost.kind === 'mana') this.payMana(playerId, cost.symbols, context.x)
|
||||
else this.payNonManaCost(cost, playerId, source, context)
|
||||
}
|
||||
}
|
||||
|
||||
protected canPayNonManaCost(cost: Cost, playerId: string, source: GameObject): boolean {
|
||||
const player = this.getPlayer(playerId)
|
||||
switch (cost.kind) {
|
||||
case 'tap':
|
||||
return !source.tapped
|
||||
case 'untap':
|
||||
return source.tapped
|
||||
case 'tap_other':
|
||||
return this.objectsMatching(cost.selector, source).some(object => !object.tapped)
|
||||
case 'energy':
|
||||
return player.energy >= cost.amount
|
||||
case 'pay_life':
|
||||
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':
|
||||
return this.objectsMatching(cost.selector, source).length > 0
|
||||
case 'sacrifice_self':
|
||||
return source.zone === 'battlefield'
|
||||
case 'exile_self':
|
||||
return source.zone === 'graveyard'
|
||||
case 'exile_from_graveyard':
|
||||
return this.objectsMatching(cost.selector, source).length > 0
|
||||
case 'return_to_hand':
|
||||
return this.objectsMatching(cost.selector, source).length > 0
|
||||
case 'put_counter':
|
||||
return this.objectsMatching(cost.selector, source).length > 0
|
||||
case 'remove_counters': {
|
||||
const amount = this.value(cost.amount, this.staticContext(source))
|
||||
const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source]
|
||||
return objects.some(object => (object.counters[cost.counter] ?? 0) >= amount)
|
||||
}
|
||||
case 'mill':
|
||||
return player.library.length >= (cost.amount.kind === 'number' ? cost.amount.value : 0)
|
||||
case 'choice':
|
||||
return cost.options.some(option => option.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source)))
|
||||
case 'waterbend':
|
||||
return this.canPayMana(player, parseManaCost('{0}', 0))
|
||||
case 'reveal':
|
||||
case 'behold':
|
||||
case 'choose':
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
protected payNonManaCost(cost: Cost, playerId: string, source: GameObject, context: EffectContext): void {
|
||||
const player = this.getPlayer(playerId)
|
||||
switch (cost.kind) {
|
||||
case 'tap':
|
||||
source.tapped = true
|
||||
return
|
||||
case 'untap':
|
||||
source.tapped = false
|
||||
return
|
||||
case 'tap_other': {
|
||||
const target = this.objectsMatching(cost.selector, source).find(object => !object.tapped)
|
||||
if (!target) throw new GameError('No permanent to tap')
|
||||
target.tapped = true
|
||||
return
|
||||
}
|
||||
case 'energy':
|
||||
player.energy -= cost.amount
|
||||
return
|
||||
case 'loyalty':
|
||||
this.addCounters(source, 'loyalty', cost.amount, true)
|
||||
return
|
||||
case 'pay_life':
|
||||
this.loseLife(playerId, this.value(cost.amount, context))
|
||||
return
|
||||
case 'discard': {
|
||||
const amount = this.value(cost.amount, context)
|
||||
this.discardCards(playerId, amount, cost.random, context)
|
||||
return
|
||||
}
|
||||
case 'sacrifice': {
|
||||
const target = this.objectsMatching(cost.selector, source)[0]
|
||||
if (!target) throw new GameError('No permanent to sacrifice')
|
||||
this.moveToZone(target, 'graveyard', { silent: false })
|
||||
return
|
||||
}
|
||||
case 'sacrifice_self':
|
||||
this.moveToZone(source, 'graveyard', { silent: false })
|
||||
return
|
||||
case 'exile_self':
|
||||
this.moveToZone(source, 'exile', { silent: false })
|
||||
return
|
||||
case 'exile_from_graveyard': {
|
||||
const target = this.objectsMatching(cost.selector, source)[0]
|
||||
if (!target) throw new GameError('No card to exile')
|
||||
this.moveToZone(target, 'exile', { silent: false })
|
||||
return
|
||||
}
|
||||
case 'return_to_hand': {
|
||||
const target = this.objectsMatching(cost.selector, source)[0]
|
||||
if (!target) throw new GameError('No permanent to return')
|
||||
this.moveToZone(target, 'hand', { silent: false })
|
||||
return
|
||||
}
|
||||
case 'put_counter': {
|
||||
const target = this.objectsMatching(cost.selector, source)[0]
|
||||
if (!target) throw new GameError('No permanent for counter')
|
||||
this.addCounters(target, cost.counter, 1)
|
||||
return
|
||||
}
|
||||
case 'remove_counters': {
|
||||
const amount = this.value(cost.amount, context)
|
||||
const objects = cost.selector ? this.objectsMatching(cost.selector, source) : [source]
|
||||
const target = objects.find(object => (object.counters[cost.counter] ?? 0) >= amount)
|
||||
if (!target) throw new GameError('No counters to remove')
|
||||
target.counters[cost.counter] = Math.max(0, (target.counters[cost.counter] ?? 0) - amount)
|
||||
return
|
||||
}
|
||||
case 'mill':
|
||||
this.millCards(playerId, this.value(cost.amount, context))
|
||||
return
|
||||
case 'reveal':
|
||||
case 'behold':
|
||||
case 'choose':
|
||||
return
|
||||
case 'choice': {
|
||||
const option = cost.options.find(entries => entries.every(entry => entry.kind === 'mana' || this.canPayNonManaCost(entry, playerId, source)))
|
||||
if (!option) throw new GameError('No payable cost choice')
|
||||
this.payCosts(option, playerId, source, context)
|
||||
return
|
||||
}
|
||||
case 'waterbend':
|
||||
case 'blight':
|
||||
case 'forage':
|
||||
case 'collect_evidence':
|
||||
throw new GameError(`Unsupported cost: ${cost.kind}`)
|
||||
default:
|
||||
throw new GameError(`Unsupported cost: ${(cost as { kind: string }).kind}`)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Targeting
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected hasLegalTargets(source: GameObject, playerId: string, effects?: Effect[]): boolean {
|
||||
const list = effects ?? (source.definition.abilities ?? [])
|
||||
.filter((ability): ability is Extract<Ability, { kind: 'spell' }> => ability.kind === 'spell')
|
||||
.flatMap(ability => ability.effects)
|
||||
try {
|
||||
this.selectTargets(list, source, playerId, [], 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (error instanceof GameError) return false
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
protected isActivatedAbilityPlayable(
|
||||
playerId: string,
|
||||
source: GameObject,
|
||||
index: number,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
): boolean {
|
||||
if (source.zone !== 'battlefield' || source.controller !== playerId) return false
|
||||
if (this.hasRestriction(source, 'cant_activate')) return false
|
||||
if (ability.condition && !this.checkCondition(ability.condition, source)) return false
|
||||
if (ability.timing === 'sorcery' && !this.isMainPhaseWithEmptyStack(playerId)) return false
|
||||
if (ability.costs.some(cost => cost.kind === 'tap') && this.isCreature(source)
|
||||
&& source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) {
|
||||
return false
|
||||
}
|
||||
if (ability.activationsPerTurn !== undefined
|
||||
&& (source.activations[index] ?? 0) >= ability.activationsPerTurn) {
|
||||
return false
|
||||
}
|
||||
for (const cost of ability.costs) {
|
||||
if (cost.kind === 'mana') {
|
||||
if (!this.canAffordMana(playerId, cost.symbols, 0)) return false
|
||||
} else if (!this.canPayNonManaCost(cost, playerId, source)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return this.hasLegalTargets(source, playerId, ability.effects)
|
||||
}
|
||||
}
|
||||
468
backend/src/game/game-base.ts
Normal file
468
backend/src/game/game-base.ts
Normal file
@@ -0,0 +1,468 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
|
||||
/**
|
||||
* A deliberately small but real Magic rules engine: zones, priority, the stack,
|
||||
* turn phases, combat, state-based actions, mana, triggered/activated/static
|
||||
* abilities, and an interpreter for the compiled card-effect AST.
|
||||
*/
|
||||
export abstract class GameBase {
|
||||
readonly players: PlayerState[]
|
||||
|
||||
readonly objects = new Map<string, GameObject>()
|
||||
|
||||
readonly stack: StackItem[] = []
|
||||
|
||||
readonly log: string[] = []
|
||||
|
||||
turn = 0
|
||||
|
||||
activePlayer = ''
|
||||
|
||||
phase: Phase = 'beginning'
|
||||
|
||||
step: Step = 'untap'
|
||||
|
||||
priority = ''
|
||||
|
||||
status: 'not_started' | 'mulligan' | 'active' | 'finished' = 'not_started'
|
||||
winner?: string
|
||||
|
||||
/** Opening-hand choices, keyed by player id. */
|
||||
readonly mulligans = new Map<string, MulliganState>()
|
||||
/** Blocks all other actions until the searching player picks a card. */
|
||||
pendingSearch?: PendingSearch
|
||||
|
||||
/** "As this enters, choose..." prompts, in entry order. */
|
||||
readonly pendingChoices: PendingChoice[] = []
|
||||
|
||||
get pendingChoice(): PendingChoice | undefined {
|
||||
return this.pendingChoices[0]
|
||||
}
|
||||
|
||||
protected readonly config: GameConfig
|
||||
|
||||
protected readonly rng: () => number
|
||||
|
||||
protected readonly startingHandSize: number
|
||||
|
||||
protected readonly firstPlayer: string
|
||||
|
||||
protected readonly continuousEffects: ContinuousEffect[] = []
|
||||
|
||||
protected readonly damageShields: DamageShield[] = []
|
||||
|
||||
protected passesInRow = 0
|
||||
|
||||
protected blockersDeclared = new Set<string>()
|
||||
|
||||
protected nextId = 0
|
||||
|
||||
protected autoManaDepth = 0
|
||||
|
||||
protected autoAdvanceDepth = 0
|
||||
|
||||
protected statDepth = 0
|
||||
|
||||
protected keywordDepth = 0
|
||||
|
||||
protected combatDamageDone = false
|
||||
|
||||
protected readonly triggeredThisTurn = new Set<string>()
|
||||
|
||||
constructor(config: GameConfig) {
|
||||
if (config.players.length < 2) throw new GameError('A game needs at least two players')
|
||||
const ids = new Set(config.players.map(player => player.id))
|
||||
if (ids.size !== config.players.length) throw new GameError('Player ids must be unique')
|
||||
|
||||
this.config = config
|
||||
this.startingHandSize = config.startingHandSize ?? 7
|
||||
this.firstPlayer = config.firstPlayer ?? config.players[0].id
|
||||
if (!ids.has(this.firstPlayer)) throw new GameError(`Unknown first player: ${this.firstPlayer}`)
|
||||
this.rng = config.seed === undefined ? Math.random : mulberry32(config.seed)
|
||||
|
||||
const startingLife = config.startingLife ?? 40
|
||||
this.players = config.players.map(player => ({
|
||||
id: player.id,
|
||||
name: player.name ?? player.id,
|
||||
life: player.life ?? startingLife,
|
||||
lost: false,
|
||||
manaPool: emptyPool(),
|
||||
library: [],
|
||||
hand: [],
|
||||
graveyard: [],
|
||||
exile: [],
|
||||
battlefield: [],
|
||||
command: [],
|
||||
commanderDamage: {},
|
||||
commanderCasts: {},
|
||||
landPlayedThisTurn: false,
|
||||
cardsDrawnThisTurn: 0,
|
||||
lifeGainedThisTurn: 0,
|
||||
spellsCastThisTurn: 0,
|
||||
creaturesDiedThisTurn: 0,
|
||||
nonlandPermanentsEnteredThisTurn: 0,
|
||||
attackedThisTurn: false,
|
||||
creaturesAttackedThisTurn: 0,
|
||||
damageTakenThisTurn: 0,
|
||||
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) {
|
||||
const object = this.createObject(definition, playerConfig.id)
|
||||
this.getPlayer(playerConfig.id).library.push(object.id)
|
||||
}
|
||||
if (config.commander && playerConfig.commander) {
|
||||
const commander = this.createObject(playerConfig.commander, playerConfig.id)
|
||||
commander.isCommander = true
|
||||
commander.zone = 'command'
|
||||
this.getPlayer(playerConfig.id).command.push(commander.id)
|
||||
this.getPlayer(playerConfig.id).commanderId = commander.id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get player(): PlayerState {
|
||||
return this.getPlayer(this.activePlayer)
|
||||
}
|
||||
|
||||
getPlayer(id: string): PlayerState {
|
||||
const player = this.players.find(entry => entry.id === id)
|
||||
if (!player) throw new GameError(`Unknown player: ${id}`)
|
||||
return player
|
||||
}
|
||||
|
||||
getObject(id: string): GameObject {
|
||||
const object = this.objects.get(id)
|
||||
if (!object) throw new GameError(`Unknown object: ${id}`)
|
||||
return object
|
||||
}
|
||||
|
||||
protected createObject(definition: CardDefinition, owner: string): GameObject {
|
||||
const object: GameObject = {
|
||||
id: this.generateId('card'),
|
||||
definition,
|
||||
owner,
|
||||
controller: owner,
|
||||
zone: 'library',
|
||||
tapped: false,
|
||||
damage: 0,
|
||||
deathtouched: false,
|
||||
counters: {},
|
||||
isToken: false,
|
||||
enteredTurn: 0,
|
||||
blockedBy: [],
|
||||
attachments: [],
|
||||
regenerationShields: 0,
|
||||
activations: {},
|
||||
}
|
||||
this.objects.set(object.id, object)
|
||||
return object
|
||||
}
|
||||
|
||||
protected generateId(prefix: string): string {
|
||||
this.nextId++
|
||||
return `${prefix}_${this.nextId}`
|
||||
}
|
||||
|
||||
protected logMessage(message: string): void {
|
||||
this.log.push(message)
|
||||
}
|
||||
|
||||
abstract start(): void;
|
||||
abstract keepHand(playerId: string): void;
|
||||
abstract mulligan(playerId: string): void;
|
||||
abstract putOnBottom(playerId: string, cardId: string): void;
|
||||
protected abstract requireMulligan(playerId: string): MulliganState;
|
||||
protected abstract beginGame(): void;
|
||||
abstract addCard(
|
||||
playerId: string,
|
||||
definition: CardDefinition,
|
||||
zone: Zone,
|
||||
options?: { controller?: string; tapped?: boolean; silent?: boolean },
|
||||
): GameObject;
|
||||
abstract movePermanent(playerId: string, cardId: string, x: number, y: number): void;
|
||||
abstract moveToZone(
|
||||
objectOrId: GameObject | string,
|
||||
zone: Zone,
|
||||
options?: { controller?: string; tapped?: boolean; silent?: boolean; toTop?: boolean },
|
||||
): GameObject;
|
||||
abstract getPower(objectOrId: GameObject | string): number;
|
||||
abstract getToughness(objectOrId: GameObject | string): number;
|
||||
abstract hasKeyword(objectOrId: GameObject | string, keyword: string): boolean;
|
||||
abstract playLand(playerId: string, cardId: string): GameObject;
|
||||
abstract castSpell(playerId: string, cardId: string, options: ActionOptions ): StackItem;
|
||||
protected abstract alternativeCostFor(object: GameObject): Extract<Ability, { kind: 'alternative_cost' }> | undefined;
|
||||
protected abstract payAlternativeCost(
|
||||
ability: Extract<Ability, { kind: 'alternative_cost' }>,
|
||||
playerId: string,
|
||||
source: GameObject,
|
||||
): void;
|
||||
protected abstract spellCostIncrease(object: GameObject): number;
|
||||
protected abstract spellCostReduction(object: GameObject): CostReduction;
|
||||
protected abstract reducedSpellCost(object: GameObject, symbols: string): string;
|
||||
protected abstract overloadEffects(effects: Effect[]): Effect[];
|
||||
protected abstract overloadTarget(target: Target): Target;
|
||||
abstract activateAbility(playerId: string, sourceId: string, abilityIndex: number, options: ActionOptions ): StackItem | undefined;
|
||||
abstract declareAttackers(playerId: string, attacks: CombatAttack[]): void;
|
||||
abstract concede(playerId: string): void;
|
||||
abstract declareBlockers(playerId: string, blocks: CombatBlock[]): void;
|
||||
protected abstract defendingPlayers(): Set<string>;
|
||||
protected abstract finishBlocking(): void;
|
||||
abstract resolveCombatDamage(): void;
|
||||
abstract pass(playerId?: string): void;
|
||||
abstract resolveStack(): void;
|
||||
abstract endTurn(playerId: string): void;
|
||||
abstract canPlayCard(playerId: string, cardId: string): boolean;
|
||||
protected abstract playableFromExile(playerId: string, object: GameObject): boolean;
|
||||
abstract chooseSearchCard(playerId: string, cardId: string): void;
|
||||
abstract searchCandidates(playerId: string): GameObject[];
|
||||
abstract searchPool(playerId: string): GameObject[];
|
||||
abstract chooseHideawayCard(playerId: string, cardId: string): void;
|
||||
abstract chooseCreatureType(playerId: string, type: string): void;
|
||||
abstract chooseColor(playerId: string, color: string): void;
|
||||
abstract chooseOptional(playerId: string, accept: boolean): void;
|
||||
abstract chooseCostPayment(playerId: string, pay: boolean): void;
|
||||
abstract autoAdvance(): void;
|
||||
protected abstract beginTurn(): void;
|
||||
protected abstract finishTurn(): void;
|
||||
protected abstract advancePhase(): void;
|
||||
protected abstract clearCombat(): void;
|
||||
protected abstract resolveTop(): void;
|
||||
protected abstract counterStackItem(item: StackItem): void;
|
||||
protected abstract canCastAtThisTime(playerId: string, object: GameObject): boolean;
|
||||
protected abstract isMainPhaseWithEmptyStack(playerId: string): boolean;
|
||||
protected abstract payMana(playerId: string, symbols: string, x: number): void;
|
||||
protected abstract canPayMana(player: PlayerState, cost: ManaCost): boolean;
|
||||
protected abstract deductMana(player: PlayerState, cost: ManaCost): void;
|
||||
protected abstract autoTapForMana(player: PlayerState, cost: ManaCost): void;
|
||||
protected abstract findFreeManaAbility(source: GameObject): { index: number; ability: Extract<Ability, { kind: 'activated' }> } | undefined;
|
||||
protected abstract activateManaSource(source: GameObject, cost: ManaCost): void;
|
||||
protected abstract manaAbilityColor(
|
||||
source: GameObject,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
player: PlayerState,
|
||||
cost: ManaCost,
|
||||
): ManaColor | undefined;
|
||||
abstract manaColorChoices(source: GameObject, abilityIndex: number): ManaColor[] | undefined;
|
||||
protected abstract manaAbilityAllowedColors(
|
||||
source: GameObject,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
): Set<ManaColor> | undefined;
|
||||
protected abstract neededColor(player: PlayerState, cost: ManaCost, allowed?: Set<ManaColor>): ManaColor | undefined;
|
||||
protected abstract addMana(playerId: string, mana: ManaSpec, preferred?: ManaColor, source?: GameObject): void;
|
||||
protected abstract landManaColors(playerId: string, opponentsOnly: boolean, seen?: Set<string>): Set<ManaColor>;
|
||||
protected abstract anyColorRestrictionColors(
|
||||
mana: ManaSpec,
|
||||
playerId: string,
|
||||
seen?: Set<string>,
|
||||
source?: GameObject,
|
||||
): Set<ManaColor> | undefined;
|
||||
protected abstract payCosts(costs: Cost[], playerId: string, source: GameObject, context: EffectContext): void;
|
||||
protected abstract canPayNonManaCost(cost: Cost, playerId: string, source: GameObject): boolean;
|
||||
protected abstract payNonManaCost(cost: Cost, playerId: string, source: GameObject, context: EffectContext): void;
|
||||
protected abstract selectTargets(
|
||||
effects: Effect[],
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
provided: TargetChoice[],
|
||||
mode: number,
|
||||
): TargetChoice[];
|
||||
abstract legalTargetsForCard(playerId: string, cardId: string): TargetChoice[];
|
||||
abstract legalTargetsForAbility(playerId: string, sourceId: string, abilityIndex: number): TargetChoice[];
|
||||
protected abstract collectTargets(
|
||||
effects: Effect[],
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
mode: number,
|
||||
): TargetChoice[];
|
||||
protected abstract legalTargets(
|
||||
target: Target,
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
playerOnly: 'opponent' | 'any' | undefined,
|
||||
): TargetChoice[];
|
||||
protected abstract targetChoiceMatches(
|
||||
choice: TargetChoice,
|
||||
target: Target,
|
||||
source: GameObject,
|
||||
playerOnly: 'opponent' | 'any' | undefined,
|
||||
): boolean;
|
||||
protected abstract resolveTargets(context: EffectContext, target: Target): ResolvedTarget[];
|
||||
protected abstract playersForEffect(ref: PlayerRef, context: EffectContext): string[];
|
||||
protected abstract playersForValue(ref: PlayerRef, context: EffectContext): string[];
|
||||
protected abstract applyEffects(context: EffectContext, effects: Effect[]): void;
|
||||
protected abstract hideaway(context: EffectContext, effect: Extract<Effect, { op: 'hideaway' }>): void;
|
||||
protected abstract playExiledCard(playerId: string, object: GameObject, free: boolean | undefined): boolean;
|
||||
protected abstract explore(context: EffectContext, effect: Extract<Effect, { op: 'keyword_action' }>): void;
|
||||
protected abstract incubate(context: EffectContext, amount: Value | undefined): void;
|
||||
protected abstract impulse(context: EffectContext): void;
|
||||
protected abstract dig(
|
||||
context: EffectContext,
|
||||
effect: Extract<Effect, { op: 'dig' }>,
|
||||
): void;
|
||||
protected abstract tryPayUnless(cost: Cost, playerId: string | undefined, source: GameObject, context: EffectContext): boolean;
|
||||
protected abstract addContinuousEffect(
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
effect: Extract<Effect, { op: 'pump' | 'set_pt' | 'grant' | 'restriction' }>,
|
||||
affectedIds: string[],
|
||||
duration: Duration,
|
||||
): void;
|
||||
protected abstract continuousContext(effect: ContinuousEffect): EffectContext;
|
||||
protected abstract staticContext(source: GameObject): EffectContext;
|
||||
protected abstract contextFor(
|
||||
source: GameObject,
|
||||
controller: string,
|
||||
targets: TargetChoice[],
|
||||
x: number,
|
||||
mode: number,
|
||||
triggerSubject?: GameObject,
|
||||
eventPlayer?: string,
|
||||
eventAmount?: number,
|
||||
): EffectContext;
|
||||
protected abstract value(value: Value, context: EffectContext): number;
|
||||
protected abstract preventedAmount(target: ResolvedTarget, amount: number, combat: boolean, source?: GameObject): number;
|
||||
/** Applies "if ... would ..., instead ..." amount replacements. */
|
||||
protected abstract replacementAmount(
|
||||
what: 'life_gain' | 'damage' | 'draw' | 'energy',
|
||||
playerId: string,
|
||||
amount: number,
|
||||
source?: GameObject,
|
||||
combat?: boolean,
|
||||
): number;
|
||||
protected abstract damageTarget(
|
||||
target: ResolvedTarget,
|
||||
amount: number,
|
||||
source: GameObject,
|
||||
combat: boolean,
|
||||
): void;
|
||||
protected abstract destroyPermanent(object: GameObject): void;
|
||||
protected abstract createToken(playerId: string, spec: TokenSpec, context: EffectContext): GameObject;
|
||||
protected abstract createTokenCopy(playerId: string, source: GameObject, notLegendary?: boolean): GameObject;
|
||||
protected abstract attach(source: GameObject, target: GameObject): void;
|
||||
protected abstract addCounters(object: GameObject, counter: string, amount: number, silent?: boolean): void;
|
||||
protected abstract dispatchEvent(event: EventContext): void;
|
||||
protected abstract matchesTrigger(event: EventContext, trigger: TriggerEvent, source: GameObject): boolean;
|
||||
protected abstract subjectMatches(target: Target, source: GameObject, event: EventContext): boolean;
|
||||
protected abstract whoMatches(who: 'you' | 'opponent' | 'each_player', source: GameObject, eventPlayer: string | undefined): boolean;
|
||||
protected abstract staticAbilities(): { source: GameObject; ability: Extract<Ability, { kind: 'static' }> }[];
|
||||
protected abstract staticTargets(source: GameObject, target: Target): GameObject[];
|
||||
protected abstract tokenMultiplier(playerId: string, creatureToken: boolean): number;
|
||||
protected abstract exilesInsteadOfGraveyard(object: GameObject): boolean;
|
||||
protected abstract applyEntersReplacements(object: GameObject): void;
|
||||
protected abstract queueEnterChoices(object: GameObject): void;
|
||||
protected abstract hasRestriction(object: GameObject, rule: string): boolean;
|
||||
protected abstract checkCondition(condition: Condition, source: GameObject, context?: EffectContext): boolean;
|
||||
protected abstract dealCombatDamage(): void;
|
||||
protected abstract dealCombatDamageRound(firstStrike: boolean): void;
|
||||
protected abstract damageDefender(attacker: GameObject, amount: number): void;
|
||||
protected abstract requireCanAttack(attacker: GameObject, playerId: string): void;
|
||||
protected abstract hasMeaningfulAction(playerId: string): boolean;
|
||||
protected abstract isActivatedAbilityPlayable(
|
||||
playerId: string,
|
||||
source: GameObject,
|
||||
index: number,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
): boolean;
|
||||
protected abstract hasLegalTargets(source: GameObject, playerId: string, effects?: Effect[]): boolean;
|
||||
protected abstract canAffordMana(playerId: string, symbols: string, x: number): boolean;
|
||||
protected abstract canAttackWithAny(playerId: string): boolean;
|
||||
protected abstract canBlockWithAny(playerId: string): boolean;
|
||||
protected abstract handleLeavesBattlefield(object: GameObject, destination: Zone): void;
|
||||
protected abstract runStateBasedActions(): void;
|
||||
protected abstract losePlayer(playerId: string): void;
|
||||
protected abstract gainLife(playerId: string, amount: number): void;
|
||||
protected abstract loseLife(playerId: string, amount: number): void;
|
||||
protected abstract drawCard(playerId: string, silent: boolean): void;
|
||||
protected abstract drawCards(playerId: string, amount: number): void;
|
||||
protected abstract discardCards(playerId: string, amount: number, random: boolean | undefined, context: EffectContext): void;
|
||||
protected abstract millCards(playerId: string, amount: number): void;
|
||||
protected abstract searchLibrary(
|
||||
playerId: string,
|
||||
selector: ObjectSelector,
|
||||
amount: number,
|
||||
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
|
||||
tapped: boolean,
|
||||
shuffle: boolean,
|
||||
zones?: ('library' | 'graveyard')[],
|
||||
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean },
|
||||
): void;
|
||||
protected abstract findSearchCandidates(
|
||||
playerId: string,
|
||||
selector: ObjectSelector,
|
||||
zones?: ('library' | 'graveyard')[],
|
||||
): GameObject[];
|
||||
protected abstract searchableObjects(playerId: string, zones?: ('library' | 'graveyard')[]): GameObject[];
|
||||
protected abstract moveSearchedCard(
|
||||
object: GameObject,
|
||||
playerId: string,
|
||||
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
|
||||
tapped: boolean,
|
||||
): void;
|
||||
protected abstract searchLibraryLimit(playerId: string): number | undefined;
|
||||
protected abstract shuffleLibrary(player: PlayerState): void;
|
||||
protected abstract removeFromZone(object: GameObject): void;
|
||||
protected abstract objectsMatching(selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): GameObject[];
|
||||
protected abstract matchesSelector(object: GameObject, selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): boolean;
|
||||
protected abstract isCreature(object: GameObject): boolean;
|
||||
protected abstract isLand(object: GameObject): boolean;
|
||||
protected abstract isInstant(object: GameObject): boolean;
|
||||
protected abstract isInstantOrSorcery(object: GameObject): boolean;
|
||||
protected abstract isPermanent(object: GameObject): boolean;
|
||||
protected abstract hasType(object: GameObject, type: string): boolean;
|
||||
protected abstract hasKeywordForDefinition(definition: CardDefinition, keyword: string): boolean;
|
||||
protected abstract battlefieldObjects(): GameObject[];
|
||||
protected abstract alivePlayers(): PlayerState[];
|
||||
protected abstract opponentsOf(playerId: string): string[];
|
||||
protected abstract nextAlivePlayer(playerId: string): string;
|
||||
protected abstract requirePriority(playerId: string): void;
|
||||
protected abstract emptyManaPools(): void;
|
||||
protected abstract removeExpiringEffects(playerId: string): void;
|
||||
protected abstract removeEndOfNextTurnEffects(playerId: string): void;
|
||||
protected abstract removeEffectsByDuration(duration: Duration): void;
|
||||
protected abstract counterStat(counters: Record<string, number>, stat: 'power' | 'toughness'): number;
|
||||
protected abstract findStackItem(id: string): StackItem | undefined;
|
||||
protected abstract playerSource(playerId: string): GameObject;
|
||||
}
|
||||
309
backend/src/game/game-combat.ts
Normal file
309
backend/src/game/game-combat.ts
Normal file
@@ -0,0 +1,309 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameMana } from './game-mana.js'
|
||||
|
||||
export abstract class GameCombat extends GameMana {
|
||||
/** Declares attackers, beginning combat first if necessary. */
|
||||
declareAttackers(playerId: string, attacks: CombatAttack[]): void {
|
||||
this.requirePriority(playerId)
|
||||
if (this.stack.length) throw new GameError('Cannot declare attackers while the stack is not empty')
|
||||
if (this.activePlayer !== playerId) throw new GameError('Only the active player can attack')
|
||||
if (this.phase === 'precombat_main') {
|
||||
this.phase = 'combat'
|
||||
this.step = 'declare_attackers'
|
||||
this.dispatchEvent({ kind: 'begin_combat', player: playerId })
|
||||
}
|
||||
if (this.phase !== 'combat' || this.step !== 'declare_attackers') {
|
||||
throw new GameError('Not in the declare attackers step')
|
||||
}
|
||||
|
||||
const seen = new Set<string>()
|
||||
for (const attack of attacks) {
|
||||
if (seen.has(attack.attackerId)) throw new GameError('A creature can only attack once')
|
||||
seen.add(attack.attackerId)
|
||||
const attacker = this.getObject(attack.attackerId)
|
||||
this.requireCanAttack(attacker, playerId)
|
||||
const defender = this.getPlayer(attack.defenderId)
|
||||
if (defender.id === playerId) throw new GameError('A player cannot attack themselves')
|
||||
if (attacks.length === 1 && this.hasRestriction(attacker, 'cant_attack_alone')) {
|
||||
throw new GameError('That creature cannot attack alone')
|
||||
}
|
||||
attacker.attacking = attack.defenderId
|
||||
if (!this.hasKeyword(attacker, 'Vigilance')) attacker.tapped = true
|
||||
this.getPlayer(playerId).attackedThisTurn = true
|
||||
this.getPlayer(playerId).creaturesAttackedThisTurn++
|
||||
this.dispatchEvent({ kind: 'attacks', player: playerId, subject: attacker })
|
||||
}
|
||||
|
||||
this.step = attacks.length ? 'declare_blockers' : 'end_combat'
|
||||
this.blockersDeclared.clear()
|
||||
this.passesInRow = 0
|
||||
this.priority = this.nextAlivePlayer(playerId)
|
||||
this.logMessage(`${this.getPlayer(playerId).name} attacks with ${attacks.length} creature(s)`)
|
||||
}
|
||||
|
||||
/** Declares blockers for the current combat. */
|
||||
declareBlockers(playerId: string, blocks: CombatBlock[]): void {
|
||||
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('Resolve the pending choice first')
|
||||
if (this.priority !== playerId) throw new GameError('You do not have priority')
|
||||
|
||||
const seen = new Set<string>()
|
||||
for (const block of blocks) {
|
||||
if (seen.has(block.blockerId)) throw new GameError('A creature can only block once')
|
||||
seen.add(block.blockerId)
|
||||
const blocker = this.getObject(block.blockerId)
|
||||
const attacker = this.getObject(block.attackerId)
|
||||
if (blocker.controller !== playerId) throw new GameError('You do not control that blocker')
|
||||
if (blocker.zone !== 'battlefield' || attacker.zone !== 'battlefield') throw new GameError('Object is not on the battlefield')
|
||||
if (!this.isCreature(blocker)) throw new GameError('Only creatures can block')
|
||||
if (blocker.tapped) throw new GameError('Tapped creatures cannot block')
|
||||
if (blocker.blocking) throw new GameError('Creature is already blocking')
|
||||
if (attacker.attacking !== playerId) throw new GameError('That creature is not attacking you')
|
||||
if (this.hasRestriction(blocker, 'cant_block')) throw new GameError('That creature cannot block')
|
||||
if (blocks.length === 1 && this.hasRestriction(blocker, 'cant_block_alone')) {
|
||||
throw new GameError('That creature cannot block alone')
|
||||
}
|
||||
if (this.hasRestriction(attacker, 'cant_be_blocked')) throw new GameError('That creature cannot be blocked')
|
||||
if (attacker.blockedBy.length > 0 && this.hasRestriction(attacker, 'cant_be_blocked_by_more_than_one')) {
|
||||
throw new GameError('That creature cannot be blocked by more than one creature')
|
||||
}
|
||||
for (const effect of this.restrictionEffects(attacker, 'cant_be_blocked_by_power')) {
|
||||
const limit = effect.value ? this.value(effect.value, this.staticContext(attacker)) : 0
|
||||
const power = this.getPower(blocker)
|
||||
if (effect.comparison === 'or_less' ? power <= limit : power >= limit) {
|
||||
throw new GameError('That creature cannot block this attacker')
|
||||
}
|
||||
}
|
||||
if (this.hasRestriction(blocker, 'can_block_only_flying') && !this.hasKeyword(attacker, 'Flying')) {
|
||||
throw new GameError('That creature can block only flyers')
|
||||
}
|
||||
if (this.hasKeyword(attacker, 'Flying') && !this.hasKeyword(blocker, 'Flying') && !this.hasKeyword(blocker, 'Reach')) {
|
||||
throw new GameError('That creature cannot block a flyer')
|
||||
}
|
||||
blocker.blocking = attacker.id
|
||||
attacker.blockedBy.push(blocker.id)
|
||||
this.dispatchEvent({ kind: 'blocks', player: playerId, subject: blocker })
|
||||
}
|
||||
|
||||
this.blockersDeclared.add(playerId)
|
||||
this.logMessage(`${this.getPlayer(playerId).name} declares ${blocks.length} blocker(s)`)
|
||||
if ([...this.defendingPlayers()].every(id => this.blockersDeclared.has(id))) {
|
||||
this.finishBlocking()
|
||||
} else {
|
||||
this.passesInRow = 0
|
||||
this.priority = this.nextAlivePlayer(playerId)
|
||||
}
|
||||
}
|
||||
|
||||
protected defendingPlayers(): Set<string> {
|
||||
return new Set(this.battlefieldObjects()
|
||||
.filter(object => object.attacking)
|
||||
.map(object => object.attacking as string))
|
||||
}
|
||||
|
||||
protected finishBlocking(): void {
|
||||
this.step = 'combat_damage'
|
||||
this.combatDamageDone = false
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
}
|
||||
|
||||
/** Resolves the combat damage step. Also runs automatically when both players pass. */
|
||||
resolveCombatDamage(): void {
|
||||
if (this.phase !== 'combat' || this.step !== 'combat_damage') throw new GameError('Not in the combat damage step')
|
||||
if (this.combatDamageDone) throw new GameError('Combat damage has already been dealt')
|
||||
this.combatDamageDone = true
|
||||
this.dealCombatDamage()
|
||||
this.runStateBasedActions()
|
||||
}
|
||||
|
||||
protected dealCombatDamage(): void {
|
||||
const attackers = this.battlefieldObjects().filter(object => object.attacking)
|
||||
const anyFirstStrike = attackers.some(object => this.hasKeyword(object, 'First strike') || this.hasKeyword(object, 'Double strike'))
|
||||
|| attackers.some(object => object.blockedBy
|
||||
.map(id => this.objects.get(id))
|
||||
.some(blocker => blocker && (this.hasKeyword(blocker, 'First strike') || this.hasKeyword(blocker, 'Double strike'))))
|
||||
|
||||
if (anyFirstStrike) this.dealCombatDamageRound(true)
|
||||
this.dealCombatDamageRound(false)
|
||||
this.step = 'end_combat'
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
}
|
||||
|
||||
protected dealCombatDamageRound(firstStrike: boolean): void {
|
||||
for (const attacker of this.battlefieldObjects()) {
|
||||
if (attacker.zone !== 'battlefield' || !attacker.attacking) continue
|
||||
const doubleStrike = this.hasKeyword(attacker, 'Double strike')
|
||||
const first = this.hasKeyword(attacker, 'First strike')
|
||||
if (firstStrike ? (!first && !doubleStrike) : (first && !doubleStrike)) continue
|
||||
|
||||
let power = this.getPower(attacker)
|
||||
const blockers = attacker.blockedBy
|
||||
.map(id => this.objects.get(id))
|
||||
.filter((object): object is GameObject => Boolean(object && object.zone === 'battlefield' && object.blocking === attacker.id))
|
||||
const deathtouch = this.hasKeyword(attacker, 'Deathtouch')
|
||||
const trample = this.hasKeyword(attacker, 'Trample')
|
||||
|
||||
if (!blockers.length) {
|
||||
this.damageDefender(attacker, power)
|
||||
} else {
|
||||
let remaining = power
|
||||
for (let index = 0; index < blockers.length && remaining > 0; index++) {
|
||||
const blocker = blockers[index]
|
||||
const lethal = deathtouch ? 1 : Math.max(0, this.getToughness(blocker) - blocker.damage)
|
||||
const assign = index === blockers.length - 1 && !trample
|
||||
? remaining
|
||||
: Math.min(remaining, Math.max(lethal, 1))
|
||||
if (assign <= 0) continue
|
||||
this.damageTarget({ kind: 'object', object: blocker }, assign, attacker, true)
|
||||
remaining -= assign
|
||||
}
|
||||
if (trample && remaining > 0) this.damageDefender(attacker, remaining)
|
||||
|
||||
for (const blocker of blockers) {
|
||||
if (blocker.zone !== 'battlefield' || blocker.blocking !== attacker.id) continue
|
||||
const blockerDouble = this.hasKeyword(blocker, 'Double strike')
|
||||
const blockerFirst = this.hasKeyword(blocker, 'First strike')
|
||||
if (firstStrike ? (!blockerFirst && !blockerDouble) : (blockerFirst && !blockerDouble)) continue
|
||||
this.damageTarget({ kind: 'object', object: attacker }, this.getPower(blocker), blocker, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
this.runStateBasedActions()
|
||||
}
|
||||
|
||||
protected damageDefender(attacker: GameObject, amount: number): void {
|
||||
const defenderId = attacker.attacking
|
||||
if (!defenderId) return
|
||||
const player = this.players.find(entry => entry.id === defenderId)
|
||||
if (player) {
|
||||
this.damageTarget({ kind: 'player', id: player.id }, amount, attacker, true)
|
||||
return
|
||||
}
|
||||
const permanent = this.objects.get(defenderId)
|
||||
if (permanent?.zone === 'battlefield') {
|
||||
this.damageTarget({ kind: 'object', object: permanent }, amount, attacker, true)
|
||||
}
|
||||
}
|
||||
|
||||
protected requireCanAttack(attacker: GameObject, playerId: string): void {
|
||||
if (attacker.zone !== 'battlefield') throw new GameError('Attacker is not on the battlefield')
|
||||
if (attacker.controller !== playerId) throw new GameError('You do not control that creature')
|
||||
if (!this.isCreature(attacker)) throw new GameError('Only creatures can attack')
|
||||
if (attacker.tapped) throw new GameError('Tapped creatures cannot attack')
|
||||
if (attacker.enteredTurn >= this.turn && !this.hasKeyword(attacker, 'Haste')) {
|
||||
throw new GameError('That creature has summoning sickness')
|
||||
}
|
||||
if (this.hasRestriction(attacker, 'cant_attack')) throw new GameError('That creature cannot attack')
|
||||
}
|
||||
|
||||
protected canAttackWithAny(playerId: string): boolean {
|
||||
return this.battlefieldObjects().some(object => {
|
||||
try {
|
||||
this.requireCanAttack(object, playerId)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (error instanceof GameError) return false
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** Restriction effects with the given rule that currently affect an object. */
|
||||
protected restrictionEffects(object: GameObject, rule: string): Extract<StaticEffect, { op: 'restriction' }>[] {
|
||||
const found: Extract<StaticEffect, { op: 'restriction' }>[] = []
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'restriction' || effect.rule !== rule) continue
|
||||
if (this.staticTargets(source, effect.target).some(target => target.id === object.id)) found.push(effect)
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'restriction' || continuous.effect.rule !== rule) continue
|
||||
if (continuous.affectedIds.includes(object.id)) found.push(continuous.effect)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
protected canBlockWithAny(playerId: string): boolean {
|
||||
const attackers = this.battlefieldObjects().filter(object => object.attacking === playerId)
|
||||
if (!attackers.length) return false
|
||||
return this.battlefieldObjects().some(blocker => {
|
||||
if (blocker.controller !== playerId) return false
|
||||
if (!this.isCreature(blocker) || blocker.tapped || blocker.blocking) return false
|
||||
if (this.hasRestriction(blocker, 'cant_block')) return false
|
||||
return attackers.some(attacker => {
|
||||
if (this.hasRestriction(attacker, 'cant_be_blocked')) return false
|
||||
if (this.hasRestriction(blocker, 'can_block_only_flying') && !this.hasKeyword(attacker, 'Flying')) return false
|
||||
const blockedByPower = this.restrictionEffects(attacker, 'cant_be_blocked_by_power').some(effect => {
|
||||
const limit = effect.value ? this.value(effect.value, this.staticContext(attacker)) : 0
|
||||
const power = this.getPower(blocker)
|
||||
return effect.comparison === 'or_less' ? power <= limit : power >= limit
|
||||
})
|
||||
if (blockedByPower) return false
|
||||
return !this.hasKeyword(attacker, 'Flying')
|
||||
|| this.hasKeyword(blocker, 'Flying')
|
||||
|| this.hasKeyword(blocker, 'Reach')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Zones, state-based actions, and utilities
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected clearCombat(): void {
|
||||
this.blockersDeclared.clear()
|
||||
for (const object of this.objects.values()) {
|
||||
if (object.zone !== 'battlefield') continue
|
||||
object.attacking = undefined
|
||||
object.blockedBy = []
|
||||
object.blocking = undefined
|
||||
}
|
||||
this.combatDamageDone = false
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stack
|
||||
// ---------------------------------------------------------------------------
|
||||
}
|
||||
1220
backend/src/game/game-effects.ts
Normal file
1220
backend/src/game/game-effects.ts
Normal file
File diff suppressed because it is too large
Load Diff
270
backend/src/game/game-helpers.ts
Normal file
270
backend/src/game/game-helpers.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
|
||||
export type ResolvedTarget =
|
||||
| { kind: 'player'; id: string }
|
||||
| { kind: 'object'; object: GameObject }
|
||||
| { kind: 'stack'; item: StackItem }
|
||||
|
||||
export interface EventContext {
|
||||
kind: TriggerEvent['kind']
|
||||
player?: string
|
||||
subject?: GameObject
|
||||
amount?: number
|
||||
counter?: string
|
||||
ordinal?: number
|
||||
mode?: 'gain' | 'lose'
|
||||
recipient?: 'player' | 'creature' | 'permanent' | 'any'
|
||||
combat?: boolean
|
||||
spell?: GameObject
|
||||
spellItem?: StackItem
|
||||
}
|
||||
|
||||
export interface EffectContext {
|
||||
source: GameObject
|
||||
controller: string
|
||||
targets: TargetChoice[]
|
||||
lastTarget?: ResolvedTarget
|
||||
/** Objects dealt damage by the most recent damage effect, for "dealt damage this way". */
|
||||
lastDamaged?: GameObject[]
|
||||
triggerSubject?: GameObject
|
||||
eventPlayer?: string
|
||||
eventAmount?: number
|
||||
x: number
|
||||
mode: number
|
||||
/** Color picked for a mana ability, so choice effects produce it. */
|
||||
manaColor?: ManaColor
|
||||
/** Whether the "you may" branch was taken; undefined means no branch was offered. */
|
||||
optionalTaken?: boolean
|
||||
}
|
||||
|
||||
export interface ContinuousEffect {
|
||||
id: string
|
||||
sourceId: string
|
||||
controller: string
|
||||
effect: Extract<Effect, { op: 'pump' | 'set_pt' | 'grant' | 'restriction' }>
|
||||
affectedIds: string[]
|
||||
duration: Duration
|
||||
createdTurn: number
|
||||
}
|
||||
|
||||
export interface DamageShield {
|
||||
/** Object or player ids this shield covers; empty with `global` covers everything. */
|
||||
ids: Set<string>
|
||||
global: boolean
|
||||
/** When set, only damage dealt by these source objects is prevented. */
|
||||
sourceIds?: Set<string>
|
||||
/** When set, only damage from sources matching this selector is prevented. */
|
||||
sourceSelector?: ObjectSelector
|
||||
remaining: number | 'all'
|
||||
combatOnly: boolean
|
||||
/** "If damage is prevented this way, ..." follow-up. */
|
||||
then?: Effect[]
|
||||
sourceId?: string
|
||||
controller?: string
|
||||
/** Target choices left over when the shield was made, for its follow-up. */
|
||||
targets?: TargetChoice[]
|
||||
/** Recipient the shield was made for, so "that creature" resolves in the follow-up. */
|
||||
lastTarget?: ResolvedTarget
|
||||
}
|
||||
|
||||
export interface ManaCost {
|
||||
generic: number
|
||||
colored: ManaColor[]
|
||||
hybrid: { colors: ManaColor[]; life: number }[]
|
||||
}
|
||||
|
||||
export const MANA_COLORS: ManaColor[] = ['W', 'U', 'B', 'R', 'G', 'C']
|
||||
export const COLOR_NAMES: Record<string, ManaColor> = {
|
||||
white: 'W',
|
||||
blue: 'U',
|
||||
black: 'B',
|
||||
red: 'R',
|
||||
green: 'G',
|
||||
colorless: 'C',
|
||||
}
|
||||
|
||||
export function emptyPool(): ManaPool {
|
||||
return { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 }
|
||||
}
|
||||
|
||||
export function parseManaCost(symbols: string, x = 0): ManaCost {
|
||||
const cost: ManaCost = { generic: 0, colored: [], hybrid: [] }
|
||||
for (const match of symbols.matchAll(/\{([^}]+)\}/g)) {
|
||||
const symbol = match[1].toUpperCase()
|
||||
if (/^\d+$/.test(symbol)) {
|
||||
cost.generic += Number(symbol)
|
||||
} else if (symbol === 'X') {
|
||||
cost.generic += x
|
||||
} else if (symbol === 'S') {
|
||||
cost.colored.push('C')
|
||||
} else if (/^[WUBRGC]$/.test(symbol)) {
|
||||
cost.colored.push(symbol as ManaColor)
|
||||
} else if (symbol.includes('/')) {
|
||||
const parts = symbol.split('/')
|
||||
const colors = parts
|
||||
.filter(part => /^[WUBRG]$/.test(part))
|
||||
.map(part => part as ManaColor)
|
||||
if (colors.length) cost.hybrid.push({ colors, life: parts.includes('P') ? 2 : 0 })
|
||||
else cost.generic += 1
|
||||
} else {
|
||||
cost.generic += 1
|
||||
}
|
||||
}
|
||||
return cost
|
||||
}
|
||||
|
||||
export interface CostReduction {
|
||||
generic: number
|
||||
colored: ManaColor[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic reductions only remove generic mana; colored ones remove matching pips.
|
||||
* shortcut: hybrid and phyrexian pips are not reduced; upgrade when a card needs it.
|
||||
*/
|
||||
export function reduceManaSymbols(symbols: string, reduction: CostReduction): string {
|
||||
let generic = reduction.generic
|
||||
const colored = [...reduction.colored]
|
||||
const result: string[] = []
|
||||
for (const match of symbols.matchAll(/\{([^}]+)\}/g)) {
|
||||
const symbol = match[1].toUpperCase()
|
||||
if (/^\d+$/.test(symbol) && generic > 0) {
|
||||
const remaining = Math.max(0, Number(symbol) - generic)
|
||||
generic = Math.max(0, generic - Number(symbol))
|
||||
if (remaining > 0) result.push(`{${remaining}}`)
|
||||
continue
|
||||
}
|
||||
const index = colored.indexOf(symbol as ManaColor)
|
||||
if (index >= 0) {
|
||||
colored.splice(index, 1)
|
||||
continue
|
||||
}
|
||||
result.push(`{${match[1]}}`)
|
||||
}
|
||||
return result.join('')
|
||||
}
|
||||
|
||||
export function manaValueOf(definition: CardDefinition): number {
|
||||
if (definition.manaValue !== undefined) return definition.manaValue
|
||||
const cost = parseManaCost(definition.manaCost ?? '')
|
||||
return cost.generic + cost.colored.length + cost.hybrid.length
|
||||
}
|
||||
|
||||
export function colorOfSymbol(symbol: string): ManaColor {
|
||||
const bare = symbol.replace(/[{}]/g, '').toUpperCase()
|
||||
if (bare === 'S') return 'C'
|
||||
if (/^[WUBRGC]$/.test(bare)) return bare as ManaColor
|
||||
return 'C'
|
||||
}
|
||||
|
||||
export function tokenCard(token: {
|
||||
name?: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
}): { definition: CardDefinition; backFace?: CardDefinition } {
|
||||
const predefined = predefinedToken(token)
|
||||
const types = predefined?.types ?? token.types
|
||||
const subtypes = predefined?.subtypes ?? token.subtypes
|
||||
const colors = [...new Set([...(predefined?.colors ?? []), ...token.colors])]
|
||||
const keywords = [...(predefined?.keywords ?? []), ...(token.keywords ?? [])]
|
||||
const definition = tokenFace({
|
||||
name: predefined?.name ?? token.name ?? (subtypes.map(capitalize).join(' ') || 'Token'),
|
||||
types,
|
||||
subtypes,
|
||||
colors,
|
||||
power: token.power ?? predefined?.power,
|
||||
toughness: token.toughness ?? predefined?.toughness,
|
||||
keywords,
|
||||
abilities: predefined?.abilities,
|
||||
})
|
||||
const backFace = predefined?.backFace
|
||||
? tokenFace({ ...predefined.backFace, keywords: predefined.backFace.keywords ?? [] })
|
||||
: undefined
|
||||
return { definition, backFace }
|
||||
}
|
||||
|
||||
export function capitalize(word: string): string {
|
||||
return word[0]?.toUpperCase() + word.slice(1)
|
||||
}
|
||||
|
||||
export function tokenFace(fields: {
|
||||
name: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
abilities?: Ability[]
|
||||
}): CardDefinition {
|
||||
return {
|
||||
oracleId: `token:${fields.name}`,
|
||||
name: fields.name,
|
||||
typeLine: [fields.types.join(' '), fields.subtypes.length ? `— ${fields.subtypes.join(' ')}` : ''].join(' ').trim(),
|
||||
manaValue: 0,
|
||||
colors: fields.colors,
|
||||
power: fields.power,
|
||||
toughness: fields.toughness,
|
||||
abilities: [
|
||||
...(fields.abilities ?? []),
|
||||
...(fields.keywords ?? []).map(keyword => ({ kind: 'keyword' as const, keyword })),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
export class GameError extends Error {}
|
||||
|
||||
|
||||
export function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0
|
||||
let value = state
|
||||
value = Math.imul(value ^ (value >>> 15), value | 1)
|
||||
value ^= value + Math.imul(value ^ (value >>> 7), value | 61)
|
||||
return ((value ^ (value >>> 14)) >>> 0) / 4294967296
|
||||
}
|
||||
}
|
||||
|
||||
369
backend/src/game/game-mana.ts
Normal file
369
backend/src/game/game-mana.ts
Normal file
@@ -0,0 +1,369 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameStats } from './game-stats.js'
|
||||
|
||||
export abstract class GameMana extends GameStats {
|
||||
protected payMana(playerId: string, symbols: string, x: number): void {
|
||||
if (!symbols) return
|
||||
const player = this.getPlayer(playerId)
|
||||
const cost = parseManaCost(symbols, x)
|
||||
const pool = { ...player.manaPool }
|
||||
const tapped = player.battlefield
|
||||
.map(id => this.objects.get(id))
|
||||
.filter((object): object is GameObject => Boolean(object?.tapped))
|
||||
.map(object => object.id)
|
||||
this.autoTapForMana(player, cost)
|
||||
if (!this.canPayMana(player, cost)) {
|
||||
player.manaPool = pool
|
||||
for (const id of player.battlefield) {
|
||||
const object = this.objects.get(id)
|
||||
if (object) object.tapped = tapped.includes(id)
|
||||
}
|
||||
throw new GameError('Not enough mana')
|
||||
}
|
||||
this.deductMana(player, cost)
|
||||
}
|
||||
|
||||
protected canPayMana(player: PlayerState, cost: ManaCost): boolean {
|
||||
const pool = { ...player.manaPool }
|
||||
const payColor = (color: ManaColor): boolean => {
|
||||
if (pool[color] <= 0) return false
|
||||
pool[color]--
|
||||
return true
|
||||
}
|
||||
for (const color of cost.colored) {
|
||||
if (!payColor(color)) return false
|
||||
}
|
||||
for (const hybrid of cost.hybrid) {
|
||||
const color = hybrid.colors.find(entry => pool[entry] > 0)
|
||||
if (color) pool[color]--
|
||||
else if (!(hybrid.life > 0 && player.life >= hybrid.life)) return false
|
||||
}
|
||||
const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0)
|
||||
return remaining >= cost.generic
|
||||
}
|
||||
|
||||
protected deductMana(player: PlayerState, cost: ManaCost): void {
|
||||
for (const color of cost.colored) player.manaPool[color]--
|
||||
for (const hybrid of cost.hybrid) {
|
||||
const color = hybrid.colors.find(entry => player.manaPool[entry] > 0)
|
||||
if (color) player.manaPool[color]--
|
||||
else if (hybrid.life > 0) this.loseLife(player.id, hybrid.life)
|
||||
else throw new GameError('Not enough mana')
|
||||
}
|
||||
let generic = cost.generic
|
||||
for (const color of MANA_COLORS) {
|
||||
const used = Math.min(player.manaPool[color], generic)
|
||||
player.manaPool[color] -= used
|
||||
generic -= used
|
||||
}
|
||||
if (generic > 0) throw new GameError('Not enough mana')
|
||||
}
|
||||
|
||||
protected autoTapForMana(player: PlayerState, cost: ManaCost): void {
|
||||
if (this.autoManaDepth > 0) return
|
||||
let guard = 0
|
||||
while (!this.canPayMana(player, cost) && guard++ < 25) {
|
||||
const source = this.players
|
||||
.flatMap(entry => entry.battlefield)
|
||||
.map(id => this.objects.get(id))
|
||||
.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<ManaColor> | undefined } => Boolean(entry))
|
||||
.filter(entry => this.neededColor(player, cost, entry.allowed) !== undefined)
|
||||
.sort((a, b) => (a.allowed?.size ?? Number.MAX_SAFE_INTEGER) - (b.allowed?.size ?? Number.MAX_SAFE_INTEGER))[0]?.object
|
||||
if (!source) break
|
||||
this.autoManaDepth++
|
||||
try {
|
||||
this.activateManaSource(source, cost)
|
||||
} finally {
|
||||
this.autoManaDepth--
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected findFreeManaAbility(source: GameObject): { index: number; ability: Extract<Ability, { kind: 'activated' }> } | undefined {
|
||||
const abilities = source.definition.abilities ?? []
|
||||
for (let index = 0; index < abilities.length; index++) {
|
||||
const ability = abilities[index]
|
||||
if (ability.kind !== 'activated') continue
|
||||
if (!ability.effects.length || !ability.effects.every(effect => effect.op === 'add_mana')) continue
|
||||
if (ability.costs.length !== 1 || ability.costs[0].kind !== 'tap') continue
|
||||
if (source.tapped) continue
|
||||
if (this.isCreature(source) && source.enteredTurn >= this.turn && !this.hasKeyword(source, 'Haste')) continue
|
||||
return { index, ability }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
protected activateManaSource(source: GameObject, cost: ManaCost): void {
|
||||
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
|
||||
}
|
||||
for (const effect of found.ability.effects) {
|
||||
if (effect.op === 'add_mana') this.addMana(source.controller, effect.mana, color, source)
|
||||
}
|
||||
}
|
||||
|
||||
protected manaAbilityColor(
|
||||
source: GameObject,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
player: PlayerState,
|
||||
cost: ManaCost,
|
||||
): ManaColor | undefined {
|
||||
return this.neededColor(player, cost, this.manaAbilityAllowedColors(source, ability))
|
||||
}
|
||||
|
||||
/**
|
||||
* Colors a mana ability lets its controller choose between. Undefined when
|
||||
* the ability has no choice, such as fixed or single-color mana.
|
||||
*/
|
||||
manaColorChoices(source: GameObject, abilityIndex: number): ManaColor[] | undefined {
|
||||
const ability = (source.definition.abilities ?? [])[abilityIndex]
|
||||
if (!ability || ability.kind !== 'activated') return undefined
|
||||
let colors: ManaColor[] | undefined
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'add_mana') continue
|
||||
if (effect.mana.kind === 'symbols' && effect.mana.oneOf) {
|
||||
colors = [...new Set(effect.mana.symbols.map(colorOfSymbol))]
|
||||
} else if (effect.mana.kind === 'any_color') {
|
||||
const allowed = this.anyColorRestrictionColors(effect.mana, source.controller, undefined, source)
|
||||
colors = allowed
|
||||
? MANA_COLORS.filter(color => color !== 'C' && allowed.has(color))
|
||||
: ['W', 'U', 'B', 'R', 'G']
|
||||
}
|
||||
}
|
||||
return colors && colors.length > 1 ? colors : undefined
|
||||
}
|
||||
|
||||
protected manaAbilityAllowedColors(
|
||||
source: GameObject,
|
||||
ability: Extract<Ability, { kind: 'activated' }>,
|
||||
): Set<ManaColor> | undefined {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'add_mana') continue
|
||||
if (effect.mana.kind === 'symbols' && effect.mana.oneOf) {
|
||||
return new Set(effect.mana.symbols.map(colorOfSymbol))
|
||||
}
|
||||
return this.anyColorRestrictionColors(effect.mana, source.controller, undefined, source)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
protected neededColor(player: PlayerState, cost: ManaCost, allowed?: Set<ManaColor>): ManaColor | undefined {
|
||||
for (const color of cost.colored) {
|
||||
if (player.manaPool[color] > 0) continue
|
||||
return allowed && !allowed.has(color) ? undefined : color
|
||||
}
|
||||
for (const hybrid of cost.hybrid) {
|
||||
if (hybrid.colors.some(color => player.manaPool[color] > 0)) continue
|
||||
return hybrid.colors.find(color => !allowed || allowed.has(color))
|
||||
}
|
||||
if (allowed) return MANA_COLORS.find(color => allowed.has(color))
|
||||
return 'W'
|
||||
}
|
||||
|
||||
protected addMana(playerId: string, mana: ManaSpec, preferred?: ManaColor, source?: GameObject): 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)]++
|
||||
return
|
||||
}
|
||||
const amount = this.value(mana.amount, {
|
||||
source: this.playerSource(playerId),
|
||||
controller: playerId,
|
||||
targets: [],
|
||||
x: 0,
|
||||
mode: 0,
|
||||
})
|
||||
const allowed = this.anyColorRestrictionColors(mana, playerId, undefined, source)
|
||||
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.
|
||||
*/
|
||||
protected landManaColors(playerId: string, opponentsOnly: boolean, seen = new Set<string>()): Set<ManaColor> {
|
||||
const colors = new Set<ManaColor>()
|
||||
const opponents = this.opponentsOf(playerId)
|
||||
for (const object of this.battlefieldObjects()) {
|
||||
if (!this.isLand(object) || seen.has(object.id)) continue
|
||||
if (opponentsOnly ? !opponents.includes(object.controller) : object.controller !== playerId) continue
|
||||
seen.add(object.id)
|
||||
for (const ability of object.definition.abilities ?? []) {
|
||||
if (ability.kind !== 'activated') continue
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'add_mana') continue
|
||||
if (effect.mana.kind === 'symbols') {
|
||||
for (const symbol of effect.mana.symbols) {
|
||||
for (const letter of symbol.match(/[WUBRG]/gi) ?? []) colors.add(letter.toUpperCase() as ManaColor)
|
||||
}
|
||||
} else {
|
||||
const nested = this.anyColorRestrictionColors(effect.mana, object.controller, seen)
|
||||
if (nested) {
|
||||
for (const color of nested) colors.add(color)
|
||||
} else {
|
||||
for (const color of MANA_COLORS) if (color !== 'C') colors.add(color)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
seen.delete(object.id)
|
||||
}
|
||||
return colors
|
||||
}
|
||||
|
||||
/** The colors an any-color mana source may produce, when the restriction is known. */
|
||||
protected anyColorRestrictionColors(
|
||||
mana: ManaSpec,
|
||||
playerId: string,
|
||||
seen?: Set<string>,
|
||||
source?: GameObject,
|
||||
): Set<ManaColor> | undefined {
|
||||
if (mana.kind !== 'any_color') return undefined
|
||||
if (mana.restriction === 'chosen color') {
|
||||
return source?.chosenColor ? new Set([source.chosenColor]) : new Set()
|
||||
}
|
||||
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)
|
||||
}
|
||||
if (mana.restriction === "commander's color identity") {
|
||||
const commander = this.objects.get(this.getPlayer(playerId).commanderId ?? '')
|
||||
const identity = commander?.definition.colorIdentity ?? []
|
||||
return new Set(identity.filter((color): color is ManaColor => /^[WUBRG]$/.test(color)))
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Affordability check that mirrors auto-tapping without changing the game.
|
||||
* shortcut: only land-based any_color restrictions are modelled; mana
|
||||
* restricted by a commander identity or a spell type is still flexible.
|
||||
*/
|
||||
protected canAffordMana(playerId: string, symbols: string, x: number): boolean {
|
||||
if (!symbols) return true
|
||||
const player = this.getPlayer(playerId)
|
||||
const cost = parseManaCost(symbols, x)
|
||||
const pool = { ...player.manaPool }
|
||||
let flexible = 0
|
||||
const restricted: { colors: Set<ManaColor>; amount: number }[] = []
|
||||
for (const object of this.battlefieldObjects()) {
|
||||
if (object.controller !== playerId) continue
|
||||
const found = this.findFreeManaAbility(object)
|
||||
if (!found) continue
|
||||
for (const effect of found.ability.effects) {
|
||||
if (effect.op !== 'add_mana') continue
|
||||
if (effect.mana.kind === 'symbols') {
|
||||
for (const symbol of effect.mana.symbols) pool[colorOfSymbol(symbol)]++
|
||||
} else {
|
||||
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
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for (const color of cost.colored) {
|
||||
if (!take(color)) return false
|
||||
}
|
||||
for (const hybrid of cost.hybrid) {
|
||||
if (hybrid.colors.some(take)) continue
|
||||
if (!(hybrid.life > 0 && life >= hybrid.life)) return false
|
||||
life -= hybrid.life
|
||||
}
|
||||
const remaining = MANA_COLORS.reduce((total, color) => total + pool[color], 0)
|
||||
+ flexible
|
||||
+ restricted.reduce((total, entry) => total + entry.amount, 0)
|
||||
return remaining >= cost.generic
|
||||
}
|
||||
|
||||
protected emptyManaPools(): void {
|
||||
for (const player of this.players) player.manaPool = emptyPool()
|
||||
}
|
||||
}
|
||||
306
backend/src/game/game-stats.ts
Normal file
306
backend/src/game/game-stats.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameBase } from './game-base.js'
|
||||
|
||||
export abstract class GameStats extends GameBase {
|
||||
getPower(objectOrId: GameObject | string): number {
|
||||
const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId
|
||||
const base = object.definition.power ?? 0
|
||||
if (this.statDepth > 0) return base
|
||||
this.statDepth++
|
||||
try {
|
||||
let power = base
|
||||
let toughness = object.definition.toughness ?? 0
|
||||
|
||||
for (const staticSource of this.staticAbilities()) {
|
||||
for (const effect of staticSource.ability.effects) {
|
||||
if (effect.op !== 'set_pt') continue
|
||||
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
|
||||
if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source))
|
||||
if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source))
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue
|
||||
const context = this.continuousContext(continuous)
|
||||
if (continuous.effect.power) power = this.value(continuous.effect.power, context)
|
||||
if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context)
|
||||
}
|
||||
|
||||
const counterPower = this.counterStat(object.counters, 'power')
|
||||
const counterToughness = this.counterStat(object.counters, 'toughness')
|
||||
power += counterPower
|
||||
toughness += counterToughness
|
||||
|
||||
for (const staticSource of this.staticAbilities()) {
|
||||
for (const effect of staticSource.ability.effects) {
|
||||
if (effect.op !== 'pump') continue
|
||||
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
|
||||
const context = this.staticContext(staticSource.source)
|
||||
power += this.value(effect.power, context)
|
||||
toughness += this.value(effect.toughness, context)
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue
|
||||
const context = this.continuousContext(continuous)
|
||||
power += this.value(continuous.effect.power, context)
|
||||
toughness += this.value(continuous.effect.toughness, context)
|
||||
}
|
||||
return power
|
||||
} finally {
|
||||
this.statDepth--
|
||||
}
|
||||
}
|
||||
|
||||
getToughness(objectOrId: GameObject | string): number {
|
||||
const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId
|
||||
const base = object.definition.toughness ?? 0
|
||||
if (this.statDepth > 0) return base
|
||||
this.statDepth++
|
||||
try {
|
||||
let power = base
|
||||
let toughness = object.definition.toughness ?? 0
|
||||
|
||||
for (const staticSource of this.staticAbilities()) {
|
||||
for (const effect of staticSource.ability.effects) {
|
||||
if (effect.op !== 'set_pt') continue
|
||||
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
|
||||
if (effect.power) power = this.value(effect.power, this.staticContext(staticSource.source))
|
||||
if (effect.toughness) toughness = this.value(effect.toughness, this.staticContext(staticSource.source))
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'set_pt' || !continuous.affectedIds.includes(object.id)) continue
|
||||
const context = this.continuousContext(continuous)
|
||||
if (continuous.effect.power) power = this.value(continuous.effect.power, context)
|
||||
if (continuous.effect.toughness) toughness = this.value(continuous.effect.toughness, context)
|
||||
}
|
||||
|
||||
toughness += this.counterStat(object.counters, 'toughness')
|
||||
|
||||
for (const staticSource of this.staticAbilities()) {
|
||||
for (const effect of staticSource.ability.effects) {
|
||||
if (effect.op !== 'pump') continue
|
||||
if (!this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) continue
|
||||
toughness += this.value(effect.toughness, this.staticContext(staticSource.source))
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'pump' || !continuous.affectedIds.includes(object.id)) continue
|
||||
toughness += this.value(continuous.effect.toughness, this.continuousContext(continuous))
|
||||
}
|
||||
return toughness
|
||||
} finally {
|
||||
this.statDepth--
|
||||
}
|
||||
}
|
||||
|
||||
hasKeyword(objectOrId: GameObject | string, keyword: string): boolean {
|
||||
const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId
|
||||
const wanted = keyword.toLowerCase()
|
||||
if (this.keywordDepth > 0) {
|
||||
for (const ability of object.definition.abilities ?? []) {
|
||||
if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
this.keywordDepth++
|
||||
try {
|
||||
for (const ability of object.definition.abilities ?? []) {
|
||||
if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true
|
||||
if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for (const staticSource of this.staticAbilities()) {
|
||||
for (const effect of staticSource.ability.effects) {
|
||||
if (effect.op !== 'grant' || effect.keyword.toLowerCase() !== wanted) continue
|
||||
if (this.staticTargets(staticSource.source, effect.target).some(target => target.id === object.id)) return true
|
||||
}
|
||||
}
|
||||
for (const continuous of this.continuousEffects) {
|
||||
if (continuous.effect.op !== 'grant' || continuous.effect.keyword.toLowerCase() !== wanted) continue
|
||||
if (continuous.affectedIds.includes(object.id)) return true
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
this.keywordDepth--
|
||||
}
|
||||
}
|
||||
|
||||
protected hasKeywordForDefinition(definition: CardDefinition, keyword: string): boolean {
|
||||
const wanted = keyword.toLowerCase()
|
||||
for (const ability of definition.abilities ?? []) {
|
||||
if (ability.kind === 'keyword' && ability.keyword.toLowerCase() === wanted) return true
|
||||
if (ability.kind === 'keywords' && ability.keywords.some(entry => entry.keyword.toLowerCase() === wanted)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
protected isCreature(object: GameObject): boolean {
|
||||
return this.hasType(object, 'creature')
|
||||
}
|
||||
|
||||
protected isLand(object: GameObject): boolean {
|
||||
return this.hasType(object, 'land')
|
||||
}
|
||||
|
||||
protected isInstant(object: GameObject): boolean {
|
||||
return this.hasType(object, 'instant')
|
||||
}
|
||||
|
||||
protected isInstantOrSorcery(object: GameObject): boolean {
|
||||
return this.hasType(object, 'instant') || this.hasType(object, 'sorcery')
|
||||
}
|
||||
|
||||
protected isPermanent(object: GameObject): boolean {
|
||||
if (this.isInstantOrSorcery(object)) return false
|
||||
return ['creature', 'artifact', 'enchantment', 'planeswalker', 'battle', 'land']
|
||||
.some(type => this.hasType(object, type))
|
||||
}
|
||||
|
||||
protected hasType(object: GameObject, type: string): boolean {
|
||||
const words = object.definition.typeLine.toLowerCase().split(/[\s—–\-/,()]+/)
|
||||
return words.includes(type.toLowerCase())
|
||||
}
|
||||
|
||||
protected battlefieldObjects(): GameObject[] {
|
||||
return [...this.objects.values()].filter(object => object.zone === 'battlefield')
|
||||
}
|
||||
|
||||
protected alivePlayers(): PlayerState[] {
|
||||
return this.players.filter(player => !player.lost)
|
||||
}
|
||||
|
||||
protected opponentsOf(playerId: string): string[] {
|
||||
return this.alivePlayers().filter(player => player.id !== playerId).map(player => player.id)
|
||||
}
|
||||
|
||||
protected nextAlivePlayer(playerId: string): string {
|
||||
const start = this.players.findIndex(player => player.id === playerId)
|
||||
for (let offset = 1; offset <= this.players.length; offset++) {
|
||||
const player = this.players[(start + offset) % this.players.length]
|
||||
if (!player.lost) return player.id
|
||||
}
|
||||
return playerId
|
||||
}
|
||||
|
||||
protected counterStat(counters: Record<string, number>, stat: 'power' | 'toughness'): number {
|
||||
let total = 0
|
||||
for (const [counter, count] of Object.entries(counters)) {
|
||||
const match = counter.match(/^([+-])(\d+)\/([+-])(\d+)$/)
|
||||
if (!match) continue
|
||||
const value = stat === 'power' ? `${match[1]}${match[2]}` : `${match[3]}${match[4]}`
|
||||
total += Number(value) * count
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
protected objectsMatching(selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): GameObject[] {
|
||||
const zone = zoneOverride ?? selector.zone ?? 'battlefield'
|
||||
return [...this.objects.values()].filter(object => this.matchesSelector(object, selector, source, zone))
|
||||
}
|
||||
|
||||
protected matchesSelector(object: GameObject, selector: ObjectSelector, source: GameObject, zoneOverride?: Zone): boolean {
|
||||
const zone = zoneOverride ?? selector.zone ?? 'battlefield'
|
||||
if (object.zone !== zone) return false
|
||||
if (selector.other && object.id === source.id) return false
|
||||
|
||||
const typeLine = object.definition.typeLine.toLowerCase()
|
||||
const words = new Set(typeLine.split(/[\s—–\-/,()]+/).filter(Boolean))
|
||||
const matchesWords = (values: string[]): boolean => {
|
||||
const matches = values.map(value => words.has(value.toLowerCase()))
|
||||
return selector.match === 'any' ? matches.some(Boolean) : matches.every(Boolean)
|
||||
}
|
||||
// "Permanent" is a zone property, not a word on the type line.
|
||||
const types = selector.types?.filter(type => type.toLowerCase() !== 'permanent')
|
||||
if (types?.length && !matchesWords(types)) return false
|
||||
if (selector.excludeTypes?.some(type => words.has(type.toLowerCase()))) return false
|
||||
if (selector.supertypes?.length && !matchesWords(selector.supertypes)) return false
|
||||
if (selector.subtypes?.length && !matchesWords(selector.subtypes)) return false
|
||||
|
||||
if (selector.controller === 'you' && object.controller !== source.controller) return false
|
||||
if (selector.controller === 'opponent' && object.controller === source.controller) return false
|
||||
if (selector.owner === 'you' && object.owner !== source.controller) return false
|
||||
if (selector.owner === 'opponent' && object.owner === source.controller) return false
|
||||
|
||||
const colors = object.definition.colors ?? []
|
||||
if (selector.colors?.length) {
|
||||
const matches = selector.colors.map(color => colors.includes(color))
|
||||
if (selector.match === 'any' ? !matches.some(Boolean) : !matches.every(Boolean)) return false
|
||||
}
|
||||
if (selector.excludeColors?.some(color => color === 'C' ? colors.length === 0 : colors.includes(color))) return false
|
||||
if (selector.tapped !== undefined && object.tapped !== selector.tapped) return false
|
||||
if (selector.attacking !== undefined && Boolean(object.attacking) !== selector.attacking) return false
|
||||
if (selector.token !== undefined && object.isToken !== selector.token) return false
|
||||
if (selector.name && object.definition.name.toLowerCase() !== selector.name.toLowerCase()) return false
|
||||
if (selector.counters) {
|
||||
const count = object.counters[selector.counters.counter] ?? 0
|
||||
if (count < selector.counters.atLeast) return false
|
||||
}
|
||||
if (selector.power) {
|
||||
const power = this.getPower(object)
|
||||
if (selector.power.atLeast !== undefined && power < selector.power.atLeast) return false
|
||||
if (selector.power.atMost !== undefined && power > selector.power.atMost) return false
|
||||
}
|
||||
if (selector.toughness) {
|
||||
const toughness = this.getToughness(object)
|
||||
if (selector.toughness.atLeast !== undefined && toughness < selector.toughness.atLeast) return false
|
||||
if (selector.toughness.atMost !== undefined && toughness > selector.toughness.atMost) return false
|
||||
}
|
||||
if (selector.manaValue) {
|
||||
const value = manaValueOf(object.definition)
|
||||
if (selector.manaValue.atLeast !== undefined && value < selector.manaValue.atLeast) return false
|
||||
if (selector.manaValue.atMost !== undefined && value > selector.manaValue.atMost) return false
|
||||
}
|
||||
if (selector.keywords?.some(keyword => !this.hasKeyword(object, keyword))) return false
|
||||
if (selector.excludeKeywords?.some(keyword => this.hasKeyword(object, keyword))) return false
|
||||
if (selector.attached) {
|
||||
const attached = [...this.objects.values()].some(attachment => attachment.attachedTo === object.id
|
||||
&& (selector.attached === 'equipped' ? this.hasType(attachment, 'equipment') : this.hasType(attachment, 'aura')))
|
||||
if (!attached) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rules helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
}
|
||||
485
backend/src/game/game-turn.ts
Normal file
485
backend/src/game/game-turn.ts
Normal file
@@ -0,0 +1,485 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameActions } from './game-actions.js'
|
||||
|
||||
export class GameTurn extends GameActions {
|
||||
/**
|
||||
* 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)
|
||||
for (const player of this.players) {
|
||||
for (let i = 0; i < this.startingHandSize; i++) {
|
||||
if (!player.library.length) break
|
||||
this.drawCard(player.id, true)
|
||||
}
|
||||
}
|
||||
|
||||
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--
|
||||
}
|
||||
|
||||
protected 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
|
||||
}
|
||||
|
||||
protected 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 =>
|
||||
ability.kind === 'static' && ability.effects.some(effect =>
|
||||
effect.op === 'restriction' && effect.rule === 'begin_on_battlefield'))
|
||||
if (beginsOnBattlefield) this.moveToZone(object, 'battlefield', { controller: player.id, silent: true })
|
||||
}
|
||||
}
|
||||
|
||||
this.status = 'active'
|
||||
this.turn = 1
|
||||
this.activePlayer = this.firstPlayer
|
||||
this.beginTurn()
|
||||
}
|
||||
|
||||
/** Marks a player as having forfeited. */
|
||||
concede(playerId: string): void {
|
||||
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)
|
||||
}
|
||||
|
||||
/** Passes priority. When all players pass, the top of the stack resolves or the phase advances. */
|
||||
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('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
|
||||
this.passesInRow++
|
||||
|
||||
if (!this.stack.length && this.phase === 'combat' && this.step === 'declare_blockers') {
|
||||
const defenders = this.defendingPlayers()
|
||||
if (defenders.has(actual)) this.blockersDeclared.add(actual)
|
||||
if ([...defenders].every(id => this.blockersDeclared.has(id))) {
|
||||
this.finishBlocking()
|
||||
} else {
|
||||
this.priority = this.nextAlivePlayer(actual)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (this.stack.length) {
|
||||
if (this.passesInRow >= alive) {
|
||||
this.passesInRow = 0
|
||||
this.resolveTop()
|
||||
this.priority = this.getPlayer(this.activePlayer).lost ? this.nextAlivePlayer(this.activePlayer) : this.activePlayer
|
||||
} else {
|
||||
this.priority = this.nextAlivePlayer(actual)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (this.passesInRow >= alive) {
|
||||
this.passesInRow = 0
|
||||
this.advancePhase()
|
||||
} else {
|
||||
this.priority = this.nextAlivePlayer(actual)
|
||||
}
|
||||
}
|
||||
|
||||
/** Convenience for tests and scripted games: resolve the stack without advancing phases. */
|
||||
resolveStack(): void {
|
||||
let guard = 0
|
||||
while (this.stack.length && this.status === 'active' && !this.pendingSearch && !this.pendingChoice
|
||||
&& guard++ < 1000) {
|
||||
this.pass(this.priority)
|
||||
}
|
||||
}
|
||||
|
||||
/** Ends the active player's turn, skipping any remaining combat. */
|
||||
endTurn(playerId: string): void {
|
||||
this.requirePriority(playerId)
|
||||
if (playerId !== this.activePlayer) throw new GameError('Only the active player can end the turn')
|
||||
if (this.stack.length) throw new GameError('Cannot end the turn while the stack is not empty')
|
||||
this.clearCombat()
|
||||
this.phase = 'ending'
|
||||
this.step = 'end_step'
|
||||
this.dispatchEvent({ kind: 'end_step', player: playerId })
|
||||
this.resolveStack()
|
||||
if (this.status !== 'active' || this.pendingSearch || this.pendingChoice) return
|
||||
this.finishTurn()
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
autoAdvance(): void {
|
||||
if (this.status !== 'active' || this.pendingSearch || this.pendingChoice || this.autoAdvanceDepth > 0) return
|
||||
this.autoAdvanceDepth++
|
||||
const turn = this.turn
|
||||
try {
|
||||
let guard = 0
|
||||
while (this.status === 'active' && !this.pendingSearch && !this.pendingChoice
|
||||
&& this.turn === turn && guard++ < 100) {
|
||||
const actor = this.priority
|
||||
if (!actor || this.hasMeaningfulAction(actor)) break
|
||||
this.pass(actor)
|
||||
}
|
||||
} finally {
|
||||
this.autoAdvanceDepth--
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Turn structure
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected beginTurn(): void {
|
||||
const player = this.getPlayer(this.activePlayer)
|
||||
this.phase = 'beginning'
|
||||
this.step = 'untap'
|
||||
this.passesInRow = 0
|
||||
this.priority = player.id
|
||||
player.landPlayedThisTurn = false
|
||||
player.cardsDrawnThisTurn = 0
|
||||
player.lifeGainedThisTurn = 0
|
||||
player.spellsCastThisTurn = 0
|
||||
player.creaturesDiedThisTurn = 0
|
||||
player.nonlandPermanentsEnteredThisTurn = 0
|
||||
player.attackedThisTurn = false
|
||||
player.creaturesAttackedThisTurn = 0
|
||||
player.damageTakenThisTurn = 0
|
||||
player.manaPool = emptyPool()
|
||||
this.triggeredThisTurn.clear()
|
||||
|
||||
this.removeExpiringEffects(player.id)
|
||||
for (const id of [...player.battlefield]) {
|
||||
const object = this.objects.get(id)
|
||||
if (!object || object.zone !== 'battlefield') continue
|
||||
if (!this.hasRestriction(object, 'doesnt_untap')) object.tapped = false
|
||||
}
|
||||
|
||||
this.step = 'upkeep'
|
||||
this.dispatchEvent({ kind: 'upkeep', player: player.id })
|
||||
if (this.status !== 'active') return
|
||||
|
||||
this.step = 'draw'
|
||||
if (!this.skipsDrawStep(player.id)) this.drawCard(player.id, false)
|
||||
if (this.status !== 'active') return
|
||||
|
||||
this.phase = 'precombat_main'
|
||||
this.step = 'main'
|
||||
this.priority = player.id
|
||||
this.passesInRow = 0
|
||||
}
|
||||
|
||||
/** True when a permanent that player controls replaces their draw step. */
|
||||
private skipsDrawStep(playerId: string): boolean {
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
if (source.controller !== playerId) continue
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'restriction' || effect.rule !== 'skip_draw_step') continue
|
||||
if (effect.target.kind === 'player' && (effect.target.who === 'you' || effect.target.who === 'each_player')) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
protected finishTurn(): void {
|
||||
const player = this.getPlayer(this.activePlayer)
|
||||
while (player.hand.length > 7) {
|
||||
const cardId = player.hand[player.hand.length - 1]
|
||||
this.moveToZone(cardId, 'graveyard', { silent: true })
|
||||
}
|
||||
for (const object of this.objects.values()) {
|
||||
if (object.zone === 'battlefield') {
|
||||
object.damage = 0
|
||||
object.deathtouched = false
|
||||
}
|
||||
}
|
||||
this.removeEffectsByDuration('until_end_of_turn')
|
||||
// shortcut: every prevention shield expires at end of turn; upgrade when a
|
||||
// permanent prevention effect is parsed (currently only one-shot shields).
|
||||
this.damageShields.length = 0
|
||||
this.removeEndOfNextTurnEffects(player.id)
|
||||
this.clearCombat()
|
||||
for (const entry of this.players) entry.manaPool = emptyPool()
|
||||
|
||||
if (this.status !== 'active') return
|
||||
this.turn++
|
||||
this.activePlayer = this.nextAlivePlayer(this.activePlayer)
|
||||
this.beginTurn()
|
||||
}
|
||||
|
||||
protected advancePhase(): void {
|
||||
if (this.status !== 'active') return
|
||||
if (this.stack.length) return
|
||||
this.emptyManaPools()
|
||||
|
||||
if (this.step === 'main' && this.phase === 'precombat_main') {
|
||||
this.phase = 'combat'
|
||||
this.step = 'begin_combat'
|
||||
this.dispatchEvent({ kind: 'begin_combat', player: this.activePlayer })
|
||||
this.step = 'declare_attackers'
|
||||
this.priority = this.activePlayer
|
||||
this.passesInRow = 0
|
||||
return
|
||||
}
|
||||
if (this.step === 'declare_attackers') {
|
||||
this.step = 'end_combat'
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
return
|
||||
}
|
||||
if (this.step === 'declare_blockers') {
|
||||
this.step = 'combat_damage'
|
||||
this.combatDamageDone = false
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
return
|
||||
}
|
||||
if (this.step === 'combat_damage') {
|
||||
this.combatDamageDone = true
|
||||
this.dealCombatDamage()
|
||||
this.runStateBasedActions()
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
return
|
||||
}
|
||||
if (this.step === 'end_combat') {
|
||||
this.clearCombat()
|
||||
this.removeEffectsByDuration('until_end_of_combat')
|
||||
this.phase = 'postcombat_main'
|
||||
this.step = 'main'
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
return
|
||||
}
|
||||
if (this.step === 'main' && this.phase === 'postcombat_main') {
|
||||
this.phase = 'ending'
|
||||
this.step = 'end_step'
|
||||
this.dispatchEvent({ kind: 'end_step', player: this.activePlayer })
|
||||
this.passesInRow = 0
|
||||
this.priority = this.activePlayer
|
||||
return
|
||||
}
|
||||
if (this.step === 'end_step') {
|
||||
this.finishTurn()
|
||||
}
|
||||
}
|
||||
|
||||
protected resolveTop(): void {
|
||||
const top = this.stack[this.stack.length - 1]
|
||||
if (!top) return
|
||||
if (top.optional && top.optionalAccepted === undefined) {
|
||||
this.pendingChoices.push({
|
||||
playerId: top.controller,
|
||||
sourceId: top.source.id,
|
||||
what: 'optional',
|
||||
label: top.label,
|
||||
})
|
||||
return
|
||||
}
|
||||
const item = this.stack.pop()
|
||||
if (!item) return
|
||||
if (item.kind === 'spell' && item.source.zone !== 'stack') return
|
||||
|
||||
const context = this.contextFor(
|
||||
item.source,
|
||||
item.controller,
|
||||
item.targets,
|
||||
item.x,
|
||||
item.mode,
|
||||
item.triggerSubject,
|
||||
item.eventPlayer,
|
||||
item.eventAmount,
|
||||
)
|
||||
context.optionalTaken = item.optionalAccepted !== false
|
||||
// Declining a "you may" still runs the "If you don't/Otherwise" branches.
|
||||
// shortcut: optionality covers the whole effect list, not just its first
|
||||
// sentence; upgrade when a card mixes an optional sentence with an
|
||||
// unconditional later sentence.
|
||||
const declined = item.optionalAccepted === false
|
||||
const effects = declined
|
||||
? item.effects.filter(effect => effect.op === 'conditional'
|
||||
&& (effect.condition.kind === 'if_you_dont' || effect.condition.kind === 'otherwise'))
|
||||
: item.effects
|
||||
|
||||
if (item.kind === 'spell') {
|
||||
if (this.isPermanent(item.source)) {
|
||||
if (item.source.zone === 'stack') {
|
||||
this.moveToZone(item.source, 'battlefield', { controller: item.controller, silent: false })
|
||||
}
|
||||
this.applyEffects(context, effects)
|
||||
} else {
|
||||
this.applyEffects(context, effects)
|
||||
if (item.source.zone === 'stack') this.moveToZone(item.source, 'graveyard', { silent: true })
|
||||
}
|
||||
} else {
|
||||
this.applyEffects(context, effects)
|
||||
}
|
||||
|
||||
this.logMessage(`Resolved ${item.label}`)
|
||||
this.runStateBasedActions()
|
||||
}
|
||||
|
||||
protected counterStackItem(item: StackItem): void {
|
||||
const index = this.stack.indexOf(item)
|
||||
if (index >= 0) this.stack.splice(index, 1)
|
||||
if (item.kind === 'spell' && item.source.zone === 'stack') {
|
||||
this.moveToZone(item.source, 'graveyard', { silent: true })
|
||||
}
|
||||
this.logMessage(`Countered ${item.label}`)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Casting, mana, and costs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
protected canCastAtThisTime(playerId: string, object: GameObject): boolean {
|
||||
const instant = this.isInstant(object)
|
||||
const flash = this.hasKeywordForDefinition(object.definition, 'Flash')
|
||||
if (instant || flash) return true
|
||||
return this.isMainPhaseWithEmptyStack(playerId)
|
||||
}
|
||||
|
||||
protected isMainPhaseWithEmptyStack(playerId: string): boolean {
|
||||
return this.activePlayer === playerId
|
||||
&& (this.phase === 'precombat_main' || this.phase === 'postcombat_main')
|
||||
&& this.step === 'main'
|
||||
&& this.stack.length === 0
|
||||
}
|
||||
|
||||
protected 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('Resolve the pending choice first')
|
||||
if (this.priority !== playerId) throw new GameError('You do not have priority')
|
||||
}
|
||||
|
||||
protected hasMeaningfulAction(playerId: string): boolean {
|
||||
if (this.status !== 'active' || this.priority !== playerId || this.pendingChoice) return false
|
||||
const player = this.getPlayer(playerId)
|
||||
if (player.lost) return false
|
||||
|
||||
if (this.phase === 'combat' && this.step === 'declare_attackers' && !this.stack.length
|
||||
&& this.activePlayer === playerId && this.canAttackWithAny(playerId)) {
|
||||
return true
|
||||
}
|
||||
if (this.phase === 'combat' && this.step === 'declare_blockers' && !this.stack.length
|
||||
&& this.canBlockWithAny(playerId)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if ([...player.hand, ...player.command, ...player.exile].some(id => this.canPlayCard(playerId, id))) return true
|
||||
|
||||
for (const id of player.battlefield) {
|
||||
const object = this.objects.get(id)
|
||||
if (!object) continue
|
||||
const abilities = object.definition.abilities ?? []
|
||||
for (let index = 0; index < abilities.length; index++) {
|
||||
const ability = abilities[index]
|
||||
if (ability.kind !== 'activated') continue
|
||||
// Mana abilities alone do not advance the game; counting them would
|
||||
// stop auto-pass on every untapped land.
|
||||
if (ability.effects.length && ability.effects.every(effect => effect.op === 'add_mana')) continue
|
||||
if (this.isActivatedAbilityPlayable(playerId, object, index, ability)) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
479
backend/src/game/game-zones.ts
Normal file
479
backend/src/game/game-zones.ts
Normal file
@@ -0,0 +1,479 @@
|
||||
import type {
|
||||
Ability,
|
||||
Condition,
|
||||
Cost,
|
||||
Duration,
|
||||
Effect,
|
||||
ManaSpec,
|
||||
ObjectSelector,
|
||||
PlayerRef,
|
||||
StaticEffect,
|
||||
Target,
|
||||
TokenSpec,
|
||||
TriggerEvent,
|
||||
Value,
|
||||
Zone,
|
||||
} from '../effects/types.js'
|
||||
import type {
|
||||
ActionOptions,
|
||||
CardDefinition,
|
||||
CombatAttack,
|
||||
CombatBlock,
|
||||
GameObject,
|
||||
GameConfig,
|
||||
ManaColor,
|
||||
ManaPool,
|
||||
MulliganState,
|
||||
PendingChoice,
|
||||
PendingSearch,
|
||||
Phase,
|
||||
PlayerState,
|
||||
StackItem,
|
||||
Step,
|
||||
TargetChoice,
|
||||
} from './types.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { predefinedToken } from './tokens.js'
|
||||
|
||||
import { GameError, ResolvedTarget, EventContext, EffectContext, ContinuousEffect, DamageShield, ManaCost, CostReduction, MANA_COLORS, COLOR_NAMES, emptyPool, parseManaCost, reduceManaSymbols, manaValueOf, colorOfSymbol, tokenCard, capitalize, tokenFace, mulberry32 } from './game-helpers.js'
|
||||
import { GameCombat } from './game-combat.js'
|
||||
|
||||
export abstract class GameZones extends GameCombat {
|
||||
/**
|
||||
* Adds a card directly to a zone. Intended for setup, tests, and future
|
||||
* deck-building flows; by default no enter/leave triggers fire.
|
||||
*/
|
||||
addCard(
|
||||
playerId: string,
|
||||
definition: CardDefinition,
|
||||
zone: Zone,
|
||||
options: { controller?: string; tapped?: boolean; silent?: boolean } = {},
|
||||
): GameObject {
|
||||
const object = this.createObject(definition, playerId)
|
||||
this.moveToZone(object, zone, { ...options, silent: options.silent ?? true })
|
||||
return object
|
||||
}
|
||||
|
||||
/** Purely cosmetic board layout: normalized center within the controller's mat. */
|
||||
movePermanent(playerId: string, cardId: string, x: number, y: number): void {
|
||||
const object = this.getObject(cardId)
|
||||
if (object.zone !== 'battlefield') throw new GameError('That card is not on the battlefield')
|
||||
if (object.controller !== playerId) throw new GameError('You do not control that permanent')
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new GameError('Invalid position')
|
||||
object.position = {
|
||||
x: Math.min(1, Math.max(0, x)),
|
||||
y: Math.min(1, Math.max(0, y)),
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves an object to a zone, firing leave/enter triggers unless silenced. */
|
||||
moveToZone(
|
||||
objectOrId: GameObject | string,
|
||||
zone: Zone,
|
||||
options: { controller?: string; tapped?: boolean; silent?: boolean; toTop?: boolean } = {},
|
||||
): GameObject {
|
||||
const object = typeof objectOrId === 'string' ? this.getObject(objectOrId) : objectOrId
|
||||
// A commander may go to the command zone instead of the graveyard, exile,
|
||||
// hand, or library. This engine always takes that replacement.
|
||||
let destination: Zone = object.isCommander && zone !== 'battlefield' && zone !== 'stack' && zone !== 'command'
|
||||
? 'command'
|
||||
: zone
|
||||
if (destination === 'graveyard' && this.exilesInsteadOfGraveyard(object)) destination = 'exile'
|
||||
if (destination === 'graveyard' && object.exileOnDeathTurn === this.turn && this.isCreature(object)) destination = 'exile'
|
||||
const from = object.zone
|
||||
this.removeFromZone(object)
|
||||
object.zone = destination
|
||||
if (destination !== 'exile') object.faceDown = undefined
|
||||
|
||||
if (destination === 'battlefield') {
|
||||
object.controller = options.controller ?? object.owner
|
||||
object.tapped = options.tapped ?? false
|
||||
object.damage = 0
|
||||
object.deathtouched = false
|
||||
object.attacking = undefined
|
||||
object.blockedBy = []
|
||||
object.blocking = undefined
|
||||
object.activations = {}
|
||||
object.chosenCreatureType = undefined
|
||||
object.chosenColor = undefined
|
||||
object.enteredTurn = this.turn
|
||||
object.exileOnDeathTurn = undefined
|
||||
this.getPlayer(object.controller).battlefield.push(object.id)
|
||||
if (from !== 'battlefield') {
|
||||
if (this.turn > 0 && !this.isLand(object)) {
|
||||
this.getPlayer(object.controller).nonlandPermanentsEnteredThisTurn++
|
||||
}
|
||||
if (!options.silent) {
|
||||
this.applyEntersReplacements(object)
|
||||
this.queueEnterChoices(object)
|
||||
this.dispatchEvent({ kind: 'enters', player: object.controller, subject: object })
|
||||
}
|
||||
}
|
||||
} else {
|
||||
object.position = undefined
|
||||
object.controller = object.owner
|
||||
object.chosenCreatureType = undefined
|
||||
object.chosenColor = undefined
|
||||
const owner = this.getPlayer(object.owner)
|
||||
if (destination === 'hand') owner.hand.push(object.id)
|
||||
else if (destination === 'graveyard') owner.graveyard.push(object.id)
|
||||
else if (destination === 'exile') owner.exile.push(object.id)
|
||||
else if (destination === 'command') {
|
||||
object.tapped = false
|
||||
owner.command.push(object.id)
|
||||
} else if (destination === 'library') {
|
||||
if (options.toTop) owner.library.unshift(object.id)
|
||||
else owner.library.push(object.id)
|
||||
}
|
||||
}
|
||||
|
||||
if (from === 'battlefield' && destination !== 'battlefield') {
|
||||
this.handleLeavesBattlefield(object, destination)
|
||||
}
|
||||
|
||||
if (object.isToken && from === 'battlefield' && destination !== 'battlefield') {
|
||||
this.objects.delete(object.id)
|
||||
}
|
||||
|
||||
return object
|
||||
}
|
||||
|
||||
protected handleLeavesBattlefield(object: GameObject, destination: Zone): void {
|
||||
if (object.attachedTo) {
|
||||
const attached = this.objects.get(object.attachedTo)
|
||||
if (attached) attached.attachments = attached.attachments.filter(id => id !== object.id)
|
||||
object.attachedTo = undefined
|
||||
}
|
||||
for (const attachmentId of [...object.attachments]) {
|
||||
const attachment = this.objects.get(attachmentId)
|
||||
if (attachment) attachment.attachedTo = undefined
|
||||
}
|
||||
object.attachments = []
|
||||
object.attacking = undefined
|
||||
object.blockedBy = []
|
||||
object.blocking = undefined
|
||||
object.linkedExile = undefined
|
||||
|
||||
for (let index = this.continuousEffects.length - 1; index >= 0; index--) {
|
||||
const effect = this.continuousEffects[index]
|
||||
if (effect.sourceId !== object.id) continue
|
||||
if (effect.duration === 'permanent' || effect.duration === 'while_source_on_battlefield') {
|
||||
this.continuousEffects.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
if (destination === 'graveyard' && this.isCreature(object)) {
|
||||
this.getPlayer(object.controller).creaturesDiedThisTurn++
|
||||
this.dispatchEvent({ kind: 'dies', player: object.controller, subject: object })
|
||||
}
|
||||
this.dispatchEvent({ kind: 'leaves_battlefield', player: object.controller, subject: object })
|
||||
}
|
||||
|
||||
protected runStateBasedActions(): void {
|
||||
if (this.status !== 'active') return
|
||||
let changed = true
|
||||
let guard = 0
|
||||
while (changed && guard++ < 50 && this.status === 'active') {
|
||||
changed = false
|
||||
for (const player of this.players) {
|
||||
if (!player.lost && (player.life <= 0 || player.poison >= 10
|
||||
|| Object.values(player.commanderDamage).some(damage => damage >= 21))) {
|
||||
this.losePlayer(player.id)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (this.status !== 'active') return
|
||||
for (const id of [...this.battlefieldObjects().map(object => object.id)]) {
|
||||
const object = this.objects.get(id)
|
||||
if (!object || object.zone !== 'battlefield' || !this.isCreature(object)) continue
|
||||
const lethal = this.getToughness(object) <= 0
|
||||
|| object.damage >= this.getToughness(object)
|
||||
|| (object.deathtouched && object.damage > 0)
|
||||
if (!lethal) continue
|
||||
if (this.hasKeyword(object, 'Indestructible')) continue
|
||||
if (object.regenerationShields > 0) {
|
||||
object.regenerationShields--
|
||||
object.tapped = true
|
||||
object.damage = 0
|
||||
object.deathtouched = false
|
||||
object.attacking = undefined
|
||||
object.blockedBy = []
|
||||
object.blocking = undefined
|
||||
} else {
|
||||
this.moveToZone(object, 'graveyard', { silent: false })
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
for (const player of this.alivePlayers()) {
|
||||
const legends = new Map<string, GameObject[]>()
|
||||
for (const object of this.battlefieldObjects()) {
|
||||
if (object.controller !== player.id || !/\blegendary\b/i.test(object.definition.typeLine)) continue
|
||||
const name = object.definition.name.toLowerCase()
|
||||
legends.set(name, [...(legends.get(name) ?? []), object])
|
||||
}
|
||||
for (const copies of legends.values()) {
|
||||
// shortcut: keeps the first copy found, not the player's choice; ask when the API can pause for it
|
||||
for (const extra of copies.slice(1)) {
|
||||
this.moveToZone(extra, 'graveyard', { silent: false })
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected losePlayer(playerId: string): void {
|
||||
const player = this.getPlayer(playerId)
|
||||
if (player.lost) return
|
||||
player.lost = true
|
||||
this.logMessage(`${player.name} loses the game`)
|
||||
const alive = this.alivePlayers()
|
||||
if (alive.length <= 1) {
|
||||
this.status = 'finished'
|
||||
this.winner = alive[0]?.id
|
||||
if (this.winner) this.logMessage(`${this.getPlayer(this.winner).name} wins`)
|
||||
}
|
||||
}
|
||||
|
||||
protected gainLife(playerId: string, amount: number): void {
|
||||
amount = this.replacementAmount('life_gain', playerId, amount)
|
||||
if (amount <= 0) return
|
||||
const player = this.getPlayer(playerId)
|
||||
if (player.lost) return
|
||||
player.life += amount
|
||||
player.lifeGainedThisTurn += amount
|
||||
this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'gain' })
|
||||
}
|
||||
|
||||
protected loseLife(playerId: string, amount: number): void {
|
||||
if (amount <= 0) return
|
||||
const player = this.getPlayer(playerId)
|
||||
if (player.lost) return
|
||||
player.life -= amount
|
||||
this.dispatchEvent({ kind: 'life', player: playerId, amount, mode: 'lose' })
|
||||
this.runStateBasedActions()
|
||||
}
|
||||
|
||||
protected drawCard(playerId: string, silent: boolean): void {
|
||||
const count = this.replacementAmount('draw', playerId, 1)
|
||||
for (let i = 0; i < count; i++) this.drawOne(playerId, silent)
|
||||
}
|
||||
|
||||
private drawOne(playerId: string, silent: boolean): void {
|
||||
const player = this.getPlayer(playerId)
|
||||
if (player.lost) return
|
||||
if (!player.library.length) {
|
||||
this.losePlayer(playerId)
|
||||
return
|
||||
}
|
||||
const id = player.library.shift()
|
||||
if (!id) return
|
||||
player.hand.push(id)
|
||||
const object = this.getObject(id)
|
||||
object.zone = 'hand'
|
||||
object.controller = playerId
|
||||
player.cardsDrawnThisTurn++
|
||||
if (!silent) {
|
||||
this.dispatchEvent({ kind: 'draw', player: playerId, amount: 1, ordinal: player.cardsDrawnThisTurn })
|
||||
}
|
||||
}
|
||||
|
||||
protected drawCards(playerId: string, amount: number): void {
|
||||
for (let i = 0; i < amount; i++) this.drawCard(playerId, false)
|
||||
}
|
||||
|
||||
protected discardCards(playerId: string, amount: number, random: boolean | undefined, context: EffectContext): void {
|
||||
const player = this.getPlayer(playerId)
|
||||
for (let i = 0; i < amount && player.hand.length; i++) {
|
||||
const index = random ? Math.floor(this.rng() * player.hand.length) : 0
|
||||
const id = player.hand[index]
|
||||
this.moveToZone(id, 'graveyard', { silent: false })
|
||||
}
|
||||
void context
|
||||
}
|
||||
|
||||
protected millCards(playerId: string, amount: number): void {
|
||||
const player = this.getPlayer(playerId)
|
||||
for (let i = 0; i < amount && player.library.length; i++) {
|
||||
const id = player.library[0]
|
||||
this.moveToZone(id, 'graveyard', { silent: true })
|
||||
}
|
||||
}
|
||||
|
||||
protected searchLibrary(
|
||||
playerId: string,
|
||||
selector: ObjectSelector,
|
||||
amount: number,
|
||||
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
|
||||
tapped: boolean,
|
||||
shuffle: boolean,
|
||||
zones?: ('library' | 'graveyard')[],
|
||||
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean },
|
||||
): void {
|
||||
// shortcut: a search only pauses itself; later effects in the same ability
|
||||
// still run before the pick, and a second search in that ability is skipped.
|
||||
// Most search lines are a single effect.
|
||||
if (this.pendingSearch) return
|
||||
const player = this.getPlayer(playerId)
|
||||
// Searching then shuffling is the same as shuffling first when the picked
|
||||
// cards go on top, and it keeps the shuffle from burying them again.
|
||||
if (shuffle && (destination === 'top' || split?.destination === 'top')) {
|
||||
this.shuffleLibrary(player)
|
||||
shuffle = false
|
||||
}
|
||||
let remaining = amount
|
||||
let first = true
|
||||
while (remaining > 0) {
|
||||
const pickDestination = first ? destination : (split?.destination ?? destination)
|
||||
const pickTapped = first ? tapped : (split?.tapped ?? tapped)
|
||||
const candidates = this.findSearchCandidates(playerId, selector, zones)
|
||||
if (!candidates.length) break
|
||||
if (candidates.length > 1) {
|
||||
this.pendingSearch = {
|
||||
playerId,
|
||||
selector,
|
||||
remaining,
|
||||
destination: pickDestination,
|
||||
tapped: pickTapped,
|
||||
shuffle,
|
||||
zones,
|
||||
...(first && split && remaining > 1 ? { split } : {}),
|
||||
}
|
||||
return
|
||||
}
|
||||
this.moveSearchedCard(candidates[0], playerId, pickDestination, pickTapped)
|
||||
remaining--
|
||||
first = false
|
||||
}
|
||||
if (shuffle) this.shuffleLibrary(player)
|
||||
}
|
||||
|
||||
protected findSearchCandidates(
|
||||
playerId: string,
|
||||
selector: ObjectSelector,
|
||||
zones?: ('library' | 'graveyard')[],
|
||||
): GameObject[] {
|
||||
const source = this.playerSource(playerId)
|
||||
return this.searchableObjects(playerId, zones)
|
||||
.filter(object => this.matchesSelector(object, selector, source, object.zone))
|
||||
}
|
||||
|
||||
protected searchableObjects(playerId: string, zones?: ('library' | 'graveyard')[]): GameObject[] {
|
||||
const player = this.getPlayer(playerId)
|
||||
const allowed = zones ?? ['library']
|
||||
const libraryLimit = this.searchLibraryLimit(playerId)
|
||||
const ids = allowed.includes('library')
|
||||
? player.library.slice(0, libraryLimit ?? player.library.length)
|
||||
: []
|
||||
if (allowed.includes('graveyard')) ids.push(...player.graveyard)
|
||||
return ids.map(id => this.getObject(id)).filter(object => object.owner === playerId)
|
||||
}
|
||||
|
||||
protected moveSearchedCard(
|
||||
object: GameObject,
|
||||
playerId: string,
|
||||
destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom',
|
||||
tapped: boolean,
|
||||
): void {
|
||||
if (destination === 'battlefield') {
|
||||
this.moveToZone(object, 'battlefield', { controller: playerId, tapped, silent: false })
|
||||
} else if (destination === 'hand') {
|
||||
this.moveToZone(object, 'hand', { silent: false })
|
||||
} else if (destination === 'graveyard') {
|
||||
this.moveToZone(object, 'graveyard', { silent: false })
|
||||
} else if (destination === 'top') {
|
||||
this.moveToZone(object, 'library', { toTop: true, silent: false })
|
||||
} else {
|
||||
this.moveToZone(object, 'library', { silent: false })
|
||||
}
|
||||
}
|
||||
|
||||
// shortcut: the limit is recomputed after each pick, so a multi-card search
|
||||
// can see one new card per pick. Upgrade when a card searches for several
|
||||
// cards while Aven Mindcensor is out.
|
||||
protected searchLibraryLimit(playerId: string): number | undefined {
|
||||
let limit: number | undefined
|
||||
for (const { source, ability } of this.staticAbilities()) {
|
||||
for (const effect of ability.effects) {
|
||||
if (effect.op !== 'search_restriction') continue
|
||||
const applies = effect.who === 'you' ? playerId === source.controller : playerId !== source.controller
|
||||
if (!applies) continue
|
||||
const amount = this.value(effect.amount, this.staticContext(source))
|
||||
limit = limit === undefined ? amount : Math.min(limit, amount)
|
||||
}
|
||||
}
|
||||
return limit
|
||||
}
|
||||
|
||||
protected shuffleLibrary(player: PlayerState): void {
|
||||
for (let index = player.library.length - 1; index > 0; index--) {
|
||||
const swap = Math.floor(this.rng() * (index + 1))
|
||||
const temp = player.library[index]
|
||||
player.library[index] = player.library[swap]
|
||||
player.library[swap] = temp
|
||||
}
|
||||
}
|
||||
|
||||
protected removeFromZone(object: GameObject): void {
|
||||
const owner = this.getPlayer(object.owner)
|
||||
if (object.zone === 'battlefield') {
|
||||
const controller = this.getPlayer(object.controller)
|
||||
controller.battlefield = controller.battlefield.filter(id => id !== object.id)
|
||||
} else if (object.zone === 'hand') owner.hand = owner.hand.filter(id => id !== object.id)
|
||||
else if (object.zone === 'graveyard') owner.graveyard = owner.graveyard.filter(id => id !== object.id)
|
||||
else if (object.zone === 'exile') owner.exile = owner.exile.filter(id => id !== object.id)
|
||||
else if (object.zone === 'command') owner.command = owner.command.filter(id => id !== object.id)
|
||||
else if (object.zone === 'library') owner.library = owner.library.filter(id => id !== object.id)
|
||||
}
|
||||
|
||||
protected removeExpiringEffects(playerId: string): void {
|
||||
for (let index = this.continuousEffects.length - 1; index >= 0; index--) {
|
||||
const effect = this.continuousEffects[index]
|
||||
if ((effect.duration === 'until_your_next_turn' || effect.duration === 'until_controllers_next_untap_step')
|
||||
&& effect.controller === playerId) {
|
||||
this.continuousEffects.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** "Until the end of your next turn" skips the turn the effect was created in. */
|
||||
protected removeEndOfNextTurnEffects(playerId: string): void {
|
||||
for (let index = this.continuousEffects.length - 1; index >= 0; index--) {
|
||||
const effect = this.continuousEffects[index]
|
||||
if (effect.duration === 'until_end_of_your_next_turn' && effect.controller === playerId
|
||||
&& effect.createdTurn !== this.turn) {
|
||||
this.continuousEffects.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected removeEffectsByDuration(duration: Duration): void {
|
||||
for (let index = this.continuousEffects.length - 1; index >= 0; index--) {
|
||||
if (this.continuousEffects[index].duration === duration) this.continuousEffects.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
protected findStackItem(id: string): StackItem | undefined {
|
||||
return this.stack.find(item => item.id === id) ?? this.stack.find(item => item.source.id === id)
|
||||
}
|
||||
|
||||
protected playerSource(playerId: string): GameObject {
|
||||
return {
|
||||
id: `player:${playerId}`,
|
||||
definition: { oracleId: `player:${playerId}`, name: this.getPlayer(playerId).name, typeLine: '' },
|
||||
owner: playerId,
|
||||
controller: playerId,
|
||||
zone: 'battlefield',
|
||||
tapped: false,
|
||||
damage: 0,
|
||||
deathtouched: false,
|
||||
counters: {},
|
||||
isToken: false,
|
||||
enteredTurn: 0,
|
||||
blockedBy: [],
|
||||
attachments: [],
|
||||
regenerationShields: 0,
|
||||
activations: {},
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,9 +2,10 @@ import { randomUUID } from 'node:crypto'
|
||||
import { getCard, type Card } from '../cards.js'
|
||||
import { deletePlaymatImage, PlaymatError, scryfallArtUrl, storePlaymatImage } from '../images.js'
|
||||
import { getCardDefinition } from './catalog.js'
|
||||
import { CREATURE_TYPES } from './creature-types.js'
|
||||
import { validateCommanderDeck } from './commander.js'
|
||||
import { Game, GameError } from './game.js'
|
||||
import type { CardDefinition, GameObject, ManaPool, TargetChoice } from './types.js'
|
||||
import type { CardDefinition, GameObject, ManaColor, ManaPool, TargetChoice } from './types.js'
|
||||
|
||||
export class MatchError extends Error {
|
||||
constructor(message: string, readonly status = 400) {
|
||||
@@ -25,6 +26,13 @@ export interface ActionPayload {
|
||||
targets?: TargetChoice[]
|
||||
x?: number
|
||||
mode?: number
|
||||
overload?: boolean
|
||||
choice?: string
|
||||
/** Mana color picked when activating a mana ability that can make several. */
|
||||
color?: string
|
||||
pay?: boolean
|
||||
/** Answer to a "you may ..." prompt. */
|
||||
accept?: boolean
|
||||
position?: { x?: unknown; y?: unknown }
|
||||
attackers?: { attackerId: string; defenderId: string }[]
|
||||
blocks?: { blockerId: string; attackerId: string }[]
|
||||
@@ -54,7 +62,15 @@ export interface CardView {
|
||||
attacking?: string
|
||||
blockedBy: string[]
|
||||
blocking?: string
|
||||
abilities: { index: number; kind: string; text?: string }[]
|
||||
/** Creature type chosen as this permanent entered, if any. */
|
||||
chosenType?: string
|
||||
/** Number of face-down cards exiled under this permanent (hideaway). */
|
||||
hiddenCards?: number
|
||||
/** This exiled card is face down; its identity is not included. */
|
||||
faceDown?: boolean
|
||||
/** Legal choices for this card's targets, for the cast panel. */
|
||||
targets?: TargetChoice[]
|
||||
abilities: { index: number; kind: string; text?: string; targets?: TargetChoice[]; manaColors?: string[] }[]
|
||||
/** Viewer-specific: can this card be played from hand right now? */
|
||||
playable?: boolean
|
||||
}
|
||||
@@ -105,6 +121,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[]
|
||||
@@ -115,6 +133,23 @@ export interface MatchView {
|
||||
remaining: number
|
||||
destination: string
|
||||
cards: CardView[]
|
||||
/** Every card in the searched zones, populated only for its chooser. */
|
||||
library?: CardView[]
|
||||
}
|
||||
/** Present while an "as this enters, choose..." prompt waits for its controller. */
|
||||
pendingChoice?: {
|
||||
player: string
|
||||
what: string
|
||||
sourceId: string
|
||||
sourceName: string
|
||||
/** Life total to display for a `pay_life` cost. */
|
||||
amount?: number
|
||||
/** Ability name shown when asking about a "you may" effect. */
|
||||
label?: string
|
||||
/** Choices to offer, populated only for the chooser. */
|
||||
options: string[]
|
||||
/** Cards to choose from for hideaway, populated only for the chooser. */
|
||||
cards?: CardView[]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,6 +382,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,
|
||||
@@ -403,10 +439,21 @@ export function performAction(matchId: string, token: string | undefined, action
|
||||
targets,
|
||||
x: Number.isFinite(action.x) ? Number(action.x) : 0,
|
||||
mode: Number.isFinite(action.mode) ? Number(action.mode) : 0,
|
||||
overload: action.overload === true,
|
||||
manaColor: manaColorOf(action.color),
|
||||
}
|
||||
|
||||
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
|
||||
@@ -425,6 +472,25 @@ export function performAction(matchId: string, token: string | undefined, action
|
||||
case 'choose_search':
|
||||
game.chooseSearchCard(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'choose_hideaway':
|
||||
game.chooseHideawayCard(seat.playerId, requireId(action.cardId))
|
||||
break
|
||||
case 'choose_type':
|
||||
if (typeof action.choice !== 'string') throw new MatchError('Missing type choice')
|
||||
game.chooseCreatureType(seat.playerId, action.choice)
|
||||
break
|
||||
case 'choose_color':
|
||||
if (typeof action.choice !== 'string') throw new MatchError('Missing color choice')
|
||||
game.chooseColor(seat.playerId, action.choice)
|
||||
break
|
||||
case 'choose_optional':
|
||||
if (typeof action.accept !== 'boolean') throw new MatchError('Missing optional choice')
|
||||
game.chooseOptional(seat.playerId, action.accept)
|
||||
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 => ({
|
||||
@@ -463,9 +529,46 @@ function requireId(id: unknown): string {
|
||||
return id
|
||||
}
|
||||
|
||||
function manaColorOf(value: unknown): ManaColor | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (typeof value !== 'string' || !/^[WUBRGCS]$/i.test(value)) throw new MatchError('Invalid mana color')
|
||||
return value.toUpperCase() as ManaColor
|
||||
}
|
||||
|
||||
function cardView(game: Game, object: GameObject, abilities = true): CardView {
|
||||
// Face-down exiled cards (hideaway) keep their identity server-side only.
|
||||
if (object.faceDown) {
|
||||
return {
|
||||
id: object.id,
|
||||
oracleId: '',
|
||||
name: 'Face-down card',
|
||||
typeLine: '',
|
||||
colors: [],
|
||||
colorIdentity: [],
|
||||
tapped: false,
|
||||
damage: 0,
|
||||
counters: {},
|
||||
isToken: false,
|
||||
isCommander: false,
|
||||
zone: object.zone,
|
||||
controller: object.controller,
|
||||
owner: object.owner,
|
||||
blockedBy: [],
|
||||
faceDown: true,
|
||||
abilities: [],
|
||||
}
|
||||
}
|
||||
const definition = object.definition
|
||||
const creature = /creature/i.test(definition.typeLine)
|
||||
const hiddenCards = object.zone === 'battlefield'
|
||||
? (object.linkedExile ?? []).filter(id => {
|
||||
const linked = game.objects.get(id)
|
||||
return linked?.zone === 'exile' && linked.faceDown
|
||||
}).length
|
||||
: 0
|
||||
const targets = object.zone === 'hand' || object.zone === 'command' || object.zone === 'exile'
|
||||
? game.legalTargetsForCard(object.owner, object.id)
|
||||
: []
|
||||
return {
|
||||
id: object.id,
|
||||
oracleId: definition.oracleId,
|
||||
@@ -490,11 +593,18 @@ function cardView(game: Game, object: GameObject, abilities = true): CardView {
|
||||
attacking: object.attacking,
|
||||
blockedBy: [...object.blockedBy],
|
||||
blocking: object.blocking,
|
||||
chosenType: object.chosenCreatureType,
|
||||
hiddenCards: hiddenCards || undefined,
|
||||
targets: targets.length ? targets : undefined,
|
||||
abilities: abilities
|
||||
? (definition.abilities ?? []).map((ability, index) => ({
|
||||
index,
|
||||
kind: ability.kind,
|
||||
text: 'text' in ability ? ability.text : undefined,
|
||||
manaColors: game.manaColorChoices(object, index),
|
||||
targets: ability.kind === 'activated' && object.zone === 'battlefield'
|
||||
? game.legalTargetsForAbility(object.controller, object.id, index)
|
||||
: undefined,
|
||||
}))
|
||||
: [],
|
||||
}
|
||||
@@ -519,6 +629,16 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
const game = match.game
|
||||
if (!game) return view
|
||||
|
||||
const hiddenUnderSource = new Set<string>()
|
||||
for (const player of game.players) {
|
||||
for (const id of player.battlefield) {
|
||||
for (const linked of game.getObject(id).linkedExile ?? []) {
|
||||
const object = game.objects.get(linked)
|
||||
if (object?.zone === 'exile' && object.faceDown) hiddenUnderSource.add(linked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view.players = match.seats.map(seat => {
|
||||
const player = game.getPlayer(seat.playerId)
|
||||
return {
|
||||
@@ -531,7 +651,15 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
libraryCount: player.library.length,
|
||||
battlefield: player.battlefield.map(id => cardView(game, game.getObject(id))),
|
||||
graveyard: player.graveyard.map(id => cardView(game, game.getObject(id), false)),
|
||||
exile: player.exile.map(id => cardView(game, game.getObject(id), false)),
|
||||
exile: player.exile
|
||||
.filter(id => !hiddenUnderSource.has(id))
|
||||
.map(id => {
|
||||
const playable = player.id === viewerId && game.canPlayCard(viewerId, id)
|
||||
return {
|
||||
...cardView(game, game.getObject(id), playable),
|
||||
...(playable ? { playable } : {}),
|
||||
}
|
||||
}),
|
||||
command: player.command.map(id => cardView(game, game.getObject(id), false)),
|
||||
commanderId: player.commanderId,
|
||||
commanderDamage: Object.entries(player.commanderDamage)
|
||||
@@ -548,6 +676,7 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
|
||||
const viewer = game.getPlayer(viewerId)
|
||||
const search = game.pendingSearch
|
||||
const choice = game.pendingChoice
|
||||
view.game = {
|
||||
turn: game.turn,
|
||||
activePlayer: game.activePlayer,
|
||||
@@ -556,6 +685,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,
|
||||
@@ -568,6 +700,24 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
playable: game.canPlayCard(viewerId, id),
|
||||
})),
|
||||
manaPool: { ...viewer.manaPool },
|
||||
pendingChoice: choice
|
||||
? {
|
||||
player: choice.playerId,
|
||||
what: choice.what,
|
||||
sourceId: choice.sourceId,
|
||||
sourceName: game.objects.get(choice.sourceId)?.definition.name ?? 'Permanent',
|
||||
amount: choice.amount,
|
||||
label: choice.label,
|
||||
options: choice.playerId === viewerId
|
||||
? choice.what === 'creature_type'
|
||||
? [...CREATURE_TYPES]
|
||||
: choice.what === 'color' ? ['White', 'Blue', 'Black', 'Red', 'Green'] : []
|
||||
: [],
|
||||
cards: choice.playerId === viewerId && choice.what === 'hideaway'
|
||||
? (choice.cardIds ?? []).map(id => cardView(game, game.getObject(id), false))
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
pendingSearch: search
|
||||
? {
|
||||
player: search.playerId,
|
||||
@@ -576,6 +726,9 @@ function serialize(match: Match, viewerId: string): MatchView {
|
||||
cards: search.playerId === viewerId
|
||||
? game.searchCandidates(viewerId).map(object => cardView(game, object, false))
|
||||
: [],
|
||||
...(search.playerId === viewerId
|
||||
? { library: game.searchPool(viewerId).map(object => cardView(game, object, false)) }
|
||||
: {}),
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
|
||||
414
backend/src/game/tokens.ts
Normal file
414
backend/src/game/tokens.ts
Normal file
@@ -0,0 +1,414 @@
|
||||
import type { Ability, Cost, Effect, StaticEffect } from '../effects/types.js'
|
||||
|
||||
/**
|
||||
* The predefined tokens from rule 111.10. Effects that name one of these
|
||||
* tokens ("create a Treasure token") use these characteristics instead of
|
||||
* whatever the oracle parser managed to infer from the words.
|
||||
*/
|
||||
export interface PredefinedTokenFace {
|
||||
name: string
|
||||
types: string[]
|
||||
subtypes: string[]
|
||||
colors: string[]
|
||||
power?: number
|
||||
toughness?: number
|
||||
keywords?: string[]
|
||||
abilities?: Ability[]
|
||||
}
|
||||
|
||||
export interface PredefinedToken extends PredefinedTokenFace {
|
||||
/** Back face of a double-faced token, currently only Incubator. */
|
||||
backFace?: PredefinedTokenFace
|
||||
}
|
||||
|
||||
function activated(costs: Cost[], effects: Effect[], text: string, timing?: 'sorcery'): Ability {
|
||||
return { kind: 'activated', costs, effects, timing, optional: false, text }
|
||||
}
|
||||
|
||||
function anyColor(): Effect {
|
||||
return {
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: false },
|
||||
}
|
||||
}
|
||||
|
||||
function drawOne(): Effect {
|
||||
return { op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }
|
||||
}
|
||||
|
||||
function pumpEnchanted(power: number, toughness: number): StaticEffect {
|
||||
return {
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: power },
|
||||
toughness: { kind: 'number', value: toughness },
|
||||
}
|
||||
}
|
||||
|
||||
function grantEnchanted(keyword: string, value?: string): StaticEffect {
|
||||
return {
|
||||
op: 'grant',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
keyword,
|
||||
...(value ? { value } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
const tap: Cost = { kind: 'tap' }
|
||||
const sacrificeSelf: Cost = { kind: 'sacrifice_self' }
|
||||
const mana = (symbols: string): Cost => ({ kind: 'mana', symbols })
|
||||
const enchantCreature: Ability = { kind: 'keyword', keyword: 'Enchant', value: 'creature' }
|
||||
|
||||
function attackTrigger(effects: Effect[], text: string, condition?: Extract<Ability, { kind: 'triggered' }>['condition']): Ability {
|
||||
return {
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'attacks',
|
||||
subject: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
},
|
||||
...(condition ? { condition } : {}),
|
||||
effects,
|
||||
optional: false,
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
export const PREDEFINED_TOKENS: Record<string, PredefinedToken> = {
|
||||
treasure: {
|
||||
name: 'Treasure',
|
||||
types: ['artifact'],
|
||||
subtypes: ['treasure'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap, sacrificeSelf],
|
||||
[anyColor()],
|
||||
'{T}, Sacrifice this artifact: Add one mana of any color.',
|
||||
)],
|
||||
},
|
||||
food: {
|
||||
name: 'Food',
|
||||
types: ['artifact'],
|
||||
subtypes: ['food'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), tap, sacrificeSelf],
|
||||
[{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' }],
|
||||
'{2}, {T}, Sacrifice this artifact: You gain 3 life.',
|
||||
)],
|
||||
},
|
||||
gold: {
|
||||
name: 'Gold',
|
||||
types: ['artifact'],
|
||||
subtypes: ['gold'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[sacrificeSelf],
|
||||
[anyColor()],
|
||||
'Sacrifice this artifact: Add one mana of any color.',
|
||||
)],
|
||||
},
|
||||
walker: {
|
||||
name: 'Walker',
|
||||
types: ['creature'],
|
||||
subtypes: ['zombie'],
|
||||
colors: ['B'],
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
},
|
||||
shard: {
|
||||
name: 'Shard',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['shard'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), sacrificeSelf],
|
||||
[
|
||||
{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } },
|
||||
drawOne(),
|
||||
],
|
||||
'{2}, Sacrifice this enchantment: Scry 1, then draw a card.',
|
||||
)],
|
||||
},
|
||||
clue: {
|
||||
name: 'Clue',
|
||||
types: ['artifact'],
|
||||
subtypes: ['clue'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), sacrificeSelf],
|
||||
[drawOne()],
|
||||
'{2}, Sacrifice this artifact: Draw a card.',
|
||||
)],
|
||||
},
|
||||
blood: {
|
||||
name: 'Blood',
|
||||
types: ['artifact'],
|
||||
subtypes: ['blood'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, { kind: 'discard', amount: { kind: 'number', value: 1 }, player: 'you' }, sacrificeSelf],
|
||||
[drawOne()],
|
||||
'{1}, {T}, Discard a card, Sacrifice this artifact: Draw a card.',
|
||||
)],
|
||||
},
|
||||
powerstone: {
|
||||
name: 'Powerstone',
|
||||
types: ['artifact'],
|
||||
subtypes: ['powerstone'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
// shortcut: the pool does not track restricted mana yet, so this is
|
||||
// usable for any spell. Upgrade when spell-type mana restrictions matter.
|
||||
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
|
||||
}],
|
||||
'{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
|
||||
)],
|
||||
},
|
||||
incubator: {
|
||||
name: 'Incubator',
|
||||
types: ['artifact'],
|
||||
subtypes: ['incubator'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}')],
|
||||
[{ op: 'transform', target: { kind: 'self' } }],
|
||||
'{2}: Transform this artifact.',
|
||||
)],
|
||||
backFace: {
|
||||
name: 'Phyrexian',
|
||||
types: ['artifact', 'creature'],
|
||||
subtypes: ['phyrexian'],
|
||||
colors: [],
|
||||
power: 0,
|
||||
toughness: 0,
|
||||
},
|
||||
},
|
||||
map: {
|
||||
name: 'Map',
|
||||
types: ['artifact'],
|
||||
subtypes: ['map'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'keyword_action',
|
||||
action: 'explore',
|
||||
target: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'target' },
|
||||
}],
|
||||
'{1}, {T}, Sacrifice this artifact: Target creature you control explores. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
junk: {
|
||||
name: 'Junk',
|
||||
types: ['artifact'],
|
||||
subtypes: ['junk'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[tap, sacrificeSelf],
|
||||
[{ op: 'keyword_action', action: 'impulse' }],
|
||||
'{T}, Sacrifice this artifact: Exile the top card of your library. You may play that card this turn. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
lander: {
|
||||
name: 'Lander',
|
||||
types: ['artifact'],
|
||||
subtypes: ['lander'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{2}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { supertypes: ['basic'], types: ['land'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}],
|
||||
'{2}, {T}, Sacrifice this artifact: Search your library for a basic land card, put it onto the battlefield tapped, then shuffle.',
|
||||
)],
|
||||
},
|
||||
mutagen: {
|
||||
name: 'Mutagen',
|
||||
types: ['artifact'],
|
||||
subtypes: ['mutagen'],
|
||||
colors: [],
|
||||
abilities: [activated(
|
||||
[mana('{1}'), tap, sacrificeSelf],
|
||||
[{
|
||||
op: 'put_counters',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
'{1}, {T}, Sacrifice this artifact: Put a +1/+1 counter on target creature. Activate only as a sorcery.',
|
||||
'sorcery',
|
||||
)],
|
||||
},
|
||||
vibranium: {
|
||||
name: 'Vibranium',
|
||||
types: ['artifact'],
|
||||
subtypes: ['vibranium'],
|
||||
colors: [],
|
||||
keywords: ['Indestructible'],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{C}'], restriction: 'artifact spells' },
|
||||
}],
|
||||
'Indestructible\n{T}: Add {C}. This mana can\'t be spent to cast a nonartifact spell.',
|
||||
)],
|
||||
},
|
||||
heartwood: {
|
||||
name: 'Heartwood',
|
||||
types: ['artifact'],
|
||||
subtypes: ['heartwood'],
|
||||
colors: ['R', 'G'],
|
||||
abilities: [activated(
|
||||
[tap],
|
||||
[{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'symbols', symbols: ['{R}', '{G}'], oneOf: true },
|
||||
}],
|
||||
'{T}: Add {R} or {G}.',
|
||||
)],
|
||||
},
|
||||
cursed: {
|
||||
name: 'Cursed Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'set_pt',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
base: true,
|
||||
}],
|
||||
text: 'Enchanted creature has base power and toughness 1/1.',
|
||||
},
|
||||
],
|
||||
},
|
||||
monster: {
|
||||
name: 'Monster Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Trample')], text: 'Enchanted creature gets +1/+1 and has trample.' },
|
||||
],
|
||||
},
|
||||
royal: {
|
||||
name: 'Royal Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1), grantEnchanted('Ward', '{1}')], text: 'Enchanted creature gets +1/+1 and has ward {1}.' },
|
||||
],
|
||||
},
|
||||
sorcerer: {
|
||||
name: 'Sorcerer Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
|
||||
attackTrigger(
|
||||
[{ op: 'scry', player: 'you', amount: { kind: 'number', value: 1 } }],
|
||||
'Whenever enchanted creature attacks, scry 1.',
|
||||
),
|
||||
],
|
||||
},
|
||||
virtuous: {
|
||||
name: 'Virtuous Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { attached: 'enchanted', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
|
||||
toughness: { kind: 'count', selector: { types: ['enchantment'], controller: 'you' } },
|
||||
}],
|
||||
text: 'Enchanted creature gets +1/+1 for each enchantment you control.',
|
||||
},
|
||||
],
|
||||
},
|
||||
wicked: {
|
||||
name: 'Wicked Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
{ kind: 'static', effects: [pumpEnchanted(1, 1)], text: 'Enchanted creature gets +1/+1.' },
|
||||
{
|
||||
kind: 'triggered',
|
||||
// Curse of the Werefox and friends put this in the graveyard; the
|
||||
// engine only distinguishes "died" for creatures, so any leave triggers it.
|
||||
event: { kind: 'leaves_battlefield', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'life', player: 'each_opponent', amount: { kind: 'number', value: 1 }, mode: 'lose' }],
|
||||
optional: false,
|
||||
text: 'When this token is put into a graveyard from the battlefield, each opponent loses 1 life.',
|
||||
},
|
||||
],
|
||||
},
|
||||
'young hero': {
|
||||
name: 'Young Hero Role',
|
||||
types: ['enchantment'],
|
||||
subtypes: ['aura', 'role'],
|
||||
colors: [],
|
||||
abilities: [
|
||||
enchantCreature,
|
||||
attackTrigger(
|
||||
[{
|
||||
op: 'put_counters',
|
||||
target: { kind: 'trigger_subject' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
'Whenever enchanted creature attacks, if its toughness is 3 or less, put a +1/+1 counter on it.',
|
||||
{ kind: 'event_subject_toughness_at_most', amount: 3 },
|
||||
),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
/** Finds a predefined token by subtype or name, including "Cursed Role". */
|
||||
export function predefinedToken(spec: { name?: string; subtypes: string[] }): PredefinedToken | undefined {
|
||||
const words = spec.subtypes.map(word => word.toLowerCase())
|
||||
const roleIndex = words.indexOf('role')
|
||||
const candidates = roleIndex >= 0 ? [words.slice(0, roleIndex).join(' ')] : []
|
||||
candidates.push(...words)
|
||||
for (const candidate of candidates) {
|
||||
const token = PREDEFINED_TOKENS[candidate]
|
||||
if (token) return token
|
||||
}
|
||||
if (spec.name) {
|
||||
const name = spec.name.toLowerCase()
|
||||
return PREDEFINED_TOKENS[name] ?? PREDEFINED_TOKENS[name.replace(/\s+role$/, '')]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
@@ -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<ManaColor, number>
|
||||
@@ -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 {
|
||||
@@ -64,6 +75,8 @@ export interface PlayerState {
|
||||
creaturesDiedThisTurn: number
|
||||
nonlandPermanentsEnteredThisTurn: number
|
||||
attackedThisTurn: boolean
|
||||
creaturesAttackedThisTurn: number
|
||||
damageTakenThisTurn: number
|
||||
energy: number
|
||||
poison: number
|
||||
}
|
||||
@@ -81,6 +94,12 @@ export interface GameObject {
|
||||
counters: Record<string, number>
|
||||
isToken: boolean
|
||||
token?: TokenSpec
|
||||
/** Back face of a double-faced token (Incubator); transform swaps it in. */
|
||||
backFace?: CardDefinition
|
||||
/** Set when a card would be exiled instead of dying this turn. */
|
||||
exileOnDeathTurn?: number
|
||||
/** Set by impulse effects; the card may be played from exile this turn. */
|
||||
playableFromExileTurn?: number
|
||||
isCommander?: boolean
|
||||
enteredTurn: number
|
||||
/** Normalized center on the controller's mat; absent means auto-arranged. */
|
||||
@@ -90,6 +109,14 @@ export interface GameObject {
|
||||
blocking?: string
|
||||
attachments: string[]
|
||||
attachedTo?: string
|
||||
/** Cards exiled with this object, such as a card hidden by hideaway. */
|
||||
linkedExile?: string[]
|
||||
/** Exiled face down (hideaway); its identity is hidden from every view. */
|
||||
faceDown?: boolean
|
||||
/** Creature type chosen as this permanent entered (Cavern of Souls). */
|
||||
chosenCreatureType?: string
|
||||
/** Color chosen as this permanent entered (mana of the chosen color). */
|
||||
chosenColor?: ManaColor
|
||||
regenerationShields: number
|
||||
activations: Record<number, number>
|
||||
}
|
||||
@@ -112,12 +139,19 @@ export interface StackItem {
|
||||
triggerSubject?: GameObject
|
||||
eventPlayer?: string
|
||||
eventAmount?: number
|
||||
/** "You may ..." — ask the controller before resolving. */
|
||||
optional?: boolean
|
||||
/** Undefined until the controller answers; false skips the main effects. */
|
||||
optionalAccepted?: boolean
|
||||
}
|
||||
|
||||
export interface ActionOptions {
|
||||
targets?: TargetChoice[]
|
||||
x?: number
|
||||
mode?: number
|
||||
overload?: boolean
|
||||
/** Color chosen for a mana ability that can produce more than one. */
|
||||
manaColor?: ManaColor
|
||||
}
|
||||
|
||||
/** A search that is waiting for its player to pick one of several matching cards. */
|
||||
@@ -129,6 +163,23 @@ export interface PendingSearch {
|
||||
tapped: boolean
|
||||
shuffle: boolean
|
||||
zones?: ('library' | 'graveyard')[]
|
||||
/** Where the picks after the first one go (Cultivate-style searches). */
|
||||
split?: { destination: 'hand' | 'battlefield' | 'graveyard' | 'top' | 'bottom'; tapped: boolean }
|
||||
}
|
||||
|
||||
/** A pause such as "as this enters..." or a hideaway look. Blocks all actions until its controller picks. */
|
||||
export interface PendingChoice {
|
||||
playerId: string
|
||||
sourceId: string
|
||||
what: 'creature_type' | 'color' | 'pay_cost' | 'hideaway' | 'optional'
|
||||
/** Cost to pay to avoid entering tapped. */
|
||||
cost?: Cost
|
||||
/** Ability or spell name shown for an optional choice. */
|
||||
label?: string
|
||||
/** Life total to display for a `pay_life` cost. */
|
||||
amount?: number
|
||||
/** Cards to choose from for `hideaway`. */
|
||||
cardIds?: string[]
|
||||
}
|
||||
|
||||
export interface CombatAttack {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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> = {}): 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}'] },
|
||||
}])
|
||||
})
|
||||
|
||||
@@ -84,6 +84,46 @@ Deck
|
||||
assert.match(result.errors.join(' '), /exactly 100/)
|
||||
})
|
||||
|
||||
test('a commander identity mana source only offers colors in the identity', () => {
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingHandSize: 0,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: [basicLand('Forest')], commander: commanderDefinition('Test Commander', { colors: ['U', 'R'], colorIdentity: ['U', 'R'] }) },
|
||||
{ id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
const tower = game.addCard('p1', {
|
||||
oracleId: 'command-tower',
|
||||
name: 'Command Tower',
|
||||
typeLine: 'Land',
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: {
|
||||
kind: 'any_color',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
oneColor: false,
|
||||
restriction: "commander's color identity",
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: "{T}: Add one mana of any color in your commander's color identity.",
|
||||
}],
|
||||
}, 'battlefield')
|
||||
|
||||
assert.deepEqual(game.manaColorChoices(tower, 0), ['U', 'R'])
|
||||
assert.throws(() => game.activateAbility('p1', tower.id, 0, { manaColor: 'G' }), /cannot produce/)
|
||||
assert.equal(tower.tapped, false)
|
||||
game.activateAbility('p1', tower.id, 0, { manaColor: 'R' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 1)
|
||||
})
|
||||
|
||||
test('a commander starts in the command zone, pays tax, and returns there from the graveyard', () => {
|
||||
const commander = commanderDefinition('Test Commander')
|
||||
const game = new Game({
|
||||
@@ -91,8 +131,8 @@ test('a commander starts in the command zone, pays tax, and returns there from t
|
||||
startingHandSize: 0,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: [], commander },
|
||||
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
|
||||
{ id: 'p1', deck: [basicLand('Forest')], commander },
|
||||
{ id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
@@ -138,8 +178,8 @@ test('twenty-one commander damage loses the game', () => {
|
||||
startingHandSize: 0,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: [], commander },
|
||||
{ id: 'p2', deck: [], commander: commanderDefinition('Other Commander') },
|
||||
{ id: 'p1', deck: [basicLand('Forest')], commander },
|
||||
{ id: 'p2', deck: [basicLand('Forest')], commander: commanderDefinition('Other Commander') },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
|
||||
@@ -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[] {
|
||||
@@ -29,6 +29,58 @@ test('enters trigger with a draw effect', () => {
|
||||
assert.equal(ability.effects[0].op, 'draw')
|
||||
})
|
||||
|
||||
test('compound effects resolve "it" through the previous target', () => {
|
||||
const [ability] = creature('When this enters, tap target creature an opponent controls and put a stun counter on it.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
if (ability.kind !== 'triggered') return
|
||||
assert.deepEqual(ability.effects[1], {
|
||||
op: 'put_counters',
|
||||
target: { kind: 'previous_target' },
|
||||
counter: 'stun',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
})
|
||||
})
|
||||
|
||||
test('compound effects share an explicit player subject', () => {
|
||||
const [ability] = spell('Target player draws two cards and loses 2 life.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[1], {
|
||||
op: 'life',
|
||||
player: 'target_player',
|
||||
amount: { kind: 'number', value: 2 },
|
||||
mode: 'lose',
|
||||
})
|
||||
})
|
||||
|
||||
test('damage triggers without a recipient use the event amount', () => {
|
||||
const [ability] = creature('Whenever this deals damage, you gain that much life.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
if (ability.kind !== 'triggered') return
|
||||
assert.equal(ability.event.kind, 'deals_damage')
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'life',
|
||||
player: 'you',
|
||||
amount: { kind: 'event_amount' },
|
||||
mode: 'gain',
|
||||
})
|
||||
})
|
||||
|
||||
test('a later sentence can refer to a token created by an earlier one', () => {
|
||||
const [ability] = creature(
|
||||
'When this enters, create a 0/0 green and blue Fractal creature token. Put three +1/+1 counters on it.',
|
||||
)
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
if (ability.kind !== 'triggered') return
|
||||
assert.equal(ability.effects[0].op, 'create_token')
|
||||
assert.deepEqual(ability.effects[1], {
|
||||
op: 'put_counters',
|
||||
target: { kind: 'previous_target' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 3 },
|
||||
})
|
||||
})
|
||||
|
||||
test('activated mana ability', () => {
|
||||
const [ability] = creature('{T}: Add {G}.')
|
||||
assert.equal(ability.kind, 'activated')
|
||||
@@ -41,6 +93,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')
|
||||
@@ -56,6 +135,62 @@ test('search effect keeps destination, tapped, and shuffle', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('search can put the chosen card on top of the library', () => {
|
||||
const [ability] = spell('Search your library for a creature card, reveal it, then shuffle and put the card on top.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['creature'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'top',
|
||||
tapped: false,
|
||||
shuffle: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('a two-card search can split between the battlefield and hand', () => {
|
||||
const [ability] = spell('Search your library for up to two basic land cards, reveal those cards, put one onto the battlefield tapped and the other into your hand, then shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 2 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
split: { destination: 'hand', tapped: false },
|
||||
})
|
||||
})
|
||||
|
||||
test('"if you search your library this way, shuffle" keeps the search', () => {
|
||||
const [ability] = spell('Search your library for a card named Sol Ring, reveal it, and put it into your hand. If you search your library this way, shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { name: 'sol ring', types: [] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'hand',
|
||||
tapped: false,
|
||||
shuffle: true,
|
||||
})
|
||||
})
|
||||
|
||||
test('search selectors support an exact mana value', () => {
|
||||
const [ability] = spell('Search your library for an artifact card with mana value 3, reveal it, put it into your hand, then shuffle.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
const effect = ability.effects[0]
|
||||
assert.equal(effect.op, 'search')
|
||||
if (effect.op !== 'search') return
|
||||
assert.deepEqual(effect.selector, { types: ['artifact'], manaValue: { atLeast: 3, atMost: 3 } })
|
||||
})
|
||||
|
||||
test('"it" refers to the triggering object when unambiguous', () => {
|
||||
const [ability] = creature('Whenever another creature enters, put a +1/+1 counter on it.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
@@ -66,11 +201,16 @@ test('"it" refers to the triggering object when unambiguous', () => {
|
||||
assert.deepEqual(effect.target, { kind: 'trigger_subject' })
|
||||
})
|
||||
|
||||
test('ambiguous "it" is left unsupported instead of guessed', () => {
|
||||
test('a target introduced in one clause is the "it" of the next', () => {
|
||||
const [ability] = creature(
|
||||
'When this creature enters, tap target creature an opponent controls and put a stun counter on it.',
|
||||
)
|
||||
assert.equal(ability.kind, 'unsupported')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
if (ability.kind !== 'triggered') return
|
||||
const effect = ability.effects[1]
|
||||
assert.equal(effect.op, 'put_counters')
|
||||
if (effect.op !== 'put_counters') return
|
||||
assert.deepEqual(effect.target, { kind: 'previous_target' })
|
||||
})
|
||||
|
||||
test('modal text is unsupported', () => {
|
||||
@@ -92,6 +232,24 @@ test('static anthem', () => {
|
||||
assert.equal(target.selector.controller, 'you')
|
||||
})
|
||||
|
||||
test('negative colors become an excluded color filter', () => {
|
||||
const [ability] = spell('Destroy target nonblack creature.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'destroy',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { types: ['creature'], excludeColors: ['B'] },
|
||||
mode: 'target',
|
||||
},
|
||||
})
|
||||
|
||||
const source = formatAbility(ability)
|
||||
assert.match(source, /withoutColor\('black'\)/)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
})
|
||||
|
||||
test('enters-with-counters is a static replacement effect', () => {
|
||||
const [ability] = creature('This creature enters with X +1/+1 counters on it.')
|
||||
assert.equal(ability.kind, 'static')
|
||||
@@ -113,10 +271,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\)/)
|
||||
})
|
||||
|
||||
@@ -145,7 +303,40 @@ 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('token-doubling replacement lines compile and round-trip', () => {
|
||||
const cases: Array<[string, object]> = [
|
||||
[
|
||||
'If an effect would create one or more tokens under your control, it creates twice that many of those tokens instead.',
|
||||
{ op: 'token_multiplier', multiplier: 2, who: 'you' },
|
||||
],
|
||||
[
|
||||
'If one or more tokens would be created under your control, twice that many of those tokens are created instead.',
|
||||
{ op: 'token_multiplier', multiplier: 2, who: 'you' },
|
||||
],
|
||||
[
|
||||
'If one or more tokens would be created, twice that many of those tokens are created instead.',
|
||||
{ op: 'token_multiplier', multiplier: 2, who: 'each_player' },
|
||||
],
|
||||
[
|
||||
'If one or more creature tokens would be created under your control, three times that many of those tokens are created instead.',
|
||||
{ op: 'token_multiplier', multiplier: 3, who: 'you', creatureOnly: true },
|
||||
],
|
||||
]
|
||||
for (const [text, expected] of cases) {
|
||||
const [ability] = creature(text)
|
||||
assert.equal(ability.kind, 'static')
|
||||
if (ability.kind !== 'static') return
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(ability.effects[0])), expected)
|
||||
|
||||
const source = formatAbility(ability)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
}
|
||||
})
|
||||
|
||||
test('all effects are typed', () => {
|
||||
@@ -220,6 +411,172 @@ test('"When <subject>" triggers and bare "gain life" effects parse', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('"This ability triggers only once" marks the trigger', () => {
|
||||
const [ability] = creature('At the beginning of your second main phase, if this is tapped, put a flying counter on it. This ability triggers only once.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
if (ability.kind !== 'triggered') return
|
||||
assert.deepEqual(ability.event, { kind: 'main_phase', who: 'you', phase: 'postcombat' })
|
||||
assert.equal(ability.oncePerTurn, true)
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'put_counters',
|
||||
target: { kind: 'self' },
|
||||
counter: 'flying',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
})
|
||||
})
|
||||
|
||||
test('impulse exiles the top cards and grants play permission', () => {
|
||||
const [ability] = spell('Exile the top three cards of your library. Until end of turn, you may play those cards.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'impulse',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 3 },
|
||||
faceDown: false,
|
||||
})
|
||||
})
|
||||
|
||||
test('a mana ability can produce the chosen color', () => {
|
||||
const [ability] = creature('{T}: Add one mana of the chosen color.')
|
||||
assert.equal(ability.kind, 'activated')
|
||||
if (ability.kind !== 'activated') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: {
|
||||
kind: 'any_color',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
oneColor: true,
|
||||
restriction: 'chosen color',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test('doubling counters compiles to its own effect', () => {
|
||||
const [ability] = spell('Double the number of +1/+1 counters on target creature.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'double_counters',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
counter: '+1/+1',
|
||||
})
|
||||
})
|
||||
|
||||
test('damage prevention compiles with its shield and scope', () => {
|
||||
const [shield] = spell('Prevent the next 3 damage that would be dealt to target creature this turn.')
|
||||
assert.equal(shield.kind, 'spell')
|
||||
if (shield.kind !== 'spell') return
|
||||
assert.equal(shield.effects[0].op, 'prevent_damage')
|
||||
const first = shield.effects[0]
|
||||
if (first.op !== 'prevent_damage') return
|
||||
assert.deepEqual(first.target, { kind: 'object', selector: { types: ['creature'] }, mode: 'target' })
|
||||
assert.deepEqual(first.amount, { kind: 'number', value: 3 })
|
||||
assert.equal(first.duration, 'until_end_of_turn')
|
||||
assert.equal(first.global, undefined)
|
||||
|
||||
const [global] = spell('Prevent all combat damage that would be dealt this turn.')
|
||||
assert.equal(global.kind, 'spell')
|
||||
if (global.kind !== 'spell') return
|
||||
const second = global.effects[0]
|
||||
if (second.op !== 'prevent_damage') return
|
||||
assert.equal(second.amount, 'all')
|
||||
assert.equal(second.combatOnly, true)
|
||||
assert.equal(second.global, true)
|
||||
})
|
||||
|
||||
test('counter and energy replacement lines compile', () => {
|
||||
const [counters] = creature('If one or more +1/+1 counters would be put on a creature you control, twice that many +1/+1 counters are put on that creature instead.')
|
||||
assert.equal(counters.kind, 'static')
|
||||
if (counters.kind !== 'static') return
|
||||
assert.equal(counters.effects[0].op, 'counter_multiplier')
|
||||
if (counters.effects[0].op !== 'counter_multiplier') return
|
||||
assert.equal(counters.effects[0].counter, '+1/+1')
|
||||
assert.equal(counters.effects[0].multiplier, 2)
|
||||
|
||||
const [energy] = creature('If you would get one or more {E}, you get twice that many {E} instead.')
|
||||
assert.equal(energy.kind, 'static')
|
||||
if (energy.kind !== 'static') return
|
||||
assert.deepEqual(energy.effects[0], { op: 'replacement_amount', what: 'energy', multiplier: 2 })
|
||||
})
|
||||
|
||||
test('static source-filtered prevention compiles', () => {
|
||||
const [ability] = creature('Prevent all damage that would be dealt to this by artifact creatures.')
|
||||
assert.equal(ability.kind, 'static')
|
||||
if (ability.kind !== 'static') return
|
||||
assert.deepEqual(ability.effects[0], {
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'self' },
|
||||
amount: 'all',
|
||||
combatOnly: undefined,
|
||||
duration: 'permanent',
|
||||
sourceSelector: { types: ['artifact', 'creature'] },
|
||||
})
|
||||
})
|
||||
|
||||
test('source-scoped prevention compiles with its chosen source', () => {
|
||||
const [ability] = spell('Prevent all damage a red source of your choice would deal this turn.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
const shield = ability.effects[0]
|
||||
assert.equal(shield.op, 'prevent_damage')
|
||||
if (shield.op !== 'prevent_damage') return
|
||||
assert.deepEqual(shield.source, { kind: 'object', selector: { colors: ['R'] }, mode: 'target' })
|
||||
assert.equal(shield.global, true)
|
||||
})
|
||||
|
||||
test('a prevention follow-up compiles into the shield', () => {
|
||||
const [ability] = spell('Prevent the next 3 damage that would be dealt to target creature this turn. If damage is prevented this way, this deals that much damage to any target.')
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
const shield = ability.effects[0]
|
||||
assert.equal(shield.op, 'prevent_damage')
|
||||
if (shield.op !== 'prevent_damage') return
|
||||
assert.deepEqual(shield.then, [{
|
||||
op: 'damage',
|
||||
target: { kind: 'any' },
|
||||
amount: { kind: 'event_amount' },
|
||||
}])
|
||||
})
|
||||
|
||||
test('replacement amount lines compile', () => {
|
||||
const [life] = creature('If you would gain life, you gain twice that much life instead.')
|
||||
assert.equal(life.kind, 'static')
|
||||
if (life.kind !== 'static') return
|
||||
assert.deepEqual(life.effects[0], { op: 'replacement_amount', what: 'life_gain', multiplier: 2 })
|
||||
|
||||
const [plus] = creature('If you would gain life, you gain that much life plus 1 instead.')
|
||||
assert.equal(plus.kind, 'static')
|
||||
if (plus.kind !== 'static') return
|
||||
assert.deepEqual(plus.effects[0], { op: 'replacement_amount', what: 'life_gain', multiplier: 1, add: 1 })
|
||||
|
||||
const [draw] = creature('If you would draw a card, draw two cards instead.')
|
||||
assert.equal(draw.kind, 'static')
|
||||
if (draw.kind !== 'static') return
|
||||
assert.deepEqual(draw.effects[0], { op: 'replacement_amount', what: 'draw', multiplier: 2 })
|
||||
})
|
||||
|
||||
test('"skip your draw step" and attack-or-block restrictions compile', () => {
|
||||
const [skip] = creature('Skip your draw step.')
|
||||
assert.equal(skip.kind, 'static')
|
||||
if (skip.kind !== 'static') return
|
||||
assert.deepEqual(skip.effects[0], {
|
||||
op: 'restriction',
|
||||
target: { kind: 'player', who: 'you', mode: 'target' },
|
||||
rule: 'skip_draw_step',
|
||||
})
|
||||
|
||||
const [lock] = creature('Enchanted creature cannot attack or block, and its activated abilities cannot be activated.')
|
||||
assert.equal(lock.kind, 'static')
|
||||
if (lock.kind !== 'static') return
|
||||
assert.deepEqual(lock.effects.map(effect => effect.op === 'restriction' ? effect.rule : effect.op), [
|
||||
'cant_attack',
|
||||
'cant_block',
|
||||
'cant_activate',
|
||||
])
|
||||
})
|
||||
|
||||
test('a trailing condition becomes a static condition', () => {
|
||||
const [ability] = creature('This creature cannot attack if defending player controls an untapped land.')
|
||||
assert.equal(ability.kind, 'static')
|
||||
@@ -243,9 +600,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)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -259,7 +616,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
|
||||
@@ -268,9 +625,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')
|
||||
@@ -283,6 +640,53 @@ test('counter-removal costs parse and round-trip through pseudocode', () => {
|
||||
}])
|
||||
})
|
||||
|
||||
test('hideaway lands exile a card and gate playing it on their condition', () => {
|
||||
const lands: Array<[string, string, string]> = [
|
||||
["Clive's Hideaway", `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
{T}: Add {C}.
|
||||
{2}, {T}: You may play the exiled card without paying its mana cost if you control four or more legendary creatures.`, 'you_control'],
|
||||
['Howltooth Hollow', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {B}.
|
||||
{B}, {T}: You may play the exiled card without paying its mana cost if each player has no cards in hand.`, 'cards_in_hand_at_most'],
|
||||
['Mosswort Bridge', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {G}.
|
||||
{G}, {T}: You may play the exiled card without paying its mana cost if creatures you control have total power 10 or greater.`, 'total_power'],
|
||||
['Shelldock Isle', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {U}.
|
||||
{U}, {T}: You may play the exiled card without paying its mana cost if a library has twenty or fewer cards in it.`, 'library_at_most'],
|
||||
['Spinerock Knoll', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {R}.
|
||||
{R}, {T}: You may play the exiled card without paying its mana cost if an opponent was dealt 7 or more damage this turn.`, 'opponent_damaged_this_turn'],
|
||||
['Windbrisk Heights', `Hideaway 4 (When this land enters, look at the top four cards of your library, exile one face down, then put the rest on the bottom in a random order.)
|
||||
This land enters tapped.
|
||||
{T}: Add {W}.
|
||||
{W}, {T}: You may play the exiled card without paying its mana cost if you attacked with three or more creatures this turn.`, 'attacked_with_creatures'],
|
||||
]
|
||||
|
||||
for (const [name, text, condition] of lands) {
|
||||
const abilities = compileText(text, name, [], 'Land')
|
||||
assert.equal(abilities.filter(ability => ability.kind === 'unsupported').length, 0, name)
|
||||
|
||||
const hideaway = abilities.find(ability => ability.kind === 'triggered' && ability.effects.some(effect => effect.op === 'hideaway'))
|
||||
assert.equal(hideaway?.kind, 'triggered', name)
|
||||
if (hideaway?.kind !== 'triggered') continue
|
||||
assert.deepEqual(hideaway.effects, [{ op: 'hideaway', amount: { kind: 'number', value: 4 } }], name)
|
||||
|
||||
const activated = abilities.at(-1)
|
||||
assert.equal(activated?.kind, 'activated', name)
|
||||
if (activated?.kind !== 'activated') continue
|
||||
const [effect] = activated.effects
|
||||
assert.equal(effect.op, 'conditional', name)
|
||||
if (effect.op !== 'conditional') continue
|
||||
assert.equal(effect.condition.kind, condition, name)
|
||||
assert.deepEqual(effect.effects, [{ op: 'play_exiled', player: 'you', free: true }], name)
|
||||
}
|
||||
})
|
||||
|
||||
test('a trigger returns its own card from the graveyard', () => {
|
||||
const [ability] = creature('When this dies, return this from your graveyard to the battlefield with a finality counter on it.')
|
||||
assert.equal(ability.kind, 'triggered')
|
||||
@@ -295,3 +699,221 @@ test('a trigger returns its own card from the graveyard', () => {
|
||||
counters: { counter: 'finality', amount: { kind: 'number', value: 1 } },
|
||||
}])
|
||||
})
|
||||
|
||||
test('Commander-batch oracle lines compile to dedicated nodes', () => {
|
||||
const [free] = spell('If you control a commander, you may cast this without paying its mana cost.')
|
||||
assert.equal(free.kind, 'alternative_cost')
|
||||
if (free.kind !== 'alternative_cost') return
|
||||
assert.deepEqual(free.condition, { kind: 'you_control_commander' })
|
||||
assert.deepEqual(free.costs, [])
|
||||
|
||||
const [overload] = spell('Overload {6}{U}')
|
||||
assert.deepEqual(overload, { kind: 'overload', cost: '{6}{U}', text: 'Overload {6}{U}' })
|
||||
|
||||
const [graves] = creature('When this enters, exile all graveyards.')
|
||||
assert.equal(graves.kind, 'triggered')
|
||||
if (graves.kind !== 'triggered') return
|
||||
assert.deepEqual(graves.effects, [{ op: 'exile_graveyards' }])
|
||||
|
||||
const [rest] = creature('If a card or token would be put into a graveyard from anywhere, exile it instead.')
|
||||
assert.equal(rest.kind, 'static')
|
||||
if (rest.kind !== 'static') return
|
||||
assert.deepEqual(rest.effects, [{ op: 'exile_instead_of_graveyard' }])
|
||||
|
||||
const [leyline] = creature("If a card would be put into an opponent's graveyard from anywhere, exile it instead.")
|
||||
assert.equal(leyline.kind, 'static')
|
||||
if (leyline.kind !== 'static') return
|
||||
assert.deepEqual(leyline.effects, [{ op: 'exile_instead_of_graveyard', owner: 'opponent' }])
|
||||
|
||||
const [thalia] = creature('Noncreature spells cost {1} more to cast.')
|
||||
assert.equal(thalia.kind, 'static')
|
||||
if (thalia.kind !== 'static') return
|
||||
assert.deepEqual(thalia.effects, [{
|
||||
op: 'cost_increase',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
spellType: 'noncreature',
|
||||
}])
|
||||
|
||||
const [linvala] = creature("Activated abilities of creatures your opponents control can't be activated.")
|
||||
assert.equal(linvala.kind, 'static')
|
||||
if (linvala.kind !== 'static') return
|
||||
assert.deepEqual(linvala.effects, [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'each' },
|
||||
rule: 'cant_activate',
|
||||
}])
|
||||
|
||||
const [aven] = creature('If an opponent would search a library, that player searches the top four cards of that library instead.')
|
||||
assert.equal(aven.kind, 'static')
|
||||
if (aven.kind !== 'static') return
|
||||
assert.deepEqual(aven.effects, [{
|
||||
op: 'search_restriction',
|
||||
who: 'opponent',
|
||||
amount: { kind: 'number', value: 4 },
|
||||
}])
|
||||
|
||||
const [field] = compileText(
|
||||
'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
'Field of the Dead',
|
||||
[],
|
||||
'Land',
|
||||
)
|
||||
assert.equal(field.kind, 'triggered')
|
||||
if (field.kind !== 'triggered') return
|
||||
assert.deepEqual(field.condition, {
|
||||
kind: 'distinct_names',
|
||||
selector: { types: ['land'] },
|
||||
atLeast: 7,
|
||||
})
|
||||
})
|
||||
|
||||
test('spell cost reductions compile their conditions and mana symbols', () => {
|
||||
const [bears] = creature('Creature spells you cast cost {1} less to cast.')
|
||||
assert.equal(bears.kind, 'static')
|
||||
if (bears.kind !== 'static') return
|
||||
assert.deepEqual(bears.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', types: ['creature'] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}])
|
||||
|
||||
const [cantrips] = creature('Instant and sorcery spells cost {2} less to cast.')
|
||||
assert.equal(cantrips.kind, 'static')
|
||||
if (cantrips.kind !== 'static') return
|
||||
assert.deepEqual(cantrips.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { match: 'any', types: ['instant', 'sorcery'] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 2 },
|
||||
}])
|
||||
|
||||
const [legendary] = creature('Legendary spells you cast cost {R}{G} less to cast. This effect reduces only the amount of colored mana you pay.')
|
||||
assert.equal(legendary.kind, 'static')
|
||||
if (legendary.kind !== 'static') return
|
||||
assert.deepEqual(legendary.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', supertypes: ['legendary'], types: [] },
|
||||
mode: 'each',
|
||||
},
|
||||
symbols: '{R}{G}',
|
||||
}])
|
||||
|
||||
const [tribal] = creature("Each spell you cast that's a Demon, Horror, or Nightmare costs {1} less to cast.")
|
||||
assert.equal(tribal.kind, 'static')
|
||||
if (tribal.kind !== 'static') return
|
||||
assert.deepEqual(tribal.effects, [{
|
||||
op: 'cost_reduction',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', match: 'any', subtypes: ['demon', 'horror', 'nightmare'], types: [] },
|
||||
mode: 'each',
|
||||
},
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}])
|
||||
})
|
||||
|
||||
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}'),
|
||||
...creature('When this enters, exile all graveyards.'),
|
||||
...creature('If a card or token would be put into a graveyard from anywhere, exile it instead.'),
|
||||
...creature("If a card would be put into an opponent's graveyard from anywhere, exile it instead."),
|
||||
...creature('Noncreature spells cost {1} more to cast.'),
|
||||
...creature('Creature spells you cast cost {1} less to cast.'),
|
||||
...creature('Legendary spells you cast cost {R}{G} less to cast.'),
|
||||
...creature("Each spell you cast that's a Demon, Horror, or Nightmare costs {1} less to cast."),
|
||||
...creature("Activated abilities of creatures your opponents control can't be activated."),
|
||||
...creature('If an opponent would search a library, that player searches the top four cards of that library instead.'),
|
||||
...compileText(
|
||||
'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
'Field of the Dead',
|
||||
[],
|
||||
'Land',
|
||||
),
|
||||
]
|
||||
for (const ability of abilities) {
|
||||
const source = formatAbility(ability)
|
||||
const reparsed = parseCardSource(`export default [${source}]`).abilities[0]
|
||||
assert.ok(reparsed)
|
||||
assert.equal(formatAbility(reparsed), source)
|
||||
}
|
||||
})
|
||||
|
||||
test('Role token creation compiles with the attachment target', () => {
|
||||
for (const role of ['Cursed', 'Monster', 'Royal', 'Sorcerer', 'Virtuous', 'Wicked', 'Young Hero']) {
|
||||
const [ability] = spell(`Create a ${role} Role token attached to target creature you control.`)
|
||||
assert.equal(ability.kind, 'spell')
|
||||
if (ability.kind !== 'spell') return
|
||||
const effect = ability.effects[0]
|
||||
assert.equal(effect.op, 'create_token')
|
||||
if (effect.op !== 'create_token') return
|
||||
assert.equal(effect.token.name, role)
|
||||
assert.deepEqual(effect.token.subtypes, ['aura', 'role'])
|
||||
assert.deepEqual(effect.attachTo, {
|
||||
kind: 'object',
|
||||
selector: { controller: 'you', types: ['creature'] },
|
||||
mode: 'target',
|
||||
})
|
||||
|
||||
const source = formatAbility(ability)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
}
|
||||
})
|
||||
|
||||
test('token-creation replacement lines compile and round-trip', () => {
|
||||
const cases: Array<[string, object]> = [
|
||||
[
|
||||
'If you would create a Food token, instead create a Food token and a Treasure token.',
|
||||
{ op: 'token_replacement', from: ['food'], tokens: [{ types: ['artifact'], subtypes: ['food'], colors: [] }, { types: ['artifact'], subtypes: ['treasure'], colors: [] }], who: 'you' },
|
||||
],
|
||||
[
|
||||
'If you would create a Clue, Food, or Treasure token, instead create one of each.',
|
||||
{ op: 'token_replacement', from: ['clue', 'food', 'treasure'], tokens: [{ name: 'Clue', types: ['artifact'], subtypes: ['clue'], colors: [] }, { name: 'Food', types: ['artifact'], subtypes: ['food'], colors: [] }, { name: 'Treasure', types: ['artifact'], subtypes: ['treasure'], colors: [] }], who: 'you' },
|
||||
],
|
||||
]
|
||||
for (const [text, expected] of cases) {
|
||||
const [ability] = creature(text)
|
||||
assert.equal(ability.kind, 'static')
|
||||
if (ability.kind !== 'static') return
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(ability.effects[0])), expected)
|
||||
|
||||
const source = formatAbility(ability)
|
||||
assert.equal(formatAbility(parseCardSource(`export default [${source}]`).abilities[0]), source)
|
||||
}
|
||||
})
|
||||
|
||||
test('exile-instead-of-dying clauses compile', () => {
|
||||
const [damaged] = spell('This deals 3 damage to any target. If a creature dealt damage this way would die this turn, exile it instead.')
|
||||
assert.equal(damaged.kind, 'spell')
|
||||
if (damaged.kind !== 'spell') return
|
||||
assert.deepEqual(damaged.effects[1], { op: 'exile_instead_of_dying', target: { kind: 'damaged' } })
|
||||
|
||||
const [that] = spell('This deals 3 damage to target creature. If that creature would die this turn, exile it instead.')
|
||||
assert.equal(that.kind, 'spell')
|
||||
if (that.kind !== 'spell') return
|
||||
assert.deepEqual(that.effects[1], { op: 'exile_instead_of_dying', target: { kind: 'previous_target' } })
|
||||
})
|
||||
|
||||
test('equipped and enchanted conditions gate static abilities', () => {
|
||||
const [equipped] = creature('As long as this is equipped, it gets +2/+0 and has menace.')
|
||||
assert.equal(equipped.kind, 'static')
|
||||
if (equipped.kind !== 'static') return
|
||||
assert.equal(equipped.condition?.kind, 'source_equipped')
|
||||
assert.equal(equipped.effects[0].op, 'pump')
|
||||
assert.equal(equipped.effects[1].op, 'grant')
|
||||
|
||||
const [enchanted] = creature('As long as this is enchanted, it has flying.')
|
||||
assert.equal(enchanted.kind, 'static')
|
||||
if (enchanted.kind !== 'static') return
|
||||
assert.equal(enchanted.condition?.kind, 'source_enchanted')
|
||||
})
|
||||
|
||||
283
backend/test/game-core.test.ts
Normal file
283
backend/test/game-core.test.ts
Normal file
@@ -0,0 +1,283 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('turns start at the first main phase, draw opening hands, and pass to the next player', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingHandSize: 7,
|
||||
players: [
|
||||
{ id: 'p1', deck: Array.from({ length: 10 }, () => forest) },
|
||||
{ id: 'p2', deck: Array.from({ length: 10 }, () => forest) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
|
||||
assert.equal(game.turn, 1)
|
||||
assert.equal(game.activePlayer, 'p1')
|
||||
assert.equal(game.phase, 'precombat_main')
|
||||
assert.equal(game.step, 'main')
|
||||
assert.equal(game.priority, 'p1')
|
||||
assert.equal(game.getPlayer('p1').life, 40)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 8)
|
||||
assert.equal(game.getPlayer('p1').library.length, 2)
|
||||
|
||||
game.endTurn('p1')
|
||||
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.activePlayer, 'p2')
|
||||
assert.equal(game.getPlayer('p2').hand.length, 8)
|
||||
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, 6)
|
||||
})
|
||||
|
||||
test('passing priority twice advances from the main phase into combat', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
game.pass('p1')
|
||||
assert.equal(game.priority, 'p2')
|
||||
game.pass('p2')
|
||||
|
||||
assert.equal(game.phase, 'combat')
|
||||
assert.equal(game.step, 'declare_attackers')
|
||||
assert.equal(game.priority, 'p1')
|
||||
})
|
||||
|
||||
test('a spell goes on the stack, auto-taps mana, and resolves its compiled effect', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
|
||||
assert.equal(game.stack.length, 1)
|
||||
assert.equal(mountain.tapped, true)
|
||||
assert.equal(game.priority, 'p2')
|
||||
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.stack.length, 0)
|
||||
assert.equal(game.getPlayer('p2').life, 37)
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
|
||||
})
|
||||
|
||||
test('permanents can be repositioned by their controller and positions are cleared on zone changes', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
|
||||
game.movePermanent('p1', bear.id, 0.25, 0.75)
|
||||
assert.deepEqual(bear.position, { x: 0.25, y: 0.75 })
|
||||
|
||||
game.movePermanent('p1', bear.id, -1, 2)
|
||||
assert.deepEqual(bear.position, { x: 0, y: 1 })
|
||||
assert.throws(() => game.movePermanent('p2', bear.id, 0.5, 0.5), /control/)
|
||||
|
||||
game.moveToZone(bear, 'graveyard')
|
||||
assert.equal(bear.position, undefined)
|
||||
})
|
||||
|
||||
test('doubling counters doubles each kind on the target', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const target = game.addCard('p1', creature('Counter Bear', 2, 3), 'battlefield')
|
||||
target.counters['+1/+1'] = 2
|
||||
target.counters['charge'] = 1
|
||||
const doubler = spell('Doubler', [{
|
||||
op: 'double_counters',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
}])
|
||||
const cardInHand = game.addCard('p1', doubler, 'hand')
|
||||
game.castSpell('p1', cardInHand.id, { targets: [{ kind: 'object', id: target.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(target.counters['+1/+1'], 4)
|
||||
assert.equal(target.counters.charge, 2)
|
||||
})
|
||||
|
||||
test('damage prevention shields absorb the next damage', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = creature('Bear', 2, 3)
|
||||
const target = game.addCard('p1', bear, 'battlefield')
|
||||
const bolt = spell('Bolt', [{ op: 'damage', target: { kind: 'object', selector: { types: ['creature'] } }, amount: { kind: 'number', value: 5 } }])
|
||||
const shield = spell('Shield', [{
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
amount: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_turn',
|
||||
}])
|
||||
|
||||
const shieldCard = game.addCard('p1', shield, 'hand')
|
||||
game.castSpell('p1', shieldCard.id, { targets: [{ kind: 'object', id: target.id }] })
|
||||
game.resolveStack()
|
||||
const boltCard = game.addCard('p1', bolt, 'hand')
|
||||
game.castSpell('p1', boltCard.id, { targets: [{ kind: 'object', id: target.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(target.damage, 2)
|
||||
assert.equal(target.zone, 'battlefield')
|
||||
})
|
||||
|
||||
test('a "you may" spell asks its controller and honors the choice', () => {
|
||||
const optionalSpell = card('Optional Test', {
|
||||
typeLine: 'Instant',
|
||||
abilities: [{
|
||||
kind: 'spell',
|
||||
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' }],
|
||||
optional: true,
|
||||
text: 'You may gain 3 life.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
const accept = game.addCard('p1', optionalSpell, 'hand')
|
||||
game.castSpell('p1', accept.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.pendingChoice?.what, 'optional')
|
||||
const before = game.getPlayer('p1').life
|
||||
game.chooseOptional('p1', true)
|
||||
assert.equal(game.getPlayer('p1').life, before + 3)
|
||||
|
||||
const decline = game.addCard('p1', optionalSpell, 'hand')
|
||||
game.castSpell('p1', decline.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.pendingChoice?.what, 'optional')
|
||||
const after = game.getPlayer('p1').life
|
||||
game.chooseOptional('p1', false)
|
||||
assert.equal(game.getPlayer('p1').life, after)
|
||||
assert.equal(decline.zone, 'graveyard')
|
||||
})
|
||||
|
||||
test('declining a "you may" runs the "if you don\'t" branch', () => {
|
||||
const optionalSpell = card('Optional Branch', {
|
||||
typeLine: 'Instant',
|
||||
abilities: [{
|
||||
kind: 'spell',
|
||||
effects: [
|
||||
{ op: 'life', player: 'you', amount: { kind: 'number', value: 2 }, mode: 'gain' },
|
||||
{
|
||||
op: 'conditional',
|
||||
condition: { kind: 'if_you_dont' },
|
||||
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'lose' }],
|
||||
},
|
||||
],
|
||||
optional: true,
|
||||
text: 'You may gain 2 life. If you don\'t, you lose 1 life.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const spellCard = game.addCard('p1', optionalSpell, 'hand')
|
||||
game.castSpell('p1', spellCard.id)
|
||||
game.resolveStack()
|
||||
const before = game.getPlayer('p1').life
|
||||
game.chooseOptional('p1', false)
|
||||
assert.equal(game.getPlayer('p1').life, before - 1)
|
||||
})
|
||||
|
||||
test('a compiled "you may" enters trigger asks and applies the choice', () => {
|
||||
const abilities = compileText(
|
||||
'When this creature enters, you may gain 2 life.',
|
||||
'Optional Bear',
|
||||
[],
|
||||
'Creature — Bear',
|
||||
)
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Optional Bear', 2, 2, abilities), 'hand')
|
||||
|
||||
game.castSpell('p1', bear.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.pendingChoice?.what, 'optional')
|
||||
const before = game.getPlayer('p1').life
|
||||
game.chooseOptional('p1', true)
|
||||
assert.equal(game.getPlayer('p1').life, before + 2)
|
||||
})
|
||||
|
||||
test('a land that chooses a color produces that color', () => {
|
||||
const landDef = card('Chosen Color Land', {
|
||||
typeLine: 'Land',
|
||||
abilities: [
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'choose', what: 'color' }],
|
||||
text: 'As this enters, choose a color.',
|
||||
},
|
||||
{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'add_mana',
|
||||
player: 'you',
|
||||
mana: { kind: 'any_color', amount: { kind: 'number', value: 1 }, oneColor: true, restriction: 'chosen color' },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{T}: Add one mana of the chosen color.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const land = game.addCard('p1', landDef, 'hand')
|
||||
|
||||
game.playLand('p1', land.id)
|
||||
assert.equal(game.pendingChoice?.what, 'color')
|
||||
game.chooseColor('p1', 'Blue')
|
||||
|
||||
game.activateAbility('p1', land.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').manaPool.U, 1)
|
||||
})
|
||||
343
backend/test/game-effects.test.ts
Normal file
343
backend/test/game-effects.test.ts
Normal file
@@ -0,0 +1,343 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('impulse exiles the top cards and lets the player cast them this turn', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const impulseSpell = game.addCard('p1', spell('Impulse Test', [
|
||||
{ op: 'impulse', player: 'you', amount: { kind: 'number', value: 2 } },
|
||||
]), 'hand')
|
||||
const top = game.addCard('p1', spell('Top Card', []), 'library')
|
||||
const second = game.addCard('p1', spell('Second Card', []), 'library')
|
||||
|
||||
game.castSpell('p1', impulseSpell.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(top.zone, 'exile')
|
||||
assert.equal(second.zone, 'exile')
|
||||
assert.equal(top.playableFromExileTurn, game.turn)
|
||||
assert.equal(second.playableFromExileTurn, game.turn)
|
||||
assert.doesNotThrow(() => game.castSpell('p1', top.id))
|
||||
})
|
||||
|
||||
test('hideaway exiles a card and its linked ability plays it for free once the condition is met', () => {
|
||||
const hideawayLand = card('Hideaway Test', {
|
||||
typeLine: 'Land',
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'hideaway', amount: { kind: 'number', value: 4 } }],
|
||||
optional: false,
|
||||
text: 'Hideaway 4',
|
||||
},
|
||||
{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'conditional',
|
||||
condition: { kind: 'total_power', controller: 'you', atLeast: 10 },
|
||||
effects: [{ op: 'play_exiled', player: 'you', free: true }],
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Play the exiled card without paying its mana cost if creatures you control have total power 10 or greater.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const hidden = game.addCard('p1', creature('Hidden Bear', 2, 2), 'library')
|
||||
for (const name of ['Filler One', 'Filler Two', 'Filler Three']) {
|
||||
game.addCard('p1', creature(name, 1, 1), 'library')
|
||||
}
|
||||
const library = game.getPlayer('p1').library
|
||||
library.splice(library.indexOf(hidden.id), 1)
|
||||
library.unshift(hidden.id)
|
||||
const land = game.addCard('p1', hideawayLand, 'hand')
|
||||
|
||||
game.playLand('p1', land.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.pendingChoice?.what, 'hideaway')
|
||||
assert.equal(game.pendingChoice?.playerId, 'p1')
|
||||
assert.equal(game.pendingChoice?.cardIds?.length, 4)
|
||||
assert.ok(game.pendingChoice?.cardIds?.includes(hidden.id))
|
||||
assert.throws(() => game.chooseHideawayCard('p2', hidden.id), GameError)
|
||||
const looked = [...game.getPlayer('p1').library.slice(0, 4)]
|
||||
game.chooseHideawayCard('p1', hidden.id)
|
||||
assert.equal(game.pendingChoice, undefined)
|
||||
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
assert.equal(hidden.faceDown, true)
|
||||
assert.deepEqual(land.linkedExile, [hidden.id])
|
||||
assert.deepEqual(
|
||||
game.getPlayer('p1').library.slice(-3).sort(),
|
||||
looked.filter(id => id !== hidden.id).sort(),
|
||||
)
|
||||
|
||||
game.activateAbility('p1', land.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
|
||||
game.addCard('p1', creature('Big Bear', 10, 10), 'battlefield')
|
||||
game.activateAbility('p1', land.id, 1)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(hidden.zone, 'battlefield')
|
||||
assert.equal(hidden.faceDown, undefined)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(hidden.id))
|
||||
})
|
||||
|
||||
test('playing a card hidden by hideaway uses the land drop', () => {
|
||||
const hideawayLand = card('Hideaway Land', {
|
||||
typeLine: 'Land',
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'hideaway', amount: { kind: 'number', value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Hideaway 1',
|
||||
},
|
||||
{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'conditional',
|
||||
condition: { kind: 'total_power', controller: 'you', atLeast: 0 },
|
||||
effects: [{ op: 'play_exiled', player: 'you', free: true }],
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Play the exiled card without paying its mana cost.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const hidden = game.addCard('p1', land('Island', 'U'), 'library')
|
||||
const library = game.getPlayer('p1').library
|
||||
library.splice(library.indexOf(hidden.id), 1)
|
||||
library.unshift(hidden.id)
|
||||
const source = game.addCard('p1', hideawayLand, 'hand')
|
||||
|
||||
game.playLand('p1', source.id)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
assert.equal(hidden.faceDown, true)
|
||||
|
||||
game.getPlayer('p1').landPlayedThisTurn = true
|
||||
game.activateAbility('p1', source.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'exile')
|
||||
|
||||
game.getPlayer('p1').landPlayedThisTurn = false
|
||||
game.activateAbility('p1', source.id, 1)
|
||||
game.resolveStack()
|
||||
assert.equal(hidden.zone, 'battlefield')
|
||||
assert.equal(game.getPlayer('p1').landPlayedThisTurn, true)
|
||||
})
|
||||
|
||||
test('enters triggers from compiled card code fire and resolve through the stack', () => {
|
||||
const soulWarden = card('Soul Warden', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
colors: ['W'],
|
||||
abilities: [{
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'enters',
|
||||
subject: { kind: 'object', selector: { other: true, types: ['creature'] }, mode: 'each' },
|
||||
},
|
||||
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'gain' }],
|
||||
optional: false,
|
||||
text: 'Whenever another creature enters, you gain 1 life.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', soulWarden, 'battlefield')
|
||||
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1), 'hand')
|
||||
|
||||
game.castSpell('p1', elves.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.getPlayer('p1').life, 41)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(elves.id))
|
||||
})
|
||||
|
||||
test('activated mana abilities produce mana and creatures have summoning sickness', () => {
|
||||
const solRing = card('Sol Ring', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{C}', '{C}'] } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {C}{C}.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 5 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 5 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const ring = game.addCard('p1', solRing, 'battlefield')
|
||||
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1, [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{G}'] } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {G}.',
|
||||
}]), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', ring.id, 0)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 2 })
|
||||
assert.equal(ring.tapped, true)
|
||||
assert.throws(() => game.activateAbility('p1', elves.id, 0), GameError)
|
||||
|
||||
game.endTurn('p1')
|
||||
game.endTurn('p2')
|
||||
assert.equal(elves.tapped, false)
|
||||
game.activateAbility('p1', elves.id, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 1)
|
||||
})
|
||||
|
||||
test('a player who runs out of cards loses and the last player wins', () => {
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [
|
||||
{ id: 'p1', deck: [card('Filler')] },
|
||||
{ id: 'p2', deck: [] },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
game.endTurn('p1')
|
||||
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p1')
|
||||
assert.equal(game.getPlayer('p2').lost, true)
|
||||
})
|
||||
|
||||
test('lethal damage to a player ends the game', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2', life: 3 }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p1')
|
||||
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()
|
||||
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const expensive = game.addCard('p1', spell('Expensive Spell', [], '{R}{R}'), 'hand')
|
||||
|
||||
assert.throws(() => game.castSpell('p1', expensive.id), GameError)
|
||||
assert.equal(mountain.tapped, false)
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 0)
|
||||
assert.ok(game.getPlayer('p1').hand.includes(expensive.id))
|
||||
})
|
||||
|
||||
test('phyrexian mana can be paid with exactly enough life', () => {
|
||||
const game = setup([{ id: 'p1', life: 2 }, { id: 'p2' }])
|
||||
game.start()
|
||||
const spellCard = game.addCard('p1', spell('Gitaxian Probe', [], '{W/P}'), 'hand')
|
||||
|
||||
assert.doesNotThrow(() => game.castSpell('p1', spellCard.id))
|
||||
assert.equal(game.getPlayer('p1').life, 0)
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p2')
|
||||
})
|
||||
|
||||
test('an unless cost auto-taps the mana sources of the payer', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const forests = [
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
|
||||
]
|
||||
const edict = game.addCard('p1', spell('Edict', [{
|
||||
op: 'sacrifice',
|
||||
player: 'opponent',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
unless: { kind: 'mana', symbols: '{2}' },
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', edict.id, {
|
||||
targets: [{ kind: 'player', id: 'p2' }, { kind: 'object', id: bear.id }],
|
||||
})
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(bear.zone, 'battlefield')
|
||||
assert.ok(forests.every(forest => forest.tapped))
|
||||
assert.equal(game.getPlayer('p2').manaPool.G, 0)
|
||||
})
|
||||
|
||||
test('damage followed by exile-instead-of-dying sends the damaged creature to exile', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p2', creature('Doomed Bear', 2, 2), 'battlefield')
|
||||
const burn = game.addCard('p1', spell('Exiling Burn', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
{ op: 'exile_instead_of_dying', target: { kind: 'damaged' } },
|
||||
]), 'hand')
|
||||
|
||||
game.castSpell('p1', burn.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(bear.zone, 'exile')
|
||||
assert.ok(game.getPlayer('p2').exile.includes(bear.id))
|
||||
assert.ok(!game.getPlayer('p2').graveyard.includes(bear.id))
|
||||
})
|
||||
155
backend/test/game-mana.test.ts
Normal file
155
backend/test/game-mana.test.ts
Normal file
@@ -0,0 +1,155 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
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 mana ability that makes one of several colors uses the chosen color', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const dual = game.addCard('p1', card('Dual Land', {
|
||||
typeLine: 'Land',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{W}', '{U}'], oneOf: true } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {W} or {U}.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
|
||||
assert.deepEqual(game.manaColorChoices(dual, 0), ['W', 'U'])
|
||||
game.activateAbility('p1', dual.id, 0, { manaColor: 'U' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.U, 1)
|
||||
assert.equal(game.getPlayer('p1').manaPool.W, 0)
|
||||
})
|
||||
|
||||
test('a mana color the ability cannot make is rejected before tapping', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const mono = game.addCard('p1', land('Mono Land', 'W'), 'battlefield')
|
||||
|
||||
assert.throws(() => game.activateAbility('p1', mono.id, 0, { manaColor: 'G' }), GameError)
|
||||
assert.equal(mono.tapped, false)
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 0)
|
||||
})
|
||||
|
||||
test('an any-color mana source produces the chosen color and offers all five', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const rainbow = game.addCard('p1', 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.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
|
||||
assert.deepEqual(game.manaColorChoices(rainbow, 0), ['W', 'U', 'B', 'R', 'G'])
|
||||
game.activateAbility('p1', rainbow.id, 0, { manaColor: 'R' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 1)
|
||||
})
|
||||
|
||||
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',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'Creatures you control get +1/+1.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const anthemObject = game.addCard('p1', anthem, 'battlefield')
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const enemy = game.addCard('p2', creature('Enemy Bear', 2, 2), 'battlefield')
|
||||
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
assert.equal(game.getPower(enemy), 2)
|
||||
assert.equal(game.getPower(anthemObject), 0)
|
||||
})
|
||||
663
backend/test/game-rules.test.ts
Normal file
663
backend/test/game-rules.test.ts
Normal file
@@ -0,0 +1,663 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('canPlayCard reports legal lands and spells for the player with priority', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
|
||||
const bear = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{G}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', forest.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), false)
|
||||
assert.equal(game.canPlayCard('p2', forest.id), false)
|
||||
|
||||
game.playLand('p1', forest.id)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), true)
|
||||
})
|
||||
|
||||
test('autoAdvance skips empty phases and stops when someone can act', () => {
|
||||
const expensive = card('Expensive', { manaCost: '{5}' })
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [
|
||||
{ id: 'p1', deck: [expensive] },
|
||||
{ id: 'p2', deck: [expensive] },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
game.addCard('p1', land('Forest', 'G'), 'battlefield')
|
||||
|
||||
// The only action is a mana ability, which should not hold the phase open.
|
||||
game.autoAdvance()
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.activePlayer, 'p2')
|
||||
assert.equal(game.phase, 'precombat_main')
|
||||
assert.equal(game.priority, 'p2')
|
||||
|
||||
const hasty = creature('Hasty', 2, 2, [{ kind: 'keyword', keyword: 'Haste' }])
|
||||
game.addCard('p2', hasty, 'battlefield')
|
||||
game.autoAdvance()
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.phase, 'combat')
|
||||
assert.equal(game.step, 'declare_attackers')
|
||||
assert.equal(game.priority, 'p2')
|
||||
})
|
||||
|
||||
test('every defending player declares blocks before combat damage in multiplayer', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }])
|
||||
game.start()
|
||||
const first = game.addCard('p1', creature('First Attacker', 2, 2), 'battlefield')
|
||||
const second = game.addCard('p1', creature('Second Attacker', 3, 3), 'battlefield')
|
||||
first.enteredTurn = 0
|
||||
second.enteredTurn = 0
|
||||
|
||||
game.declareAttackers('p1', [
|
||||
{ attackerId: first.id, defenderId: 'p2' },
|
||||
{ attackerId: second.id, defenderId: 'p3' },
|
||||
])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
|
||||
game.declareBlockers('p2', [])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
assert.equal(game.priority, 'p3')
|
||||
|
||||
game.declareBlockers('p3', [])
|
||||
assert.equal(game.step, 'combat_damage')
|
||||
|
||||
game.resolveCombatDamage()
|
||||
assert.equal(game.getPlayer('p2').life, 38)
|
||||
assert.equal(game.getPlayer('p3').life, 37)
|
||||
})
|
||||
|
||||
test('counter-removal costs are paid and fail when counters run out', () => {
|
||||
const vessel = card('Spore Vessel', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'remove_counters', counter: 'spore', amount: { kind: 'number', value: 2 } }],
|
||||
effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Remove two spore counters from this: Draw a card.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2' }])
|
||||
game.start()
|
||||
const source = game.addCard('p1', vessel, 'battlefield')
|
||||
source.counters.spore = 3
|
||||
|
||||
game.activateAbility('p1', source.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(source.counters.spore, 1)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 2)
|
||||
|
||||
assert.throws(() => game.activateAbility('p1', source.id, 0), GameError)
|
||||
assert.equal(source.counters.spore, 1)
|
||||
})
|
||||
|
||||
test('a free alternative cost needs a commander and skips the mana cost', () => {
|
||||
const maneuver = card('Flawless Maneuver', {
|
||||
typeLine: 'Instant',
|
||||
manaCost: '{2}{W}',
|
||||
manaValue: 3,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'alternative_cost',
|
||||
costs: [],
|
||||
condition: { kind: 'you_control_commander' },
|
||||
text: 'If you control a commander, you may cast this spell without paying its mana cost.',
|
||||
},
|
||||
{
|
||||
kind: 'spell',
|
||||
effects: [{
|
||||
op: 'grant',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
|
||||
keyword: 'Indestructible',
|
||||
duration: 'until_end_of_turn',
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Creatures you control gain indestructible until end of turn.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingHandSize: 0,
|
||||
commander: true,
|
||||
players: [
|
||||
{ id: 'p1', deck: [card('Filler')], commander: creature('Test Commander', 2, 2) },
|
||||
{ id: 'p2', deck: [card('Filler')], commander: creature('Other Commander', 2, 2) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
const spell = game.addCard('p1', maneuver, 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', spell.id), false)
|
||||
assert.throws(() => game.castSpell('p1', spell.id), GameError)
|
||||
|
||||
game.moveToZone(game.getPlayer('p1').commanderId!, 'battlefield', { silent: true })
|
||||
|
||||
assert.equal(game.canPlayCard('p1', spell.id), true)
|
||||
game.castSpell('p1', spell.id)
|
||||
assert.equal(game.stack.length, 1)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 0 })
|
||||
})
|
||||
|
||||
test('overload pays the overload cost and widens the spell target', () => {
|
||||
const rift = card('Cyclonic Rift', {
|
||||
typeLine: 'Instant',
|
||||
manaCost: '{U}',
|
||||
manaValue: 1,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'spell',
|
||||
effects: [{
|
||||
op: 'return_to_hand',
|
||||
target: {
|
||||
kind: 'object',
|
||||
selector: { controller: 'opponent', types: ['permanent'], excludeTypes: ['land'] },
|
||||
mode: 'target',
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: "Return target nonland permanent you don't control to its owner's hand.",
|
||||
},
|
||||
{ kind: 'overload', cost: '{1}{U}', text: 'Overload {1}{U}' },
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const island = game.addCard('p1', land('Island', 'U'), 'battlefield')
|
||||
const wastes = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const ownCreature = game.addCard('p1', creature('Own Bear', 2, 2), 'battlefield')
|
||||
const theirCreature = game.addCard('p2', creature('Their Bear', 2, 2), 'battlefield')
|
||||
const theirArtifact = game.addCard('p2', card('Their Rock', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
}), 'battlefield')
|
||||
const theirLand = game.addCard('p2', land('Forest', 'G'), 'battlefield')
|
||||
const spell = game.addCard('p1', rift, 'hand')
|
||||
|
||||
game.castSpell('p1', spell.id, { overload: true })
|
||||
|
||||
assert.equal(island.tapped, true)
|
||||
assert.equal(wastes.tapped, true)
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p2').hand.includes(theirCreature.id))
|
||||
assert.ok(game.getPlayer('p2').hand.includes(theirArtifact.id))
|
||||
assert.ok(game.getPlayer('p2').battlefield.includes(theirLand.id))
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(ownCreature.id))
|
||||
})
|
||||
|
||||
test('a noncreature cost increase taxes spells but not creatures', () => {
|
||||
const thalia = card('Thalia, Guardian of Thraben', {
|
||||
typeLine: 'Legendary Creature — Human Soldier',
|
||||
power: 2,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'cost_increase', amount: { kind: 'number', value: 1 }, spellType: 'noncreature' }],
|
||||
text: 'Noncreature spells cost {1} more to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', thalia, 'battlefield')
|
||||
const first = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const instant = game.addCard('p1', spell('Ponder', [
|
||||
{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } },
|
||||
], '{1}'), 'hand')
|
||||
const bears = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{1}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', instant.id), false)
|
||||
assert.equal(game.canPlayCard('p1', bears.id), true)
|
||||
|
||||
game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
assert.equal(game.canPlayCard('p1', instant.id), true)
|
||||
game.castSpell('p1', instant.id)
|
||||
assert.equal(first.tapped, true)
|
||||
})
|
||||
|
||||
test('spell cost reductions match the spell type and controller', () => {
|
||||
const baral = card('Baral, Chief of Compliance', {
|
||||
typeLine: 'Legendary Creature — Human Wizard',
|
||||
power: 1,
|
||||
toughness: 3,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'cost_reduction',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['instant', 'sorcery'], match: 'any' }, mode: 'each' },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'Instant and sorcery spells you cast cost {1} less to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', baral, 'battlefield')
|
||||
const wastes = game.addCard('p1', land('Wastes', 'C'), 'battlefield')
|
||||
const sorcery = game.addCard('p1', card('Divination', {
|
||||
typeLine: 'Sorcery',
|
||||
manaCost: '{2}',
|
||||
abilities: [{ kind: 'spell', effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }], optional: false, text: 'Draw a card.' }],
|
||||
}), 'hand')
|
||||
const bears = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{2}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', sorcery.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bears.id), false)
|
||||
|
||||
game.castSpell('p1', sorcery.id)
|
||||
assert.equal(wastes.tapped, true)
|
||||
})
|
||||
|
||||
test('a colored cost reduction removes matching pips and nothing else', () => {
|
||||
const edgewalker = card('Edgewalker', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'cost_reduction',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'], match: 'any', subtypes: ['cleric', 'soldier'] }, mode: 'each' },
|
||||
symbols: '{W}{B}',
|
||||
}],
|
||||
text: 'Cleric spells you cast cost {W}{B} less to cast.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', edgewalker, 'battlefield')
|
||||
game.addCard('p1', land('Plains', 'W'), 'battlefield')
|
||||
game.addCard('p1', land('Swamp', 'B'), 'battlefield')
|
||||
const cleric = game.addCard('p1', card('Cleric Test', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
const soldier = game.addCard('p1', card('Soldier Test', {
|
||||
typeLine: 'Creature — Human Soldier',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
const bear = game.addCard('p1', card('Bear Test', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
colors: ['W', 'B'],
|
||||
manaCost: '{1}{W}{B}',
|
||||
manaValue: 3,
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', cleric.id), true)
|
||||
assert.equal(game.canPlayCard('p1', soldier.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), false)
|
||||
game.castSpell('p1', cleric.id)
|
||||
})
|
||||
|
||||
test('Linvala stops only opponents from activating creature abilities', () => {
|
||||
const linvala = card('Linvala, Keeper of Silence', {
|
||||
typeLine: 'Legendary Creature — Angel',
|
||||
power: 3,
|
||||
toughness: 4,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'restriction',
|
||||
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'each' },
|
||||
rule: 'cant_activate',
|
||||
}],
|
||||
text: "Activated abilities of creatures your opponents control can't be activated.",
|
||||
}],
|
||||
})
|
||||
const drawAbility = {
|
||||
kind: 'activated' as const,
|
||||
costs: [],
|
||||
effects: [{ op: 'draw' as const, player: 'you' as const, amount: { kind: 'number' as const, value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Draw a card.',
|
||||
}
|
||||
const game = setup([{ id: 'p1', deck: [card('Filler'), card('Filler')] }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', linvala, 'battlefield')
|
||||
const own = game.addCard('p1', creature('Own Cleric', 1, 1, [drawAbility]), 'battlefield')
|
||||
const theirs = game.addCard('p2', creature('Their Cleric', 1, 1, [drawAbility]), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', own.id, 0)
|
||||
assert.equal(game.stack.length, 1)
|
||||
|
||||
game.resolveStack()
|
||||
game.pass('p1')
|
||||
assert.throws(() => game.activateAbility('p2', theirs.id, 0), /cannot activate/)
|
||||
})
|
||||
|
||||
test('Aven Mindcensor limits an opponent search to the top four cards', () => {
|
||||
const aven = card('Aven Mindcensor', {
|
||||
typeLine: 'Creature — Bird Wizard',
|
||||
power: 2,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'search_restriction', who: 'opponent', amount: { kind: 'number', value: 4 } }],
|
||||
text: 'If an opponent would search a library, that player searches the top four cards of that library instead.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2', deck: [] }])
|
||||
game.start()
|
||||
game.addCard('p1', aven, 'battlefield')
|
||||
for (const name of ['Forest', 'Island', 'Mountain', 'Plains', 'Swamp', 'Wastes']) {
|
||||
game.addCard('p2', land(name, 'C'), 'library')
|
||||
}
|
||||
const topFour = game.getPlayer('p2').library.slice(0, 4)
|
||||
const growth = game.addCard('p2', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.pass('p1')
|
||||
game.castSpell('p2', growth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.deepEqual(
|
||||
game.searchCandidates('p2').map(object => object.id).sort(),
|
||||
[...topFour].sort(),
|
||||
)
|
||||
})
|
||||
|
||||
test('Rest in Peace exiles all graveyards and replaces later graveyard moves', () => {
|
||||
const rest = card('Rest in Peace', {
|
||||
typeLine: 'Enchantment',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'triggered',
|
||||
event: { kind: 'enters', subject: { kind: 'self' } },
|
||||
effects: [{ op: 'exile_graveyards' }],
|
||||
optional: false,
|
||||
text: 'When this enchantment enters, exile all graveyards.',
|
||||
},
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'exile_instead_of_graveyard' }],
|
||||
text: 'If a card or token would be put into a graveyard from anywhere, exile it instead.',
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const oldSpell = game.addCard('p1', spell('Old Spell', []), 'graveyard')
|
||||
const oldCreature = game.addCard('p2', creature('Old Bear', 2, 2), 'graveyard')
|
||||
const doomed = game.addCard('p1', creature('Doomed Bear', 2, 2), 'battlefield')
|
||||
|
||||
game.addCard('p1', rest, 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p1').exile.includes(oldSpell.id))
|
||||
assert.ok(game.getPlayer('p2').exile.includes(oldCreature.id))
|
||||
assert.deepEqual(game.getPlayer('p1').graveyard, [])
|
||||
assert.deepEqual(game.getPlayer('p2').graveyard, [])
|
||||
|
||||
game.moveToZone(doomed, 'graveyard')
|
||||
|
||||
assert.equal(doomed.zone, 'exile')
|
||||
assert.ok(game.getPlayer('p1').exile.includes(doomed.id))
|
||||
})
|
||||
|
||||
test("Leyline of the Void exiles only opponents' cards and starts on the battlefield", () => {
|
||||
const leyline = card('Leyline of the Void', {
|
||||
typeLine: 'Enchantment',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'restriction', target: { kind: 'self' }, rule: 'begin_on_battlefield' }],
|
||||
text: 'If this card is in your opening hand, you may begin the game with it on the battlefield.',
|
||||
},
|
||||
{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'exile_instead_of_graveyard', owner: 'opponent' }],
|
||||
text: "If a card would be put into an opponent's graveyard from anywhere, exile it instead.",
|
||||
},
|
||||
],
|
||||
})
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [{ id: 'p1', deck: [card('Filler')] }, { id: 'p2', deck: [card('Filler')] }],
|
||||
})
|
||||
const leylineObject = game.addCard('p1', leyline, 'hand')
|
||||
game.start()
|
||||
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(leylineObject.id))
|
||||
assert.ok(!game.getPlayer('p1').hand.includes(leylineObject.id))
|
||||
|
||||
const theirs = game.addCard('p2', creature('Their Bear', 2, 2), 'battlefield')
|
||||
const own = game.addCard('p1', creature('Own Bear', 2, 2), 'battlefield')
|
||||
game.moveToZone(theirs, 'graveyard')
|
||||
game.moveToZone(own, 'graveyard')
|
||||
|
||||
assert.equal(theirs.zone, 'exile')
|
||||
assert.equal(own.zone, 'graveyard')
|
||||
})
|
||||
|
||||
test('Field of the Dead makes a Zombie at seven differently named lands', () => {
|
||||
const field = card('Field of the Dead', {
|
||||
typeLine: 'Land',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'enters',
|
||||
subject: {
|
||||
kind: 'object',
|
||||
selector: { other: true, controller: 'you', types: ['land'] },
|
||||
mode: 'each',
|
||||
includeSelf: true,
|
||||
},
|
||||
},
|
||||
condition: { kind: 'distinct_names', selector: { types: ['land'] }, atLeast: 7 },
|
||||
effects: [{
|
||||
op: 'create_token',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
token: {
|
||||
types: ['creature'],
|
||||
subtypes: ['zombie'],
|
||||
colors: ['B'],
|
||||
power: { kind: 'number', value: 2 },
|
||||
toughness: { kind: 'number', value: 2 },
|
||||
},
|
||||
}],
|
||||
optional: false,
|
||||
text: 'Whenever this or another land you control enters, if you control seven or more lands with different names, create a 2/2 black Zombie creature token.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', field, 'battlefield')
|
||||
for (const name of ['Forest', 'Island', 'Mountain', 'Plains']) {
|
||||
game.addCard('p1', land(name, 'C'), 'battlefield')
|
||||
}
|
||||
|
||||
game.addCard('p1', land('Swamp', 'C'), 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken).length, 0)
|
||||
|
||||
game.addCard('p1', land('Wastes', 'C'), 'battlefield', { silent: false })
|
||||
game.resolveStack()
|
||||
|
||||
const tokens = game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.equal(tokens.length, 1)
|
||||
assert.equal(tokens[0].definition.typeLine.toLowerCase().includes('zombie'), true)
|
||||
})
|
||||
|
||||
test('predefined Treasure, Gold, Powerstone, Heartwood, and Vibranium tokens produce mana', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
const treasure = makeToken(game, { types: ['artifact'], subtypes: ['treasure'], colors: [] })
|
||||
assert.equal(treasure.definition.name, 'Treasure')
|
||||
game.activateAbility('p1', treasure.id, 0, { manaColor: 'G' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 1)
|
||||
assert.equal(treasure.zone, 'graveyard')
|
||||
|
||||
const gold = makeToken(game, { types: ['artifact'], subtypes: ['gold'], colors: [] })
|
||||
game.activateAbility('p1', gold.id, 0, { manaColor: 'R' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 1)
|
||||
|
||||
const powerstone = makeToken(game, { types: ['artifact'], subtypes: ['powerstone'], colors: [] })
|
||||
game.activateAbility('p1', powerstone.id, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.C, 1)
|
||||
|
||||
const heartwood = makeToken(game, { types: ['artifact'], subtypes: ['heartwood'], colors: [] })
|
||||
game.activateAbility('p1', heartwood.id, 0, { manaColor: 'G' })
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 2)
|
||||
|
||||
const vibranium = makeToken(game, { types: ['artifact'], subtypes: ['vibranium'], colors: [] })
|
||||
assert.equal(game.hasKeyword(vibranium, 'Indestructible'), true)
|
||||
game.activateAbility('p1', vibranium.id, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.C, 2)
|
||||
})
|
||||
|
||||
test('predefined Food, Clue, Blood, and Shard tokens sacrifice for their effects', () => {
|
||||
const game = setup([{
|
||||
id: 'p1',
|
||||
deck: Array.from({ length: 6 }, (_, index) => card(`Filler ${index}`)),
|
||||
}, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
const food = makeToken(game, { types: ['artifact'], subtypes: ['food'], colors: [] })
|
||||
addMana(game, 'G', 'G')
|
||||
game.activateAbility('p1', food.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').life, 43)
|
||||
assert.equal(food.zone, 'graveyard')
|
||||
|
||||
game.addCard('p1', card('Discard Fodder'), 'hand')
|
||||
const discard = game.getObject(game.getPlayer('p1').hand[0])
|
||||
const handAfterFood = game.getPlayer('p1').hand.length
|
||||
const blood = makeToken(game, { types: ['artifact'], subtypes: ['blood'], colors: [] })
|
||||
addMana(game, 'G')
|
||||
game.activateAbility('p1', blood.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(discard.zone, 'graveyard')
|
||||
assert.equal(game.getPlayer('p1').hand.length, handAfterFood)
|
||||
|
||||
const clue = makeToken(game, { types: ['artifact'], subtypes: ['clue'], colors: [] })
|
||||
addMana(game, 'G', 'G')
|
||||
game.activateAbility('p1', clue.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').hand.length, handAfterFood + 1)
|
||||
|
||||
const shard = makeToken(game, { types: ['enchantment'], subtypes: ['shard'], colors: [] })
|
||||
addMana(game, 'G', 'G')
|
||||
game.activateAbility('p1', shard.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').hand.length, handAfterFood + 2)
|
||||
})
|
||||
|
||||
test('Walker and Incubator tokens use their predefined characteristics', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
const walker = makeToken(game, { types: ['artifact'], subtypes: ['walker'], colors: [] })
|
||||
assert.equal(walker.definition.name, 'Walker')
|
||||
assert.equal(game.getPower(walker), 2)
|
||||
assert.equal(game.getToughness(walker), 2)
|
||||
assert.deepEqual(walker.definition.colors, ['B'])
|
||||
|
||||
const maker = game.addCard('p1', card('Incubator Maker', {
|
||||
typeLine: 'Artifact',
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'keyword_action', action: 'incubate', amount: { kind: 'number', value: 2 } }],
|
||||
optional: false,
|
||||
text: '{T}: Incubate 2.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.activateAbility('p1', maker.id, 0)
|
||||
game.resolveStack()
|
||||
|
||||
const incubator = game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id))
|
||||
.find(object => object.isToken && object.definition.name === 'Incubator')
|
||||
assert.ok(incubator)
|
||||
assert.equal(incubator.counters['+1/+1'], 2)
|
||||
|
||||
addMana(game, 'G', 'G')
|
||||
game.activateAbility('p1', incubator.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(incubator.definition.name, 'Phyrexian')
|
||||
assert.equal(game.getPower(incubator), 2)
|
||||
assert.equal(game.getToughness(incubator), 2)
|
||||
})
|
||||
|
||||
test('predefined Map, Lander, and Mutagen tokens use their activated abilities', () => {
|
||||
const mapGame = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
|
||||
mapGame.start()
|
||||
const topCard = mapGame.addCard('p1', card('Top Card'), 'library')
|
||||
const bear = mapGame.addCard('p1', creature('Bear', 2, 2), 'battlefield')
|
||||
addMana(mapGame, 'G')
|
||||
const map = makeToken(mapGame, { types: ['artifact'], subtypes: ['map'], colors: [] })
|
||||
mapGame.activateAbility('p1', map.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
mapGame.resolveStack()
|
||||
assert.equal(bear.counters['+1/+1'], 1)
|
||||
assert.equal(topCard.zone, 'graveyard')
|
||||
|
||||
addMana(mapGame, 'G')
|
||||
const mutagen = makeToken(mapGame, { types: ['artifact'], subtypes: ['mutagen'], colors: [] })
|
||||
mapGame.activateAbility('p1', mutagen.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
mapGame.resolveStack()
|
||||
assert.equal(bear.counters['+1/+1'], 2)
|
||||
|
||||
const landGame = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
|
||||
landGame.start()
|
||||
const forest = landGame.addCard('p1', land('Forest', 'G'), 'library')
|
||||
addMana(landGame, 'G', 'G')
|
||||
const lander = makeToken(landGame, { types: ['artifact'], subtypes: ['lander'], colors: [] })
|
||||
landGame.activateAbility('p1', lander.id, 0)
|
||||
landGame.resolveStack()
|
||||
assert.equal(forest.zone, 'battlefield')
|
||||
assert.equal(forest.tapped, true)
|
||||
})
|
||||
204
backend/test/game-search.test.ts
Normal file
204
backend/test/game-search.test.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('a search that shuffles and puts the chosen card on top leaves it on top', () => {
|
||||
const bear = creature('Bear', 2, 2)
|
||||
const elf = creature('Elf', 1, 1)
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bearObject = game.addCard('p1', bear, 'library')
|
||||
const elfObject = game.addCard('p1', elf, 'library')
|
||||
const worldlyTutor = game.addCard('p1', spell('Worldly Tutor', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['creature'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'top',
|
||||
tapped: false,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', worldlyTutor.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.pendingSearch?.playerId, 'p1')
|
||||
|
||||
game.chooseSearchCard('p1', elfObject.id)
|
||||
|
||||
assert.equal(game.getPlayer('p1').library[0], elfObject.id)
|
||||
assert.ok(game.getPlayer('p1').library.includes(bearObject.id))
|
||||
})
|
||||
|
||||
test('as-enters creature type choices pause until the controller picks', () => {
|
||||
const cavern = card('Cavern of Souls', {
|
||||
typeLine: 'Land',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'choose', what: 'creature_type' }],
|
||||
text: 'As this enters, choose a creature type.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const object = game.addCard('p1', cavern, 'hand')
|
||||
game.playLand('p1', object.id)
|
||||
|
||||
assert.equal(game.pendingChoice?.sourceId, object.id)
|
||||
assert.equal(game.pendingChoice?.playerId, 'p1')
|
||||
assert.throws(() => game.pass('p1'), GameError)
|
||||
assert.throws(() => game.chooseCreatureType('p2', 'Elf'), GameError)
|
||||
assert.throws(() => game.chooseCreatureType('p1', 'Not A Type'), GameError)
|
||||
|
||||
game.chooseCreatureType('p1', 'elf')
|
||||
assert.equal(object.chosenCreatureType, 'Elf')
|
||||
assert.equal(game.pendingChoice, undefined)
|
||||
|
||||
game.moveToZone(object, 'graveyard')
|
||||
assert.equal(object.chosenCreatureType, undefined)
|
||||
game.moveToZone(object, 'battlefield', { silent: false })
|
||||
assert.equal(game.pendingChoice?.sourceId, object.id)
|
||||
})
|
||||
|
||||
test('a split search sends the first pick to the battlefield and the next to hand', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const island = land('Island', 'U')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forestObject = game.addCard('p1', forest, 'library')
|
||||
const islandObject = game.addCard('p1', island, 'library')
|
||||
const cultivate = game.addCard('p1', spell('Cultivate', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 2 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
split: { destination: 'hand', tapped: false },
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', cultivate.id)
|
||||
game.resolveStack()
|
||||
|
||||
game.chooseSearchCard('p1', islandObject.id)
|
||||
assert.equal(game.pendingSearch?.destination, 'hand')
|
||||
game.chooseSearchCard('p1', forestObject.id)
|
||||
|
||||
assert.equal(game.pendingSearch, undefined)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
|
||||
assert.equal(islandObject.tapped, true)
|
||||
assert.ok(game.getPlayer('p1').hand.includes(forestObject.id))
|
||||
})
|
||||
|
||||
test('autoAdvance stops instead of passing while a search needs a pick', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Forest', 'G'), 'library')
|
||||
game.addCard('p1', land('Island', 'U'), 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.autoAdvance()
|
||||
|
||||
assert.equal(game.pendingSearch?.playerId, 'p1')
|
||||
assert.equal(game.priority, 'p1')
|
||||
})
|
||||
|
||||
test('static replacement effects make permanents enter tapped with counters', () => {
|
||||
const slow = creature('Slow Bear', 2, 2, [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'enters_tapped', target: { kind: 'self' } }],
|
||||
text: 'This enters tapped.',
|
||||
}, {
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'enters_with_counters',
|
||||
target: { kind: 'self' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'This enters with a +1/+1 counter.',
|
||||
}])
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', slow, 'hand')
|
||||
|
||||
game.castSpell('p1', bear.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(bear.tapped, true)
|
||||
assert.equal(bear.counters['+1/+1'], 1)
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
})
|
||||
|
||||
function shockLand(): CardDefinition {
|
||||
return card('Steam Vents', {
|
||||
typeLine: 'Land — Island Mountain',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'enters_tapped', target: { kind: 'self' }, unlessCost: { kind: 'pay_life', amount: { kind: 'number', value: 2 } } }],
|
||||
text: "As this land enters, you may pay 2 life. If you don't, it enters tapped.",
|
||||
}, {
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{U}', '{R}'], oneOf: true } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {U} or {R}.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
test('a land can pay life to enter untapped or enter tapped', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const vents = game.addCard('p1', shockLand(), 'hand')
|
||||
game.playLand('p1', vents.id)
|
||||
|
||||
assert.equal(vents.tapped, false)
|
||||
assert.equal(game.pendingChoice?.what, 'pay_cost')
|
||||
assert.equal(game.pendingChoice?.amount, 2)
|
||||
assert.throws(() => game.chooseCostPayment('p2', true), GameError)
|
||||
|
||||
game.chooseCostPayment('p1', true)
|
||||
assert.equal(game.getPlayer('p1').life, 38)
|
||||
assert.equal(vents.tapped, false)
|
||||
assert.equal(game.pendingChoice, undefined)
|
||||
|
||||
const second = game.addCard('p1', shockLand(), 'hand')
|
||||
game.moveToZone(second, 'battlefield', { controller: 'p1', silent: false })
|
||||
assert.equal(game.pendingChoice?.what, 'pay_cost')
|
||||
|
||||
game.chooseCostPayment('p1', false)
|
||||
assert.equal(second.tapped, true)
|
||||
assert.equal(game.getPlayer('p1').life, 38)
|
||||
})
|
||||
|
||||
test('a choice mana ability adds only the color the spell needs', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const vents = game.addCard('p1', shockLand(), 'battlefield')
|
||||
const red = game.addCard('p1', spell('Red Spell', [], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', red.id)
|
||||
|
||||
assert.equal(vents.tapped, true)
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.U, 0)
|
||||
})
|
||||
520
backend/test/game-targets.test.ts
Normal file
520
backend/test/game-targets.test.ts
Normal file
@@ -0,0 +1,520 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('temporary pump effects expire at end of turn', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Giant Growth', [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
power: { kind: 'number', value: 3 },
|
||||
toughness: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_turn',
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
assert.equal(game.getToughness(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 2)
|
||||
})
|
||||
|
||||
test('the engine exposes legal creature targets for a card', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Giant Growth', [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
power: { kind: 'number', value: 3 },
|
||||
toughness: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_turn',
|
||||
}]), 'hand')
|
||||
|
||||
assert.deepEqual(game.legalTargetsForCard('p1', growth.id), [{ kind: 'object', id: bear.id }])
|
||||
})
|
||||
|
||||
test('excluded colors filter legal targets', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
game.addCard('p2', card('Black Bear', { typeLine: 'Creature — Bear', colors: ['B'], power: 2, toughness: 2 }), 'battlefield')
|
||||
const green = game.addCard('p2', card('Green Bear', { typeLine: 'Creature — Bear', colors: ['G'], power: 2, toughness: 2 }), 'battlefield')
|
||||
const doomBlade = game.addCard('p1', spell('Doom Blade', [{
|
||||
op: 'destroy',
|
||||
target: { kind: 'object', selector: { types: ['creature'], excludeColors: ['B'] }, mode: 'target' },
|
||||
}]), 'hand')
|
||||
|
||||
assert.deepEqual(game.legalTargetsForCard('p1', doomBlade.id), [{ kind: 'object', id: green.id }])
|
||||
})
|
||||
|
||||
test('the engine exposes legal targets for an activated ability', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const pinger = game.addCard('p1', card('Pinger', {
|
||||
typeLine: 'Creature — Test',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
optional: false,
|
||||
text: '{T}: This creature deals 1 damage to target creature an opponent controls.',
|
||||
effects: [{
|
||||
op: 'damage',
|
||||
target: { kind: 'object', selector: { controller: 'opponent', types: ['creature'] }, mode: 'target' },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
}],
|
||||
}), 'battlefield')
|
||||
|
||||
assert.deepEqual(game.legalTargetsForAbility('p1', pinger.id, 0), [{ kind: 'object', id: bear.id }])
|
||||
})
|
||||
|
||||
test('"until the end of your next turn" lasts through the controller next turn', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Growth', [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
power: { kind: 'number', value: 3 },
|
||||
toughness: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_your_next_turn',
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p2')
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 2)
|
||||
})
|
||||
|
||||
test('counter replacement doubles counters put on matching creatures', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Hardened Scales Test', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'counter_multiplier',
|
||||
target: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'each' },
|
||||
counter: '+1/+1',
|
||||
multiplier: 2,
|
||||
}],
|
||||
text: 'If one or more +1/+1 counters would be put on a creature you control, twice that many are put on it instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Counter Bear', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Growth', [{
|
||||
op: 'put_counters',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 2 },
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(bear.counters['+1/+1'], 4)
|
||||
})
|
||||
|
||||
test('energy replacement doubles energy gained', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Energy Doubler', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'replacement_amount', what: 'energy', multiplier: 2 }],
|
||||
text: 'If you would get one or more {E}, you get twice that many {E} instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
const spark = game.addCard('p1', spell('Spark', [
|
||||
{ op: 'energy', player: 'you', amount: { kind: 'number', value: 2 } },
|
||||
]), 'hand')
|
||||
|
||||
game.castSpell('p1', spark.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').energy, 4)
|
||||
})
|
||||
|
||||
test('a static source-filtered prevention stops only matching damage', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const protectedCreature = game.addCard('p1', card('Ward Golem', {
|
||||
typeLine: 'Artifact Creature — Golem',
|
||||
power: 2,
|
||||
toughness: 5,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'self' },
|
||||
amount: 'all',
|
||||
duration: 'permanent',
|
||||
sourceSelector: { types: ['creature'] },
|
||||
}],
|
||||
text: 'Prevent all damage that would be dealt to this by creatures.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
const plain = game.addCard('p1', creature('Plain Bear', 2, 5), 'battlefield')
|
||||
const pinger = game.addCard('p2', card('Pinger', {
|
||||
typeLine: 'Creature — Test',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'damage',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
amount: { kind: 'number', value: 3 },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{0}: Deal 3 damage to target creature.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
|
||||
while (game.priority !== 'p2') game.pass(game.priority)
|
||||
game.activateAbility('p2', pinger.id, 0, { targets: [{ kind: 'object', id: protectedCreature.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(protectedCreature.damage, 0)
|
||||
|
||||
while (game.priority !== 'p2') game.pass(game.priority)
|
||||
game.activateAbility('p2', pinger.id, 0, { targets: [{ kind: 'object', id: plain.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(plain.damage, 3)
|
||||
})
|
||||
|
||||
test('a source-scoped shield only stops the chosen source', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const pinger = (name: string) => card(name, {
|
||||
typeLine: 'Creature — Test',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [],
|
||||
effects: [{
|
||||
op: 'damage',
|
||||
target: { kind: 'player', who: 'opponent', mode: 'target' },
|
||||
amount: { kind: 'number', value: 3 },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{0}: Deal 3 damage to target opponent.',
|
||||
}],
|
||||
})
|
||||
const chosen = game.addCard('p2', pinger('Chosen Pinger'), 'battlefield')
|
||||
const other = game.addCard('p2', pinger('Other Pinger'), 'battlefield')
|
||||
game.start()
|
||||
|
||||
const shield = spell('Source Shield', [{
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'any' },
|
||||
amount: 'all',
|
||||
duration: 'until_end_of_turn',
|
||||
global: true,
|
||||
source: { kind: 'object', selector: {}, mode: 'target' },
|
||||
}])
|
||||
const shieldCard = game.addCard('p1', shield, 'hand')
|
||||
game.castSpell('p1', shieldCard.id, { targets: [{ kind: 'object', id: chosen.id }] })
|
||||
game.resolveStack()
|
||||
|
||||
while (game.priority !== 'p2') game.pass(game.priority)
|
||||
game.activateAbility('p2', chosen.id, 0, { targets: [{ kind: 'player', id: 'p1' }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').life, 40)
|
||||
|
||||
while (game.priority !== 'p2') game.pass(game.priority)
|
||||
game.activateAbility('p2', other.id, 0, { targets: [{ kind: 'player', id: 'p1' }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').life, 37)
|
||||
})
|
||||
|
||||
test('a prevention follow-up runs with the prevented amount', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const target = game.addCard('p1', creature('Shielded Bear', 2, 5), 'battlefield')
|
||||
const shield = spell('Shield', [{
|
||||
op: 'prevent_damage',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
amount: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_turn',
|
||||
then: [{
|
||||
op: 'damage',
|
||||
target: { kind: 'player', who: 'opponent', mode: 'target' },
|
||||
amount: { kind: 'event_amount' },
|
||||
}],
|
||||
}])
|
||||
const bolt = spell('Bolt', [{
|
||||
op: 'damage',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
amount: { kind: 'number', value: 5 },
|
||||
}])
|
||||
|
||||
const shieldCard = game.addCard('p1', shield, 'hand')
|
||||
game.castSpell('p1', shieldCard.id, {
|
||||
targets: [{ kind: 'object', id: target.id }, { kind: 'player', id: 'p2' }],
|
||||
})
|
||||
game.resolveStack()
|
||||
const boltCard = game.addCard('p1', bolt, 'hand')
|
||||
game.castSpell('p1', boltCard.id, { targets: [{ kind: 'object', id: target.id }] })
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(target.damage, 2)
|
||||
assert.equal(game.getPlayer('p2').life, 37)
|
||||
})
|
||||
|
||||
test('color-specific damage replacement only boosts matching sources', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Red Enhancer', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'replacement_amount', what: 'damage', multiplier: 1, add: 1, sourceColor: 'R' }],
|
||||
text: 'If a red source would deal damage, it deals that much damage plus 1 instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
const redBolt = game.addCard('p1', card('Red Bolt', {
|
||||
typeLine: 'Instant',
|
||||
colors: ['R'],
|
||||
abilities: [{
|
||||
kind: 'spell',
|
||||
effects: [{ op: 'damage', target: { kind: 'player', who: 'opponent', mode: 'target' }, amount: { kind: 'number', value: 3 } }],
|
||||
optional: false,
|
||||
text: 'Deal 3 damage.',
|
||||
}],
|
||||
}), 'hand')
|
||||
|
||||
game.castSpell('p1', redBolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p2').life, 36)
|
||||
})
|
||||
|
||||
test('life-gain replacement doubles the life gained', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Life Doubler', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'replacement_amount', what: 'life_gain', multiplier: 2 }],
|
||||
text: 'If you would gain life, you gain twice that much life instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
const heal = game.addCard('p1', spell('Heal', [
|
||||
{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' },
|
||||
]), 'hand')
|
||||
|
||||
game.castSpell('p1', heal.id)
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p1').life, 46)
|
||||
})
|
||||
|
||||
test('damage replacement doubles damage from sources you control', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Furnace', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'replacement_amount', what: 'damage', multiplier: 2 }],
|
||||
text: 'If a source you control would deal damage, it deals double that damage instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
const bolt = game.addCard('p1', spell('Bolt', [
|
||||
{ op: 'damage', target: { kind: 'player', who: 'opponent', mode: 'target' }, amount: { kind: 'number', value: 3 } },
|
||||
]), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPlayer('p2').life, 34)
|
||||
})
|
||||
|
||||
test('draw replacement doubles each draw', () => {
|
||||
const deck = [card('Filler One'), card('Filler Two'), card('Filler Three'), card('Filler Four')]
|
||||
const game = setup([{ id: 'p1', deck }, { id: 'p2', deck }])
|
||||
game.addCard('p1', card('Draw Doubler', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'replacement_amount', what: 'draw', multiplier: 2 }],
|
||||
text: 'If you would draw a card, draw two cards instead.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
assert.equal(game.getPlayer('p1').hand.length, 2)
|
||||
assert.equal(game.getPlayer('p2').hand.length, 0)
|
||||
})
|
||||
|
||||
test('"skip your draw step" stops its controller drawing', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.addCard('p1', card('Necro Test', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'restriction', target: { kind: 'player', who: 'you', mode: 'target' }, rule: 'skip_draw_step' }],
|
||||
text: 'Skip your draw step.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
game.start()
|
||||
|
||||
assert.equal(game.getPlayer('p1').hand.length, 0)
|
||||
assert.equal(game.getPlayer('p1').library.length, 1)
|
||||
|
||||
game.endTurn('p1')
|
||||
game.endTurn('p2')
|
||||
assert.equal(game.activePlayer, 'p1')
|
||||
assert.equal(game.getPlayer('p1').hand.length, 0)
|
||||
assert.equal(game.getPlayer('p1').library.length, 1)
|
||||
})
|
||||
|
||||
test('an unblockable attacker rejects declared blockers', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const attacker = game.addCard('p1', card('Slippery Otter', {
|
||||
typeLine: 'Creature — Otter',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_blocked' }],
|
||||
text: 'This creature cannot be blocked.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield')
|
||||
game.start()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
|
||||
assert.throws(
|
||||
() => game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }]),
|
||||
/cannot be blocked/,
|
||||
)
|
||||
})
|
||||
|
||||
test('a "can\'t be countered" spell survives a counterspell', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const uncounterable = card('Uncounterable', {
|
||||
typeLine: 'Instant',
|
||||
abilities: [
|
||||
{ kind: 'spell', effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 3 }, mode: 'gain' }], optional: false, text: 'Gain 3 life.' },
|
||||
{ kind: 'static', effects: [{ op: 'restriction', target: { kind: 'self' }, rule: 'cant_be_countered' }], text: 'This spell cannot be countered.' },
|
||||
],
|
||||
})
|
||||
const counterspell = spell('Counterspell', [{ op: 'counter', what: 'spell', target: { kind: 'spell', selector: {}, mode: 'target' } }])
|
||||
const target = game.addCard('p1', uncounterable, 'hand')
|
||||
const counterCard = game.addCard('p2', counterspell, 'hand')
|
||||
|
||||
game.castSpell('p1', target.id)
|
||||
game.castSpell('p2', counterCard.id, { targets: [{ kind: 'spell', id: game.stack[game.stack.length - 1].id }] })
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.getPlayer('p1').life, 43)
|
||||
assert.equal(target.zone, 'graveyard')
|
||||
})
|
||||
|
||||
test('combat damage kills creatures and moves them to the graveyard', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const attacker = game.addCard('p1', creature('Attacker', 2, 2), 'battlefield')
|
||||
const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield')
|
||||
game.start()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
assert.equal(game.priority, 'p2')
|
||||
assert.equal(attacker.tapped, true)
|
||||
|
||||
game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }])
|
||||
game.resolveCombatDamage()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 40)
|
||||
assert.equal(game.step, 'end_combat')
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(attacker.id))
|
||||
assert.ok(game.getPlayer('p2').graveyard.includes(blocker.id))
|
||||
})
|
||||
|
||||
test('unblocked attackers deal damage to the defending player', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const attacker = game.addCard('p1', creature('Attacker', 3, 3), 'battlefield')
|
||||
game.start()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
|
||||
game.declareBlockers('p2', [])
|
||||
game.resolveCombatDamage()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 37)
|
||||
})
|
||||
|
||||
test('counterspell counters a spell on the stack', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
game.addCard('p2', land('Island', 'U'), 'battlefield')
|
||||
game.addCard('p2', land('Island', 'U'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
const counterspell = game.addCard('p2', spell('Counterspell', [
|
||||
{ op: 'counter', what: 'spell', target: { kind: 'spell', selector: { types: [] }, mode: 'target' } },
|
||||
], '{U}{U}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.castSpell('p2', counterspell.id)
|
||||
assert.equal(game.stack.length, 2)
|
||||
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 40)
|
||||
assert.equal(game.stack.length, 0)
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
|
||||
assert.ok(game.getPlayer('p2').graveyard.includes(counterspell.id))
|
||||
})
|
||||
|
||||
test('activated abilities create tokens that enter the battlefield', () => {
|
||||
const maker = card('Goblin Maker', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'create_token',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
token: { name: 'Goblin', types: ['creature'], subtypes: ['goblin'], colors: ['R'], power: { kind: 'number', value: 1 }, toughness: { kind: 'number', value: 1 } },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{T}: Create a 1/1 Goblin.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const source = game.addCard('p1', maker, 'battlefield')
|
||||
|
||||
game.activateAbility('p1', source.id, 0)
|
||||
assert.equal(game.stack.length, 1)
|
||||
game.resolveStack()
|
||||
|
||||
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.equal(tokens.length, 1)
|
||||
assert.equal(tokens[0].definition.name, 'Goblin')
|
||||
assert.equal(game.getPower(tokens[0]), 1)
|
||||
})
|
||||
224
backend/test/game-tokens.test.ts
Normal file
224
backend/test/game-tokens.test.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
import { card, creature, spell, land, exoticOrchard, setup, tokenMaker, tokenDoubler, makeToken, addMana, roleMaker, shockLand } from './helpers.js'
|
||||
|
||||
test('token doublers stack and only apply to their controller', () => {
|
||||
const goblin: TokenSpec = {
|
||||
types: ['creature'],
|
||||
subtypes: ['goblin'],
|
||||
colors: ['R'],
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
}
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const p1Maker = game.addCard('p1', tokenMaker('P1 Maker', goblin), 'battlefield')
|
||||
game.addCard('p1', tokenDoubler('Parallel Lives', 2), 'battlefield')
|
||||
game.addCard('p1', tokenDoubler('Anointed Procession', 2), 'battlefield')
|
||||
const p2Maker = game.addCard('p2', tokenMaker('P2 Maker', goblin), 'battlefield')
|
||||
game.addCard('p2', tokenDoubler('Adrix and Nev', 2), 'battlefield')
|
||||
const tokensOf = (playerId: string): number => game.getPlayer(playerId).battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken).length
|
||||
|
||||
game.activateAbility('p1', p1Maker.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(tokensOf('p1'), 4)
|
||||
assert.equal(tokensOf('p2'), 0)
|
||||
|
||||
game.endTurn('p1')
|
||||
game.activateAbility('p2', p2Maker.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(tokensOf('p2'), 2)
|
||||
})
|
||||
|
||||
test('Primal Vigor doubles tokens for every player', () => {
|
||||
const goblin: TokenSpec = {
|
||||
types: ['creature'],
|
||||
subtypes: ['goblin'],
|
||||
colors: ['R'],
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
}
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const p1Maker = game.addCard('p1', tokenMaker('P1 Maker', goblin), 'battlefield')
|
||||
game.addCard('p1', tokenDoubler('Primal Vigor', 2, 'each_player'), 'battlefield')
|
||||
const p2Maker = game.addCard('p2', tokenMaker('P2 Maker', goblin), 'battlefield')
|
||||
const tokensOf = (playerId: string): number => game.getPlayer(playerId).battlefield
|
||||
.map(id => game.getObject(id)).filter(object => object.isToken).length
|
||||
|
||||
game.activateAbility('p1', p1Maker.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(tokensOf('p1'), 2)
|
||||
|
||||
game.endTurn('p1')
|
||||
game.activateAbility('p2', p2Maker.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(tokensOf('p2'), 2)
|
||||
})
|
||||
|
||||
test('Ojer Taq triples creature tokens but not other tokens', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const creatureMaker = game.addCard('p1', tokenMaker('Creature Maker', {
|
||||
types: ['creature'],
|
||||
subtypes: ['goblin'],
|
||||
colors: ['R'],
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
}), 'battlefield')
|
||||
const treasureMaker = game.addCard('p1', tokenMaker('Treasure Maker', {
|
||||
types: ['artifact'], subtypes: ['treasure'], colors: [],
|
||||
}), 'battlefield')
|
||||
game.addCard('p1', tokenDoubler('Ojer Taq', 3, 'you', true), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', creatureMaker.id, 0)
|
||||
game.resolveStack()
|
||||
game.activateAbility('p1', treasureMaker.id, 0)
|
||||
game.resolveStack()
|
||||
|
||||
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.equal(tokens.filter(object => object.definition.typeLine.toLowerCase().includes('creature')).length, 3)
|
||||
assert.equal(tokens.filter(object => object.definition.typeLine.toLowerCase().includes('treasure')).length, 1)
|
||||
})
|
||||
|
||||
test('search effects find cards in the library and put them onto the battlefield tapped', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const found = game.addCard('p1', forest, 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(found.id))
|
||||
assert.equal(found.tapped, true)
|
||||
})
|
||||
|
||||
test('search effects let the player pick among multiple matching cards', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const island = land('Island', 'U')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forestObject = game.addCard('p1', forest, 'library')
|
||||
const islandObject = game.addCard('p1', island, 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.pendingSearch?.playerId, 'p1')
|
||||
assert.deepEqual(
|
||||
game.searchCandidates('p1').map(object => object.id).sort(),
|
||||
[forestObject.id, islandObject.id].sort(),
|
||||
)
|
||||
assert.equal(forestObject.zone, 'library')
|
||||
assert.throws(() => game.pass('p1'), GameError)
|
||||
|
||||
game.chooseSearchCard('p1', islandObject.id)
|
||||
|
||||
assert.equal(game.pendingSearch, undefined)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
|
||||
assert.equal(islandObject.tapped, true)
|
||||
assert.ok(game.getPlayer('p1').library.includes(forestObject.id))
|
||||
})
|
||||
|
||||
test('Junk exiles the top card and lets its controller cast it that turn', () => {
|
||||
const game = setup([{ id: 'p1', deck: [card('Filler')] }, { id: 'p2' }])
|
||||
game.start()
|
||||
const exiled = game.addCard('p1', spell('Top Spell', [], ''), 'library')
|
||||
const junk = makeToken(game, { types: ['artifact'], subtypes: ['junk'], colors: [] })
|
||||
|
||||
game.activateAbility('p1', junk.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(exiled.zone, 'exile')
|
||||
assert.equal(game.canPlayCard('p1', exiled.id), true)
|
||||
|
||||
game.castSpell('p1', exiled.id)
|
||||
game.resolveStack()
|
||||
assert.equal(exiled.zone, 'graveyard')
|
||||
})
|
||||
|
||||
test('Role tokens attach to the target creature and apply their abilities', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Bear', 2, 2), 'battlefield')
|
||||
const maker = game.addCard('p1', roleMaker('Monster'), 'battlefield')
|
||||
|
||||
assert.deepEqual(game.legalTargetsForAbility('p1', maker.id, 0), [{ kind: 'object', id: bear.id }])
|
||||
game.activateAbility('p1', maker.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
|
||||
const role = game.getPlayer('p1').battlefield
|
||||
.map(id => game.getObject(id))
|
||||
.find(object => object.isToken)
|
||||
assert.ok(role)
|
||||
assert.equal(role.definition.name, 'Monster Role')
|
||||
assert.match(role.definition.typeLine.toLowerCase(), /enchantment — aura role/)
|
||||
assert.equal(role.attachedTo, bear.id)
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
assert.equal(game.hasKeyword(bear, 'Trample'), true)
|
||||
})
|
||||
|
||||
test('Young Hero Role triggers when the enchanted creature attacks with toughness 3 or less', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const bear = game.addCard('p1', creature('Bear', 2, 2), 'battlefield')
|
||||
game.start()
|
||||
const maker = game.addCard('p1', roleMaker('Young Hero'), 'battlefield')
|
||||
game.activateAbility('p1', maker.id, 0, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: bear.id, defenderId: 'p2' }])
|
||||
game.resolveStack()
|
||||
assert.equal(bear.counters['+1/+1'], 1)
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
})
|
||||
|
||||
test('token creation replacement swaps the created token', () => {
|
||||
const food: TokenSpec = {
|
||||
name: 'Food',
|
||||
types: ['artifact'],
|
||||
subtypes: ['food'],
|
||||
colors: [],
|
||||
abilities: [{ kind: 'activated', costs: [{ kind: 'tap' }, { kind: 'mana', cost: '{2}' }], effects: [] }],
|
||||
}
|
||||
const treasure: TokenSpec = { name: 'Treasure', types: ['artifact'], subtypes: ['treasure'], colors: [] }
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const maker = game.addCard('p1', tokenMaker('Food Maker', food), 'battlefield')
|
||||
game.addCard('p1', card('Token Replacer', {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'token_replacement', from: ['food'], tokens: [food, treasure], who: 'you' }],
|
||||
text: 'If you would create a Food token, instead create a Food token and a Treasure token.',
|
||||
}],
|
||||
}), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', maker.id, 0)
|
||||
game.resolveStack()
|
||||
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.deepEqual(tokens.map(token => token.definition.name).sort(), ['Food', 'Treasure'])
|
||||
})
|
||||
@@ -1,647 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import type { Ability, Effect } from '../src/effects/types.js'
|
||||
import type { CardDefinition } from '../src/game/types.js'
|
||||
|
||||
function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
|
||||
return {
|
||||
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
|
||||
name,
|
||||
typeLine: 'Creature — Test',
|
||||
manaValue: 0,
|
||||
colors: [],
|
||||
abilities: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function creature(name: string, power: number, toughness: number, abilities: Ability[] = []): CardDefinition {
|
||||
return card(name, { typeLine: 'Creature — Test', power, toughness, abilities })
|
||||
}
|
||||
|
||||
function spell(name: string, effects: Effect[], manaCost = ''): CardDefinition {
|
||||
return card(name, { typeLine: 'Instant', manaCost, manaValue: 0, abilities: [{ kind: 'spell', effects, optional: false, text: name }] })
|
||||
}
|
||||
|
||||
function land(name: string, color: string): CardDefinition {
|
||||
return card(name, {
|
||||
typeLine: `Basic Land — ${name}`,
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
|
||||
optional: false,
|
||||
text: `{T}: Add {${color}}.`,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
|
||||
const game = new Game({
|
||||
seed: 7,
|
||||
startingHandSize: 0,
|
||||
players: players.map(player => ({ id: player.id, life: player.life, deck: player.deck ?? [card('Filler')] })),
|
||||
})
|
||||
return game
|
||||
}
|
||||
|
||||
test('turns start at the first main phase, draw opening hands, and pass to the next player', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const game = new Game({
|
||||
seed: 1,
|
||||
startingHandSize: 7,
|
||||
players: [
|
||||
{ id: 'p1', deck: Array.from({ length: 10 }, () => forest) },
|
||||
{ id: 'p2', deck: Array.from({ length: 10 }, () => forest) },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
|
||||
assert.equal(game.turn, 1)
|
||||
assert.equal(game.activePlayer, 'p1')
|
||||
assert.equal(game.phase, 'precombat_main')
|
||||
assert.equal(game.step, 'main')
|
||||
assert.equal(game.priority, 'p1')
|
||||
assert.equal(game.getPlayer('p1').life, 40)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 7)
|
||||
assert.equal(game.getPlayer('p1').library.length, 3)
|
||||
|
||||
game.endTurn('p1')
|
||||
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.activePlayer, 'p2')
|
||||
assert.equal(game.getPlayer('p2').hand.length, 8)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 7)
|
||||
})
|
||||
|
||||
test('passing priority twice advances from the main phase into combat', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
|
||||
game.pass('p1')
|
||||
assert.equal(game.priority, 'p2')
|
||||
game.pass('p2')
|
||||
|
||||
assert.equal(game.phase, 'combat')
|
||||
assert.equal(game.step, 'declare_attackers')
|
||||
assert.equal(game.priority, 'p1')
|
||||
})
|
||||
|
||||
test('a spell goes on the stack, auto-taps mana, and resolves its compiled effect', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
|
||||
assert.equal(game.stack.length, 1)
|
||||
assert.equal(mountain.tapped, true)
|
||||
assert.equal(game.priority, 'p2')
|
||||
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.stack.length, 0)
|
||||
assert.equal(game.getPlayer('p2').life, 37)
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
|
||||
})
|
||||
|
||||
test('permanents can be repositioned by their controller and positions are cleared on zone changes', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
|
||||
game.movePermanent('p1', bear.id, 0.25, 0.75)
|
||||
assert.deepEqual(bear.position, { x: 0.25, y: 0.75 })
|
||||
|
||||
game.movePermanent('p1', bear.id, -1, 2)
|
||||
assert.deepEqual(bear.position, { x: 0, y: 1 })
|
||||
assert.throws(() => game.movePermanent('p2', bear.id, 0.5, 0.5), /control/)
|
||||
|
||||
game.moveToZone(bear, 'graveyard')
|
||||
assert.equal(bear.position, undefined)
|
||||
})
|
||||
|
||||
test('enters triggers from compiled card code fire and resolve through the stack', () => {
|
||||
const soulWarden = card('Soul Warden', {
|
||||
typeLine: 'Creature — Human Cleric',
|
||||
power: 1,
|
||||
toughness: 1,
|
||||
colors: ['W'],
|
||||
abilities: [{
|
||||
kind: 'triggered',
|
||||
event: {
|
||||
kind: 'enters',
|
||||
subject: { kind: 'object', selector: { other: true, types: ['creature'] }, mode: 'each' },
|
||||
},
|
||||
effects: [{ op: 'life', player: 'you', amount: { kind: 'number', value: 1 }, mode: 'gain' }],
|
||||
optional: false,
|
||||
text: 'Whenever another creature enters, you gain 1 life.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', soulWarden, 'battlefield')
|
||||
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1), 'hand')
|
||||
|
||||
game.castSpell('p1', elves.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.getPlayer('p1').life, 41)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(elves.id))
|
||||
})
|
||||
|
||||
test('activated mana abilities produce mana and creatures have summoning sickness', () => {
|
||||
const solRing = card('Sol Ring', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{C}', '{C}'] } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {C}{C}.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 5 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 5 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const ring = game.addCard('p1', solRing, 'battlefield')
|
||||
const elves = game.addCard('p1', creature('Llanowar Elves', 1, 1, [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: ['{G}'] } }],
|
||||
optional: false,
|
||||
text: '{T}: Add {G}.',
|
||||
}]), 'battlefield')
|
||||
|
||||
game.activateAbility('p1', ring.id, 0)
|
||||
assert.deepEqual(game.getPlayer('p1').manaPool, { W: 0, U: 0, B: 0, R: 0, G: 0, C: 2 })
|
||||
assert.equal(ring.tapped, true)
|
||||
assert.throws(() => game.activateAbility('p1', elves.id, 0), GameError)
|
||||
|
||||
game.endTurn('p1')
|
||||
game.endTurn('p2')
|
||||
assert.equal(elves.tapped, false)
|
||||
game.activateAbility('p1', elves.id, 0)
|
||||
assert.equal(game.getPlayer('p1').manaPool.G, 1)
|
||||
})
|
||||
|
||||
test('static pump effects apply to matching creatures only', () => {
|
||||
const anthem = card('Glorious Anthem', {
|
||||
typeLine: 'Enchantment',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { controller: 'you', types: ['creature'] }, mode: 'each' },
|
||||
power: { kind: 'number', value: 1 },
|
||||
toughness: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'Creatures you control get +1/+1.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const anthemObject = game.addCard('p1', anthem, 'battlefield')
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const enemy = game.addCard('p2', creature('Enemy Bear', 2, 2), 'battlefield')
|
||||
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
assert.equal(game.getPower(enemy), 2)
|
||||
assert.equal(game.getPower(anthemObject), 0)
|
||||
})
|
||||
|
||||
test('temporary pump effects expire at end of turn', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Giant Growth', [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
power: { kind: 'number', value: 3 },
|
||||
toughness: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_turn',
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
assert.equal(game.getToughness(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 2)
|
||||
})
|
||||
|
||||
test('"until the end of your next turn" lasts through the controller next turn', () => {
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2', deck: Array.from({ length: 3 }, () => card('Filler')) }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const growth = game.addCard('p1', spell('Growth', [{
|
||||
op: 'pump',
|
||||
target: { kind: 'object', selector: { types: ['creature'] }, mode: 'target' },
|
||||
power: { kind: 'number', value: 3 },
|
||||
toughness: { kind: 'number', value: 3 },
|
||||
duration: 'until_end_of_your_next_turn',
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', growth.id, { targets: [{ kind: 'object', id: bear.id }] })
|
||||
game.resolveStack()
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p2')
|
||||
assert.equal(game.getPower(bear), 5)
|
||||
|
||||
game.endTurn('p1')
|
||||
assert.equal(game.getPower(bear), 2)
|
||||
})
|
||||
|
||||
test('combat damage kills creatures and moves them to the graveyard', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const attacker = game.addCard('p1', creature('Attacker', 2, 2), 'battlefield')
|
||||
const blocker = game.addCard('p2', creature('Blocker', 2, 2), 'battlefield')
|
||||
game.start()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
assert.equal(game.priority, 'p2')
|
||||
assert.equal(attacker.tapped, true)
|
||||
|
||||
game.declareBlockers('p2', [{ blockerId: blocker.id, attackerId: attacker.id }])
|
||||
game.resolveCombatDamage()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 40)
|
||||
assert.equal(game.step, 'end_combat')
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(attacker.id))
|
||||
assert.ok(game.getPlayer('p2').graveyard.includes(blocker.id))
|
||||
})
|
||||
|
||||
test('unblocked attackers deal damage to the defending player', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
const attacker = game.addCard('p1', creature('Attacker', 3, 3), 'battlefield')
|
||||
game.start()
|
||||
|
||||
game.declareAttackers('p1', [{ attackerId: attacker.id, defenderId: 'p2' }])
|
||||
game.declareBlockers('p2', [])
|
||||
game.resolveCombatDamage()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 37)
|
||||
})
|
||||
|
||||
test('counterspell counters a spell on the stack', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
game.addCard('p2', land('Island', 'U'), 'battlefield')
|
||||
game.addCard('p2', land('Island', 'U'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
const counterspell = game.addCard('p2', spell('Counterspell', [
|
||||
{ op: 'counter', what: 'spell', target: { kind: 'spell', selector: { types: [] }, mode: 'target' } },
|
||||
], '{U}{U}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.castSpell('p2', counterspell.id)
|
||||
assert.equal(game.stack.length, 2)
|
||||
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.getPlayer('p2').life, 40)
|
||||
assert.equal(game.stack.length, 0)
|
||||
assert.ok(game.getPlayer('p1').graveyard.includes(bolt.id))
|
||||
assert.ok(game.getPlayer('p2').graveyard.includes(counterspell.id))
|
||||
})
|
||||
|
||||
test('activated abilities create tokens that enter the battlefield', () => {
|
||||
const maker = card('Goblin Maker', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'create_token',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
token: { name: 'Goblin', types: ['creature'], subtypes: ['goblin'], colors: ['R'], power: { kind: 'number', value: 1 }, toughness: { kind: 'number', value: 1 } },
|
||||
}],
|
||||
optional: false,
|
||||
text: '{T}: Create a 1/1 Goblin.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const source = game.addCard('p1', maker, 'battlefield')
|
||||
|
||||
game.activateAbility('p1', source.id, 0)
|
||||
assert.equal(game.stack.length, 1)
|
||||
game.resolveStack()
|
||||
|
||||
const tokens = game.getPlayer('p1').battlefield.map(id => game.getObject(id)).filter(object => object.isToken)
|
||||
assert.equal(tokens.length, 1)
|
||||
assert.equal(tokens[0].definition.name, 'Goblin')
|
||||
assert.equal(game.getPower(tokens[0]), 1)
|
||||
})
|
||||
|
||||
test('search effects find cards in the library and put them onto the battlefield tapped', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const found = game.addCard('p1', forest, 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(found.id))
|
||||
assert.equal(found.tapped, true)
|
||||
})
|
||||
|
||||
test('search effects let the player pick among multiple matching cards', () => {
|
||||
const forest = land('Forest', 'G')
|
||||
const island = land('Island', 'U')
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forestObject = game.addCard('p1', forest, 'library')
|
||||
const islandObject = game.addCard('p1', island, 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.pendingSearch?.playerId, 'p1')
|
||||
assert.deepEqual(
|
||||
game.searchCandidates('p1').map(object => object.id).sort(),
|
||||
[forestObject.id, islandObject.id].sort(),
|
||||
)
|
||||
assert.equal(forestObject.zone, 'library')
|
||||
assert.throws(() => game.pass('p1'), GameError)
|
||||
|
||||
game.chooseSearchCard('p1', islandObject.id)
|
||||
|
||||
assert.equal(game.pendingSearch, undefined)
|
||||
assert.ok(game.getPlayer('p1').battlefield.includes(islandObject.id))
|
||||
assert.equal(islandObject.tapped, true)
|
||||
assert.ok(game.getPlayer('p1').library.includes(forestObject.id))
|
||||
})
|
||||
|
||||
test('autoAdvance stops instead of passing while a search needs a pick', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Forest', 'G'), 'library')
|
||||
game.addCard('p1', land('Island', 'U'), 'library')
|
||||
const rampantGrowth = game.addCard('p1', spell('Rampant Growth', [{
|
||||
op: 'search',
|
||||
player: 'you',
|
||||
selector: { types: ['land'], supertypes: ['basic'] },
|
||||
amount: { kind: 'number', value: 1 },
|
||||
destination: 'battlefield',
|
||||
tapped: true,
|
||||
shuffle: true,
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', rampantGrowth.id)
|
||||
game.autoAdvance()
|
||||
|
||||
assert.equal(game.pendingSearch?.playerId, 'p1')
|
||||
assert.equal(game.priority, 'p1')
|
||||
})
|
||||
|
||||
test('static replacement effects make permanents enter tapped with counters', () => {
|
||||
const slow = creature('Slow Bear', 2, 2, [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'enters_tapped', target: { kind: 'self' } }],
|
||||
text: 'This enters tapped.',
|
||||
}, {
|
||||
kind: 'static',
|
||||
effects: [{
|
||||
op: 'enters_with_counters',
|
||||
target: { kind: 'self' },
|
||||
counter: '+1/+1',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
}],
|
||||
text: 'This enters with a +1/+1 counter.',
|
||||
}])
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p1', slow, 'hand')
|
||||
|
||||
game.castSpell('p1', bear.id)
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(bear.tapped, true)
|
||||
assert.equal(bear.counters['+1/+1'], 1)
|
||||
assert.equal(game.getPower(bear), 3)
|
||||
assert.equal(game.getToughness(bear), 3)
|
||||
})
|
||||
|
||||
test('a player who runs out of cards loses and the last player wins', () => {
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [
|
||||
{ id: 'p1', deck: [card('Filler')] },
|
||||
{ id: 'p2', deck: [] },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
game.endTurn('p1')
|
||||
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p1')
|
||||
assert.equal(game.getPlayer('p2').lost, true)
|
||||
})
|
||||
|
||||
test('lethal damage to a player ends the game', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2', life: 3 }])
|
||||
game.start()
|
||||
game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const bolt = game.addCard('p1', spell('Lightning Bolt', [
|
||||
{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } },
|
||||
], '{R}'), 'hand')
|
||||
|
||||
game.castSpell('p1', bolt.id, { targets: [{ kind: 'player', id: 'p2' }] })
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p1')
|
||||
assert.equal(game.getPlayer('p2').life, 0)
|
||||
})
|
||||
|
||||
test('a failed mana payment leaves mana sources untapped and the pool unchanged', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const mountain = game.addCard('p1', land('Mountain', 'R'), 'battlefield')
|
||||
const expensive = game.addCard('p1', spell('Expensive Spell', [], '{R}{R}'), 'hand')
|
||||
|
||||
assert.throws(() => game.castSpell('p1', expensive.id), GameError)
|
||||
assert.equal(mountain.tapped, false)
|
||||
assert.equal(game.getPlayer('p1').manaPool.R, 0)
|
||||
assert.ok(game.getPlayer('p1').hand.includes(expensive.id))
|
||||
})
|
||||
|
||||
test('phyrexian mana can be paid with exactly enough life', () => {
|
||||
const game = setup([{ id: 'p1', life: 2 }, { id: 'p2' }])
|
||||
game.start()
|
||||
const spellCard = game.addCard('p1', spell('Gitaxian Probe', [], '{W/P}'), 'hand')
|
||||
|
||||
assert.doesNotThrow(() => game.castSpell('p1', spellCard.id))
|
||||
assert.equal(game.getPlayer('p1').life, 0)
|
||||
assert.equal(game.status, 'finished')
|
||||
assert.equal(game.winner, 'p2')
|
||||
})
|
||||
|
||||
test('an unless cost auto-taps the mana sources of the payer', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const bear = game.addCard('p2', creature('Grizzly Bears', 2, 2), 'battlefield')
|
||||
const forests = [
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
|
||||
game.addCard('p2', land('Forest', 'G'), 'battlefield'),
|
||||
]
|
||||
const edict = game.addCard('p1', spell('Edict', [{
|
||||
op: 'sacrifice',
|
||||
player: 'opponent',
|
||||
target: { kind: 'object', selector: { types: ['creature'] } },
|
||||
unless: { kind: 'mana', symbols: '{2}' },
|
||||
}]), 'hand')
|
||||
|
||||
game.castSpell('p1', edict.id, {
|
||||
targets: [{ kind: 'player', id: 'p2' }, { kind: 'object', id: bear.id }],
|
||||
})
|
||||
game.resolveStack()
|
||||
|
||||
assert.equal(bear.zone, 'battlefield')
|
||||
assert.ok(forests.every(forest => forest.tapped))
|
||||
assert.equal(game.getPlayer('p2').manaPool.G, 0)
|
||||
})
|
||||
|
||||
test('canPlayCard reports legal lands and spells for the player with priority', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }])
|
||||
game.start()
|
||||
const forest = game.addCard('p1', land('Forest', 'G'), 'hand')
|
||||
const bear = game.addCard('p1', card('Grizzly Bears', {
|
||||
typeLine: 'Creature — Bear',
|
||||
power: 2,
|
||||
toughness: 2,
|
||||
manaCost: '{G}',
|
||||
}), 'hand')
|
||||
|
||||
assert.equal(game.canPlayCard('p1', forest.id), true)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), false)
|
||||
assert.equal(game.canPlayCard('p2', forest.id), false)
|
||||
|
||||
game.playLand('p1', forest.id)
|
||||
assert.equal(game.canPlayCard('p1', bear.id), true)
|
||||
})
|
||||
|
||||
test('autoAdvance skips empty phases and stops when someone can act', () => {
|
||||
const expensive = card('Expensive', { manaCost: '{5}' })
|
||||
const game = new Game({
|
||||
seed: 3,
|
||||
startingHandSize: 0,
|
||||
players: [
|
||||
{ id: 'p1', deck: [expensive] },
|
||||
{ id: 'p2', deck: [expensive] },
|
||||
],
|
||||
})
|
||||
game.start()
|
||||
game.addCard('p1', land('Forest', 'G'), 'battlefield')
|
||||
|
||||
// The only action is a mana ability, which should not hold the phase open.
|
||||
game.autoAdvance()
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.activePlayer, 'p2')
|
||||
assert.equal(game.phase, 'precombat_main')
|
||||
assert.equal(game.priority, 'p2')
|
||||
|
||||
const hasty = creature('Hasty', 2, 2, [{ kind: 'keyword', keyword: 'Haste' }])
|
||||
game.addCard('p2', hasty, 'battlefield')
|
||||
game.autoAdvance()
|
||||
assert.equal(game.turn, 2)
|
||||
assert.equal(game.phase, 'combat')
|
||||
assert.equal(game.step, 'declare_attackers')
|
||||
assert.equal(game.priority, 'p2')
|
||||
})
|
||||
|
||||
test('every defending player declares blocks before combat damage in multiplayer', () => {
|
||||
const game = setup([{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }])
|
||||
game.start()
|
||||
const first = game.addCard('p1', creature('First Attacker', 2, 2), 'battlefield')
|
||||
const second = game.addCard('p1', creature('Second Attacker', 3, 3), 'battlefield')
|
||||
first.enteredTurn = 0
|
||||
second.enteredTurn = 0
|
||||
|
||||
game.declareAttackers('p1', [
|
||||
{ attackerId: first.id, defenderId: 'p2' },
|
||||
{ attackerId: second.id, defenderId: 'p3' },
|
||||
])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
|
||||
game.declareBlockers('p2', [])
|
||||
assert.equal(game.step, 'declare_blockers')
|
||||
assert.equal(game.priority, 'p3')
|
||||
|
||||
game.declareBlockers('p3', [])
|
||||
assert.equal(game.step, 'combat_damage')
|
||||
|
||||
game.resolveCombatDamage()
|
||||
assert.equal(game.getPlayer('p2').life, 38)
|
||||
assert.equal(game.getPlayer('p3').life, 37)
|
||||
})
|
||||
|
||||
test('counter-removal costs are paid and fail when counters run out', () => {
|
||||
const vessel = card('Spore Vessel', {
|
||||
typeLine: 'Artifact',
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'remove_counters', counter: 'spore', amount: { kind: 'number', value: 2 } }],
|
||||
effects: [{ op: 'draw', player: 'you', amount: { kind: 'number', value: 1 } }],
|
||||
optional: false,
|
||||
text: 'Remove two spore counters from this: Draw a card.',
|
||||
}],
|
||||
})
|
||||
const game = setup([{ id: 'p1', deck: Array.from({ length: 3 }, () => card('Filler')) }, { id: 'p2' }])
|
||||
game.start()
|
||||
const source = game.addCard('p1', vessel, 'battlefield')
|
||||
source.counters.spore = 3
|
||||
|
||||
game.activateAbility('p1', source.id, 0)
|
||||
game.resolveStack()
|
||||
assert.equal(source.counters.spore, 1)
|
||||
assert.equal(game.getPlayer('p1').hand.length, 1)
|
||||
|
||||
assert.throws(() => game.activateAbility('p1', source.id, 0), GameError)
|
||||
assert.equal(source.counters.spore, 1)
|
||||
})
|
||||
159
backend/test/helpers.ts
Normal file
159
backend/test/helpers.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { Game, GameError } from '../src/game/game.js'
|
||||
import { compileText } from '../src/effects/compile.js'
|
||||
import type { Ability, Effect, TokenSpec } from '../src/effects/types.js'
|
||||
import type { CardDefinition, GameObject } from '../src/game/types.js'
|
||||
|
||||
export function card(name: string, overrides: Partial<CardDefinition> = {}): CardDefinition {
|
||||
return {
|
||||
oracleId: name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
|
||||
name,
|
||||
typeLine: 'Creature — Test',
|
||||
manaValue: 0,
|
||||
colors: [],
|
||||
abilities: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
export function creature(name: string, power: number, toughness: number, abilities: Ability[] = []): CardDefinition {
|
||||
return card(name, { typeLine: 'Creature — Test', power, toughness, abilities })
|
||||
}
|
||||
|
||||
export function spell(name: string, effects: Effect[], manaCost = ''): CardDefinition {
|
||||
return card(name, { typeLine: 'Instant', manaCost, manaValue: 0, abilities: [{ kind: 'spell', effects, optional: false, text: name }] })
|
||||
}
|
||||
|
||||
export function land(name: string, color: string): CardDefinition {
|
||||
return card(name, {
|
||||
typeLine: `Basic Land — ${name}`,
|
||||
power: undefined,
|
||||
toughness: undefined,
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'add_mana', player: 'you', mana: { kind: 'symbols', symbols: [`{${color}}`] } }],
|
||||
optional: false,
|
||||
text: `{T}: Add {${color}}.`,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
export 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.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
export function setup(players: { id: string; deck?: CardDefinition[]; life?: number }[]): Game {
|
||||
const game = new Game({
|
||||
seed: 7,
|
||||
startingHandSize: 0,
|
||||
players: players.map(player => ({ id: player.id, life: player.life, deck: player.deck ?? [card('Filler')] })),
|
||||
})
|
||||
return game
|
||||
}
|
||||
|
||||
export function tokenMaker(name: string, token: TokenSpec): CardDefinition {
|
||||
return card(name, {
|
||||
typeLine: 'Artifact',
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{ op: 'create_token', player: 'you', amount: { kind: 'number', value: 1 }, token }],
|
||||
optional: false,
|
||||
text: '{T}: Create a token.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
export function tokenDoubler(
|
||||
name: string,
|
||||
multiplier: number,
|
||||
who: 'you' | 'each_player' = 'you',
|
||||
creatureOnly = false,
|
||||
): CardDefinition {
|
||||
return card(name, {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'static',
|
||||
effects: [{ op: 'token_multiplier', multiplier, who, ...(creatureOnly ? { creatureOnly: true } : {}) }],
|
||||
text: 'Token replacement.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
export function makeToken(game: Game, token: TokenSpec, playerId = 'p1'): GameObject {
|
||||
const maker = game.addCard(playerId, tokenMaker('Token Maker', token), 'battlefield')
|
||||
game.activateAbility(playerId, maker.id, 0)
|
||||
game.resolveStack()
|
||||
const tokens = game.getPlayer(playerId).battlefield
|
||||
.map(id => game.getObject(id))
|
||||
.filter(object => object.isToken)
|
||||
return tokens[tokens.length - 1]
|
||||
}
|
||||
|
||||
export function addMana(game: Game, ...symbols: string[]): void {
|
||||
for (const symbol of symbols) {
|
||||
const source = game.addCard('p1', land('Mana Land', symbol), 'battlefield')
|
||||
game.activateAbility('p1', source.id, 0)
|
||||
}
|
||||
}
|
||||
|
||||
export function roleMaker(name: string): CardDefinition {
|
||||
return card(`${name} Role Maker`, {
|
||||
typeLine: 'Enchantment',
|
||||
abilities: [{
|
||||
kind: 'activated',
|
||||
costs: [{ kind: 'tap' }],
|
||||
effects: [{
|
||||
op: 'create_token',
|
||||
player: 'you',
|
||||
amount: { kind: 'number', value: 1 },
|
||||
token: { name, types: ['enchantment'], subtypes: ['aura', 'role'], colors: [] },
|
||||
attachTo: { kind: 'object', selector: { types: ['creature'], controller: 'you' }, mode: 'target' },
|
||||
}],
|
||||
optional: false,
|
||||
text: `{T}: Create a ${name} Role token attached to target creature you control.`,
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export 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}.',
|
||||
}],
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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')
|
||||
})
|
||||
|
||||
194
backend/test/source.test.ts
Normal file
194
backend/test/source.test.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import test from 'node:test'
|
||||
import type { Card } from '../src/cards.js'
|
||||
import { formatCard } from '../src/effects/format.js'
|
||||
import {
|
||||
compileImplementation,
|
||||
deleteOverride,
|
||||
readAllOverrides,
|
||||
readOverride,
|
||||
writeOverride,
|
||||
} from '../src/effects/implementations.js'
|
||||
import { parseCardSource, SourceParseError } from '../src/effects/source.js'
|
||||
|
||||
const CARD: Card = {
|
||||
oracle_id: '00000000-0000-4000-8000-000000000001',
|
||||
name: 'Test Card',
|
||||
layout: 'normal',
|
||||
cmc: 1,
|
||||
type_line: 'Creature — Human',
|
||||
colors: [],
|
||||
color_identity: [],
|
||||
keywords: [],
|
||||
}
|
||||
|
||||
const SOURCE = `export default [
|
||||
triggered(when.enters(self), [
|
||||
modal(1, 1, [
|
||||
[
|
||||
exile(target(permanents.withType('creature').other().ownedBy('you'))),
|
||||
schedule('next_end_step', [returnToBattlefield(previousTarget)]),
|
||||
],
|
||||
]),
|
||||
]),
|
||||
staticAbility([
|
||||
grantAbility(each(permanents.withType('land').enchanted()), triggered(when.upkeep(you), [
|
||||
pay([manaCost('{W}{W}')]),
|
||||
ifThen(ifYouDo(), [gainLife(you, 1)]),
|
||||
], { optional: true })),
|
||||
]),
|
||||
]`
|
||||
|
||||
test('card source round-trips through the compiler and formatter', () => {
|
||||
const compiled = compileImplementation(CARD, SOURCE)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
assert.equal(compiled.typeLine, CARD.type_line)
|
||||
|
||||
const rendered = formatCard(compiled)
|
||||
assert.match(rendered, /export default card\('Creature — Human', \[/)
|
||||
const reparsed = compileImplementation(CARD, rendered)
|
||||
assert.equal(formatCard(reparsed), rendered)
|
||||
assert.equal(reparsed.typeLine, CARD.type_line)
|
||||
assert.equal(reparsed.abilities.length, 2)
|
||||
|
||||
const [triggered] = reparsed.abilities
|
||||
assert.equal(triggered.kind, 'triggered')
|
||||
if (triggered.kind !== 'triggered') return
|
||||
assert.equal(triggered.effects[0].op, 'modal')
|
||||
if (triggered.effects[0].op !== 'modal') return
|
||||
assert.equal(triggered.effects[0].modes[0][1].op, 'schedule')
|
||||
|
||||
const staticAbility = reparsed.abilities[1]
|
||||
assert.equal(staticAbility.kind, 'static')
|
||||
if (staticAbility.kind !== 'static') return
|
||||
assert.equal(staticAbility.effects[0].op, 'grant_ability')
|
||||
if (staticAbility.effects[0].op !== 'grant_ability') return
|
||||
assert.equal(staticAbility.effects[0].ability.kind, 'triggered')
|
||||
})
|
||||
|
||||
test('card source declares the card type line for the engine', () => {
|
||||
const compiled = compileImplementation(CARD, `export default card('Artifact Creature — Golem', [keyword('Vigilance')])`)
|
||||
assert.equal(compiled.typeLine, 'Artifact Creature — Golem')
|
||||
assert.match(formatCard(compiled), /export default card\('Artifact Creature — Golem', \[/)
|
||||
})
|
||||
|
||||
test('multi-face card source declares one type line per face', () => {
|
||||
const faces: Card = {
|
||||
...CARD,
|
||||
layout: 'transform',
|
||||
card_faces: [
|
||||
{ name: 'Front', type_line: 'Sorcery', colors: [] },
|
||||
{ name: 'Back', type_line: 'Creature — Human', colors: [] },
|
||||
],
|
||||
}
|
||||
const source = `export default faces(
|
||||
face('Front', 'Instant', [spell([draw(you, 2)])]),
|
||||
face('Back', 'Creature — Human', [keyword('Flying')]),
|
||||
)`
|
||||
const compiled = compileImplementation(faces, source)
|
||||
assert.deepEqual(compiled.faces?.map(face => face.typeLine), ['Instant', 'Creature — Human'])
|
||||
const rendered = formatCard(compiled)
|
||||
assert.equal(formatCard(compileImplementation(faces, rendered)), rendered)
|
||||
})
|
||||
|
||||
test('effect lists accept callbacks in place of arrays', () => {
|
||||
const CALLBACK_SOURCE = `export default [
|
||||
triggered(when.enters(self), () => draw(you, 1)),
|
||||
triggered(when.dies(self), () => {
|
||||
draw(you, 1)
|
||||
gainLife(you, 1);
|
||||
}),
|
||||
staticAbility(() => staticPump(each(creatures.youControl()), 1, 1)),
|
||||
spell([
|
||||
modal(1, 1, [
|
||||
() => draw(you, 2),
|
||||
() => { gainLife(you, 3) },
|
||||
]),
|
||||
]),
|
||||
]`
|
||||
|
||||
const compiled = compileImplementation(CARD, CALLBACK_SOURCE)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
const [enters, dies, staticAbility, spell] = compiled.abilities
|
||||
assert.equal(enters.kind, 'triggered')
|
||||
if (enters.kind !== 'triggered') return
|
||||
assert.deepEqual(enters.effects.map(effect => effect.op), ['draw'])
|
||||
|
||||
assert.equal(dies.kind, 'triggered')
|
||||
if (dies.kind !== 'triggered') return
|
||||
assert.deepEqual(dies.effects.map(effect => effect.op), ['draw', 'life'])
|
||||
|
||||
assert.equal(staticAbility.kind, 'static')
|
||||
if (staticAbility.kind !== 'static') return
|
||||
assert.deepEqual(staticAbility.effects.map(effect => effect.op), ['pump'])
|
||||
|
||||
assert.equal(spell.kind, 'spell')
|
||||
if (spell.kind !== 'spell') return
|
||||
assert.equal(spell.effects[0].op, 'modal')
|
||||
if (spell.effects[0].op !== 'modal') return
|
||||
assert.deepEqual(spell.effects[0].modes.map(mode => mode.map(effect => effect.op)), [['draw'], ['life']])
|
||||
})
|
||||
|
||||
test('invalid source reports its line', () => {
|
||||
assert.throws(
|
||||
() => parseCardSource('export default [\n draw(you)\n]'),
|
||||
(error: unknown) => error instanceof SourceParseError && error.line === 2,
|
||||
)
|
||||
})
|
||||
|
||||
test('unknown AST discriminants are rejected', () => {
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [spell([{ op: 'nope' }])]"),
|
||||
(error: unknown) => error instanceof SourceParseError && /expected an effect/.test(error.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [{ kind: 'nope' }]"),
|
||||
(error: unknown) => error instanceof SourceParseError && /expected an ability/.test(error.message),
|
||||
)
|
||||
assert.throws(
|
||||
() => parseCardSource("export default [triggered(when.nope(self), [])]"),
|
||||
(error: unknown) => error instanceof SourceParseError,
|
||||
)
|
||||
})
|
||||
|
||||
test('manual implementations persist one file per card', async (t) => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'commander-overrides-'))
|
||||
const previous = process.env.CARD_OVERRIDES_DIR
|
||||
process.env.CARD_OVERRIDES_DIR = dir
|
||||
t.after(async () => {
|
||||
if (previous === undefined) delete process.env.CARD_OVERRIDES_DIR
|
||||
else process.env.CARD_OVERRIDES_DIR = previous
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
await writeOverride(CARD.oracle_id, SOURCE)
|
||||
const stored = await readOverride(CARD.oracle_id)
|
||||
assert.equal(stored?.source, `${SOURCE}\n`)
|
||||
assert.equal((await readAllOverrides()).get(CARD.oracle_id), `${SOURCE}\n`)
|
||||
|
||||
const compiled = compileImplementation(CARD, stored!.source)
|
||||
assert.equal(compiled.manual, true)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
await deleteOverride(CARD.oracle_id)
|
||||
assert.equal(await readOverride(CARD.oracle_id), undefined)
|
||||
})
|
||||
|
||||
test('entersTapped accepts an unlessCost builder and round-trips', () => {
|
||||
const source = `export default [
|
||||
staticAbility([entersTapped(self, { unlessCost: payLife(2) })]),
|
||||
]`
|
||||
const compiled = compileImplementation(CARD, source)
|
||||
assert.equal(compiled.status, 'supported')
|
||||
|
||||
const rendered = formatCard(compiled)
|
||||
assert.match(rendered, /entersTapped\(self, \{ unlessCost: payLife\(2\) \}\)/)
|
||||
|
||||
const reparsed = compileImplementation(CARD, rendered)
|
||||
assert.deepEqual(reparsed.abilities, compiled.abilities)
|
||||
})
|
||||
@@ -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/)
|
||||
})
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,212 +0,0 @@
|
||||
<template>
|
||||
<section class="pseudo-guide">
|
||||
<header class="guide-head">
|
||||
<h2>Card pseudocode guide</h2>
|
||||
<p class="muted">
|
||||
The editor and the compiler use the same two-way format. The
|
||||
<strong>Visual</strong> tab is a node canvas: drag sockets to connect an ability to its
|
||||
effects, and drag green value nodes (players, targets, selectors, costs) into argument
|
||||
sockets. Selector <strong>OR</strong>/<strong>AND</strong> nodes can combine two selector
|
||||
slots. It writes the same source as the text editor. Use <strong>Draft with AI</strong> for
|
||||
a first pass, then review and save.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<article>
|
||||
<h3>Shape</h3>
|
||||
<p>
|
||||
One ability per block. The header starts at column 0 and ends with a colon; effects are
|
||||
indented two spaces, one call per line. A leading <code># Card [status]</code> line is
|
||||
optional and ignored. Multi-face cards use <code>## Face Name [status]</code> sections in
|
||||
card order. Use <code>(no abilities)</code> for an empty face.
|
||||
</p>
|
||||
<pre># Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
|
||||
# Llanowar Elves [supported]
|
||||
activate {T}:
|
||||
add_mana(you, {G})</pre>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Ability blocks</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Header</th><th>Example</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>on <trigger>:</code></td><td><code>on dies(this):</code></td></tr>
|
||||
<tr><td><code>activate <cost>:</code></td><td><code>activate {2}, {T}:</code></td></tr>
|
||||
<tr><td><code>static:</code></td><td><code>static:</code></td></tr>
|
||||
<tr><td><code>spell:</code></td><td>An instant or sorcery effect line.</td></tr>
|
||||
<tr><td><code>keyword <name></code></td><td><code>keyword Flying</code></td></tr>
|
||||
<tr><td><code>keywords <a>, <b></code></td><td><code>keywords Flying, vigilance</code></td></tr>
|
||||
<tr><td><code>additional cost: <cost></code></td><td><code>additional cost: pay 2 life</code></td></tr>
|
||||
<tr><td><code>if <condition>:</code></td><td>Nested effects, indented below.</td></tr>
|
||||
<tr><td><code>choose <n>:</code></td><td>Numbered modes <code>1.</code>, <code>2.</code></td></tr>
|
||||
<tr><td><code>schedule(next_upkeep):</code></td><td>Delayed effects.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Effect calls</h3>
|
||||
<p>Effects are lowercase calls. Separate several on one line with <code>;</code>.</p>
|
||||
<pre>damage(target creature, 3)
|
||||
draw(you, 2)
|
||||
gain_life(you, 1)
|
||||
create_token(you, 1, 1/1 red goblin creature)
|
||||
put_counters(target creature, +1/+1, 2)
|
||||
destroy(target creature)
|
||||
exile(target artifact you control)
|
||||
add_mana(you, {G}{G})
|
||||
search(you, creature, 1, to hand, shuffle)
|
||||
scry(you, 2)
|
||||
pump(each creature you control, 1/1, until end of turn)</pre>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Targets, values and costs</h3>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Targets</th>
|
||||
<td><code>this</code>, <code>the triggering object</code>, <code>target creature</code>, <code>each opponent</code>, <code>up to 2 target creatures</code>, <code>any target</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Selectors</th>
|
||||
<td><code>other tapped creature you control</code>, <code>red instant from a graveyard</code>, <code>creature with power 4 or greater</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Values</th>
|
||||
<td><code>2</code>, <code>X</code>, <code>count(creature you control)</code>, <code>its power</code>, <code>that much</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Costs</th>
|
||||
<td><code>{2}{U}</code>, <code>{T}</code>, <code>pay 3 life</code>, <code>discard 1 card(s)</code>, <code>sacrifice this</code>, <code>remove 1 +1/+1 counter(s) from this</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>Durations</th>
|
||||
<td><code>until end of turn</code>, <code>until your next turn</code>, <code>until the end of your next turn</code>, <code>for as long as this remains on the battlefield</code></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Triggers, conditions and modes</h3>
|
||||
<pre>on attacks(this):
|
||||
create_token(you, 1, tapped 1/1 red goblin creature)
|
||||
|
||||
on upkeep(you):
|
||||
if you control at least 3 artifacts:
|
||||
draw(you, 1)
|
||||
|
||||
spell:
|
||||
choose 1:
|
||||
1. draw(you, 2)
|
||||
2. gain_life(you, 3)
|
||||
|
||||
static:
|
||||
grant(each creature you control, Flying)</pre>
|
||||
<p class="muted">
|
||||
Common triggers: <code>enters</code>, <code>dies</code>, <code>attacks</code>,
|
||||
<code>upkeep</code>, <code>end_step</code>, <code>cast</code>,
|
||||
<code>deals_damage</code>. Always check the generated line after saving.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>When the syntax cannot express it</h3>
|
||||
<p>
|
||||
Never guess a wrong effect. Use the preserved form and leave the line unsupported:
|
||||
</p>
|
||||
<pre>unsupported (modal bullet outside a choose block): Choose one — ...</pre>
|
||||
<p class="muted">
|
||||
The full reference lives in <code>backend/docs/card-effects.md</code>.
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pseudo-guide {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 1rem 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.guide-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
p {
|
||||
line-height: 1.5;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85em;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 0.05rem 0.3rem;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0.65rem 0.8rem;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 0.35rem 0.5rem;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
th {
|
||||
white-space: nowrap;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
tbody th {
|
||||
width: 7rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
tbody th {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
227
frontend/app/components/SourceGuide.vue
Normal file
227
frontend/app/components/SourceGuide.vue
Normal file
@@ -0,0 +1,227 @@
|
||||
<template>
|
||||
<section class="source-guide">
|
||||
<header class="guide-head">
|
||||
<h2>Card source guide</h2>
|
||||
<p class="muted">
|
||||
Implementations are a small, literal JavaScript expression that the backend evaluates with
|
||||
its own safe interpreter. It is never run as JavaScript: only the names below exist. The
|
||||
editor and the compiler use the same two-way format. Use <strong>Draft with AI</strong> for
|
||||
a first pass, then review and save.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<article>
|
||||
<h3>Shape</h3>
|
||||
<p>
|
||||
Export the card's type line and an array of abilities with
|
||||
<code>card(typeLine, [...])</code>. A leading <code>// Card [status]</code> comment is
|
||||
optional and ignored. Multi-face cards export
|
||||
<code>faces(face('Name', 'Type line', [...]), ...)</code> in card order.
|
||||
</p>
|
||||
<pre>export default card('Creature — Human Cleric', [
|
||||
keywords('Flying', 'Ward {2}'),
|
||||
triggered(when.enters(each(permanents.other().withType('creature'))), [
|
||||
gainLife(you, 1),
|
||||
]),
|
||||
activated([tapCost()], [
|
||||
addMana(you, mana('{G}')),
|
||||
]),
|
||||
])
|
||||
|
||||
export default faces(
|
||||
face('Front', 'Instant', [spell([draw(you, 2)])]),
|
||||
face('Back', 'Creature — Human', [keyword('Flying')]),
|
||||
)</pre>
|
||||
<p class="muted">
|
||||
Plain <code>export default [...]</code> is still accepted and uses the Scryfall type line.
|
||||
Effect lists also accept callbacks: <code>() => draw(you, 1)</code> for one effect,
|
||||
or <code>() => { draw(you, 1); gainLife(you, 1) }</code> for several. Arrays remain
|
||||
valid; the formatter emits callbacks.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Abilities</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th>Call</th><th>Example</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr><td><code>triggered(event, [effects], options)</code></td><td><code>triggered(when.dies(self), [draw(you, 1)])</code></td></tr>
|
||||
<tr><td><code>activated([costs], [effects], options)</code></td><td><code>activated([manaCost('{2}'), tapCost()], [...])</code></td></tr>
|
||||
<tr><td><code>staticAbility([effects], options)</code></td><td><code>staticAbility([staticPump(each(creatures.youControl()), 1, 1)])</code></td></tr>
|
||||
<tr><td><code>spell([effects], options)</code></td><td>An instant or sorcery.</td></tr>
|
||||
<tr><td><code>keyword(name, value)</code></td><td><code>keyword('Ward', '{2}')</code></td></tr>
|
||||
<tr><td><code>keywords(...names)</code></td><td><code>keywords('Flying', 'Trample')</code></td></tr>
|
||||
<tr><td><code>additionalCost([costs])</code></td><td><code>additionalCost([payLife(2)])</code></td></tr>
|
||||
<tr><td><code>chapter(['I', 'II'], [effects])</code></td><td>Saga chapters.</td></tr>
|
||||
<tr><td><code>unsupported(reason, text)</code></td><td>Preserve the oracle text when it cannot be expressed.</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted">
|
||||
Options include <code>{ condition, optional }</code>; activated abilities also accept
|
||||
<code>timing: 'sorcery'</code> and <code>activationsPerTurn</code>.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Selectors and targets</h3>
|
||||
<p>
|
||||
Start from <code>permanents</code>, <code>cards</code> or <code>creatures</code> and chain
|
||||
filters: <code>withType</code>, <code>withSubtype</code>, <code>withSupertype</code>,
|
||||
<code>withColor</code>, <code>withKeyword</code>, <code>youControl</code>,
|
||||
<code>other</code>, <code>tapped</code>, <code>token</code>, <code>powerAtLeast</code>,
|
||||
<code>manaValueAtMost</code>, <code>named</code>, <code>inZone</code>.
|
||||
</p>
|
||||
<pre>target(permanents.withType('creature').other().youControl())
|
||||
each(creatures.withColor('red').withKeyword('flying'))
|
||||
pick(cards.withType('land'), { upTo: 2 })
|
||||
targetSpell(permanents.withType('instant'))
|
||||
divided(3, creatures.attacking())
|
||||
self, triggerSubject, previousTarget, anyTarget, targetPlayerOrPlaneswalker</pre>
|
||||
<p class="muted">
|
||||
Values: numbers, <code>X</code>, <code>itsPower</code>, <code>itsToughness</code>,
|
||||
<code>count(selector)</code>, <code>cardsInHand(you)</code>,
|
||||
<code>totalPower(selector)</code>, <code>eventAmount()</code>.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Effects and costs</h3>
|
||||
<pre>damage(target(creature), 3)
|
||||
draw(you, 2)
|
||||
gainLife(you, 1)
|
||||
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 }))
|
||||
putCounters(target(creature), '+1/+1', 2)
|
||||
destroy(target(creature))
|
||||
addMana(you, mana('{G}{G}'))
|
||||
search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true })
|
||||
pump(each(creatures.youControl()), 1, 1, untilEndOfTurn)
|
||||
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)])
|
||||
modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]])</pre>
|
||||
<p>
|
||||
Costs are separate: <code>manaCost('{2}{U}')</code>, <code>tapCost()</code>,
|
||||
<code>sacrificeSelf()</code>, <code>payLife(3)</code>,
|
||||
<code>discardCost(1)</code>, <code>removeCountersCost('+1/+1', 1)</code>.
|
||||
</p>
|
||||
<p class="muted">
|
||||
Durations: <code>permanent</code>, <code>untilEndOfTurn</code>,
|
||||
<code>untilYourNextTurn</code>, <code>untilEndOfYourNextTurn</code>,
|
||||
<code>untilEndOfCombat</code>, <code>whileSourceOnBattlefield</code>.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>Triggers, statics and conditions</h3>
|
||||
<pre>triggered(when.attacks(self), [
|
||||
createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1, tapped: true })),
|
||||
])
|
||||
|
||||
triggered(when.upkeep(you), [
|
||||
ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]),
|
||||
])
|
||||
|
||||
staticAbility([
|
||||
staticGrant(each(creatures.youControl()), 'Flying'),
|
||||
])</pre>
|
||||
<p class="muted">
|
||||
Common triggers: <code>when.enters</code>, <code>when.dies</code>,
|
||||
<code>when.attacks</code>, <code>when.upkeep</code>, <code>when.endStep</code>,
|
||||
<code>when.cast</code>, <code>when.dealsDamage</code>. Common conditions:
|
||||
<code>yourTurn()</code>, <code>youControl(selector, n)</code>, <code>wasKicked()</code>,
|
||||
<code>ifYouDo()</code>, <code>otherwise()</code>. Always check the compiled result after
|
||||
saving.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h3>When the syntax cannot express it</h3>
|
||||
<p>Never guess a wrong effect. Preserve the oracle text and leave it unsupported:</p>
|
||||
<pre>unsupported('modal bullet outside a modal block', 'Choose one — ...')</pre>
|
||||
<p class="muted">
|
||||
The full reference lives in <code>backend/docs/card-effects.md</code>.
|
||||
</p>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.source-guide {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
padding: 1rem 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.guide-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
p {
|
||||
line-height: 1.5;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.85em;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
padding: 0.05rem 0.3rem;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0.65rem 0.8rem;
|
||||
background: #11151d;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.82rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 0.35rem 0.5rem;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
th {
|
||||
white-space: nowrap;
|
||||
color: var(--muted);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
tbody th {
|
||||
width: 7rem;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
tbody th {
|
||||
width: auto;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,9 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import CardGraphEditor from '../components/CardGraphEditor.vue'
|
||||
import PseudoGuide from '../components/PseudoGuide.vue'
|
||||
import SourceGuide from '../components/SourceGuide.vue'
|
||||
|
||||
type Status = 'supported' | 'partial' | 'unsupported'
|
||||
|
||||
const statusLabels: Record<Status, string> = {
|
||||
supported: 'Supported',
|
||||
partial: 'Partial',
|
||||
unsupported: 'Unsupported',
|
||||
}
|
||||
|
||||
interface CardSummary {
|
||||
oracle_id: string
|
||||
name: string
|
||||
@@ -87,7 +92,6 @@ const rarityOptions = ['common', 'uncommon', 'rare', 'mythic', 'special', 'bonus
|
||||
const cmcOptions = ['0', '1', '2', '3', '4', '5', '6', '7+']
|
||||
|
||||
const view = ref<'editor' | 'guide'>('editor')
|
||||
const editorMode = ref<'text' | 'visual'>('text')
|
||||
const search = ref('')
|
||||
const statusFilter = ref('needs-work')
|
||||
const formatFilter = ref('')
|
||||
@@ -217,7 +221,7 @@ async function translate() {
|
||||
|
||||
async function reset() {
|
||||
if (!detail.value || saving.value) return
|
||||
if (!window.confirm('Delete the manual implementation and restore the generated one?')) return
|
||||
if (!window.confirm('Delete the verified implementation and restore the generated one?')) return
|
||||
saving.value = true
|
||||
editorError.value = ''
|
||||
try {
|
||||
@@ -269,7 +273,7 @@ onMounted(() => {
|
||||
{{ stats.supported.toLocaleString() }} supported ·
|
||||
{{ stats.partial.toLocaleString() }} partial ·
|
||||
{{ stats.unsupported.toLocaleString() }} unsupported ·
|
||||
{{ stats.manual.toLocaleString() }} manual
|
||||
{{ stats.manual.toLocaleString() }} verified
|
||||
</template>
|
||||
<template v-else>Loading stats…</template>
|
||||
</p>
|
||||
@@ -292,7 +296,7 @@ onMounted(() => {
|
||||
<option value="unsupported">Not implemented</option>
|
||||
<option value="partial">Partial</option>
|
||||
<option value="supported">Supported</option>
|
||||
<option value="manual">Manual</option>
|
||||
<option value="manual">Verified</option>
|
||||
<option value="all">All cards</option>
|
||||
</select>
|
||||
<button type="submit">Search</button>
|
||||
@@ -353,8 +357,16 @@ onMounted(() => {
|
||||
v-if="card.implementation"
|
||||
class="badge"
|
||||
:class="card.implementation.status"
|
||||
>{{ card.implementation.status }}</span>
|
||||
<span v-if="card.implementation?.manual" class="badge manual">manual</span>
|
||||
:title="statusLabels[card.implementation.status]"
|
||||
:aria-label="statusLabels[card.implementation.status]"
|
||||
>{{ card.implementation.status[0] }}</span>
|
||||
<span
|
||||
v-if="card.implementation"
|
||||
class="badge"
|
||||
:class="card.implementation.manual ? 'verified' : 'generated'"
|
||||
:title="card.implementation.manual ? 'Verified' : 'Generated'"
|
||||
:aria-label="card.implementation.manual ? 'Verified' : 'Generated'"
|
||||
>{{ card.implementation.manual ? 'V' : 'G' }}</span>
|
||||
</span>
|
||||
</button>
|
||||
</CardHover>
|
||||
@@ -381,8 +393,18 @@ onMounted(() => {
|
||||
</p>
|
||||
</div>
|
||||
<div class="badges">
|
||||
<span class="badge" :class="detail.compiled.status">{{ detail.compiled.status }}</span>
|
||||
<span v-if="detail.manual" class="badge manual">manual</span>
|
||||
<span
|
||||
class="badge"
|
||||
:class="detail.compiled.status"
|
||||
:title="statusLabels[detail.compiled.status]"
|
||||
:aria-label="statusLabels[detail.compiled.status]"
|
||||
>{{ detail.compiled.status[0] }}</span>
|
||||
<span
|
||||
class="badge"
|
||||
:class="detail.manual ? 'verified' : 'generated'"
|
||||
:title="detail.manual ? 'Verified' : 'Generated'"
|
||||
:aria-label="detail.manual ? 'Verified' : 'Generated'"
|
||||
>{{ detail.manual ? 'V' : 'G' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -402,23 +424,15 @@ onMounted(() => {
|
||||
</p>
|
||||
<p v-else-if="editorError" class="error">{{ editorError }}</p>
|
||||
|
||||
<div class="row">
|
||||
<div class="tabs">
|
||||
<button type="button" :class="{ active: editorMode === 'text' }" @click="editorMode = 'text'">Text</button>
|
||||
<button type="button" :class="{ active: editorMode === 'visual' }" @click="editorMode = 'visual'">Visual</button>
|
||||
</div>
|
||||
<span class="muted grow">{{ editorMode === 'text' ? 'Pseudocode' : 'Node graph' }}</span>
|
||||
</div>
|
||||
<span class="muted">Card source</span>
|
||||
|
||||
<textarea
|
||||
v-if="editorMode === 'text'"
|
||||
v-model="source"
|
||||
spellcheck="false"
|
||||
aria-label="Card implementation"
|
||||
@keydown.ctrl.s.prevent="save"
|
||||
@keydown.meta.s.prevent="save"
|
||||
/>
|
||||
<CardGraphEditor v-else :key="detail.card.oracle_id" v-model="source" />
|
||||
|
||||
<div class="actions">
|
||||
<button type="button" class="primary" :disabled="saving || !dirty" @click="save">
|
||||
@@ -439,7 +453,7 @@ onMounted(() => {
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<PseudoGuide v-else />
|
||||
<SourceGuide v-else />
|
||||
</main>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
deleteDeck,
|
||||
exportDeckText,
|
||||
loadDecks,
|
||||
loadSharedDeck,
|
||||
newDeckId,
|
||||
saveDeck,
|
||||
shareDeck,
|
||||
type ApiCard,
|
||||
type DeckCard,
|
||||
type SavedDeck,
|
||||
@@ -26,6 +28,8 @@ interface DraftDeck {
|
||||
definePageMeta({ middleware: 'auth' })
|
||||
|
||||
const { public: { apiBase } } = useRuntimeConfig()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const BASIC_NAMES = ['Plains', 'Island', 'Swamp', 'Mountain', 'Forest']
|
||||
|
||||
const decks = ref<SavedDeck[]>([])
|
||||
@@ -43,6 +47,8 @@ const importErrors = ref<string[]>([])
|
||||
const importing = ref(false)
|
||||
const basics = ref<Record<string, ApiCard>>({})
|
||||
const showExport = ref(false)
|
||||
const shareLink = ref('')
|
||||
const shareCopied = ref(false)
|
||||
|
||||
const count = computed(() => 1 + (draft.value?.cards.length ?? 0))
|
||||
const grouped = computed(() => {
|
||||
@@ -115,6 +121,30 @@ async function reloadDecks() {
|
||||
decks.value = (await loadDecks(apiBase)).sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
}
|
||||
|
||||
async function share(deck: SavedDeck) {
|
||||
error.value = ''
|
||||
try {
|
||||
const token = await shareDeck(apiBase, deck.id)
|
||||
shareLink.value = `${window.location.origin}/decks?share=${token}`
|
||||
shareCopied.value = false
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyShareLink() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(shareLink.value)
|
||||
shareCopied.value = true
|
||||
} catch {
|
||||
shareCopied.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function closeShare() {
|
||||
shareLink.value = ''
|
||||
}
|
||||
|
||||
function selectDeck(deck: SavedDeck) {
|
||||
draft.value = {
|
||||
id: deck.id,
|
||||
@@ -314,6 +344,27 @@ function errorMessage(caught: unknown): string {
|
||||
onMounted(async () => {
|
||||
await reloadDecks()
|
||||
|
||||
const sharedToken = route.query.share
|
||||
if (typeof sharedToken === 'string' && sharedToken) {
|
||||
try {
|
||||
const deck = await loadSharedDeck(apiBase, sharedToken)
|
||||
draft.value = {
|
||||
id: newDeckId(),
|
||||
name: deck.name,
|
||||
commander: { ...deck.commander },
|
||||
cards: deck.cards.map(card => ({ ...card })),
|
||||
cardBack: deck.cardBack ?? undefined,
|
||||
}
|
||||
notice.value = 'Shared deck loaded. Save it to add it to your account.'
|
||||
} catch (caught) {
|
||||
error.value = errorMessage(caught)
|
||||
}
|
||||
// Drop the token from the URL so a reload does not import the deck again.
|
||||
const query = { ...route.query }
|
||||
delete query.share
|
||||
await router.replace({ query })
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await $fetch<{ cards: (ApiCard | null)[] }>(`${apiBase}/cards/resolve`, {
|
||||
method: 'POST',
|
||||
@@ -519,19 +570,15 @@ onMounted(async () => {
|
||||
</header>
|
||||
|
||||
<section class="decks-panel">
|
||||
<p v-if="error" class="error">{{ error }}</p>
|
||||
<p v-if="!decks.length" class="muted">No saved decks yet.</p>
|
||||
<div class="deck-grid">
|
||||
<button type="button" class="deck-tile import-tile" @click="openImport">
|
||||
<span class="plus" aria-hidden="true">+</span>
|
||||
<span class="deck-name">Import deck</span>
|
||||
</button>
|
||||
<button
|
||||
v-for="deck in decks"
|
||||
:key="deck.id"
|
||||
type="button"
|
||||
class="deck-tile"
|
||||
@click="selectDeck(deck)"
|
||||
>
|
||||
<div v-for="deck in decks" :key="deck.id" class="deck-cell">
|
||||
<button type="button" class="deck-tile" @click="selectDeck(deck)">
|
||||
<span class="deck-stack">
|
||||
<img :src="commanderImage(deck)" :alt="`${deck.commander.name} card`" loading="lazy">
|
||||
</span>
|
||||
@@ -543,9 +590,30 @@ onMounted(async () => {
|
||||
<span class="muted deck-commander">{{ deck.commander.name }}</span>
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="mini share-button"
|
||||
:aria-label="`Share ${deck.name}`"
|
||||
@click="share(deck)"
|
||||
>Share</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div v-if="shareLink" class="modal-backdrop" @click.self="closeShare">
|
||||
<div class="modal">
|
||||
<h2>Share deck</h2>
|
||||
<p class="muted">Anyone with this link can view and import a copy of the deck.</p>
|
||||
<input :value="shareLink" readonly aria-label="Share link">
|
||||
<div class="row wrap modal-actions">
|
||||
<button type="button" @click="closeShare">Done</button>
|
||||
<button type="button" class="primary" @click="copyShareLink">
|
||||
{{ shareCopied ? 'Copied' : 'Copy link' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="importOpen" class="modal-backdrop" @click.self="closeImport">
|
||||
<form class="modal" @submit.prevent="importDeck">
|
||||
<h2>Import deck</h2>
|
||||
@@ -609,6 +677,21 @@ onMounted(async () => {
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.deck-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.deck-cell .deck-tile {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.share-button {
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.deck-tile {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,846 +0,0 @@
|
||||
// Line-level model behind the visual card editor. It mirrors the canonical
|
||||
// formatter output (abilities at column 0, nested calls indented two spaces) so
|
||||
// editing a node and serializing it back keeps the pseudocode valid.
|
||||
|
||||
export interface GraphNode {
|
||||
id: number
|
||||
text: string
|
||||
kind: 'ability' | 'effect' | 'raw'
|
||||
children: GraphNode[]
|
||||
}
|
||||
|
||||
let nextId = 1
|
||||
|
||||
export function nextNodeId(): number {
|
||||
return nextId++
|
||||
}
|
||||
|
||||
export function makeNode(text: string, kind: GraphNode['kind'], children: GraphNode[] = []): GraphNode {
|
||||
return { id: nextNodeId(), text, kind, children }
|
||||
}
|
||||
|
||||
export function parseGraph(source: string): GraphNode[] {
|
||||
const roots: GraphNode[] = []
|
||||
const stack: Array<{ indent: number; node: GraphNode }> = []
|
||||
|
||||
for (const raw of source.split('\n')) {
|
||||
if (!raw.trim()) continue
|
||||
const indent = (raw.match(/^[ \t]*/)?.[0] ?? '').replace(/\t/g, ' ').length
|
||||
const text = raw.trim()
|
||||
const kind: GraphNode['kind'] =
|
||||
text.startsWith('#') || text === '(no abilities)' ? 'raw' : indent === 0 ? 'ability' : 'effect'
|
||||
const node = makeNode(text, kind)
|
||||
|
||||
while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop()
|
||||
if (stack.length) stack[stack.length - 1].node.children.push(node)
|
||||
else roots.push(node)
|
||||
stack.push({ indent, node })
|
||||
}
|
||||
|
||||
return roots
|
||||
}
|
||||
|
||||
export function serializeGraph(list: GraphNode[], depth = 0): string {
|
||||
return list
|
||||
.map(node => {
|
||||
const line = ' '.repeat(depth) + node.text
|
||||
return node.children.length ? `${line}\n${serializeGraph(node.children, depth + 1)}` : line
|
||||
})
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
/** Inserted at the top level by the visual editor's "Add ability" menu. */
|
||||
export const ABILITY_PALETTE = [
|
||||
{
|
||||
group: 'Triggered',
|
||||
items: [
|
||||
{ label: 'Enters the battlefield', value: 'on enters(this):' },
|
||||
{ label: 'Dies', value: 'on dies(this):' },
|
||||
{ label: 'Attacks', value: 'on attacks(this):' },
|
||||
{ label: 'Upkeep', value: 'on upkeep(you):' },
|
||||
{ label: 'Cast a spell', value: 'on cast(you, any spell):' },
|
||||
{ label: 'Deals damage', value: 'on deals_damage(this, any):' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Other',
|
||||
items: [
|
||||
{ label: 'Activated {T}', value: 'activate {T}:' },
|
||||
{ label: 'Activated {2}, {T}', value: 'activate {2}, {T}:' },
|
||||
{ label: 'Static', value: 'static:' },
|
||||
{ label: 'Static if a condition', value: 'static if it is your turn:' },
|
||||
{ label: 'Spell effect', value: 'spell:' },
|
||||
{ label: 'Keyword: Flying', value: 'keyword Flying' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Appended below an ability or nested block. Keep every value parseable. */
|
||||
export const EFFECT_PALETTE = [
|
||||
{
|
||||
group: 'Removal',
|
||||
items: [
|
||||
{ label: 'Damage', value: 'damage(target creature, 3)' },
|
||||
{ label: 'Destroy', value: 'destroy(target creature)' },
|
||||
{ label: 'Exile', value: 'exile(target permanent)' },
|
||||
{ label: 'Tap', value: 'tap(target creature)' },
|
||||
{ label: 'Counter spell', value: 'counter(spell, target spell)' },
|
||||
{ label: 'Sacrifice', value: 'sacrifice(you, target creature)' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Cards and life',
|
||||
items: [
|
||||
{ label: 'Draw', value: 'draw(you, 1)' },
|
||||
{ label: 'Discard', value: 'discard(you, 1)' },
|
||||
{ label: 'Mill', value: 'mill(you, 1)' },
|
||||
{ label: 'Scry', value: 'scry(you, 2)' },
|
||||
{ label: 'Surveil', value: 'surveil(you, 1)' },
|
||||
{ label: 'Search library', value: 'search(you, creature, 1, to hand, shuffle)' },
|
||||
{ label: 'Look at top', value: 'look_top(you, 3)' },
|
||||
{ label: 'Gain life', value: 'gain_life(you, 2)' },
|
||||
{ label: 'Lose life', value: 'lose_life(opponent, 2)' },
|
||||
{ label: 'Energy', value: 'energy(you, 2)' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Board',
|
||||
items: [
|
||||
{ label: 'Create token', value: 'create_token(you, 1, 1/1 white soldier creature)' },
|
||||
{ label: 'Create copy token', value: 'create_token(you, 1, copy of the triggering object, not legendary)' },
|
||||
{ label: 'Put counters', value: 'put_counters(target creature, +1/+1, 1)' },
|
||||
{ label: 'Pump', value: 'pump(target creature, 2/2, until end of turn)' },
|
||||
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
|
||||
{ label: 'Untap', value: 'untap(target permanent you control)' },
|
||||
{ label: 'Return to hand', value: 'return_to_hand(target creature)' },
|
||||
{ label: 'Add mana', value: 'add_mana(you, {G})' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Flow',
|
||||
items: [
|
||||
{ label: 'If condition', value: 'if you control at least 3 artifacts:' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Static abilities accept a different effect vocabulary than triggered/spell ones. */
|
||||
export const STATIC_EFFECT_PALETTE = [
|
||||
{
|
||||
group: 'Static effects',
|
||||
items: [
|
||||
{ label: 'Pump', value: 'pump(each creature you control, 1/1)' },
|
||||
{ label: 'Grant keyword', value: 'grant(each creature you control, Flying)' },
|
||||
{ label: 'Enters tapped', value: 'enters_tapped(this)' },
|
||||
{ label: 'Enters with counters', value: 'enters_with_counters(this, +1/+1, 1)' },
|
||||
{ label: 'Restrict', value: 'restrict(target creature, cant_attack)' },
|
||||
{ label: 'Set base P/T', value: 'set_pt(target creature, base, 1/1)' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Value nodes that can be wired into argument sockets. */
|
||||
export const VALUE_PALETTE = [
|
||||
{
|
||||
group: 'Players',
|
||||
items: [
|
||||
{ label: 'A player', value: 'target player' },
|
||||
{ label: 'Each opponent', value: 'each opponent' },
|
||||
{ label: 'Each player', value: 'each player' },
|
||||
{ label: 'You', value: 'you' },
|
||||
{ label: 'That player', value: 'that player' },
|
||||
{ label: 'Its controller', value: 'its controller' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Targets',
|
||||
items: [
|
||||
{ label: 'A creature', value: 'target creature' },
|
||||
{ label: 'A permanent', value: 'target permanent' },
|
||||
{ label: 'An artifact', value: 'target artifact' },
|
||||
{ label: 'A land', value: 'target land' },
|
||||
{ label: 'A spell', value: 'target spell' },
|
||||
{ label: 'An ability', value: 'target ability' },
|
||||
{ label: 'Any target', value: 'any target' },
|
||||
{ label: 'This', value: 'this' },
|
||||
{ label: 'The triggering object', value: 'the triggering object' },
|
||||
{ label: 'Each creature you control', value: 'each creature you control' },
|
||||
{ label: 'Each creature an opponent controls', value: 'each creature an opponent controls' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Selectors',
|
||||
items: [
|
||||
{ label: 'Creature', value: 'creature' },
|
||||
{ label: 'Artifact', value: 'artifact' },
|
||||
{ label: 'Enchantment', value: 'enchantment' },
|
||||
{ label: 'Land', value: 'land' },
|
||||
{ label: 'Red', value: 'red' },
|
||||
{ label: 'Creature you control', value: 'creature you control' },
|
||||
{ label: 'Artifact you control', value: 'artifact you control' },
|
||||
{ label: 'Tapped creature', value: 'tapped creature' },
|
||||
{ label: 'Power 4 or greater', value: 'creature with power 4 or greater' },
|
||||
{ label: 'Nontoken Dragon', value: 'each other nontoken dragon creature you control' },
|
||||
{ label: 'Nontoken Angel', value: "each nontoken angel you don't control" },
|
||||
{ label: 'Selector builder', value: '__selector__' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Tokens',
|
||||
items: [
|
||||
{ label: '1/1 white Soldier', value: '1/1 white soldier creature' },
|
||||
{ label: '1/1 red Goblin', value: '1/1 red goblin creature' },
|
||||
{ label: 'Copy of the triggering object', value: 'copy of the triggering object' },
|
||||
{ label: 'Copy, not legendary', value: 'copy of the triggering object, not legendary' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Values',
|
||||
items: [
|
||||
{ label: '1', value: '1' },
|
||||
{ label: '2', value: '2' },
|
||||
{ label: '3', value: '3' },
|
||||
{ label: 'X', value: 'X' },
|
||||
{ label: 'That much', value: 'that much' },
|
||||
{ label: 'Its power', value: 'its power' },
|
||||
{ label: 'Its toughness', value: 'its toughness' },
|
||||
{ label: 'Count creatures you control', value: 'count(creature you control)' },
|
||||
{ label: 'Cards in your hand', value: 'cards in your hand' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Costs',
|
||||
items: [
|
||||
{ label: 'Tap', value: '{T}' },
|
||||
{ label: 'Mana {2}', value: '{2}' },
|
||||
{ label: 'Pay 2 life', value: 'pay 2 life' },
|
||||
{ label: 'Sacrifice this', value: 'sacrifice this' },
|
||||
{ label: 'Discard 1 card(s)', value: 'discard 1 card(s)' },
|
||||
{ label: 'Mill 1 card(s)', value: 'mill 1 card(s)' },
|
||||
{ label: 'Remove 1 +1/+1 counter(s)', value: 'remove 1 +1/+1 counter(s) from this' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Conditions',
|
||||
items: [
|
||||
{ label: 'It is your turn', value: 'it is your turn' },
|
||||
{ label: 'This is tapped', value: 'this is tapped' },
|
||||
{ label: 'You control at least 3 artifacts', value: 'you control at least 3 artifacts' },
|
||||
{ label: 'You have at least 10 life', value: 'you have at least 10 life' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Durations',
|
||||
items: [
|
||||
{ label: 'Until end of turn', value: 'until end of turn' },
|
||||
{ label: 'Until your next turn', value: 'until your next turn' },
|
||||
{ label: 'Until the end of your next turn', value: 'until the end of your next turn' },
|
||||
{ label: 'While this remains', value: 'for as long as this remains on the battlefield' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Logic',
|
||||
items: [
|
||||
{ label: 'Selector OR', value: '__or__' },
|
||||
{ label: 'Selector AND', value: '__and__' },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
/** Human labels for effect/ability argument sockets. */
|
||||
export const ARG_HINTS: Record<string, string[]> = {
|
||||
damage: ['target', 'amount', 'source'],
|
||||
damage_divided: ['amount', 'target'],
|
||||
draw: ['player', 'amount'],
|
||||
discard: ['player', 'amount'],
|
||||
mill: ['player', 'amount'],
|
||||
gain_life: ['player', 'amount'],
|
||||
lose_life: ['player', 'amount'],
|
||||
pump: ['target', 'power/toughness', 'duration'],
|
||||
set_pt: ['target', 'power/toughness', 'duration'],
|
||||
grant: ['target', 'keyword', 'duration'],
|
||||
put_counters: ['target', 'counter', 'amount'],
|
||||
remove_counters: ['target', 'counter', 'amount'],
|
||||
create_token: ['player', 'amount', 'token', 'options'],
|
||||
destroy: ['target'],
|
||||
exile: ['target'],
|
||||
tap: ['target'],
|
||||
untap: ['target'],
|
||||
regenerate: ['target'],
|
||||
return_to_hand: ['target'],
|
||||
put_on_top: ['target'],
|
||||
sacrifice: ['player', 'target'],
|
||||
counter: ['spell|ability', 'target'],
|
||||
return_to_battlefield: ['target', 'options'],
|
||||
scry: ['player', 'amount'],
|
||||
surveil: ['player', 'amount'],
|
||||
search: ['player', 'selector', 'amount', 'destination', 'options'],
|
||||
add_mana: ['player', 'mana'],
|
||||
fight: ['target', 'target'],
|
||||
energy: ['player', 'amount'],
|
||||
attach: ['target'],
|
||||
restrict: ['target', 'rule'],
|
||||
prevent_damage: ['target', 'amount', 'duration'],
|
||||
gain_control: ['target', 'duration'],
|
||||
look_top: ['player', 'amount', 'options'],
|
||||
pay: ['cost'],
|
||||
transform: ['target'],
|
||||
}
|
||||
|
||||
/** Human labels for trigger event arguments. */
|
||||
const TRIGGER_ARG_HINTS: Record<string, string[]> = {
|
||||
enters: ['subject'],
|
||||
dies: ['subject'],
|
||||
attacks: ['subject'],
|
||||
blocks: ['subject'],
|
||||
attacks_or_blocks: ['subject'],
|
||||
enters_or_attacks: ['subject'],
|
||||
enters_or_dies: ['subject'],
|
||||
leaves_battlefield: ['subject'],
|
||||
deals_damage: ['subject', 'recipient'],
|
||||
deals_combat_damage: ['subject', 'recipient'],
|
||||
upkeep: ['player'],
|
||||
end_step: ['player'],
|
||||
begin_combat: ['player'],
|
||||
first_main_phase: ['player'],
|
||||
postcombat_main_phase: ['player'],
|
||||
cast: ['player', 'spell'],
|
||||
becomes_level: ['level'],
|
||||
draw: ['player'],
|
||||
counter_placed: ['subject', 'counter'],
|
||||
becomes_target: ['subject'],
|
||||
gain_life: ['player'],
|
||||
lose_life: ['player'],
|
||||
}
|
||||
|
||||
const TRIGGER_SUBJECT_OPTIONS = [
|
||||
'this',
|
||||
'each other creature',
|
||||
'each creature you control',
|
||||
'each other nontoken dragon creature you control',
|
||||
"each nontoken angel you don't control",
|
||||
]
|
||||
|
||||
const PLAYER_OPTIONS = ['you', 'target player', 'each opponent', 'each player', 'that player', 'its controller']
|
||||
const AMOUNT_OPTIONS = ['1', '2', '3', '4', '5', 'X', 'that much', 'count(creature you control)']
|
||||
const TOKEN_OPTIONS = [
|
||||
'1/1 white soldier creature',
|
||||
'1/1 red goblin creature',
|
||||
'copy of the triggering object',
|
||||
]
|
||||
|
||||
/** Argument slots with fixed choices become dropdowns in the visual editor. */
|
||||
export const SLOT_OPTIONS: Record<string, string[][]> = {
|
||||
enters: [TRIGGER_SUBJECT_OPTIONS],
|
||||
create_token: [PLAYER_OPTIONS, AMOUNT_OPTIONS, TOKEN_OPTIONS, ['not legendary']],
|
||||
}
|
||||
|
||||
/** Splits on `separator` outside parentheses, brackets, braces and quotes. */
|
||||
export function splitTopLevel(text: string, separator: string): string[] {
|
||||
const parts: string[] = []
|
||||
let depth = 0
|
||||
let quote = false
|
||||
let escape = false
|
||||
let start = 0
|
||||
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
const char = text[index]
|
||||
if (quote) {
|
||||
if (escape) escape = false
|
||||
else if (char === '\\') escape = true
|
||||
else if (char === '"') quote = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
quote = true
|
||||
continue
|
||||
}
|
||||
if (char === '(' || char === '[' || char === '{') depth++
|
||||
else if (char === ')' || char === ']' || char === '}') depth--
|
||||
else if (depth === 0 && text.startsWith(separator, index)) {
|
||||
parts.push(text.slice(start, index))
|
||||
index += separator.length - 1
|
||||
start = index + 1
|
||||
}
|
||||
}
|
||||
parts.push(text.slice(start))
|
||||
return parts
|
||||
}
|
||||
|
||||
export function blockOf(text: string): { kind: 'if' | 'choose' | 'schedule'; value: string } | undefined {
|
||||
const ifMatch = text.match(/^if (.+):$/)
|
||||
if (ifMatch) return { kind: 'if', value: ifMatch[1] }
|
||||
const chooseMatch = text.match(/^choose (\d+(?:-\d+)?):$/)
|
||||
if (chooseMatch) return { kind: 'choose', value: chooseMatch[1] }
|
||||
const scheduleMatch = text.match(/^schedule\((next_upkeep|next_end_step)\):$/)
|
||||
if (scheduleMatch) return { kind: 'schedule', value: scheduleMatch[1] }
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** True for nodes that carry an indented body. Mode lines can nest too. */
|
||||
export function isBlockText(text: string): boolean {
|
||||
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) || /^\d+\.\s/.test(text)
|
||||
}
|
||||
|
||||
/** Blocks that are invalid without at least one nested effect. */
|
||||
function requiresBody(text: string): boolean {
|
||||
return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text)
|
||||
}
|
||||
|
||||
export function abilityRequiresEffects(text: string): boolean {
|
||||
return /^(?:on |activate |static|spell|chapter )/.test(text)
|
||||
}
|
||||
|
||||
/** Reads a `name(arg, arg)` prefix, leaving any suffix after the closing paren. */
|
||||
export function readCallPrefix(text: string): { name: string; args: string[]; end: number } | undefined {
|
||||
const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/)
|
||||
if (!match) return undefined
|
||||
|
||||
const open = match[0].length - 1
|
||||
let depth = 0
|
||||
let quote = false
|
||||
let escape = false
|
||||
|
||||
for (let index = open; index < text.length; index++) {
|
||||
const char = text[index]
|
||||
if (quote) {
|
||||
if (escape) escape = false
|
||||
else if (char === '\\') escape = true
|
||||
else if (char === '"') quote = false
|
||||
continue
|
||||
}
|
||||
if (char === '"') {
|
||||
quote = true
|
||||
continue
|
||||
}
|
||||
if (char === '(') depth++
|
||||
else if (char === ')') {
|
||||
depth--
|
||||
if (depth === 0) {
|
||||
const inner = text.slice(open + 1, index).trim()
|
||||
return {
|
||||
name: match[1],
|
||||
args: inner ? splitTopLevel(inner, ',').map(arg => arg.trim()) : [],
|
||||
end: index + 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Reads a complete `name(arg, arg)` call; returns undefined for block headers. */
|
||||
export function parseCall(text: string): { name: string; args: string[] } | undefined {
|
||||
const trimmed = text.trim()
|
||||
const call = readCallPrefix(trimmed)
|
||||
return call && call.end === trimmed.length ? { name: call.name, args: call.args } : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a supported line into fixed text plus argument slots. Unsupported
|
||||
* lines return undefined and stay as free text.
|
||||
*/
|
||||
export function shapeFromText(text: string): NodeShape | undefined {
|
||||
if (text.startsWith('on ') && text.endsWith(':')) {
|
||||
const inner = text.slice(3, -1)
|
||||
const call = readCallPrefix(inner)
|
||||
if (call) {
|
||||
const suffix = inner.slice(call.end)
|
||||
return {
|
||||
name: `on ${call.name}`,
|
||||
head: `on ${call.name}(`,
|
||||
tail: `)${suffix}:`,
|
||||
separator: ', ',
|
||||
slots: call.args.map((arg, index) => {
|
||||
const options = SLOT_OPTIONS[call.name]?.[index]
|
||||
return {
|
||||
label: TRIGGER_ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
|
||||
text: arg,
|
||||
...(options ? { options } : {}),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (text.startsWith('activate ') && text.endsWith(':')) {
|
||||
return {
|
||||
head: 'activate ',
|
||||
tail: ':',
|
||||
separator: ', ',
|
||||
slots: [{ label: 'cost', text: text.slice('activate '.length, -1) }],
|
||||
}
|
||||
}
|
||||
|
||||
if (text.startsWith('static if ') && text.endsWith(':')) {
|
||||
return {
|
||||
head: 'static if ',
|
||||
tail: ':',
|
||||
separator: ', ',
|
||||
slots: [{ label: 'condition', text: text.slice('static if '.length, -1) }],
|
||||
}
|
||||
}
|
||||
|
||||
const block = blockOf(text)
|
||||
if (block) {
|
||||
if (block.kind === 'if') {
|
||||
return { head: 'if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: block.value }] }
|
||||
}
|
||||
if (block.kind === 'choose') {
|
||||
return { head: 'choose ', tail: ':', separator: ', ', slots: [{ label: 'modes', text: block.value }] }
|
||||
}
|
||||
return { head: 'schedule(', tail: '):', separator: ', ', slots: [{ label: 'when', text: block.value }] }
|
||||
}
|
||||
|
||||
const call = parseCall(text)
|
||||
if (call) {
|
||||
return {
|
||||
head: `${call.name}(`,
|
||||
tail: ')',
|
||||
separator: ', ',
|
||||
slots: call.args.map((arg, index) => {
|
||||
const options = SLOT_OPTIONS[call.name]?.[index]
|
||||
return {
|
||||
label: ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`,
|
||||
text: arg,
|
||||
...(options ? { options } : {}),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds every shaped line from its slots and connected value nodes. Value
|
||||
* nodes are evaluated recursively, so `or`/`and` combinators can nest.
|
||||
*/
|
||||
export function syncTexts(model: GraphModel): void {
|
||||
const byId = new Map(model.nodes.map(node => [node.id, node]))
|
||||
const valueEdges = new Map<string, number>()
|
||||
for (const edge of model.edges) {
|
||||
if (edge.port === 'value' && edge.slot !== undefined) {
|
||||
valueEdges.set(`${edge.to}:${edge.slot}`, edge.from)
|
||||
}
|
||||
}
|
||||
|
||||
function renderSlot(node: CanvasNode, index: number, stack: Set<number>): string {
|
||||
const childId = valueEdges.get(`${node.id}:${index}`)
|
||||
const child = childId !== undefined ? byId.get(childId) : undefined
|
||||
return child ? render(child, stack) : node.shape?.slots[index]?.text ?? ''
|
||||
}
|
||||
|
||||
function render(node: CanvasNode | undefined, stack: Set<number>): string {
|
||||
if (!node) return ''
|
||||
if (stack.has(node.id)) return node.kind === 'value' ? node.literal ?? '' : ''
|
||||
stack.add(node.id)
|
||||
|
||||
let text: string
|
||||
if (node.kind === 'value' && node.combine) {
|
||||
text = `${renderSlot(node, 0, stack)} ${node.combine} ${renderSlot(node, 1, stack)}`
|
||||
} else if (node.shape) {
|
||||
text = node.shape.head
|
||||
+ node.shape.slots.map((_, index) => renderSlot(node, index, stack)).join(node.shape.separator)
|
||||
+ node.shape.tail
|
||||
} else if (node.kind === 'value') {
|
||||
text = node.literal ?? node.text
|
||||
} else {
|
||||
text = node.text
|
||||
}
|
||||
|
||||
stack.delete(node.id)
|
||||
node.text = text
|
||||
return text
|
||||
}
|
||||
|
||||
for (const node of model.nodes) render(node, new Set())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Node canvas. The tree above is converted into flat nodes with explicit
|
||||
// `next` (sibling) and `body` (indented) links. Source is regenerated by
|
||||
// following those links, so the canvas and the pseudocode stay in sync.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface NodeSlot {
|
||||
label: string
|
||||
text: string
|
||||
/** Fixed choices rendered as a dropdown instead of a free-text input. */
|
||||
options?: string[]
|
||||
}
|
||||
|
||||
/** A line split into a fixed shell and the slots a value node can fill. */
|
||||
export interface NodeShape {
|
||||
name?: string
|
||||
head: string
|
||||
tail: string
|
||||
separator: string
|
||||
slots: NodeSlot[]
|
||||
}
|
||||
|
||||
export interface CanvasNode {
|
||||
id: number
|
||||
text: string
|
||||
kind: 'ability' | 'effect' | 'raw' | 'value'
|
||||
x: number
|
||||
y: number
|
||||
shape?: NodeShape
|
||||
/** Value nodes: literal source text. */
|
||||
literal?: string
|
||||
/** Value nodes: combines its two slots instead of using a literal. */
|
||||
combine?: 'or' | 'and'
|
||||
valueLabel?: string
|
||||
}
|
||||
|
||||
export type GraphPort = 'next' | 'body' | 'value'
|
||||
|
||||
export interface GraphEdge {
|
||||
id: number
|
||||
from: number
|
||||
port: GraphPort
|
||||
to: number
|
||||
/** Target argument index when port is 'value'. */
|
||||
slot?: number
|
||||
}
|
||||
|
||||
export interface GraphModel {
|
||||
nodes: CanvasNode[]
|
||||
edges: GraphEdge[]
|
||||
}
|
||||
|
||||
export interface GraphSource {
|
||||
source: string
|
||||
unlinked: number
|
||||
problems: string[]
|
||||
}
|
||||
|
||||
export const NODE_WIDTH = 230
|
||||
const CHAIN_GAP = 70
|
||||
const BODY_INDENT = NODE_WIDTH + 20
|
||||
const BODY_GAP = 70
|
||||
const ROOT_GAP = 70
|
||||
|
||||
let nextEdgeId = 1
|
||||
|
||||
export function estimateNodeHeight(text: string, slots?: number, hasName?: boolean): number {
|
||||
const count = slots ?? parseCall(text)?.args.length ?? 0
|
||||
if (!count) return hasName ? 84 : 74
|
||||
return 64 + count * 48 + (hasName ? 24 : 0)
|
||||
}
|
||||
|
||||
export function hasBodyPort(model: GraphModel, node: CanvasNode): boolean {
|
||||
return node.kind === 'effect'
|
||||
&& (isBlockText(node.text) || model.edges.some(edge => edge.from === node.id && edge.port === 'body'))
|
||||
}
|
||||
|
||||
/** Converts pseudocode into nodes and links, laid out roughly left to right. */
|
||||
export function graphFromSource(source: string): GraphModel {
|
||||
const model: GraphModel = { nodes: [], edges: [] }
|
||||
let y = 40
|
||||
|
||||
for (const root of parseGraph(source)) {
|
||||
if (root.kind === 'raw') {
|
||||
model.nodes.push({ id: root.id, text: root.text, kind: 'raw', x: 40, y })
|
||||
y += 64
|
||||
continue
|
||||
}
|
||||
const bounds = layoutTreeChain(model, [root], 40, y, 0)
|
||||
y += bounds.height + ROOT_GAP
|
||||
}
|
||||
|
||||
return model
|
||||
}
|
||||
|
||||
function layoutTreeChain(
|
||||
model: GraphModel,
|
||||
list: GraphNode[],
|
||||
x: number,
|
||||
y: number,
|
||||
depth: number,
|
||||
): { width: number; height: number } {
|
||||
let cursorX = x
|
||||
let maxHeight = 0
|
||||
let previous: number | undefined
|
||||
|
||||
for (const treeNode of list) {
|
||||
const kind: CanvasNode['kind'] = depth === 0 ? treeNode.kind : 'effect'
|
||||
const node: CanvasNode = {
|
||||
id: treeNode.id,
|
||||
text: treeNode.text,
|
||||
kind,
|
||||
x: cursorX,
|
||||
y,
|
||||
shape: shapeFromText(treeNode.text),
|
||||
}
|
||||
model.nodes.push(node)
|
||||
|
||||
if (previous !== undefined) {
|
||||
model.edges.push({ id: nextEdgeId++, from: previous, port: 'next', to: node.id })
|
||||
}
|
||||
previous = node.id
|
||||
|
||||
const height = estimateNodeHeight(node.text, node.shape?.slots.length, Boolean(node.shape?.name))
|
||||
let totalHeight = height
|
||||
let advance = NODE_WIDTH
|
||||
|
||||
if (treeNode.children.length) {
|
||||
if (depth === 0) {
|
||||
// An ability's output is its effect chain, laid out to the right.
|
||||
const chain = layoutTreeChain(model, treeNode.children, cursorX + NODE_WIDTH + CHAIN_GAP, y, 1)
|
||||
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'next', to: treeNode.children[0].id })
|
||||
totalHeight = Math.max(totalHeight, chain.height)
|
||||
advance = NODE_WIDTH + CHAIN_GAP + chain.width
|
||||
} else {
|
||||
// Blocks own an indented body below and just right of their socket.
|
||||
const body = layoutTreeChain(model, treeNode.children, cursorX + BODY_INDENT, y + height + BODY_GAP, depth + 1)
|
||||
model.edges.push({ id: nextEdgeId++, from: node.id, port: 'body', to: treeNode.children[0].id })
|
||||
totalHeight = Math.max(totalHeight, height + BODY_GAP + body.height)
|
||||
}
|
||||
}
|
||||
|
||||
maxHeight = Math.max(maxHeight, totalHeight)
|
||||
cursorX += advance + CHAIN_GAP
|
||||
}
|
||||
|
||||
return { width: cursorX - x, height: maxHeight }
|
||||
}
|
||||
|
||||
/** Rebuilds pseudocode by walking next/body links from every ability root. */
|
||||
export function sourceFromGraph(model: GraphModel): GraphSource {
|
||||
syncTexts(model)
|
||||
const byId = new Map(model.nodes.map(node => [node.id, node]))
|
||||
const outgoing = new Map<string, GraphEdge>()
|
||||
for (const edge of model.edges) {
|
||||
outgoing.set(`${edge.from}:${edge.port}`, edge)
|
||||
}
|
||||
|
||||
const lines: string[] = []
|
||||
const visited = new Set<number>()
|
||||
const problems: string[] = []
|
||||
|
||||
const label = (text: string) => (text.length > 52 ? `${text.slice(0, 49)}…` : text)
|
||||
|
||||
const checkModes = (startId: number) => {
|
||||
let mode = byId.get(startId)
|
||||
let expected = 1
|
||||
const seenModes = new Set<number>()
|
||||
while (mode && !seenModes.has(mode.id)) {
|
||||
seenModes.add(mode.id)
|
||||
const number = mode.text.match(/^(\d+)\.\s/)
|
||||
if (!number || Number(number[1]) !== expected) {
|
||||
problems.push('A choose body must be numbered 1, 2, 3…')
|
||||
return
|
||||
}
|
||||
expected++
|
||||
const next = outgoing.get(`${mode.id}:next`)
|
||||
mode = next ? byId.get(next.to) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
const emitChain = (startId: number, depth: number) => {
|
||||
let current: number | undefined = startId
|
||||
while (current !== undefined) {
|
||||
if (visited.has(current)) {
|
||||
problems.push(`Cycle at ${label(byId.get(current)?.text ?? 'node')}`)
|
||||
return
|
||||
}
|
||||
const node = byId.get(current)
|
||||
if (!node) return
|
||||
visited.add(current)
|
||||
lines.push(`${' '.repeat(depth)}${node.text}`)
|
||||
|
||||
const body = outgoing.get(`${current}:body`)
|
||||
if (body) {
|
||||
if (blockOf(node.text)?.kind === 'choose') checkModes(body.to)
|
||||
emitChain(body.to, depth + 1)
|
||||
} else if (requiresBody(node.text)) {
|
||||
problems.push(`"${label(node.text)}" has no body`)
|
||||
}
|
||||
|
||||
current = outgoing.get(`${current}:next`)?.to
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of model.nodes) {
|
||||
if (node.kind === 'raw') {
|
||||
if (!visited.has(node.id)) {
|
||||
visited.add(node.id)
|
||||
lines.push(node.text)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (node.kind !== 'ability' || visited.has(node.id)) continue
|
||||
|
||||
visited.add(node.id)
|
||||
lines.push(node.text)
|
||||
const next = outgoing.get(`${node.id}:next`)
|
||||
if (next) emitChain(next.to, 1)
|
||||
else if (abilityRequiresEffects(node.text)) problems.push(`"${label(node.text)}" has no effects`)
|
||||
}
|
||||
|
||||
const usedValues = new Set(model.edges.filter(edge => edge.port === 'value').map(edge => edge.from))
|
||||
const unlinked = model.nodes.filter(node =>
|
||||
(node.kind === 'effect' && !visited.has(node.id))
|
||||
|| (node.kind === 'value' && !usedValues.has(node.id)),
|
||||
).length
|
||||
if (unlinked) {
|
||||
problems.push(`${unlinked} unconnected node${unlinked === 1 ? '' : 's'} will be ignored`)
|
||||
}
|
||||
|
||||
return { source: lines.join('\n'), unlinked, problems }
|
||||
}
|
||||
|
||||
function reaches(model: GraphModel, start: number, target: number): boolean {
|
||||
const stack = [start]
|
||||
const seen = new Set<number>()
|
||||
while (stack.length) {
|
||||
const id = stack.pop()!
|
||||
if (id === target) return true
|
||||
if (seen.has(id)) continue
|
||||
seen.add(id)
|
||||
for (const edge of model.edges) {
|
||||
if (edge.from === id) stack.push(edge.to)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** Links an output socket to a node input or an argument slot. */
|
||||
export function connectNodes(
|
||||
model: GraphModel,
|
||||
from: number,
|
||||
port: GraphPort,
|
||||
to: number,
|
||||
slot?: number,
|
||||
): boolean {
|
||||
if (from === to) return false
|
||||
const source = model.nodes.find(node => node.id === from)
|
||||
const target = model.nodes.find(node => node.id === to)
|
||||
if (!source || !target) return false
|
||||
|
||||
if (port === 'value') {
|
||||
if (source.kind !== 'value' || !target.shape || slot === undefined || !target.shape.slots[slot]) {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
if (target.kind !== 'effect') return false
|
||||
if (port === 'body' && !hasBodyPort(model, source)) return false
|
||||
}
|
||||
if (reaches(model, to, from)) return false
|
||||
|
||||
if (port === 'value') {
|
||||
model.edges = model.edges.filter(edge =>
|
||||
!(edge.port === 'value' && edge.to === to && edge.slot === slot)
|
||||
&& !(edge.from === from && edge.port === 'value'),
|
||||
)
|
||||
model.edges.push({ id: nextEdgeId++, from, port, to, slot })
|
||||
} else {
|
||||
model.edges = model.edges.filter(edge =>
|
||||
!((edge.port === 'next' || edge.port === 'body') && edge.to === to)
|
||||
&& !(edge.from === from && edge.port === port),
|
||||
)
|
||||
model.edges.push({ id: nextEdgeId++, from, port, to })
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -83,6 +83,21 @@ export async function deleteDeck(apiBase: string, id: string): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
export async function shareDeck(apiBase: string, id: string): Promise<string> {
|
||||
const { token } = await $fetch<{ token: string }>(
|
||||
`${apiBase}/me/decks/${encodeURIComponent(id)}/share`,
|
||||
{ method: 'POST', headers: authHeaders() },
|
||||
)
|
||||
return token
|
||||
}
|
||||
|
||||
export async function loadSharedDeck(apiBase: string, token: string): Promise<SavedDeck> {
|
||||
const { deck } = await $fetch<{ deck: SavedDeck }>(
|
||||
`${apiBase}/decks/share/${encodeURIComponent(token)}`,
|
||||
)
|
||||
return deck
|
||||
}
|
||||
|
||||
export function isBasicLand(card: DeckCard): boolean {
|
||||
return /\bbasic\b/i.test(card.typeLine) && /\bland\b/i.test(card.typeLine)
|
||||
}
|
||||
|
||||
105
frontend/app/utils/gameAnimations.ts
Normal file
105
frontend/app/utils/gameAnimations.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
// Animation cues are derived by diffing two match snapshots, so they work for
|
||||
// every client (including spectators) without adding anything to the wire format.
|
||||
|
||||
export interface AnimationCardSnapshot {
|
||||
id: string
|
||||
damage?: number
|
||||
attacking?: string
|
||||
}
|
||||
|
||||
export interface AnimationPlayerSnapshot {
|
||||
id: string
|
||||
life?: number
|
||||
battlefield?: readonly AnimationCardSnapshot[]
|
||||
}
|
||||
|
||||
export interface AnimationStateSnapshot {
|
||||
id?: string
|
||||
players?: readonly AnimationPlayerSnapshot[]
|
||||
game?: {
|
||||
manaPool?: Record<string, number>
|
||||
}
|
||||
}
|
||||
|
||||
export interface CardDamageAnimation {
|
||||
cardId: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface LifeChangeAnimation {
|
||||
playerId: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface ManaGainAnimation {
|
||||
color: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export interface GameAnimations {
|
||||
enteringCardIds: string[]
|
||||
attackingCardIds: string[]
|
||||
damagedCards: CardDamageAnimation[]
|
||||
lifeChanges: LifeChangeAnimation[]
|
||||
manaGains: ManaGainAnimation[]
|
||||
}
|
||||
|
||||
function emptyAnimations(): GameAnimations {
|
||||
return {
|
||||
enteringCardIds: [],
|
||||
attackingCardIds: [],
|
||||
damagedCards: [],
|
||||
lifeChanges: [],
|
||||
manaGains: [],
|
||||
}
|
||||
}
|
||||
|
||||
function cardsByPlayer(state: AnimationStateSnapshot): Map<string, AnimationCardSnapshot> {
|
||||
const cards = new Map<string, AnimationCardSnapshot>()
|
||||
for (const player of state.players ?? []) {
|
||||
for (const card of player.battlefield ?? []) cards.set(card.id, card)
|
||||
}
|
||||
return cards
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare the previous and current match state and return the visual cues that
|
||||
* should play for the current state. The first snapshot has nothing to compare
|
||||
* against and produces no animations.
|
||||
*/
|
||||
export function diffGameState(
|
||||
previous: AnimationStateSnapshot | null | undefined,
|
||||
next: AnimationStateSnapshot,
|
||||
): GameAnimations {
|
||||
const animations = emptyAnimations()
|
||||
if (!previous) return animations
|
||||
if (previous.id && next.id && previous.id !== next.id) return animations
|
||||
|
||||
const previousCards = cardsByPlayer(previous)
|
||||
const nextCards = cardsByPlayer(next)
|
||||
for (const [id, card] of nextCards) {
|
||||
const before = previousCards.get(id)
|
||||
if (!before) animations.enteringCardIds.push(id)
|
||||
else {
|
||||
const amount = (card.damage ?? 0) - (before.damage ?? 0)
|
||||
if (amount > 0) animations.damagedCards.push({ cardId: id, amount })
|
||||
}
|
||||
if (card.attacking && !before?.attacking) animations.attackingCardIds.push(id)
|
||||
}
|
||||
|
||||
for (const player of next.players ?? []) {
|
||||
const before = previous.players?.find(entry => entry.id === player.id)
|
||||
if (!before || before.life === undefined || player.life === undefined) continue
|
||||
const amount = player.life - before.life
|
||||
if (amount) animations.lifeChanges.push({ playerId: player.id, amount })
|
||||
}
|
||||
|
||||
const previousPool = previous.game?.manaPool ?? {}
|
||||
const nextPool = next.game?.manaPool ?? {}
|
||||
for (const color of new Set([...Object.keys(nextPool), ...Object.keys(previousPool)])) {
|
||||
const amount = (nextPool[color] ?? 0) - (previousPool[color] ?? 0)
|
||||
if (amount > 0) animations.manaGains.push({ color, amount })
|
||||
}
|
||||
|
||||
return animations
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
connectNodes,
|
||||
graphFromSource,
|
||||
nextNodeId,
|
||||
parseCall,
|
||||
parseGraph,
|
||||
serializeGraph,
|
||||
shapeFromText,
|
||||
sourceFromGraph,
|
||||
syncTexts,
|
||||
} from '../app/utils/cardGraph.ts'
|
||||
import type { GraphModel } from '../app/utils/cardGraph.ts'
|
||||
|
||||
const SOURCE = `# Soul Warden [supported]
|
||||
on enters(each other creature):
|
||||
gain_life(you, 1)
|
||||
|
||||
on upkeep(you):
|
||||
if you control at least 3 artifacts:
|
||||
draw(you, 1)
|
||||
create_token(you, 1, 1/1 white soldier creature)`
|
||||
|
||||
test('parseGraph builds ability and nested effect nodes', () => {
|
||||
const roots = parseGraph(SOURCE)
|
||||
|
||||
assert.equal(roots.length, 3)
|
||||
assert.equal(roots[0].kind, 'raw')
|
||||
assert.equal(roots[1].kind, 'ability')
|
||||
assert.equal(roots[1].text, 'on enters(each other creature):')
|
||||
assert.deepEqual(roots[1].children.map(node => node.text), ['gain_life(you, 1)'])
|
||||
|
||||
const upkeep = roots[2]
|
||||
assert.equal(upkeep.children[0].text, 'if you control at least 3 artifacts:')
|
||||
assert.deepEqual(upkeep.children[0].children.map(node => node.text), ['draw(you, 1)'])
|
||||
assert.equal(upkeep.children[1].text, 'create_token(you, 1, 1/1 white soldier creature)')
|
||||
})
|
||||
|
||||
test('serializeGraph round-trips formatter output and normalizes indentation', () => {
|
||||
assert.equal(serializeGraph(parseGraph(SOURCE)), SOURCE.replace('\n\n', '\n'))
|
||||
assert.equal(
|
||||
serializeGraph(parseGraph('on dies(this):\n draw(you, 1)')),
|
||||
'on dies(this):\n draw(you, 1)',
|
||||
)
|
||||
})
|
||||
|
||||
test('graph conversion round-trips abilities, chains and nested bodies', () => {
|
||||
const model = graphFromSource(SOURCE)
|
||||
const result = sourceFromGraph(model)
|
||||
|
||||
assert.equal(result.source, SOURCE.replace('\n\n', '\n'))
|
||||
assert.equal(result.unlinked, 0)
|
||||
assert.deepEqual(result.problems, [])
|
||||
})
|
||||
|
||||
test('connectNodes replaces an input link and rejects cycles', () => {
|
||||
const model = graphFromSource(SOURCE)
|
||||
const ability = model.nodes.find(node => node.kind === 'ability' && node.text.startsWith('on enters'))
|
||||
const first = model.nodes.find(node => node.text === 'gain_life(you, 1)')
|
||||
const second = model.nodes.find(node => node.text === 'create_token(you, 1, 1/1 white soldier creature)')
|
||||
assert.ok(ability && first && second)
|
||||
|
||||
assert.equal(connectNodes(model, ability.id, 'next', second.id), true)
|
||||
assert.equal(sourceFromGraph(model).unlinked, 1)
|
||||
|
||||
assert.equal(connectNodes(model, first.id, 'next', second.id), true)
|
||||
assert.equal(connectNodes(model, second.id, 'next', first.id), false)
|
||||
})
|
||||
|
||||
test('shapeFromText exposes trigger and effect arguments', () => {
|
||||
const trigger = shapeFromText('on attacks(this):')
|
||||
assert.equal(trigger?.name, 'on attacks')
|
||||
assert.deepEqual(trigger?.slots, [{ label: 'subject', text: 'this' }])
|
||||
|
||||
const damage = shapeFromText('damage(target creature, 3)')
|
||||
assert.deepEqual(damage?.slots.map(slot => slot.label), ['target', 'amount'])
|
||||
})
|
||||
|
||||
test('shapeFromText adds dropdown choices for constant slots', () => {
|
||||
const enters = shapeFromText('on enters(each other nontoken dragon creature you control):')
|
||||
assert.deepEqual(enters?.slots[0]?.options, [
|
||||
'this',
|
||||
'each other creature',
|
||||
'each creature you control',
|
||||
'each other nontoken dragon creature you control',
|
||||
"each nontoken angel you don't control",
|
||||
])
|
||||
|
||||
const copy = shapeFromText("create_token(you, 1, copy of the triggering object, not legendary)")
|
||||
assert.deepEqual(copy?.slots.map(slot => slot.label), ['player', 'amount', 'token', 'options'])
|
||||
assert.ok(copy?.slots[2]?.options?.includes('copy of the triggering object'))
|
||||
assert.deepEqual(copy?.slots[3]?.options, ['not legendary'])
|
||||
})
|
||||
|
||||
test('value nodes fill trigger and effect argument sockets', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
on attacks(this):
|
||||
damage(target creature, 3)`)
|
||||
const trigger = model.nodes.find(node => node.kind === 'ability')
|
||||
const damage = model.nodes.find(node => node.text.startsWith('damage('))
|
||||
assert.ok(trigger && damage)
|
||||
|
||||
const player = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value' as const,
|
||||
text: 'target player',
|
||||
literal: 'target player',
|
||||
valueLabel: 'Players',
|
||||
x: 0,
|
||||
y: 0,
|
||||
}
|
||||
model.nodes.push(player)
|
||||
assert.equal(connectNodes(model, player.id, 'value', trigger.id, 0), true)
|
||||
|
||||
const artifact = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value' as const,
|
||||
text: 'target artifact',
|
||||
literal: 'target artifact',
|
||||
valueLabel: 'Targets',
|
||||
x: 0,
|
||||
y: 0,
|
||||
}
|
||||
model.nodes.push(artifact)
|
||||
assert.equal(connectNodes(model, artifact.id, 'value', damage.id, 0), true)
|
||||
|
||||
assert.equal(sourceFromGraph(model).source, `# Test [supported]
|
||||
on attacks(target player):
|
||||
damage(target artifact, 3)`)
|
||||
})
|
||||
|
||||
test('or and and value nodes combine selector slots', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
spell:
|
||||
search(you, creature, 1, to hand, shuffle)`)
|
||||
const search = model.nodes.find(node => node.text.startsWith('search('))
|
||||
assert.ok(search)
|
||||
|
||||
const combo: GraphModel['nodes'][number] = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value',
|
||||
text: '',
|
||||
combine: 'or',
|
||||
valueLabel: 'Logic',
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: {
|
||||
head: '',
|
||||
tail: '',
|
||||
separator: ' or ',
|
||||
slots: [
|
||||
{ label: 'left', text: 'creature' },
|
||||
{ label: 'right', text: 'artifact' },
|
||||
],
|
||||
},
|
||||
}
|
||||
model.nodes.push(combo)
|
||||
assert.equal(connectNodes(model, combo.id, 'value', search.id, 1), true)
|
||||
|
||||
assert.match(sourceFromGraph(model).source, /search\(you, creature or artifact, 1, to hand, shuffle\)/)
|
||||
|
||||
syncTexts(model)
|
||||
assert.equal(combo.text, 'creature or artifact')
|
||||
|
||||
combo.combine = 'and'
|
||||
combo.shape!.slots[0].text = 'red'
|
||||
combo.shape!.slots[1].text = 'creature'
|
||||
syncTexts(model)
|
||||
assert.equal(combo.text, 'red and creature')
|
||||
})
|
||||
|
||||
test('structured selector value nodes render their slots', () => {
|
||||
const model = graphFromSource(`# Test [supported]
|
||||
on enters(this):`)
|
||||
const trigger = model.nodes.find(node => node.kind === 'ability')
|
||||
assert.ok(trigger)
|
||||
|
||||
const selector: GraphModel['nodes'][number] = {
|
||||
id: nextNodeId(),
|
||||
kind: 'value',
|
||||
text: '',
|
||||
valueLabel: 'Selector',
|
||||
x: 0,
|
||||
y: 0,
|
||||
shape: {
|
||||
head: '',
|
||||
tail: '',
|
||||
separator: ' ',
|
||||
slots: [
|
||||
{ label: 'prefix', text: 'each' },
|
||||
{ label: 'state', text: 'nontoken' },
|
||||
{ label: 'type', text: 'angel' },
|
||||
{ label: 'controller', text: "you don't control" },
|
||||
],
|
||||
},
|
||||
}
|
||||
model.nodes.push(selector)
|
||||
assert.equal(connectNodes(model, selector.id, 'value', trigger.id, 0), true)
|
||||
|
||||
syncTexts(model)
|
||||
assert.equal(selector.text, "each nontoken angel you don't control")
|
||||
assert.equal(sourceFromGraph(model).source, `# Test [supported]
|
||||
on enters(each nontoken angel you don't control):`)
|
||||
})
|
||||
|
||||
test('parseCall splits arguments outside nested groups', () => {
|
||||
assert.deepEqual(parseCall('draw(you, 1)'), { name: 'draw', args: ['you', '1'] })
|
||||
assert.deepEqual(parseCall('proliferate()'), { name: 'proliferate', args: [] })
|
||||
assert.deepEqual(parseCall('damage(divided(any number, creature), 3)'), {
|
||||
name: 'damage',
|
||||
args: ['divided(any number, creature)', '3'],
|
||||
})
|
||||
assert.equal(parseCall('if you control at least 3 artifacts:'), undefined)
|
||||
})
|
||||
85
frontend/test/gameAnimations.test.ts
Normal file
85
frontend/test/gameAnimations.test.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { diffGameState } from '../app/utils/gameAnimations.ts'
|
||||
|
||||
test('diffGameState ignores the first snapshot', () => {
|
||||
const animations = diffGameState(undefined, {
|
||||
id: 'game',
|
||||
players: [{ id: 'p1', life: 40, battlefield: [{ id: 'card-1' }] }],
|
||||
game: { manaPool: { G: 2 } },
|
||||
})
|
||||
|
||||
assert.deepEqual(animations, {
|
||||
enteringCardIds: [],
|
||||
attackingCardIds: [],
|
||||
damagedCards: [],
|
||||
lifeChanges: [],
|
||||
manaGains: [],
|
||||
})
|
||||
})
|
||||
|
||||
test('diffGameState detects entering and attacking permanents', () => {
|
||||
const animations = diffGameState(
|
||||
{ id: 'game', players: [{ id: 'p1', battlefield: [{ id: 'old' }] }] },
|
||||
{
|
||||
id: 'game',
|
||||
players: [{
|
||||
id: 'p1',
|
||||
battlefield: [{ id: 'old' }, { id: 'new', attacking: 'p2' }],
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
assert.deepEqual(animations.enteringCardIds, ['new'])
|
||||
assert.deepEqual(animations.attackingCardIds, ['new'])
|
||||
})
|
||||
|
||||
test('diffGameState reports damage and life changes', () => {
|
||||
const animations = diffGameState(
|
||||
{
|
||||
id: 'game',
|
||||
players: [
|
||||
{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 1 }] },
|
||||
{ id: 'p2', life: 40 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'game',
|
||||
players: [
|
||||
{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 4 }] },
|
||||
{ id: 'p2', life: 33 },
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert.deepEqual(animations.damagedCards, [{ cardId: 'creature', amount: 3 }])
|
||||
assert.deepEqual(animations.lifeChanges, [{ playerId: 'p2', amount: -7 }])
|
||||
})
|
||||
|
||||
test('diffGameState only animates mana gains', () => {
|
||||
const animations = diffGameState(
|
||||
{ id: 'game', players: [], game: { manaPool: { G: 1, R: 2 } } },
|
||||
{ id: 'game', players: [], game: { manaPool: { G: 3, R: 0, U: 1 } } },
|
||||
)
|
||||
|
||||
assert.deepEqual(animations.manaGains, [
|
||||
{ color: 'G', amount: 2 },
|
||||
{ color: 'U', amount: 1 },
|
||||
])
|
||||
})
|
||||
|
||||
test('diffGameState is quiet when nothing visible changed', () => {
|
||||
const state = {
|
||||
id: 'game',
|
||||
players: [{ id: 'p1', life: 40, battlefield: [{ id: 'creature', damage: 2 }] }],
|
||||
game: { manaPool: { W: 1 } },
|
||||
}
|
||||
|
||||
assert.deepEqual(diffGameState(state, state), {
|
||||
enteringCardIds: [],
|
||||
attackingCardIds: [],
|
||||
damagedCards: [],
|
||||
lifeChanges: [],
|
||||
manaGains: [],
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user