# Game engine `backend/src/game/` is a small but real Magic rules engine. It consumes the compiled effect AST from `backend/src/effects/types.ts` directly — there is no second card language. Card definitions are immutable input; a `GameObject` is the per-game instance that moves between zones. ## Quick start Run the data imports first (see the root README), then: ```ts import { Game } from './src/game/game.js' import { deckFromOracleIds } from './src/game/catalog.js' const game = new Game({ seed: 1, startingLife: 40, startingHandSize: 7, commander: true, mulligans: true, players: [ { id: 'p1', deck: deckFromOracleIds(decklist1), commander: commanderCard1 }, { id: 'p2', deck: deckFromOracleIds(decklist2), commander: commanderCard2 }, ], }) game.start() ``` `commander: true` creates each supplied commander in that player's command zone. The `deck` should contain the other 99 cards; `validateCommanderDeck(commander, cards)` in `commander.ts` checks size, singleton, color identity, and the commander type. `catalog.ts` merges Scryfall card data with `data/card-effects.json`. It also adds intrinsic mana abilities for basic lands, because Scryfall's oracle text only has reminder text for them and the compiler produces no ability. 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: ```ts const bolt: CardDefinition = { oracleId: 'lightning-bolt', name: 'Lightning Bolt', typeLine: 'Instant', manaCost: '{R}', manaValue: 1, abilities: [{ kind: 'spell', optional: false, text: 'Lightning Bolt deals 3 damage to any target.', effects: [{ op: 'damage', target: { kind: 'any' }, amount: { kind: 'number', value: 3 } }], }], } ``` ## Actions | Method | Purpose | | ------ | ------- | | `start()` | Shuffles libraries and draws opening hands. With `mulligans: true`, turn 1 waits until every player keeps. | | `keepHand(playerId)` | Keeps the opening hand; begins turn 1 once every living player has kept. | | `mulligan(playerId)` | Shuffles the hand back, draws a new opening hand, and queues bottom-of-library choices (one more each time). | | `putOnBottom(playerId, cardId)` | Puts one chosen card from a mulliganed opening hand on the bottom of its owner's library. | | `playLand(playerId, cardId)` | Plays a land from hand; once per turn, main phase, empty stack. | | `castSpell(playerId, cardId, { targets, x, mode, overload })` | Puts a spell on the stack and pays its mana cost. Accepts a commander in the command zone, adds commander tax, and can pay the overload cost instead. | | `activateAbility(playerId, sourceId, abilityIndex, { targets, x, mode, 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. | Actions that use the stack move priority to the next living player. Non-instant, non-flash spells can only be cast in the active player's main phase with an empty stack. Targets may be supplied explicitly; if omitted, the first legal target is chosen automatically, which keeps scripted games short. A search effect that matches several cards pauses instead: other actions are refused until its controller calls `chooseSearchCard` (the match API uses the `choose_search` action). 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 ```text untap -> upkeep -> draw -> precombat main -> begin combat -> declare attackers -> declare blockers -> combat damage -> end combat -> postcombat main -> end step -> cleanup -> next player's turn ``` The starting player 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, 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. 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, 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, 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`, `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. - Planeswalker loyalty abilities, attacking planeswalkers, and protection/menace/defender are not implemented unless expressed as a compiled 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, except "pay a cost or enter tapped" which pauses for the controller. An optional `pay` is simply not paid when unaffordable. Search effects with several matching cards do pause for the player's pick. - "As this enters, choose a creature type" pauses for a pick and stores the type on the permanent, but no effect reads the chosen type yet. The other `choose` kinds (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 multiplayer matches, validates decks, and sends each player a personalized view (own hand only, libraries as counts) over SSE. - There is no persistence, account system, or reconnect grace period; a server restart drops all matches. ## Tests ```bash cd backend npx tsx --test test/game.test.ts test/commander.test.ts ``` The tests cover turn flow, priority, spell resolution, triggers, mana and summoning sickness, static and temporary pumps, combat, counterspells, tokens, searching, entering tapped/with counters, decking, lethal damage, commander tax and damage, decklist import, and multi-defender combat.