enjine 0.4.1 → 0.6.0

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 (158) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +196 -1
  3. data/README.md +12 -3
  4. data/SUPPORTED.md +73 -38
  5. data/docs/ARCHITECTURE.md +7 -2
  6. data/docs/MECHANICS_COVERAGE.md +10 -8
  7. data/docs/guides/api.md +2 -1
  8. data/docs/guides/card-data-format.md +146 -9
  9. data/docs/plans/dsl-gaps.md +23 -0
  10. data/docs/reference/abilities.md +299 -25
  11. data/docs/reference/costs.md +59 -6
  12. data/docs/reference/decisions.md +7 -1
  13. data/docs/reference/effects.md +200 -27
  14. data/docs/reference/filters.md +30 -3
  15. data/docs/reference/keywords.md +58 -2
  16. data/docs/reference/subtypes.md +18 -0
  17. data/docs/reference/triggers.md +94 -14
  18. data/docs/reference/types.md +20 -0
  19. data/lib/enjine/actions/play_land.rb +3 -1
  20. data/lib/enjine/actions/special_action.rb +4 -0
  21. data/lib/enjine/actions/turn_face_up.rb +25 -0
  22. data/lib/enjine/actions/unlock.rb +23 -0
  23. data/lib/enjine/card_definition.rb +54 -15
  24. data/lib/enjine/card_face_down.rb +31 -0
  25. data/lib/enjine/card_faces.rb +4 -2
  26. data/lib/enjine/card_rooms.rb +86 -0
  27. data/lib/enjine/catalog.rb +9 -3
  28. data/lib/enjine/cli/text.rb +11 -3
  29. data/lib/enjine/color_identity.rb +34 -1
  30. data/lib/enjine/decisions/casting.rb +6 -3
  31. data/lib/enjine/decisions/combat.rb +4 -2
  32. data/lib/enjine/decisions/damage_order.rb +18 -0
  33. data/lib/enjine/engine/ability_layers.rb +14 -1
  34. data/lib/enjine/engine/casting/alt_casting.rb +45 -5
  35. data/lib/enjine/engine/casting/cast_choices.rb +21 -2
  36. data/lib/enjine/engine/casting/casting.rb +42 -29
  37. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  38. data/lib/enjine/engine/casting/costs.rb +8 -1
  39. data/lib/enjine/engine/casting/payment.rb +47 -9
  40. data/lib/enjine/engine/casting/permissions.rb +19 -17
  41. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  42. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  43. data/lib/enjine/engine/characteristics.rb +11 -11
  44. data/lib/enjine/engine/combat.rb +45 -14
  45. data/lib/enjine/engine/copies.rb +12 -4
  46. data/lib/enjine/engine/crimes.rb +46 -0
  47. data/lib/enjine/engine/damage.rb +85 -1
  48. data/lib/enjine/engine/entering.rb +36 -2
  49. data/lib/enjine/engine/face_down.rb +12 -3
  50. data/lib/enjine/engine/face_down_permanents.rb +108 -0
  51. data/lib/enjine/engine/faces.rb +20 -5
  52. data/lib/enjine/engine/follow_ups.rb +4 -1
  53. data/lib/enjine/engine/mana_sources.rb +18 -3
  54. data/lib/enjine/engine/options_memo.rb +140 -0
  55. data/lib/enjine/engine/permanent_designations.rb +29 -0
  56. data/lib/enjine/engine/resolution.rb +71 -6
  57. data/lib/enjine/engine/rooms.rb +86 -0
  58. data/lib/enjine/engine/rules.rb +6 -4
  59. data/lib/enjine/engine/state_based_actions.rb +25 -4
  60. data/lib/enjine/engine/triggers.rb +25 -20
  61. data/lib/enjine/engine/turn_history.rb +43 -5
  62. data/lib/enjine/engine/turn_structure.rb +1 -0
  63. data/lib/enjine/engine/zones.rb +37 -8
  64. data/lib/enjine/engine.rb +5 -1
  65. data/lib/enjine/events.rb +11 -0
  66. data/lib/enjine/frames.rb +5 -2
  67. data/lib/enjine/fuzz.rb +3 -0
  68. data/lib/enjine/game.rb +3 -1
  69. data/lib/enjine/mana.rb +3 -0
  70. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  71. data/lib/enjine/mechanics/abilities/cost_changes.rb +32 -10
  72. data/lib/enjine/mechanics/abilities/damage_replacements.rb +137 -65
  73. data/lib/enjine/mechanics/abilities/designated.rb +57 -0
  74. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  75. data/lib/enjine/mechanics/abilities/life_replacements.rb +74 -0
  76. data/lib/enjine/mechanics/abilities/mana_ability.rb +10 -4
  77. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -20
  78. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  79. data/lib/enjine/mechanics/abilities/stack_abilities.rb +12 -7
  80. data/lib/enjine/mechanics/abilities/static.rb +19 -6
  81. data/lib/enjine/mechanics/card_spec.rb +63 -11
  82. data/lib/enjine/mechanics/costs/base.rb +68 -9
  83. data/lib/enjine/mechanics/costs/behold.rb +28 -5
  84. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  85. data/lib/enjine/mechanics/costs/collect_evidence.rb +60 -0
  86. data/lib/enjine/mechanics/costs/exile_permanent.rb +41 -0
  87. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  88. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  89. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  90. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  91. data/lib/enjine/mechanics/effects/base.rb +36 -7
  92. data/lib/enjine/mechanics/effects/become.rb +29 -12
  93. data/lib/enjine/mechanics/effects/choose_cards.rb +44 -14
  94. data/lib/enjine/mechanics/effects/copy.rb +58 -21
  95. data/lib/enjine/mechanics/effects/counters.rb +18 -6
  96. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  97. data/lib/enjine/mechanics/effects/delayed_triggers.rb +13 -6
  98. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  99. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  100. data/lib/enjine/mechanics/effects/library.rb +76 -18
  101. data/lib/enjine/mechanics/effects/may.rb +4 -2
  102. data/lib/enjine/mechanics/effects/pay.rb +27 -10
  103. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  104. data/lib/enjine/mechanics/effects/search.rb +34 -6
  105. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  106. data/lib/enjine/mechanics/filters/any_target.rb +6 -3
  107. data/lib/enjine/mechanics/filters/base.rb +36 -17
  108. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  109. data/lib/enjine/mechanics/filters/permanents.rb +7 -0
  110. data/lib/enjine/mechanics/filters/stack.rb +14 -8
  111. data/lib/enjine/mechanics/keywords/alternative_costs.rb +80 -22
  112. data/lib/enjine/mechanics/keywords/cards_have.rb +67 -0
  113. data/lib/enjine/mechanics/keywords/craft.rb +132 -0
  114. data/lib/enjine/mechanics/keywords/cycling.rb +46 -7
  115. data/lib/enjine/mechanics/keywords/extort.rb +2 -0
  116. data/lib/enjine/mechanics/keywords/face_down.rb +165 -0
  117. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  118. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  119. data/lib/enjine/mechanics/keywords/impending.rb +75 -0
  120. data/lib/enjine/mechanics/keywords/increment.rb +2 -0
  121. data/lib/enjine/mechanics/keywords/infinity.rb +46 -0
  122. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  123. data/lib/enjine/mechanics/keywords/miracle.rb +142 -0
  124. data/lib/enjine/mechanics/keywords/ninjutsu.rb +101 -0
  125. data/lib/enjine/mechanics/keywords/offspring.rb +48 -0
  126. data/lib/enjine/mechanics/keywords/persist_and_undying.rb +42 -0
  127. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  128. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  129. data/lib/enjine/mechanics/keywords/split_second.rb +29 -0
  130. data/lib/enjine/mechanics/keywords/storm_and_cascade.rb +5 -0
  131. data/lib/enjine/mechanics/keywords/void.rb +34 -0
  132. data/lib/enjine/mechanics/linked.rb +33 -3
  133. data/lib/enjine/mechanics/mana_spent.rb +1 -1
  134. data/lib/enjine/mechanics/selector.rb +62 -18
  135. data/lib/enjine/mechanics/subtypes/case.rb +68 -0
  136. data/lib/enjine/mechanics/triggers/base.rb +13 -4
  137. data/lib/enjine/mechanics/triggers/casting.rb +15 -9
  138. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  139. data/lib/enjine/mechanics/triggers/crime.rb +28 -0
  140. data/lib/enjine/mechanics/triggers/damage.rb +33 -18
  141. data/lib/enjine/mechanics/triggers/draw_and_discard.rb +19 -6
  142. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  143. data/lib/enjine/mechanics/triggers/rooms.rb +49 -0
  144. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +20 -9
  145. data/lib/enjine/mechanics/triggers/zone_changes.rb +24 -9
  146. data/lib/enjine/mechanics/types/battle.rb +130 -0
  147. data/lib/enjine/mechanics/values.rb +84 -30
  148. data/lib/enjine/replacements.rb +21 -2
  149. data/lib/enjine/rules_monitor.rb +56 -71
  150. data/lib/enjine/snapshot/deep_copy.rb +23 -0
  151. data/lib/enjine/snapshot/player_checks.rb +10 -2
  152. data/lib/enjine/snapshot.rb +2 -1
  153. data/lib/enjine/state.rb +2 -2
  154. data/lib/enjine/verify.rb +10 -3
  155. data/lib/enjine/version.rb +1 -1
  156. data/lib/enjine/view.rb +50 -14
  157. data/lib/enjine.rb +1 -1
  158. metadata +34 -1
@@ -36,12 +36,18 @@ module Enjine
36
36
  # Accepts an id ("lightning_bolt") or a display name ("Lightning Bolt"). Ids hit an exact
37
37
  # lookup; only names pay for slugging (Unicode normalization), so the engine's hot path stays cheap.
38
38
  def fetch(ref)
39
- @definitions[ref] || @faces[ref] ||
39
+ @definitions[ref] || @faces[ref] || CardDefinition::FaceDownCards.fetch(ref) ||
40
40
  @definitions.fetch(CardDefinition.slug(ref)) { raise KeyError, "unknown card #{ref.inspect}" }
41
41
  end
42
42
 
43
- def [](ref) = @definitions[ref] || @faces[ref] || @definitions[CardDefinition.slug(ref)]
44
- def include?(ref) = @definitions.key?(ref) || @faces.key?(ref) || @definitions.key?(CardDefinition.slug(ref))
43
+ # Face-down characteristics (CardDefinition::FaceDownCards) are known to every catalog without being listed in it.
44
+ def [](ref) = @definitions[ref] || @faces[ref] || CardDefinition::FaceDownCards.fetch(ref) || @definitions[CardDefinition.slug(ref)]
45
+
46
+ def include?(ref)
47
+ @definitions.key?(ref) || @faces.key?(ref) || CardDefinition::FaceDownCards.id?(ref) ||
48
+ @definitions.key?(CardDefinition.slug(ref))
49
+ end
50
+
45
51
  def ids = @definitions.keys
46
52
  def size = @definitions.size
47
53
  def each(&) = @definitions.each_value(&)
@@ -139,6 +139,8 @@ module Enjine
139
139
  when "assign_damage" then " — #{name_of(decision.details["attacker"])}: #{decision.details["remaining"]} damage left"
140
140
  when "choose_target" then " — target ##{decision.details["index"] + 1}"
141
141
  when "commander_zone" then " — #{name_of(decision.details["object"])} (your commander)"
142
+ when "damage_order"
143
+ " — damage #{decision.details["hit"].split(">").map { name_of(it) }.join(" → ")}"
142
144
  when "choose_target_count" then " — how many for target ##{decision.details["index"] + 1}"
143
145
  else ""
144
146
  end
@@ -161,22 +163,24 @@ module Enjine
161
163
  when "pay_mana"
162
164
  "Pay {#{opt[:mana]}} from mana pool#{" (restricted)" if opt[:restricted]}#{" (made by an artifact)" if opt[:from]}"
163
165
  when "target" then "Target #{name_of(opt[:target])}"
164
- when "cost" then "Use #{name_of(opt[:object])} to pay the cost"
166
+ when "cost" then opt[:creature_type] ? "Choose #{opt[:creature_type]}" : "Use #{name_of(opt[:object])} to pay the cost"
165
167
  when "behold" then "Behold #{name_of(opt[:object])}"
166
168
  when "pay" then opt[:cost] ? "Pay: #{opt[:cost]}" : "Pay"
167
169
  when "cost_option" then @game.pending_decision.details["costs"][opt[:option]]
168
170
  when "cancel" then "Cancel (rewind this cast/activation)"
169
- when "attack" then "Attack #{name_of(opt[:target])} with #{name_of(opt[:object])}"
171
+ when "attack" then "Attack #{name_of(opt[:target])}#{" with #{name_of(opt[:object])}" if opt[:object]}"
170
172
  when "block" then "Block #{name_of(opt[:attacker])} with #{name_of(opt[:object])}"
171
173
  when "assign" then "Assign 1 damage to #{name_of(opt[:object])}"
172
174
  when "done" then "Done"
173
175
  when "source" then "Choose #{name_of(opt[:object])} as the source"
176
+ when "order" then "Apply #{opt[:steps].join(", then ")} (#{opt[:amount]} damage)"
174
177
  when "devour" then "Devour #{name_of(opt[:object])}"
175
178
  when "discard", "bottom", "find" then "#{opt[:type].capitalize} #{name_of(opt[:object])}"
176
179
  when "keep" then "Keep hand"
177
180
  when "call" then "Call #{opt[:call]}"
178
181
  when "mulligan" then "Mulligan"
179
182
  when "play", "draw" then "#{opt[:type].capitalize} first"
183
+ when "card_name", "name" then "Name #{opt[:card_name] || opt[:name]}"
180
184
  else opt.inspect
181
185
  end
182
186
  end
@@ -234,6 +238,7 @@ module Enjine
234
238
  when "trigger_removed" then "#{card_name(ev["card"])}'s triggered ability is removed (#{ev["reason"]})"
235
239
  when "ability_countered" then "#{card_name(ev["card"])}'s ability is countered"
236
240
  when "spell_copied" then "#{ev["player"]} copies #{card_name(ev["card"])}#{targets(ev["targets"])}"
241
+ when "targets_changed" then "#{name_of(ev["object"])} has new targets: #{ev["targets"].map { name_of(it) }.join(", ")}"
237
242
  when "x_announced" then "#{ev["player"]} announces X = #{ev["value"]}"
238
243
  when "payment_finished" then "#{ev["player"]} #{ev["outcome"]}"
239
244
  when "attached" then "#{name_of(ev["object"])} is attached to #{name_of(ev["to"])}"
@@ -258,7 +263,9 @@ module Enjine
258
263
  when "speed_changed" then "#{ev["player"]}: speed #{ev["from"]} → #{ev["to"]}"
259
264
  when "coin_flipped"
260
265
  "#{ev["player"]} flips #{ev["heads"] ? "heads" : "tails"}#{{ true => " and wins", false => " and loses" }[ev["won"]]}"
261
- when "keyword_action" then "#{ev["player"]} #{ev["action"].to_s.tr("_", " ")}#{" #{ev["amount"]}" if ev["amount"]}"
266
+ when "keyword_action"
267
+ verb = ev["action"] == "give_gift" ? "gives a gift" : ev["action"].to_s.tr("_", " ")
268
+ "#{ev["player"]} #{verb}#{" #{ev["amount"]}" if ev["amount"]}"
262
269
  else "#{ev["type"]}: #{ev.except("type")}"
263
270
  end
264
271
  end
@@ -280,6 +287,7 @@ module Enjine
280
287
  when "sba_lethal_damage" then "#{what} dies (lethal damage)"
281
288
  when "sba_toughness" then "#{what} dies (0 toughness)"
282
289
  when "sba_loyalty" then "#{what} is put into the graveyard (0 loyalty)"
290
+ when "sba_defense" then "#{what} is put into the graveyard (0 defense)"
283
291
  when "countered" then "#{what} is countered"
284
292
  when "commander" then "#{ev["owner"]} puts #{what} into the command zone"
285
293
  when "mulligan_bottom" then "#{ev["owner"]} puts #{what} on the bottom of their library (mulligan)"
@@ -9,6 +9,9 @@ module Enjine
9
9
  module ColorIdentity
10
10
  SKIPPED_KEYS = %w[name rules_text rarity printing color_identity].freeze
11
11
  BASIC_LAND_COLORS = { plains: :W, island: :U, swamp: :B, mountain: :R, forest: :G }.freeze
12
+ # A mana ability ({"mana": {...}}) or an add_mana effect: what it adds is written in its own keys.
13
+ MANA_KEYS = %w[mana add_mana].freeze
14
+ COLOR_WORDS = { "white" => :W, "blue" => :U, "black" => :B, "red" => :R, "green" => :G }.freeze
12
15
 
13
16
  module_function
14
17
 
@@ -28,11 +31,41 @@ module Enjine
28
31
  # The colors named by every mana symbol in the card's data, hybrid and monocolored hybrid symbols included.
29
32
  def symbols(node)
30
33
  case node
31
- when Hash then node.flat_map { |key, value| SKIPPED_KEYS.include?(key) ? [] : symbols(value) }
34
+ when Hash then node.flat_map { |key, value| entry_symbols(key, value) }
32
35
  when Array then node.flat_map { symbols(it) }
33
36
  when String then node.scan(Mana::SYMBOL).flatten.flat_map { it.scan(/[WUBRG]/).map(&:to_sym) }
34
37
  else []
35
38
  end
36
39
  end
40
+
41
+ def entry_symbols(key, value)
42
+ return [] if SKIPPED_KEYS.include?(key)
43
+ return mana_symbols(value) if MANA_KEYS.include?(key) && value.is_a?(Hash)
44
+
45
+ symbols(value)
46
+ end
47
+
48
+ # Mana a card adds counts by the symbols its text would print (CR 903.4): `produce`, and the colors of a choice
49
+ # among some ("Add {B} or {G}": `"color": "any_one", "colors": ["B", "G"]`). Mana "of the chosen color" prints
50
+ # no symbol, so it adds nothing: neither `"color": "chosen"` nor one fixed color gated on the color chosen for
51
+ # the permanent (a Thriving land's {"produce": "{W}", "only_if": {"chosen": "white"}}).
52
+ def mana_symbols(ability)
53
+ rest = symbols(ability.except("produce", "colors"))
54
+ return rest if chosen_color?(ability)
55
+
56
+ choice = %w[any_one any].include?(ability["color"]) ? Array(ability["colors"]).map { it.to_s.to_sym } : []
57
+ rest + symbols(ability["produce"]) + (choice & Mana::COLORS)
58
+ end
59
+
60
+ # Whether the mana is the color chosen for the permanent: only_if {"chosen": <color word>} naming every color
61
+ # it produces.
62
+ def chosen_color?(ability)
63
+ condition = ability["only_if"]
64
+ color = condition.is_a?(Hash) && COLOR_WORDS[condition["chosen"]]
65
+ return false unless color
66
+
67
+ produced = symbols(ability["produce"])
68
+ !produced.empty? && produced.all?(color)
69
+ end
37
70
  end
38
71
  end
@@ -5,8 +5,9 @@ module Enjine
5
5
  CANCEL = { type: "cancel" }.freeze
6
6
 
7
7
  # CR 734.1: a cast or activation can be rewound ("cancel") until something irreversible has been
8
- # paid (Engine::Payment#cancellable?); a triggered ability being put on the stack never can.
9
- def self.with_cancel(engine, options) = engine.cancellable? ? options + [CANCEL] : options
8
+ # paid (Engine::Payment#cancellable?), and also after that when no other choice is left (Engine::Payment#stuck?:
9
+ # a decision never has no option); a triggered ability being put on the stack never can.
10
+ def self.with_cancel(engine, options) = engine.cancellable? || engine.stuck?(options) ? options + [CANCEL] : options
10
11
 
11
12
  # CR 601.2b / 603.3c: choose a mode of a modal spell or ability, one per decision.
12
13
  class ChooseMode < Base
@@ -162,7 +163,9 @@ module Enjine
162
163
  'pool_sources[i] names), `{type: "activate_mana", object: id, ability: ref}` ' \
163
164
  '(plus `mana: "{G}{G}"` when the mana is chosen) taps a source, `{type: "cancel"}` ' \
164
165
  "rewinds (or declines a payment asked for while resolving). Cancel isn't offered once a mana ability " \
165
- "with a cost other than {T} (a Treasure) has been activated. `{type: \"convoke\", object: id}` taps a " \
166
+ "with a cost other than {T} (a Treasure) has been activated, unless the cost can no longer be paid: then " \
167
+ "it is the only option, and rewinds keeping the mana abilities' mana in the pool (CR 734.1). " \
168
+ "`{type: \"convoke\", object: id}` taps a " \
166
169
  "creature to pay for {1} or one mana of its color (a spell with convoke); `{type: \"improvise\", object: id}` " \
167
170
  "taps an artifact to pay for {1} (a spell with improvise); `{type: \"waterbend\", object: id}` taps " \
168
171
  "an artifact or creature to pay {1} of a waterbend cost. `remaining` shows what is left to pay."
@@ -14,11 +14,13 @@ module Enjine
14
14
  end
15
15
 
16
16
  def self.options(engine, _pending)
17
- targets = engine.attack_targets
18
17
  legal = engine.attack_declaration_legal?
19
18
  done = engine.unmet_attack_requirements.empty? && legal ? [DONE] : [] # CR 508.1c-d
20
19
  withdraw = legal ? [] : engine.attackers.keys.map { { type: "withdraw", object: it } }
21
- done + engine.attack_candidates.flat_map { |id| targets.map { { type: "attack", object: id, target: it } } } + withdraw
20
+ attacks = engine.attack_candidates.flat_map do |id|
21
+ engine.attack_targets_for(id).map { { type: "attack", object: id, target: it } }
22
+ end
23
+ done + attacks + withdraw
22
24
  end
23
25
 
24
26
  def self.submit(engine, _pending, option)
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Decisions
5
+ # CR 616.1: the affected player orders the replacement and prevention effects that apply to one damage event
6
+ # (`hit`: "source>recipient"), asked only when orders lead to different results; one choice per result.
7
+ class DamageOrder < Base
8
+ def self.doc
9
+ "Order the effects that apply to damage dealt to you or a permanent you control (CR 616.1): submit one of " \
10
+ '`{type: "order", order: [effect keys], steps: [labels], amount: final damage}` exactly as listed.'
11
+ end
12
+
13
+ def self.options(_engine, pending) = pending["choices"].map { it.transform_keys(&:to_sym) }
14
+ def self.submit(engine, pending, option) = engine.damage_order_answer!(pending, option)
15
+ end
16
+ register("damage_order", DamageOrder)
17
+ end
18
+ end
@@ -5,6 +5,14 @@ module Enjine
5
5
  # Layers 5 and 6 of the layer pass (Engine::Characteristics#apply_layers): colors, and abilities gained
6
6
  # and lost in timestamp order (CR 613.1e-f, 613.7).
7
7
  module AbilityLayers
8
+ # What a static ability matches a permanent on in the layer pass: characteristics, counters and token-ness,
9
+ # plus combat and tapped status (not characteristics, so reading them never depends on the pass, CR 506.4,
10
+ # 613.8).
11
+ def facts(obj, current)
12
+ status = { "attacking" => attackers.key?(obj.id), "blocking" => state.blockers.key?(obj.id), "tapped" => obj.tapped }
13
+ Mechanics::Filters::Facts.new(chars: current, counters: obj.counters, token: token?(obj), status: status)
14
+ end
15
+
8
16
  # Layer 5 (CR 613.1e): effects that set colors, in timestamp order. Layer 6 (CR 613.1f): keyword counters
9
17
  # (CR 122.1b), keywords and abilities from static abilities and resolved effects, and "loses all
10
18
  # abilities", applied in timestamp order (CR 613.7): a removal takes away what the object had then, and
@@ -18,6 +26,8 @@ module Enjine
18
26
  changes = Mechanics::Counters.keywords(obj.counters).map { |kw| [counter_timestamp(obj, kw.to_s), 0, [:keywords, [kw]]] }
19
27
  # A creature cast with suspend has haste while its caster controls it (CR 702.62a); since it was cast.
20
28
  changes << [0, 0, [:keywords, [:haste]]] if obj.memory["haste_while_controlled_by"] == obj.controller
29
+ # Riot: "if you don't, it gains haste" as it entered (CR 702.136a), an effect with that timestamp.
30
+ changes << [timestamp_of(obj), 0, [:keywords, [:haste]]] if obj.memory["riot_haste"]
21
31
  statics.each do |source, ability|
22
32
  next unless ability.ability_changes? && ability.affects?(obj, source, facts(obj, base))
23
33
 
@@ -94,9 +104,12 @@ module Enjine
94
104
  end
95
105
 
96
106
  # Abilities a resolved effect grants (layer 6, CR 613.1f): the effect's card holds them under its ref.
107
+ # What was chosen as the effect resolved is bound into them ("hexproof from that color", CR 607.2d).
97
108
  def effect_granted_instances(effect)
109
+ chosen = effect["chosen"]
98
110
  catalog.fetch(effect["card"]).effect_granted(effect["ref"]).map do |inst|
99
- AbilityInstance.new(ref: "granted:#{effect["card"]}:#{inst.ref}", ability: inst.ability)
111
+ ability = chosen && inst.ability.respond_to?(:with_chosen) ? inst.ability.with_chosen(chosen) : inst.ability
112
+ AbilityInstance.new(ref: "granted:#{effect["card"]}:#{inst.ref}", ability: ability)
100
113
  end
101
114
  end
102
115
 
@@ -21,8 +21,21 @@ module Enjine
21
21
 
22
22
  # ---- methods ------------------------------------------------------------------------------
23
23
 
24
- # The cards in a hand with an alternative cost (only those can be cast from it with a method).
25
- def alt_cost_hand(player) = player.hand.select { |id| chars(id).abilities.any? { it.ability.kind == :alternative_cost } }
24
+ # The cards in `index`'s hand with an alternative cost (only those can be cast from it with a method): all of
25
+ # them while a permanent of theirs gives cards in their hand one (Abilities::CardsHave).
26
+ def alt_cost_hand(index)
27
+ hand = player(index).hand
28
+ return hand if granted_alt_zones(index).include?(:hand)
29
+
30
+ own = own_abilities_only?
31
+ hand.select do |id|
32
+ obj = object(id)
33
+ # no face with an alternative cost (CardDefinition#plays_itself?): a quick no (Casting#printed_faces_only?)
34
+ next false if printed_faces_only?(obj, own) && !card_off_board(obj.card)[:plays_itself]
35
+
36
+ chars(obj).abilities.any? { it.ability.kind == :alternative_cost }
37
+ end
38
+ end
26
39
 
27
40
  # A card in a graveyard or library, not a copy, with no face that has an ability to play itself
28
41
  # (CardDefinition#plays_itself?) has no play method (Engine::Permissions#play_methods): a quick no for most candidates.
@@ -39,9 +52,9 @@ module Enjine
39
52
 
40
53
  own = face_up(obj.id) { chars(obj).abilities }.filter_map do |inst|
41
54
  ability = inst.ability
42
- ability.method_for(inst.ref) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
55
+ ability.method_for(inst.ref, engine: self, obj: obj) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
43
56
  end
44
- own + warped_methods(index, obj) + plotted_methods(obj)
57
+ own + granted_alt_methods(index, obj) + warped_methods(index, obj) + plotted_methods(obj)
45
58
  end
46
59
 
47
60
  # CR 702.170d: a plotted card may be cast without paying its mana cost during its owner's main phase while
@@ -51,6 +64,33 @@ module Enjine
51
64
  turn && state.turn > turn ? [{ "via" => "plotted", "play" => "cast", "alt" => Permissions::FREE, "sorcery" => true }] : []
52
65
  end
53
66
 
67
+ GRANTED = "cards_have:"
68
+
69
+ # Alternative costs a permanent `index` controls gives their cards (Abilities::CardsHave, CR 611.3a): the ref
70
+ # "cards_have:<permanent>:<ref>" names the granting ability.
71
+ def granted_alt_methods(index, obj)
72
+ return [] if obj.zone == :outside
73
+
74
+ board_abilities(:cards_have).filter_map do |perm, grant|
75
+ next unless perm.controller == index && grant.functions?(self, obj, index)
76
+
77
+ inst = chars(perm).abilities.find { it.ability.equal?(grant) }
78
+ grant.granted.method_for("#{GRANTED}#{perm.id}:#{inst.ref}", engine: self, obj: obj)
79
+ end
80
+ end
81
+
82
+ # The zones in which permanents `index` controls give cards an alternative cost (Abilities::CardsHave).
83
+ def granted_alt_zones(index) = board_abilities(:cards_have).filter_map { |perm, grant| grant.zone if perm.controller == index }
84
+
85
+ # The alternative cost ability a method's ref names: the card's own, or one a permanent grants.
86
+ def alt_cost_ability(obj, ref)
87
+ # a spell cast face down has its card's alternative cost (morph, disguise), not its face-down abilities (CR 708.4)
88
+ return (face_down_object?(obj) ? catalog.fetch(own_card(obj)) : chars(obj)).ability(ref) unless ref.start_with?(GRANTED)
89
+
90
+ perm, inst = ref.delete_prefix(GRANTED).split(":", 2)
91
+ state.objects[perm] && chars(perm).ability(inst)&.granted
92
+ end
93
+
54
94
  # CR 702.185a: "Its owner may cast this card after the current turn has ended for as long as it remains
55
95
  # exiled." The exiled card remembers the turn it was warped in.
56
96
  def warped_methods(_index, obj)
@@ -72,7 +112,7 @@ module Enjine
72
112
  # The non-mana parts of the alternative cost being paid (a list of costs, CR 601.2h).
73
113
  def alt_cost_parts(obj, method)
74
114
  ref = method&.dig("alt", "ref") or return []
75
- chars(obj).ability(ref).choosing_costs
115
+ alt_cost_ability(obj, ref)&.choosing_costs || []
76
116
  end
77
117
 
78
118
  def alt_parts_payable?(obj, method) = alt_cost_parts(obj, method).all? { it.payable?(self, obj) }
@@ -8,7 +8,7 @@ module Enjine
8
8
  module CastChoices
9
9
  # ---- additional costs of spells (CR 601.2b, 601.2f, 702.33) ----------------------------
10
10
 
11
- def spell_cost_abilities(obj, kind) = chars(obj).abilities.map(&:ability).select { it.kind == kind }
11
+ def spell_cost_abilities(obj, kind) = abilities_of_kind(chars(obj), kind)
12
12
 
13
13
  # CR 601.2f / 118.3: the spell's mandatory non-mana additional costs can be paid.
14
14
  def additional_costs_payable?(obj) = spell_cost_abilities(obj, :additional_cost).all? { it.payable?(self, obj) }
@@ -40,10 +40,22 @@ module Enjine
40
40
  obj = object(ctx["object"])
41
41
  spell = spell_ability_of(obj)
42
42
  kick = kicked_castable?(ctx["player"], obj)
43
- plain = ability_targetable?(spell, ctx["player"], obj.id)
43
+ plain = !ctx["flash_by_cost"] && ability_targetable?(spell, ctx["player"], obj.id) # CR 601.3c
44
44
  (kick ? [{ type: "kick" }] : []) + (plain ? [{ type: "no_kick" }] : [])
45
45
  end
46
46
 
47
+ # CR 601.3c: "you may cast this spell as though it had flash if you [pay an optional additional cost]".
48
+ def flash_by_cost?(obj)
49
+ optional = spell_cost_abilities(obj, :kicker).first
50
+ optional.respond_to?(:flash?) && optional.flash?
51
+ end
52
+
53
+ # Whether casting `card` now relies on that cost rather than on its own timing.
54
+ def flash_cost_needed?(index, card)
55
+ c = chars(card)
56
+ !c.type?(:instant) && !c.keyword?(:flash) && !sorcery_timing?(index) && flash_by_cost?(card)
57
+ end
58
+
47
59
  # Whether the spell could be cast kicked: kicker payable, the kicked total affordable and its
48
60
  # kicked targets (or normal ones) available.
49
61
  def kicked_castable?(index, obj)
@@ -209,6 +221,13 @@ module Enjine
209
221
  # The object a cost is paid for: the ability's source, or the spell itself.
210
222
  def cost_payer(ctx) = object(ctx["kind"] == "ability" ? ctx["source"] : ctx["object"])
211
223
 
224
+ # The spell or ability whose costs are being paid now: the one being cast or activated, else the one resolving
225
+ # (a cost paid while it resolves, CR 118.12). It remembers what its costs chose (a creature type, cards exiled).
226
+ def cost_holder
227
+ id = casting&.[]("object") || state.frames.rfind { it["type"] == "resolve" }&.[]("object")
228
+ id && state.objects[id]
229
+ end
230
+
212
231
  def cost_entries(ctx, index) = (ctx["paid"] || []).select { it["cost"] == index }
213
232
 
214
233
  def cost_choice_candidates
@@ -14,9 +14,12 @@ module Enjine
14
14
  obj = object(id)
15
15
  defn = definition(obj)
16
16
  return false unless defn.castable?
17
- return false unless defn.instant_speed? || sorcery_timing?(index)
17
+ return false if defn.layout == "room" && defn.face_index.zero? # CR 709.3: a Room is cast as one of its doors
18
+ return false if mana_out_of_reach?(index, obj)
19
+ return false unless defn.instant_speed? || sorcery_timing?(index) || flash_by_cost?(obj)
18
20
  return false if cast_forbidden?(index, obj) # CR 101.2 (Engine::Rules)
19
21
  return false unless additional_costs_payable?(obj) # CR 601.2f: e.g. "sacrifice a creature"
22
+ return kicked_castable?(index, obj) if flash_cost_needed?(index, obj) # CR 601.3c (Engine::CastChoices)
20
23
 
21
24
  if ability_targetable?(defn.spell_ability, index, id) && # CR 601.2b: some way of paying its costs (Engine::CostOptions)
22
25
  cost_variant_affordable?(index, spell_cost_list(obj, false), obj, defn.mana_cost, nil, { "spell" => id }) do
@@ -28,25 +31,6 @@ module Enjine
28
31
  kicked_castable?(index, obj) # CR 702.33g: only the kicked spell has legal targets
29
32
  end
30
33
 
31
- # No effect gives a card off the battlefield an ability (CR 113.6b): each has only its own (and its copiable
32
- # values'), so the quick nos below hold.
33
- def own_abilities_only? = state.effects.none? { it["kind"] == "card_ability" }
34
-
35
- # A card that isn't a copy, none of whose faces has an activated ability functioning from the zone it's in
36
- # (CardDefinition#activation_zones, CR 113.6): nothing of it can be activated there.
37
- def no_activations_here?(obj)
38
- !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
39
- !card_off_board(obj.card)[:activation_zones].include?(obj.zone)
40
- end
41
-
42
- # What a card's faces can do off the battlefield (CardDefinition#plays_itself?, #activation_zones), once per
43
- # card: printed facts that never change.
44
- def card_off_board(card)
45
- (@card_off_board ||= {})[card] ||= catalog.fetch(card).faces.then do |faces|
46
- { plays_itself: faces.any?(&:plays_itself?), activation_zones: faces.flat_map(&:activation_zones).uniq }
47
- end
48
- end
49
-
50
34
  def activatable?(index, id, ability_ref)
51
35
  obj = object(id)
52
36
  ability = chars(obj).ability(ability_ref)
@@ -54,6 +38,7 @@ module Enjine
54
38
  return false unless obj.zone == ability.zone # CR 113.6: e.g. cycling only from the hand (702.29a)
55
39
  return false if ability.sorcery_speed? && !sorcery_timing?(index)
56
40
  return false if activation_forbidden?(index, obj) # CR 602.5, 101.2 (Engine::Rules)
41
+ return false if Mechanics::Keywords::SplitSecond.active?(self) # CR 702.61b
57
42
  return false unless activation_allowed?(index, obj, ability_ref, ability) # CR 602.5b
58
43
 
59
44
  if (ability.kind == :loyalty) && (obj.loyalty_turn == state.turn || (loyalty(obj) + ability.loyalty_cost).negative?)
@@ -62,8 +47,9 @@ module Enjine
62
47
  end
63
48
 
64
49
  # CR 118.3, 601.2b: some way of paying its costs (Engine::CostOptions); waterbend: CR 701.67a
50
+ costs = granter_costs(ability.costs, AbilityLayers.granted_parts(ability_ref)&.last)
65
51
  ability_targetable?(ability, index, nil, id, ref: ability_ref) &&
66
- cost_variant_affordable?(index, ability.costs, obj, nil, needs_tap?(ability) ? id : nil, { "ability" => id }) do
52
+ cost_variant_affordable?(index, costs, obj, nil, needs_tap?(ability) ? id : nil, { "ability" => id }) do
67
53
  total_cost(index, it, ability: ability, source: id)
68
54
  end
69
55
  end
@@ -111,6 +97,14 @@ module Enjine
111
97
 
112
98
  def needs_tap?(ability) = ability.costs.any?(Mechanics::Costs::Tap)
113
99
 
100
+ # A granted ability's costs that name the granting permanent ("Tap Fishing Pole", CR 607.1a), bound to
101
+ # `granter` (the permanent whose static ability granted it).
102
+ def granter_costs(costs, granter)
103
+ return costs unless granter && costs.any? { it.respond_to?(:for_granter) }
104
+
105
+ costs.map { it.respond_to?(:for_granter) ? it.for_granter(granter) : it }
106
+ end
107
+
114
108
  # The spell ability of a spell (printed, CR 113.3a).
115
109
  def spell_ability_of(obj) = definition(obj).spell_ability
116
110
 
@@ -130,10 +124,12 @@ module Enjine
130
124
  "index" => state.zone_list(card.zone, card.owner).index(card_id) }
131
125
  origin["memory"] = card.memory.slice("face_down", "may_look") if face_down?(card) # turned face up (CR 406.3a)
132
126
  origin["memory"] = card.memory.slice("prepared_for") if card.memory["prepared_for"] # a prepare spell (CR 723.3c)
133
- obj = move!(card_id, :stack, controller: index, reason: "cast")
127
+ flash_cost = !via && !face && flash_cost_needed?(index, card) # CR 601.3c: the optional cost must be paid
128
+ obj = move!(card_id, :stack, controller: index, reason: "cast", face_down_as: method&.dig("alt", "face_down")) # CR 708.4
134
129
  turn_spell_face!(obj, face) # CR 712.8b, 716.3b, 721.3b
135
130
  extra = method ? { "method" => method } : {}
136
- extra["no_priority"] = true if %w[free resolving].include?(via) # cast while resolving (CR 608.2g)
131
+ extra["flash_by_cost"] = true if flash_cost
132
+ extra["no_priority"] = true if %w[free resolving].include?(via) || method&.[]("resolving") # cast while resolving (CR 608.2g)
137
133
  start_casting!(index, obj.id, "spell", origin: origin, extra: extra)
138
134
  end
139
135
 
@@ -221,13 +217,25 @@ module Enjine
221
217
  spec = casting_targets[target_slot(ctx)] # Engine::TargetCounts: a counted slot's list may be open
222
218
  taken = spec.respond_to?(:distinct_from) ? spec.distinct_from.flat_map { Array(ctx["targets"][it]) } : []
223
219
  taken += open_target_group(ctx)
224
- candidates = spec.candidates_for(self, ctx["player"], ctx["source"]).reject do
220
+ candidates = spec.candidates_for(self, ctx["player"], ctx["source"], ctx: x_target_context(ctx)).reject do
225
221
  it == ctx["object"] || taken.include?(it) || !targetable?(it, ctx["player"], ctx["source"],
226
222
  targeter: ctx["source"] || ctx["object"])
227
223
  end
228
224
  sharing_type(candidates, spec, ctx)
229
225
  end
230
226
 
227
+ # CR 601.2b-c: X is announced before targets are chosen, so "target ... with mana value X" reads the X of the
228
+ # spell or ability being cast (a triggered ability's: the cycling ability's X, CR 702.29c). Without an X the
229
+ # filter's own default context applies.
230
+ def x_target_context(ctx) = x_context(ctx["player"], ctx["source"], state.objects[ctx["object"]])
231
+
232
+ # The same as its targets are checked on resolution (CR 608.2b, Engine::Resolution#legal_targets).
233
+ def x_context(controller, source, obj)
234
+ return nil if obj&.x.nil?
235
+
236
+ Mechanics::EffectContext.new(controller, source, obj.id, [], [])
237
+ end
238
+
231
239
  # "Target permanents that share a card type" (`shares_type_with`, CR 205.2a): only candidates sharing one
232
240
  # with the earlier target.
233
241
  def sharing_type(candidates, spec, ctx)
@@ -248,14 +256,19 @@ module Enjine
248
256
  def choose_target!(ref)
249
257
  ctx = casting
250
258
  add_chosen_target!(ctx, ref)
251
- if ref
252
- queued = state.pending_triggers.size
253
- emit Events::TargetChosen.new(player: name(ctx["player"]), object: ctx["object"], target: ref)
254
- state.pending_triggers.drop(queued).each { it["memory"] = it["memory"].merge("targeted_by" => ctx["object"]) }
255
- end
259
+ became_target!(ctx["player"], ctx["object"], ref) if ref
256
260
  ask!(nil)
257
261
  end
258
262
 
263
+ # `ref` becomes a target of the spell or ability `object` controlled by `player`: as it's cast or put on the
264
+ # stack, when its targets change (CR 115.7) and when a copy is put on the stack with it (CR 707.10).
265
+ # Abilities that trigger then (ward, CR 702.21a) learn which spell or ability targeted it.
266
+ def became_target!(player, object, ref)
267
+ queued = state.pending_triggers.size
268
+ emit Events::TargetChosen.new(player: name(player), object: object, target: ref)
269
+ state.pending_triggers.drop(queued).each { it["memory"] = it["memory"].merge("targeted_by" => object) }
270
+ end
271
+
259
272
  # CR 601.2h-i / 602.2b: remaining costs are paid, the spell becomes cast.
260
273
  def finish_casting!
261
274
  ctx = casting
@@ -52,7 +52,9 @@ module Enjine
52
52
  # additional costs (and kicker's when kicked).
53
53
  def frame_cost_list(ctx)
54
54
  case ctx["kind"]
55
- when "ability" then stack_ability(object(ctx["object"])).costs
55
+ when "ability"
56
+ obj = object(ctx["object"])
57
+ granter_costs(stack_ability(obj).costs, obj.memory["granter"]) # "Tap Fishing Pole" (CR 607.1a)
56
58
  when "spell" then spell_cost_list(object(ctx["object"]), ctx["kicked"])
57
59
  else []
58
60
  end
@@ -35,8 +35,15 @@ module Enjine
35
35
  end
36
36
  end
37
37
 
38
- # [[permanent, CostModifier], ...] on the battlefield.
38
+ # [[permanent, CostModifier], ...] on the battlefield; once per decision while legal options are computed
39
+ # (Engine#options: the board holds still meanwhile).
39
40
  def cost_modifiers
41
+ return @options_memo[:cost_modifiers] ||= scan_cost_modifiers if @options_memo
42
+
43
+ scan_cost_modifiers
44
+ end
45
+
46
+ def scan_cost_modifiers
40
47
  state.battlefield.flat_map do |id|
41
48
  obj = object(id)
42
49
  chars(obj).abilities.filter_map { [obj, it.ability] if it.ability.kind == :cost_modifier }