enjine 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/SUPPORTED.md +10 -9
  4. data/docs/guides/api.md +3 -0
  5. data/docs/guides/card-data-format.md +41 -2
  6. data/docs/plans/dsl-gaps.md +12 -12
  7. data/docs/reference/abilities.md +25 -11
  8. data/docs/reference/decisions.md +1 -1
  9. data/docs/reference/effects.md +15 -11
  10. data/lib/enjine/actions/activate_mana_ability.rb +3 -2
  11. data/lib/enjine/cli/text.rb +2 -1
  12. data/lib/enjine/decisions/casting.rb +1 -1
  13. data/lib/enjine/engine/casting/casting.rb +1 -0
  14. data/lib/enjine/engine/casting/payment.rb +20 -13
  15. data/lib/enjine/engine/casting/permissions.rb +11 -9
  16. data/lib/enjine/engine/copies.rb +8 -0
  17. data/lib/enjine/engine/damage.rb +1 -0
  18. data/lib/enjine/engine/mana_helpers.rb +75 -0
  19. data/lib/enjine/engine/mana_sources.rb +19 -8
  20. data/lib/enjine/engine/options_memo.rb +15 -2
  21. data/lib/enjine/engine/turn_history.rb +8 -0
  22. data/lib/enjine/engine/zones.rb +10 -0
  23. data/lib/enjine/mechanics/abilities/cost_changes.rb +62 -17
  24. data/lib/enjine/mechanics/abilities/entering_copy.rb +45 -16
  25. data/lib/enjine/mechanics/abilities/mana_ability.rb +54 -9
  26. data/lib/enjine/mechanics/abilities/play_permissions.rb +28 -9
  27. data/lib/enjine/mechanics/abilities/replacement_effects.rb +40 -11
  28. data/lib/enjine/mechanics/card_spec.rb +28 -2
  29. data/lib/enjine/mechanics/effects/choose_cards.rb +30 -15
  30. data/lib/enjine/mechanics/effects/counter_spell.rb +12 -5
  31. data/lib/enjine/mechanics/effects/damage.rb +24 -4
  32. data/lib/enjine/mechanics/effects/delayed_triggers.rb +3 -2
  33. data/lib/enjine/mechanics/effects/draw.rb +1 -1
  34. data/lib/enjine/mechanics/effects/loot.rb +1 -1
  35. data/lib/enjine/mechanics/effects/mana.rb +4 -1
  36. data/lib/enjine/mechanics/effects/pay.rb +14 -8
  37. data/lib/enjine/mechanics/keywords/alternative_costs.rb +3 -2
  38. data/lib/enjine/mechanics/keywords/bargain.rb +39 -0
  39. data/lib/enjine/mechanics/selector.rb +29 -8
  40. data/lib/enjine/replacements.rb +23 -5
  41. data/lib/enjine/steps.rb +1 -1
  42. data/lib/enjine/version.rb +1 -1
  43. metadata +4 -2
@@ -103,7 +103,7 @@ Untap step: `{type: "untap", object: id}` or `{type: "keep_tapped", object: id}`
103
103
  ## Priority actions
104
104
 
105
105
  - `activate` — `{type: "activate", object: id, ability: ref}` — start activating an ability (CR 602.2), including planeswalker loyalty abilities (CR 606) and abilities of cards in your hand (cycling, CR 702.29).
106
- - `activate_mana` — `{type: "activate_mana", object: id, ability: ref}` — activate a mana ability; it resolves immediately (CR 605.3). `mana: "{G}{G}"` names the mana when it is chosen as the ability is activated.
106
+ - `activate_mana` — `{type: "activate_mana", object: id, ability: ref}` — activate a mana ability; it resolves immediately (CR 605.3). `mana: "{G}{G}"` names the mana when it is chosen as the ability is activated; `tap: id` names the permanent tapped for a "tap an untapped creature you control" cost (CR 602.2b).
107
107
  - `cast` — `{type: "cast", object: id}` — start casting a card from your hand (CR 601.2). `{type: "cast", object: id, via: method}` casts a card from another zone (graveyard, exile, the top of your library) by the permission or alternative cost `via` names, e.g. beam me up (CR 601.3, 702.196). In a Commander game `via: "command"` casts your commander from the command zone, its cost including the commander tax (CR 903.8). A card outside the game is named `"outside:<card id>"` (CR 400.11b). `{type: "cast", object: id, face: 1}` casts another face of a card in your hand: a modal double-faced card's back face, an Adventure or an Omen (CR 712.8b, 716.3, 721.3). Offered only when timing allows, targets exist and enough mana is available.
108
108
  - `pass` — `{type: "pass"}` — pass priority. When all players pass in succession with an empty stack, the step ends (CR 117.4).
109
109
  - `play_land` — `{type: "play_land", object: id}` — special action: your main phase, empty stack, one land per turn plus additional land plays (CR 305.1, 305.2). With `via`: a land from another zone that an effect lets you play. With `face: 1`: a modal double-faced card played with its land back face up (CR 712.9).
@@ -509,13 +509,13 @@ Rules: CR 205.2a, CR 607.2d, CR 608.2c
509
509
 
510
510
  ## choose_cards
511
511
 
512
- You choose `count` (default 1; "any": any number; "all": every matching card, no choice) cards matching `for` from `from`: a selector (e.g. {"result": 0}, the cards an earlier effect milled) or a player's zone, {"hand": selector} / {"graveyard": selector}. `optional`: you may choose fewer. Then they are put into `put` (`discard`: from a hand, its owner discards them; `tapped` onto the battlefield, under your control; exiled cards `link`ed to the source). `look`: you look at the whole zone first; `reveal`: "chosen" reveals what you chose, "all" the whole set. `then` runs if a card was chosen, `otherwise` if none was ("if you can't"). `random: true`: the cards are picked at random (the game's random number generator) instead of chosen. `chooser`: the player who chooses (a player selector, default "you"; e.g. "each_opponent" or {"target": 0}: "target opponent chooses a card from among them"); they look at the cards they choose from, and the cards still go where `put` says under your control.
512
+ You choose `count` (default 1; "any": any number; "all": every matching card, no choice) cards matching `for` from `from`: a selector (e.g. {"result": 0}, the cards an earlier effect milled) or a player's zone, {"hand": selector} / {"graveyard": selector} / {"library": selector}, or several of them ("search its owner's graveyard, hand, and library": one choice among them all). `optional`: you may choose fewer. Then they are put into `put` (`discard`: from a hand, its owner discards them; `tapped` onto the battlefield, under your control; exiled cards `link`ed to the source). `look`: you look at the whole zone first; `reveal`: "chosen" reveals what you chose, "all" the whole set. `then` runs if a card was chosen, `otherwise` if none was ("if you can't"). `random: true`: the cards are picked at random (the game's random number generator) instead of chosen. `chooser`: the player who chooses (a player selector, default "you"; e.g. "each_opponent" or {"target": 0}: "target opponent chooses a card from among them"); they look at the cards they choose from, and the cards still go where `put` says under your control. Its amount ({"this_way": n}) is how many of the cards came from a hand ("draws a card for each card exiled from their hand this way").
513
513
 
514
- Rules: CR 701.20a, CR 701.20e, CR 400.7j, CR 608.2c, CR 607.2a, CR 118.12, CR 701.9a, CR 701.9b, CR 608.2d
514
+ Rules: CR 701.20a, CR 701.20e, CR 400.7j, CR 608.2c, CR 607.2a, CR 118.12, CR 701.9a, CR 701.9b, CR 608.2d, CR 701.23a, CR 701.23b
515
515
 
516
516
  | Parameter | Description |
517
517
  | --- | --- |
518
- | `from` | selector or {"hand"|"graveyard": player selector} |
518
+ | `from` | selector or {"hand"|"graveyard"|"library": player selector, ...} |
519
519
  | `for` | card spec |
520
520
  | `count` | integer, "any" or "all" |
521
521
  | `optional` | boolean |
@@ -700,13 +700,14 @@ Rules: CR 707.10, CR 707.10a, CR 707.10b, CR 707.10c, CR 707.10f, CR 608.3f
700
700
 
701
701
  ## counter
702
702
 
703
- Counter each referenced spell or ability: a spell leaves the stack for its owner's graveyard without resolving, an ability ceases to exist. A spell that can't be countered stays.
703
+ Counter each referenced spell or ability: a spell leaves the stack for its owner's graveyard (for exile with `exile_instead: true`) without resolving, an ability ceases to exist. A spell that can't be countered stays.
704
704
 
705
- Rules: CR 701.6a, CR 701.6b, CR 101.2
705
+ Rules: CR 701.6a, CR 701.6b, CR 101.2, CR 614.1a
706
706
 
707
707
  | Parameter | Description |
708
708
  | --- | --- |
709
709
  | `to` | selector |
710
+ | `exile_instead` | boolean: "if that spell is countered this way, exile it instead" |
710
711
 
711
712
  ```json
712
713
  {
@@ -738,9 +739,9 @@ Rules: CR 614.1a, CR 614.16, CR 611.2a, CR 122.6, CR 616.1
738
739
 
739
740
  ## counter_unless_pays
740
741
 
741
- Counter each referenced spell or ability unless its controller pays `mana` (or `waterbend`s that cost, CR 701.67a, or pays the list of costs `cost`) as this resolves (they choose, and pay like any cost; mana abilities allowed).
742
+ Counter each referenced spell or ability unless its controller pays `mana` (or `waterbend`s that cost, CR 701.67a, or pays the list of costs `cost`) as this resolves (they choose, and pay like any cost; mana abilities allowed). With `exile_instead: true`, a spell countered this way is exiled instead of being put into its owner's graveyard; if they pay, nothing happens to it.
742
743
 
743
- Rules: CR 701.6a, CR 118.12a, CR 605.3a, CR 701.67a
744
+ Rules: CR 701.6a, CR 118.12a, CR 605.3a, CR 701.67a, CR 608.2b, CR 614.1a
744
745
 
745
746
  | Parameter | Description |
746
747
  | --- | --- |
@@ -748,6 +749,7 @@ Rules: CR 701.6a, CR 118.12a, CR 605.3a, CR 701.67a
748
749
  | `waterbend` | mana cost string, instead of mana |
749
750
  | `cost` | list of costs, instead of mana |
750
751
  | `to` | selector (usually {"target": 0}) |
752
+ | `exile_instead` | boolean: "if that spell is countered this way, exile it instead" |
751
753
 
752
754
  ```json
753
755
  {
@@ -896,14 +898,15 @@ Rules: CR 615.12, CR 611.2a
896
898
 
897
899
  ## deal_damage
898
900
 
899
- Deal `amount` damage to each referenced creature, planeswalker or player. Damage to a player causes life loss; to a planeswalker removes loyalty counters; to a creature is marked until cleanup. {"this_way": n} naming it is the excess damage it dealt (beyond lethal damage, or a planeswalker's loyalty).
901
+ Deal `amount` damage to each referenced creature, planeswalker or player. Damage to a player causes life loss; to a planeswalker removes loyalty counters; to a creature is marked until cleanup. {"this_way": n} naming it is the excess damage it dealt (beyond lethal damage, or a planeswalker's loyalty). `exile_if_dies: true`: a permanent dealt damage this way that would die this turn is exiled instead (not one whose damage was prevented).
900
902
 
901
- Rules: CR 120.3a, CR 120.3c, CR 120.3e, CR 120.6, CR 120.4a, CR 120.10
903
+ Rules: CR 120.3a, CR 120.3c, CR 120.3e, CR 120.6, CR 120.4a, CR 120.10, CR 614.1a, CR 700.4
902
904
 
903
905
  | Parameter | Description |
904
906
  | --- | --- |
905
907
  | `amount` | integer |
906
908
  | `to` | selector |
909
+ | `exile_if_dies` | true: "if a permanent dealt damage this way would die this turn, exile it instead" |
907
910
 
908
911
  ```json
909
912
  {
@@ -1727,9 +1730,9 @@ Rules: CR 702.26a, CR 702.26b, CR 702.26d, CR 702.26g, CR 702.26h, CR 502.1, CR
1727
1730
 
1728
1731
  ## play_permission
1729
1732
 
1730
- A player may play (`play: "play"`, default) or cast (`"cast"`) each referenced exiled card matching `for`/`not_types`, paying its costs and following timing rules, for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step, while_exiled or while_you_control_source ("for as long as you control this creature"). With `choose: "one_per_owner"` only one chosen card per owner. `to_player`: who may play it, "controller" (default, the effect's controller), "owner" (the card's owner) or a player selector (a face-down card: only someone who may look at it). `cost_increase`: spells cast this way cost that much generic mana more. `any_mana_type: true`: mana of any type can be spent to cast those spells. `during: "your_turn"`: only during your turn. `waterbend: "mana_value"`: cast it by waterbending {X} rather than paying its mana cost, where X is its mana value.
1733
+ A player may play (`play: "play"`, default) or cast (`"cast"`) each referenced exiled card (`zone: "graveyard"`: card in a graveyard) matching `for`/`not_types`, paying its costs and following timing rules (a land uses a land play), for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step, while_exiled or while_you_control_source ("for as long as you control this creature"). With `choose: "one_per_owner"` only one chosen card per owner. `to_player`: who may play it, "controller" (default, the effect's controller), "owner" (the card's owner) or a player selector (a face-down card: only someone who may look at it). `cost_increase`: spells cast this way cost that much generic mana more. `any_mana_type: true`: mana of any type can be spent to cast those spells. `during: "your_turn"`: only during your turn. `waterbend: "mana_value"`: cast it by waterbending {X} rather than paying its mana cost, where X is its mana value.
1731
1734
 
1732
- Rules: CR 611.2a, CR 611.2b, CR 601.3, CR 305.1, CR 400.7, CR 514.2, CR 601.2f, CR 108.3, CR 406.3b, CR 609.4b, CR 118.9, CR 701.67a
1735
+ Rules: CR 611.2a, CR 611.2b, CR 601.3, CR 305.1, CR 305.2, CR 400.7, CR 514.2, CR 601.2f, CR 108.3, CR 406.3b, CR 609.4b, CR 118.9, CR 701.67a
1733
1736
 
1734
1737
  | Parameter | Description |
1735
1738
  | --- | --- |
@@ -1745,6 +1748,7 @@ Rules: CR 611.2a, CR 611.2b, CR 601.3, CR 305.1, CR 400.7, CR 514.2, CR 601.2f,
1745
1748
  | `exile_instead` | true or a card spec: if a spell cast this way (matching it) would be put into a graveyard, it's exiled instead (CR 614.1a) |
1746
1749
  | `during` | your_turn |
1747
1750
  | `waterbend` | mana_value |
1751
+ | `zone` | exile (default) | graveyard: where the referenced cards are |
1748
1752
 
1749
1753
  ```json
1750
1754
  {
@@ -7,7 +7,8 @@ module Enjine
7
7
  class ActivateManaAbility
8
8
  def self.doc
9
9
  '`{type: "activate_mana", object: id, ability: ref}` — activate a mana ability; it resolves immediately ' \
10
- '(CR 605.3). `mana: "{G}{G}"` names the mana when it is chosen as the ability is activated.'
10
+ '(CR 605.3). `mana: "{G}{G}"` names the mana when it is chosen as the ability is activated; `tap: id` names ' \
11
+ 'the permanent tapped for a "tap an untapped creature you control" cost (CR 602.2b).'
11
12
  end
12
13
 
13
14
  def self.options(engine, index)
@@ -15,7 +16,7 @@ module Enjine
15
16
  end
16
17
 
17
18
  def self.perform(engine, index, option)
18
- engine.activate_mana_ability!(index, option[:object], option[:ability], option[:mana])
19
+ engine.activate_mana_ability!(index, option[:object], option[:ability], option[:mana], option[:tap])
19
20
  engine.action_taken!(index)
20
21
  end
21
22
  end
@@ -159,7 +159,8 @@ module Enjine
159
159
  when "activate" then "Activate #{name_of(opt[:object])}: #{ability_text(opt[:object], opt[:ability])}"
160
160
  when "special_action" then "#{ability_text(opt[:object], opt[:ability])}: #{name_of(opt[:object])} (special action)"
161
161
  when "activate_mana"
162
- "Tap #{name_of(opt[:object])} for #{opt[:mana] || "mana"} (#{ability_text(opt[:object], opt[:ability])})"
162
+ "Tap #{name_of(opt[:object])}#{" and #{name_of(opt[:tap])}" if opt[:tap]} for #{opt[:mana] || "mana"} " \
163
+ "(#{ability_text(opt[:object], opt[:ability])})"
163
164
  when "pay_mana"
164
165
  "Pay {#{opt[:mana]}} from mana pool#{" (restricted)" if opt[:restricted]}#{" (made by an artifact)" if opt[:from]}"
165
166
  when "target" then "Target #{name_of(opt[:target])}"
@@ -182,7 +182,7 @@ module Enjine
182
182
  when "pay_mana" then engine.pay_mana!(option[:mana], option[:restricted], option[:from])
183
183
  when "convoke", "improvise" then engine.convoke!(option[:object], option[:type]) # CR 702.51a, 702.126a
184
184
  when "waterbend" then engine.waterbend!(option[:object]) # CR 701.67a
185
- else engine.tap_for_payment!(option[:object], option[:ability], option[:mana])
185
+ else engine.tap_for_payment!(option[:object], option[:ability], option[:mana], option[:tap])
186
186
  end
187
187
  end
188
188
  end
@@ -278,6 +278,7 @@ module Enjine
278
278
  obj.modes = ctx["modes"].dup unless ctx["modes"].empty?
279
279
  obj.mana_spent = ctx["spent"].dup if ctx["spent"]
280
280
  obj.memory["mana_from"] = Snapshot.deep_copy(ctx["spent_from"]) if ctx["spent_from"] # the sources (ManaSources)
281
+ obj.memory["cant_be_countered"] = true if ctx["uncounterable"] # mana with that rider was spent (CR 106.6, 101.2)
281
282
  record_announcements!(obj, ctx) # kicked (CR 702.33d), division (CR 601.2d), modes chosen before
282
283
  record_cast_choices!(obj, ctx) # cost choices; facing a dilemma (CR 700.17)
283
284
  waterbent!(ctx) # CR 701.67c (Engine::Waterbending)
@@ -121,6 +121,7 @@ module Enjine
121
121
  frame["remaining"] = after_paying(frame["remaining"], slot)
122
122
  (frame["spent"] ||= []) << type # what was spent matters later (sunburst, CR 702.44a; 609.4b: its real type)
123
123
  (frame["spent_from"] ||= []) << entry["from"] if entry&.key?("from") # "if mana from a Treasure was spent"
124
+ frame["uncounterable"] = true if frame["kind"] == "spell" && Mechanics::SpendOnly.uncounterable?(entry) # CR 106.6, 101.2
124
125
  (frame["refund"] ||= []) << { "mana" => type, (restricted ? "restricted" : "source") => entry }.compact # #refund_payment!
125
126
  emit Events::ManaPaid.new(player: name(frame["player"]), mana: "{#{type}}", object: frame["object"])
126
127
  ask!(nil)
@@ -168,10 +169,11 @@ module Enjine
168
169
  purpose = payment_purpose(frame)
169
170
  sources = all_mana_sources(frame["player"]).reject do |id, ref|
170
171
  spend_only = chars(id).ability(ref).spend_only
171
- reserved_for_cost?(frame, id, ref) || (spend_only && !spend_only.allows?(self, purpose))
172
+ reserved_for_cost?(frame, id, ref) || (spend_only && !spend_only.bound(self, id).allows?(self, purpose))
172
173
  end
173
174
  mana_activation_options(sources).select do |option|
174
175
  id = option[:object]
176
+ next false if option[:tap] && reserved_helper?(frame, option[:tap]) # Engine::ManaHelpers
175
177
  next !frame["irreversible"] && !irreversible_mana_ability?(id, option[:ability]) if chars(id).ability(option[:ability]).mana_cost
176
178
 
177
179
  (!frame["irreversible"] && !irreversible_mana_ability?(id, option[:ability])) ||
@@ -182,6 +184,9 @@ module Enjine
182
184
  # A mana ability that can't be undone (Abilities::ManaAbility#irreversible?).
183
185
  def irreversible_mana_ability?(id, ref) = chars(id).ability(ref).irreversible?
184
186
 
187
+ # A permanent the spell or ability being paid for still needs, which a mana ability can't tap for its cost.
188
+ def reserved_helper?(frame, id) = id == payment_excluded_source(frame) || payment_reserved(frame).include?(id)
189
+
185
190
  def reserved_for_cost?(frame, id, ref)
186
191
  return true if id == payment_excluded_source(frame)
187
192
 
@@ -206,11 +211,11 @@ module Enjine
206
211
  pool = player(frame["player"]).mana_pool.dup
207
212
  rest = player(frame["player"]).restricted_mana
208
213
  if ability.spend_only
209
- rest += produced.map { { "mana" => it.to_s, "spend_only" => ability.spend_only.data } }
214
+ rest += produced.map { { "mana" => it.to_s, "spend_only" => ability.spend_only.bound(self, id).data } }
210
215
  else
211
216
  produced.each { pool[it] += 1 }
212
217
  end
213
- used = [id, tapped_granter(option[:ability], ability)].compact
218
+ used = [id, tapped_granter(option[:ability], ability), option[:tap]].compact
214
219
  later = units_after_activating(id, option[:ability], ability) # ManaSources: it may be activated again
215
220
  payable_with?(frame, remaining_cost(frame["remaining"]), pool, payment_reserved(frame) + used, restricted: rest, extra: later)
216
221
  end
@@ -218,14 +223,14 @@ module Enjine
218
223
  # CR 605.3: activating a mana ability while paying. One whose costs include more than {T} (a
219
224
  # sacrifice, life, a discard) can't be undone, so the payment stops being cancellable. Tapping the
220
225
  # permanent that granted it can (CR 734.1: it is untapped with the source).
221
- def tap_for_payment!(id, ability_ref, mana = nil)
226
+ def tap_for_payment!(id, ability_ref, mana = nil, helper = nil)
222
227
  frame = payment
223
228
  frame["irreversible"] = true if irreversible_mana_ability?(id, ability_ref)
224
229
  granter = tapped_granter(ability_ref, chars(id).ability(ability_ref))
225
- activate_mana_ability!(frame["player"], id, ability_ref, mana)
226
- frame["tapped"] << id
227
- frame["tapped"] << granter if granter
228
- (frame["mana_tapped"] ||= []).push(*[id, granter].compact) # kept tapped by #refund_payment!
230
+ activate_mana_ability!(frame["player"], id, ability_ref, mana, helper)
231
+ tapped = [id, granter, helper].compact # the helper tapped for its cost (Engine::ManaHelpers)
232
+ frame["tapped"].push(*tapped)
233
+ (frame["mana_tapped"] ||= []).push(*tapped) # kept tapped by #refund_payment!
229
234
  ask!(nil)
230
235
  end
231
236
 
@@ -292,19 +297,21 @@ module Enjine
292
297
  # ---- countering (CR 701.6) ----------------------------------------------------------------
293
298
 
294
299
  # CR 701.6a: a countered spell goes to its owner's graveyard; a countered ability ceases to exist.
295
- # "This spell can't be countered" and "Spells [and abilities] you control can't be countered" win (CR 101.2).
296
- # Returns whether it was countered.
297
- def counter!(id)
300
+ # "This spell can't be countered", "Spells [and abilities] you control can't be countered" and a spell cast with mana
301
+ # whose rider says so (memory "cant_be_countered", CR 106.6) win (CR 101.2).
302
+ # `exile`: "If that spell is countered this way, exile it instead of putting it into its owner's graveyard"
303
+ # (CR 614.1a). Returns whether it was countered.
304
+ def counter!(id, exile: false)
298
305
  obj = object(id)
299
306
  return false if obj.ability? && player_rule?(obj.controller, "abilities_cant_be_countered")
300
- return false if !obj.ability? && (chars(obj).keyword?(:cant_be_countered) ||
307
+ return false if !obj.ability? && (chars(obj).keyword?(:cant_be_countered) || obj.memory["cant_be_countered"] ||
301
308
  player_rule?(obj.controller, "spells_cant_be_countered", obj))
302
309
 
303
310
  if obj.ability?
304
311
  emit Events::AbilityCountered.new(object: id, card: obj.card, source: obj.source)
305
312
  remove_stack_object!(id)
306
313
  else
307
- move!(id, :graveyard, reason: "countered")
314
+ move!(id, exile ? :exile : :graveyard, reason: "countered")
308
315
  end
309
316
  true
310
317
  end
@@ -41,7 +41,7 @@ module Enjine
41
41
  # distinct card) while something lets them play those.
42
42
  def permission_candidates(index, sources = permission_sources(index))
43
43
  pl = player(index)
44
- ids = alt_cost_hand(index) + pl.graveyard + state.exile + commander_candidates(index)
44
+ ids = alt_cost_hand(index) + pl.graveyard + others_graveyard_permitted(index) + state.exile + commander_candidates(index)
45
45
  ids += [pl.library.first] unless pl.library.empty?
46
46
  return ids unless sources.any? { |_, inst| inst.ability.kind == :play_from && inst.ability.outside? }
47
47
 
@@ -113,7 +113,7 @@ module Enjine
113
113
  record_result!(obj.id)
114
114
  emit Events::ZoneChanged.new(card: card, old_id: nil, new_id: obj.id, owner: name(index), from: "outside",
115
115
  to: to.to_s, reason: reason)
116
- obj
116
+ obj.tap { copy_follow_up!(it, data["enters"]) } # "When you do, ..." of entering as a copy (Engine::Copies)
117
117
  end
118
118
 
119
119
  # CR 601.2a: a spell cast from outside the game is brought into the game onto the stack.
@@ -217,13 +217,14 @@ module Enjine
217
217
 
218
218
  # ---- where methods come from ------------------------------------------------------------
219
219
 
220
- # Permissions from resolved effects (impulse draw, CR 611.2): the card is still the exiled object. A
220
+ # Permissions from resolved effects (impulse draw, CR 611.2): the card is still the exiled object (or, for a
221
+ # graveyard permission, the object in the graveyard: "mill a card. You may play that card this turn"). A
221
222
  # face-down card only for a player who may look at it (CR 406.3b). `any_mana_type`: mana of any type
222
223
  # can be spent to cast it (CR 609.4b).
223
224
  def granted_methods(index, obj)
224
225
  state.effects.filter_map do |e|
225
226
  next unless e["kind"] == "permission" && e["controller"] == index && e["affected"].include?(obj.id)
226
- next unless obj.zone == :exile && may_look?(obj, index) && (e["during"] != "your_turn" || state.active == index)
227
+ next unless obj.zone == permission_zone(e) && may_look?(obj, index) && (e["during"] != "your_turn" || state.active == index)
227
228
 
228
229
  with_waterbend_alt(obj, { "via" => "effect:#{e["timestamp"]}", "play" => e["play"], **e.slice(*RIDERS) })
229
230
  end
@@ -293,25 +294,26 @@ module Enjine
293
294
 
294
295
  # Permission to play exiled cards for a duration (CR 611.2): a continuous effect for the exiled
295
296
  # objects (a card that leaves exile is a new object, CR 400.7, so the permission ends with it).
296
- # `riders` (RIDERS) change how a card is played with this permission, and only then (`source`: CR 611.2b).
297
+ # `riders` (RIDERS) change how a card is played with this permission, and only then (`source`: CR 611.2b);
298
+ # "zone" => "graveyard" is kept on the entry: the permission is for cards in a graveyard instead.
297
299
  def grant_play_permission!(index, ids, duration:, play:, source: nil, **riders)
298
300
  return if ids.empty?
299
301
 
300
302
  state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index, "affected" => ids,
301
303
  "duration" => duration, "turn" => state.turn, "play" => play, "source" => source,
302
- **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }.compact
304
+ **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS, "zone") }.compact
303
305
  emit Events::EffectStarted.new(kind: "permission", affected: ids, details: { "duration" => duration, "play" => play })
304
306
  end
305
307
 
306
308
  # CR 514.2: at cleanup, an end_of_your_next_turn permission ends on its controller's next turn, and a
307
- # permission whose cards all left exile is gone. (end_of_turn ones end with the other
308
- # until-end-of-turn effects.)
309
+ # permission whose cards all left their zone (exile, or the graveyard) is gone (CR 400.7). (end_of_turn
310
+ # ones end with the other until-end-of-turn effects.)
309
311
  def expire_permissions!
310
312
  state.effects.reject! do |e|
311
313
  next false unless e["kind"] == "permission"
312
314
 
313
315
  (e["duration"] == "end_of_your_next_turn" && state.active == e["controller"] && state.turn > e["turn"]) ||
314
- e["affected"].none? { state.exile.include?(it) }
316
+ e["affected"].none? { state.objects[it]&.zone == permission_zone(e) }
315
317
  end
316
318
  end
317
319
 
@@ -113,6 +113,14 @@ module Enjine
113
113
  fresh.card = copy["card"]
114
114
  end
115
115
 
116
+ # CR 603.12: the follow-up of an "enter as a copy" ability ("When you do, exile that card"), run once `fresh`
117
+ # entered as a copy (Abilities::EnterAsCopy#enters_with). Its ability is on the card the permanent really is.
118
+ def copy_follow_up!(fresh, enters)
119
+ entry = enters && enters["copy_then"] or return
120
+ run_follow_ups!("follow_ups" => [entry.merge("card" => own_card(fresh), "controller" => fresh.controller,
121
+ "source" => fresh.id)])
122
+ end
123
+
116
124
  # CR 707.12: a copy of a card, created in the zone the card is in (owned by `controller`).
117
125
  def create_card_copy!(values, controller, zone)
118
126
  card, except = values
@@ -12,6 +12,7 @@ module Enjine
12
12
 
13
13
  data = propose("damage", { "source" => source, "target" => ref, "amount" => amount, "combat" => combat }).data
14
14
  dealt = deal_proposed_damage!(source, data, combat, lifelink)
15
+ yield data["target"] if block_given? && dealt.positive? # who was dealt it (redirected, CR 614.9)
15
16
  run_follow_ups!(data) # the rest of a prevention effect (CR 615.5)
16
17
  dealt
17
18
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Mana abilities whose cost taps another permanent the player chooses: "{T}, Tap an untapped creature you
6
+ # control: Add one mana of any color" (Springleaf Drum, Gene Pollinator; CR 605.3a, 602.2b, 601.2h).
7
+ # A mana ability is paid for and resolves at once (CR 605.3a), so the permanent to tap (the "helper") is
8
+ # part of the activation option: `tap: id`, one option per helper (times each mana choice). Tapping a
9
+ # permanent for a cost isn't {T}, so a creature that came under its controller's control this turn may be
10
+ # tapped (CR 302.6). With {T} in the same cost, the source can't also be its own helper: once tapped for {T}
11
+ # it is no longer untapped (CR 601.2h, 107.5). Tapping a helper can be rewound with its source (CR 734.1).
12
+ module ManaHelpers
13
+ # The helper cost of a mana ability ({"tap_permanents": ...} with count 1), or nil.
14
+ def self.helper_cost(costs) = costs.find { it.is_a?(Mechanics::Costs::TapPermanents) }
15
+
16
+ # The untapped permanents that could be tapped for the helper cost of the mana ability `ability` of the
17
+ # permanent `obj` (with its costs as bound, `costs`): those that aren't mana sources first, so the plain
18
+ # answer is listed first.
19
+ def mana_helpers(obj, costs)
20
+ cost = ManaHelpers.helper_cost(costs) or return []
21
+ ids = cost.candidates(self, obj)
22
+ ids -= [obj.id] if costs.any?(Mechanics::Costs::Tap) # CR 601.2h: {T} taps the source itself
23
+ ids.partition { chars(it).mana_abilities.empty? }.flatten
24
+ end
25
+
26
+ # Whether the mana ability has a helper to tap now (part of ManaAbility#activatable?).
27
+ def mana_helper?(obj, costs) = ManaHelpers.helper_cost(costs).nil? || !mana_helpers(obj, costs).empty?
28
+
29
+ # One activation option per helper for a mana ability with a helper cost; `options` unchanged otherwise.
30
+ def with_mana_helpers(options, id, ref, ability)
31
+ costs = mana_ability_costs(ref, ability)
32
+ return options unless ManaHelpers.helper_cost(costs)
33
+
34
+ helpers = mana_helpers(object(id), costs)
35
+ options.flat_map { |option| helpers.map { option.merge(tap: it) } }
36
+ end
37
+
38
+ # Before any cost is paid: a mana ability with a helper cost needs `helper` (an option's `tap`) to be one it
39
+ # could tap now, and one without names none.
40
+ def check_mana_helper!(obj, costs, helper)
41
+ return if ManaHelpers.helper_cost(costs) ? mana_helpers(obj, costs).include?(helper) : helper.nil?
42
+
43
+ raise ArgumentError, "#{obj.id}: #{helper.inspect} can't be tapped for this mana ability's cost (tap:)"
44
+ end
45
+
46
+ # Affordability (ManaSources#source_units) of the mana abilities with a helper cost, `deferred` as [id, ref,
47
+ # ability]. Each helper is tapped at most once and each source activated once:
48
+ # - a helper that makes no mana of its own: the source adds one unit;
49
+ # - another such source not yet used: it is tapped as the helper (it adds nothing itself), the source adds one;
50
+ # - a mana source already counted (`by_source`): tapping it for the cost only changes which mana its unit can be,
51
+ # so its unit widens to the source's mana and no unit is added.
52
+ # Greedy, in battlefield order: an estimate for which casts to offer, as convoke's is.
53
+ def add_mana_helper_units!(index, by_source, deferred, excluded)
54
+ sources = all_mana_sources(index).map(&:first)
55
+ used = []
56
+ deferred.each do |id, ref, ability|
57
+ next if used.include?(id)
58
+
59
+ helpers = mana_helpers(object(id), mana_ability_costs(ref, ability)) - excluded - used
60
+ outcomes = ability.outcomes(self, object(id))
61
+ free = helpers.find { !sources.include?(it) } || helpers.find { |h| deferred.any? { it.first == h } }
62
+ if free
63
+ used.push(id, free)
64
+ by_source[id].concat(outcomes)
65
+ elsif (counted = helpers.find { by_source.key?(it) })
66
+ used.push(id, counted)
67
+ by_source[counted].concat(outcomes)
68
+ end
69
+ end
70
+ end
71
+ end
72
+
73
+ include ManaHelpers
74
+ end
75
+ end
@@ -51,18 +51,21 @@ module Enjine
51
51
  def source_units(index, excluded, purpose = nil)
52
52
  by_source = Hash.new { |h, k| h[k] = [] }
53
53
  repeats = {}
54
+ deferred = [] # tapping another permanent too (Engine::ManaHelpers)
54
55
  all_mana_sources(index).each do |id, ref|
55
56
  next if excluded.include?(id)
56
57
 
57
58
  ability = chars(id).ability(ref)
58
- next if ability.mana_cost || (ability.spend_only && !ability.spend_only.allows?(self, purpose))
59
+ next if ability.mana_cost || (ability.spend_only && !ability.spend_only.bound(self, id).allows?(self, purpose))
59
60
  next if (granter = tapped_granter(ref, ability)) && excluded.include?(granter)
61
+ next deferred << [id, ref, ability] if ManaHelpers.helper_cost(ability.costs)
60
62
 
61
63
  # Abilities that tap the permanent granting them (CR 602.2b) make mana once among them all.
62
64
  by_source[granter ? "granter:#{granter}" : id].concat(ability.outcomes(self, object(id)))
63
65
  # CR 605.3a: one without {T} whose costs only remove counters from it can be activated again
64
66
  repeats[id] = [repeats.fetch(id, 1), ability.repeats(object(id), mana_ability_costs(ref, ability))].max unless granter
65
67
  end
68
+ add_mana_helper_units!(index, by_source, deferred, excluded) unless deferred.empty?
66
69
  units = by_source.flat_map do |key, options|
67
70
  Array.new(options.map(&:size).max.to_i * repeats.fetch(key, 1)) { options.flatten.uniq }
68
71
  end
@@ -140,27 +143,35 @@ module Enjine
140
143
  def mana_activation_options(sources)
141
144
  sources.flat_map do |id, ref|
142
145
  ability = chars(id).ability(ref)
143
- next [{ type: "activate_mana", object: id, ability: ref }] unless ability.choice?
144
-
145
- ability.outcomes(self, object(id)).map { { type: "activate_mana", object: id, ability: ref, mana: Mana.symbols(it) } }
146
+ options = if ability.choice?
147
+ ability.outcomes(self, object(id)).map { { type: "activate_mana", object: id, ability: ref, mana: Mana.symbols(it) } }
148
+ else
149
+ [{ type: "activate_mana", object: id, ability: ref }]
150
+ end
151
+ with_mana_helpers(options, id, ref, ability) # `tap`: the permanent tapped for its cost (Engine::ManaHelpers)
146
152
  end
147
153
  end
148
154
 
149
155
  # CR 605.3: pay the ability's costs and add its mana immediately. Shared by priority and payment.
150
156
  # `mana`: the mana chosen as it was activated (an option's "mana"). Restricted mana keeps its
151
157
  # restriction in the pool (CR 106.6).
152
- def activate_mana_ability!(index, id, ability_ref, mana = nil)
158
+ def activate_mana_ability!(index, id, ability_ref, mana = nil, helper = nil)
153
159
  obj = object(id)
154
160
  ability = chars(obj).ability(ability_ref) or raise ArgumentError, "#{id} has no ability #{ability_ref}"
161
+ costs = mana_ability_costs(ability_ref, ability)
162
+ check_mana_helper!(obj, costs, helper) # Engine::ManaHelpers
155
163
  chosen = mana && Mana.parse_produce(mana, [], "mana")
156
164
  from = mana_provenance(id) # before a cost sacrifices it (a Treasure)
157
165
  record_activation!("source" => id, "ability" => ability_ref) if ability.per_turn
158
166
  pay_from_pool!(index, ability.mana_cost, id) if ability.mana_cost
159
- Mechanics::Costs.payment_order(mana_ability_costs(ability_ref, ability)).map(&:first).each do |cost| # CR 601.2h
160
- cost.respond_to?(:pay_at_once!) ? cost.pay_at_once!(self, obj) : cost.pay!(self, obj)
167
+ Mechanics::Costs.payment_order(costs).map(&:first).each do |cost| # CR 601.2h
168
+ if cost.is_a?(Mechanics::Costs::TapPermanents) then tap!(object(helper)) # the chosen helper (CR 602.2b)
169
+ elsif cost.respond_to?(:pay_at_once!) then cost.pay_at_once!(self, obj)
170
+ else cost.pay!(self, obj)
171
+ end
161
172
  end
162
173
  produced = chosen || ability.outcomes(self, obj).first # CR 605.3b: a fixed amount is counted as it resolves
163
- add_mana!(index, produced, id, restriction: ability.spend_only&.data, from: from)
174
+ add_mana!(index, produced, id, restriction: ability.spend_only&.bound(self, id)&.data, from: from)
164
175
  add_mana_ability_counters!(index, obj, ability)
165
176
  end
166
177
 
@@ -44,14 +44,27 @@ module Enjine
44
44
  # only lands are asked for):
45
45
  # - an exiled card `index` doesn't own can only be played by a permission effect of theirs naming it
46
46
  # (Engine::Permissions#granted_methods; every other method needs them to own the card, CR 108.3);
47
- # - while `plain`, a card in a graveyard or library only by an ability of its own (#unplayable_elsewhere?);
47
+ # - while `plain`, a card in a graveyard or library only by an ability of its own (#unplayable_elsewhere?) or a
48
+ # permission effect naming it (a milled card, `play_permission` `zone: "graveyard"`);
48
49
  # - for the land options, a card that isn't a land (seen face up, CR 406.3a).
49
50
  def unplayable_candidate?(index, obj, plain, land)
50
51
  return true if obj.zone == :exile && obj.owner != index && !permission_named_ids(index).include?(obj.id)
51
52
 
52
- (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
53
+ (plain && unplayable_elsewhere?(obj) && !permission_named_ids(index).include?(obj.id)) ||
54
+ (land && !face_up(obj.id) { chars(obj).land? })
53
55
  end
54
56
 
57
+ # Cards in other players' graveyards a permission effect of `index` names ("you may play that card",
58
+ # Engine::Permissions#permission_candidates).
59
+ def others_graveyard_permitted(index)
60
+ return [] if state.effects.none? { it["kind"] == "permission" && it["zone"] == "graveyard" }
61
+
62
+ permission_named_ids(index).select { (obj = state.objects[it]) && obj.zone == :graveyard && obj.owner != index }
63
+ end
64
+
65
+ # The zone a permission effect's cards are played from (CR 601.3): exile unless it says "graveyard".
66
+ def permission_zone(effect) = effect["zone"] == "graveyard" ? :graveyard : :exile
67
+
55
68
  # The ids of the objects permission effects of `index` name (Engine::Permissions#granted_methods), once per
56
69
  # decision.
57
70
  def permission_named_ids(index)
@@ -15,6 +15,7 @@ module Enjine
15
15
  # #game_log for the whole game):
16
16
  # "spells" card ids of spells the player cast "life_gained" / "life_lost" totals
17
17
  # "spells_from" the zone each of those spells was cast from (CR 601.2a), in the same order
18
+ # "spells_as_cast" [types, subtypes, keywords, colors] of each of those spells as cast, in the same order
18
19
  # "lands_played" [card id, zone it was played from] of the lands the player played (CR 305.1)
19
20
  # "entered" [card id, types, subtypes] of permanents that entered under their control
20
21
  # "died" [card id, types] of their permanents put into a graveyard from the battlefield
@@ -198,9 +199,16 @@ module Enjine
198
199
  index = names.index(event.player)
199
200
  (turn_log(index)["spells"] ||= []) << event.card
200
201
  (turn_log(index)["spells_from"] ||= []) << ((spell = state.objects[event.object]) ? cast_origin(spell) : "hand")
202
+ (turn_log(index)["spells_as_cast"] ||= []) << spell_as_cast(spell, event.card) # Abilities::CostModifier "first"
201
203
  bump!(game_log(index), "spells", 1)
202
204
  end
203
205
 
206
+ # [types, subtypes, keywords, colors] of a spell as it was cast (CR 601.2a: the face cast).
207
+ def spell_as_cast(spell, card)
208
+ current = spell ? chars(spell) : catalog.fetch(card).printed_characteristics
209
+ [current.types, current.subtypes, current.keywords, current.colors].map { |list| list.map(&:to_s) }
210
+ end
211
+
204
212
  def life_recorded!(event)
205
213
  log = log_of(event.player)
206
214
  bump!(log, "life_gained", event.gain) if event.gain.positive? # CR 119.9
@@ -148,6 +148,7 @@ module Enjine
148
148
  prepare!(fresh) if to == :battlefield && data["enters"]["prepared"] # "enters prepared" (CR 723.3a)
149
149
  room_entered!(fresh, old) if to == :battlefield # CR 709.5d, 709.5h (Engine::Rooms)
150
150
  run_follow_ups!(data, "object" => fresh.id) # "exile it instead. When you do, ..." (Engine::FollowUps)
151
+ copy_follow_up!(fresh, data["enters"]) if to == :battlefield # "When you do, exile that card" (Engine::Copies)
151
152
  fresh
152
153
  end
153
154
 
@@ -246,6 +247,7 @@ module Enjine
246
247
  emit Events::ZoneChanged.new(card: definition.id, old_id: nil, new_id: obj.id, owner: name(controller),
247
248
  from: "none", to: "battlefield", reason: "create_token")
248
249
  prepare!(obj) if enters["prepared"] # CR 723.3a (Engine::Faces)
250
+ copy_follow_up!(obj, enters) # CR 603.12 (Engine::Copies)
249
251
  obj
250
252
  end
251
253
 
@@ -260,6 +262,14 @@ module Enjine
260
262
  definition
261
263
  end
262
264
 
265
+ # An instruction to draw `count` cards (CR 121.2): "if you would draw one or more cards" replacements apply
266
+ # once to it (Replacements.drawing_cards!, CR 614.11), then the cards are drawn one at a time.
267
+ def draw_cards!(index, count)
268
+ return unless count.positive?
269
+
270
+ propose("draw_cards", { "player" => index, "count" => count }).data["count"].times { draw!(index) }
271
+ end
272
+
263
273
  # CR 121.2: one card at a time. A replacement may turn one draw into several (CR 614.11); those
264
274
  # draws are the modified event, so the replacement that made them doesn't apply again (CR 614.5).
265
275
  def draw!(index, applied: [])