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
@@ -10,7 +10,8 @@ module Enjine
10
10
  # sources tapped for it ("tapped"), so an unfinished payment can be rewound (CR 734.1). Once a
11
11
  # mana ability with a cost other than {T} has been activated (a Treasure's sacrifice), the payment
12
12
  # is "irreversible": it can't be cancelled any more, and only choices that keep the rest payable
13
- # are offered, so the player can't get stuck.
13
+ # are offered. Should it still have no choice left, it may be cancelled after all (#stuck?), keeping
14
+ # the mana abilities activated (#refund_payment!).
14
15
  module Payment
15
16
  # The payment in progress: the top frame (a cast or a pay frame while a casting decision is pending).
16
17
  def payment = state.frames.last
@@ -120,6 +121,7 @@ module Enjine
120
121
  frame["remaining"] = after_paying(frame["remaining"], slot)
121
122
  (frame["spent"] ||= []) << type # what was spent matters later (sunburst, CR 702.44a; 609.4b: its real type)
122
123
  (frame["spent_from"] ||= []) << entry["from"] if entry&.key?("from") # "if mana from a Treasure was spent"
124
+ (frame["refund"] ||= []) << { "mana" => type, (restricted ? "restricted" : "source") => entry }.compact # #refund_payment!
123
125
  emit Events::ManaPaid.new(player: name(frame["player"]), mana: "{#{type}}", object: frame["object"])
124
126
  ask!(nil)
125
127
  end
@@ -178,7 +180,9 @@ module Enjine
178
180
  end
179
181
 
180
182
  # A mana ability whose costs include more than {T} and mana (a sacrifice, life, a discard) can't be undone.
181
- def irreversible_mana_ability?(id, ref) = chars(id).ability(ref).costs.any? { !it.is_a?(Mechanics::Costs::Tap) && !it.mana? }
183
+ def irreversible_mana_ability?(id, ref)
184
+ chars(id).ability(ref).costs.any? { !it.is_a?(Mechanics::Costs::Tap) && !it.is_a?(Mechanics::Costs::TapGranter) && !it.mana? }
185
+ end
182
186
 
183
187
  def reserved_for_cost?(frame, id, ref)
184
188
  return true if id == payment_excluded_source(frame)
@@ -208,16 +212,21 @@ module Enjine
208
212
  else
209
213
  produced.each { pool[it] += 1 }
210
214
  end
211
- payable_with?(frame, remaining_cost(frame["remaining"]), pool, payment_reserved(frame) + [id], restricted: rest)
215
+ used = [id, tapped_granter(option[:ability], ability)].compact
216
+ payable_with?(frame, remaining_cost(frame["remaining"]), pool, payment_reserved(frame) + used, restricted: rest)
212
217
  end
213
218
 
214
219
  # CR 605.3: activating a mana ability while paying. One whose costs include more than {T} (a
215
- # sacrifice, life, a discard) can't be undone, so the payment stops being cancellable.
220
+ # sacrifice, life, a discard) can't be undone, so the payment stops being cancellable. Tapping the
221
+ # permanent that granted it can (CR 734.1: it is untapped with the source).
216
222
  def tap_for_payment!(id, ability_ref, mana = nil)
217
223
  frame = payment
218
224
  frame["irreversible"] = true if irreversible_mana_ability?(id, ability_ref)
225
+ granter = tapped_granter(ability_ref, chars(id).ability(ability_ref))
219
226
  activate_mana_ability!(frame["player"], id, ability_ref, mana)
220
227
  frame["tapped"] << id
228
+ frame["tapped"] << granter if granter
229
+ (frame["mana_tapped"] ||= []).push(*[id, granter].compact) # kept tapped by #refund_payment!
221
230
  ask!(nil)
222
231
  end
223
232
 
@@ -245,16 +254,42 @@ module Enjine
245
254
  # Undoes the mana abilities activated for the payment (CR 734.1): untaps their sources and restores
246
255
  # the pool. Abilities that triggered meanwhile didn't trigger (CR 734.1).
247
256
  def rewind_payment!(frame)
248
- frame["tapped"].select { state.objects.key?(it) }.each do |id|
249
- object(id).tapped = false
250
- emit Events::Untapped.new(object: id)
251
- end
257
+ return refund_payment!(frame) if frame["irreversible"]
258
+
259
+ untap_for_rewind!(frame["tapped"])
252
260
  player(frame["player"]).mana_pool = Mana::TYPES.to_h { |t| [t, frame["pool"].fetch(t.to_s, 0)] }
253
261
  player(frame["player"]).restricted_mana = Snapshot.deep_copy(frame["restricted"]) if frame["restricted"]
254
262
  player(frame["player"]).pool_sources = Snapshot.deep_copy(frame["pool_sources"]) if frame.key?("pool_sources")
255
263
  state.pending_triggers.select! { frame["triggers_before"].include?(it["id"]) }
256
264
  end
257
265
 
266
+ def untap_for_rewind!(ids)
267
+ ids.select { state.objects.key?(it) }.each do |id|
268
+ object(id).tapped = false
269
+ emit Events::Untapped.new(object: id)
270
+ end
271
+ end
272
+
273
+ # Rewinding an irreversible payment (one that can't be finished, #stuck?). CR 734.1 lets the player reverse the
274
+ # mana abilities activated meanwhile, but one with a cost such as life or a sacrifice can't be undone here, so
275
+ # none is: their sources stay tapped and their mana stays in the pool, and the mana spent on this payment goes
276
+ # back to the pool. What else it tapped (convoke, waterbend, a cost's choices) is untapped.
277
+ def refund_payment!(frame)
278
+ untap_for_rewind!(frame["tapped"] - frame.fetch("mana_tapped", []))
279
+ pl = player(frame["player"])
280
+ frame.fetch("refund", []).each do |spent|
281
+ next pl.restricted_mana << Snapshot.deep_copy(spent["restricted"]) if spent["restricted"]
282
+
283
+ pl.mana_pool[spent["mana"].to_sym] += 1
284
+ (pl.pool_sources ||= []) << Snapshot.deep_copy(spent["source"]) if spent["source"]
285
+ end
286
+ end
287
+
288
+ # Whether the payment or cost choice in progress has no legal choice left: it was made irreversible (CR 605.3a)
289
+ # and can't be finished. It can then still be rewound (CR 734.1, #refund_payment!), so a decision always has
290
+ # an option.
291
+ def stuck?(options) = options.empty? && !payment.nil? && payment["kind"] != "trigger"
292
+
258
293
  # ---- countering (CR 701.6) ----------------------------------------------------------------
259
294
 
260
295
  # CR 701.6a: a countered spell goes to its owner's graveyard; a countered ability ceases to exist.
@@ -326,7 +361,10 @@ module Enjine
326
361
  special = frame["special"]
327
362
  if outcome == "paid" && state.objects.key?(special["object"])
328
363
  obj = object(special["object"])
329
- chars(obj).ability(special["ability"]).special!(self, obj, index)
364
+ if special["unlock"] then unlock_door!(obj, special["unlock"], index) # CR 709.5e (Engine::Rooms)
365
+ elsif special["face_up"] then turn_face_up!(obj, index) # CR 116.2b (Engine::FaceDownPermanents)
366
+ else chars(obj).ability(special["ability"]).special!(self, obj, index)
367
+ end
330
368
  end
331
369
  action_taken!(index)
332
370
  :done
@@ -30,8 +30,8 @@ module Enjine
30
30
  BEAM_COST_TEXT = "Return a creature you control to its owner's hand"
31
31
  OUTSIDE = "outside:"
32
32
  # Permission effect fields copied into the play method (see Effects::PlayPermission); "alt" is an
33
- # alternative cost, {"cost" => "{2}"} (airbend, CR 701.65a, 118.9).
34
- RIDERS = %w[cost_increase any_mana_type alt exile_instead].freeze
33
+ # alternative cost, {"cost" => "{2}"} (airbend, CR 701.65a, 118.9); "during" and "waterbend": Engine::Waterbending.
34
+ RIDERS = %w[cost_increase any_mana_type alt exile_instead during waterbend].freeze
35
35
 
36
36
  # ---- legal actions --------------------------------------------------------------------
37
37
 
@@ -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(pl) + pl.graveyard + state.exile + commander_candidates(index)
44
+ ids = alt_cost_hand(index) + pl.graveyard + 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
 
@@ -65,15 +65,17 @@ module Enjine
65
65
 
66
66
  # The options the block makes of each [candidate ref, object, play method]. While no permanent lets `index`
67
67
  # play cards from other zones and no card was granted an ability, a card in a graveyard or library can only
68
- # be played by an ability of its own (#unplayable_elsewhere?).
68
+ # be played by an ability of its own (#unplayable_elsewhere?); nor while one gives cards an alternative cost.
69
+ # Nor an exiled card of another owner no permission effect names (Engine::OptionsMemo#unplayable_candidate?).
70
+ # The play methods are found once per decision: the cast and the land options both ask (Engine#options).
69
71
  def candidate_methods(index, land: false, &)
70
72
  sources = permission_sources(index)
71
- plain = sources.empty? && own_abilities_only?
73
+ plain = sources.empty? && own_abilities_only? && granted_alt_zones(index).empty?
72
74
  permission_candidates(index, sources).flat_map do |ref|
73
75
  obj = candidate_object(index, ref)
74
- next [] if (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
76
+ next [] if unplayable_candidate?(index, obj, plain, land)
75
77
 
76
- play_methods(index, obj, sources).filter_map { yield ref, obj, it }
78
+ candidate_play_methods(index, ref, obj, sources).filter_map { yield ref, obj, it }
77
79
  end
78
80
  end
79
81
 
@@ -132,7 +134,8 @@ module Enjine
132
134
 
133
135
  # Permanents `index` controls whose static abilities let them play cards from other zones:
134
136
  # [[permanent, AbilityInstance], ...].
135
- def permission_sources(index)
137
+ # Memoized per decision while legal options are computed (Engine::OptionsMemo#permission_sources).
138
+ def scan_permission_sources(index)
136
139
  state.battlefield.flat_map do |id|
137
140
  obj = object(id)
138
141
  next [] unless obj.controller == index
@@ -172,8 +175,7 @@ module Enjine
172
175
  return false if returns_creature?(method["alt"]) && return_candidates(index, method["alt"]).empty?
173
176
  return false unless additional_costs_payable?(obj) && alt_parts_payable?(obj, method) # CR 601.2f
174
177
 
175
- # CR 609.4b; a stand-in for a card outside the game is passed itself (it isn't in state.objects).
176
- purpose = { "spell" => state.objects.key?(obj.id) ? obj.id : obj, "any_type" => method["any_mana_type"] }.compact
178
+ purpose = cast_purpose(obj, method) # Engine::Waterbending
177
179
  ability_targetable?(spell_ability_of(obj), index, obj.id) &&
178
180
  cost_variant_affordable?(index, spell_cost_list(obj, false), obj, method_cost(obj, method), nil, purpose) do
179
181
  harmonize_reduced(total_cost(index, it, spell: obj), best_harmonize_power(index, method)) # CR 601.2b
@@ -221,9 +223,9 @@ module Enjine
221
223
  def granted_methods(index, obj)
222
224
  state.effects.filter_map do |e|
223
225
  next unless e["kind"] == "permission" && e["controller"] == index && e["affected"].include?(obj.id)
224
- next unless obj.zone == :exile && may_look?(obj, index)
226
+ next unless obj.zone == :exile && may_look?(obj, index) && (e["during"] != "your_turn" || state.active == index)
225
227
 
226
- { "via" => "effect:#{e["timestamp"]}", "play" => e["play"], **e.slice(*RIDERS) }
228
+ with_waterbend_alt(obj, { "via" => "effect:#{e["timestamp"]}", "play" => e["play"], **e.slice(*RIDERS) })
227
229
  end
228
230
  end
229
231
 
@@ -291,13 +293,13 @@ module Enjine
291
293
 
292
294
  # Permission to play exiled cards for a duration (CR 611.2): a continuous effect for the exiled
293
295
  # objects (a card that leaves exile is a new object, CR 400.7, so the permission ends with it).
294
- # `riders` (RIDERS) change how a card is played with this permission, and only then.
295
- def grant_play_permission!(index, ids, duration:, play:, **riders)
296
+ # `riders` (RIDERS) change how a card is played with this permission, and only then (`source`: CR 611.2b).
297
+ def grant_play_permission!(index, ids, duration:, play:, source: nil, **riders)
296
298
  return if ids.empty?
297
299
 
298
- state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index,
299
- "affected" => ids, "duration" => duration, "turn" => state.turn, "play" => play,
300
- **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }
300
+ state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index, "affected" => ids,
301
+ "duration" => duration, "turn" => state.turn, "play" => play, "source" => source,
302
+ **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }.compact
301
303
  emit Events::EffectStarted.new(kind: "permission", affected: ids, details: { "duration" => duration, "play" => play })
302
304
  end
303
305
 
@@ -100,11 +100,22 @@ module Enjine
100
100
  template.map { it.is_a?(Array) ? flat.shift(it.size) : flat.shift }
101
101
  end
102
102
 
103
- # CR 115.7d: `player` chose new targets for the spell or ability `spell` (shaped like its old ones).
104
- def change_targets!(spell, targets, player)
103
+ # CR 115.7d: new targets for the spell or ability `spell` (shaped like its old ones). Each new target becomes a
104
+ # target of it (ward, "becomes the target", CR 702.21a, 603.2); a division keeps its amounts (CR 115.7f).
105
+ def change_targets!(spell, targets)
105
106
  added = targets.flatten.compact - Array(spell.targets).flatten
107
+ redivide!(spell.memory, spell.targets, targets)
106
108
  spell.targets = targets
107
- added.each { emit Events::TargetChosen.new(player: name(player), object: spell.id, target: it) }
109
+ added.each { became_target!(spell.controller, spell.id, it) }
110
+ emit Events::TargetsChanged.new(player: name(spell.controller), object: spell.id, targets: added) unless added.empty?
111
+ end
112
+
113
+ # CR 115.7f, 601.2d: the amount divided to each target goes to the target that replaced it (a copy with new
114
+ # targets, or new targets chosen for the spell).
115
+ def redivide!(memory, old, new)
116
+ division = memory["division"] or return
117
+ pairs = Array(old).flatten.zip(Array(new).flatten).select { |was, _| division.key?(was) }
118
+ memory["division"] = pairs.to_h { |was, now| [now, division[was]] }
108
119
  end
109
120
  end
110
121
 
@@ -26,10 +26,30 @@ module Enjine
26
26
  abilities.flat_map(&:costs)
27
27
  end
28
28
 
29
- # CR 601.2f: as the total cost is locked in, so is the waterbend cost's generic part.
29
+ # CR 601.2f: as the total cost is locked in, so is the waterbend cost's generic part (with an alternative cost
30
+ # that is a waterbend cost, "cast it by waterbending {X} rather than paying its mana cost").
30
31
  def lock_waterbend!(ctx)
31
32
  costs = frame_costs(ctx) # Engine::CostOptions
32
- ctx["waterbend"] = waterbend_generic(costs, ctx["x"].to_i) if costs.any?(WATERBEND)
33
+ alt = alt_waterbend(ctx["method"])
34
+ ctx["waterbend"] = waterbend_generic(costs, ctx["x"].to_i) + alt.to_i if alt || costs.any?(WATERBEND)
35
+ end
36
+
37
+ # The generic mana of a cast method's waterbend alternative cost (Engine::Permissions#granted_methods), or nil.
38
+ def alt_waterbend(method) = method&.dig("alt", "waterbend") ? Mana::Cost.parse(method["alt"]["cost"]).generic : nil
39
+
40
+ # What paying for `obj` cast with `method` may use: mana of any type (CR 609.4b), tapping for a waterbend
41
+ # alternative cost. A stand-in for a card outside the game is passed itself (it isn't in state.objects).
42
+ def cast_purpose(obj, method)
43
+ { "spell" => state.objects.key?(obj.id) ? obj.id : obj, "any_type" => method["any_mana_type"],
44
+ "waterbend" => alt_waterbend(method) }.compact
45
+ end
46
+
47
+ # A permission's method for `obj`; with "waterbend" => "mana_value" ("cast it by waterbending {X} rather than
48
+ # paying its mana cost, where X is its mana value", CR 118.9) its alternative cost is that waterbend cost.
49
+ def with_waterbend_alt(obj, method)
50
+ return method unless method.delete("waterbend")
51
+
52
+ method.merge("alt" => { "cost" => "{#{chars(obj).mana_cost&.mana_value.to_i}}", "waterbend" => true })
33
53
  end
34
54
 
35
55
  def waterbend_candidates(index, excluded = [])
@@ -23,7 +23,7 @@ module Enjine
23
23
  return Enjine::Characteristics::FACE_DOWN if face_down?(object) && @face_up != object.id # CR 406.3a
24
24
 
25
25
  # layer 1 (CR 613.2a-c): its copiable values
26
- return board_characteristics.fetch(object.id) { copy_base(object) } if object.zone == :battlefield
26
+ return board_chars(object) if object.zone == :battlefield # Engine::OptionsMemo
27
27
  return @options_memo[object.id] ||= off_board_chars(object) if @options_memo # the state holds still meanwhile
28
28
 
29
29
  off_board_chars(object)
@@ -49,10 +49,10 @@ module Enjine
49
49
  # detected separately by identity. While a static ability has a condition or a computed bonus, or a
50
50
  # permanent has a characteristic-defining power/toughness, any event may change the result, so every
51
51
  # event drops the cache (`@volatile`, see Engine#emit).
52
- LAYER_EVENTS = [Events::ZoneChanged, Events::CountersChanged, Events::EffectStarted,
53
- Events::EffectsEnded, Events::Attached, Events::Unattached, Events::ControlChanged,
54
- Events::PhasedOut, Events::PhasedIn, Events::SpeedChanged,
55
- Events::Transformed, Events::ClassLevelChanged, Events::EmblemCreated].freeze
52
+ LAYER_EVENTS = [Events::ZoneChanged, Events::CountersChanged, Events::EffectStarted, Events::EffectsEnded, Events::Attached,
53
+ Events::Unattached, Events::ControlChanged, Events::PhasedOut, Events::PhasedIn, Events::SpeedChanged,
54
+ Events::Transformed, Events::ClassLevelChanged, Events::EmblemCreated, Events::PermanentDesignated,
55
+ Events::DoorUnlocked, Events::DoorLocked, Events::TurnedFaceUp].freeze
56
56
 
57
57
  def touch! = @epoch = @epoch.to_i + 1
58
58
  def volatile_layers? = @volatile
@@ -70,13 +70,14 @@ module Enjine
70
70
  def apply_layers
71
71
  statics = static_sources
72
72
  effects = state.effects
73
- @volatile = statics.any? { |_, ability| ability.condition || ability.computed? } || defined_on_battlefield?
73
+ @volatile = statics.any? { |_, ability| ability.volatile? } || defined_on_battlefield?
74
74
  return {} if statics.empty? && effects.empty? && !@volatile && printed_board?
75
75
 
76
76
  @layering = {}
77
77
  ids = state.battlefield
78
78
  active = statics.select { |source, ability| ability.active?(self, source) }
79
- ids.each { @layering[it] = type_layers(object(it), active, effects) }
79
+ # CR 702.176a: an impending permanent's own "it's not a creature" comes first (Abilities::Impending.effects).
80
+ ids.each { @layering[it] = type_layers(object(it), active, Mechanics::Abilities::Impending.effects(self, object(it)) + effects) }
80
81
  later_layers(ids, statics, ids.select { losing_abilities?(object(it), active, effects) }, effects)
81
82
  @layering.reject { |id, c| c.equal?(definition(object(id)).printed_characteristics) }
82
83
  ensure
@@ -99,20 +100,19 @@ module Enjine
99
100
 
100
101
  # Without effects, every permanent is as printed: none has counters or is a noncreature with printed
101
102
  # power and toughness (an uncrewed Vehicle has none, CR 208.3).
102
- # A max speed ability applying changes it too (Engine::Speed).
103
+ # A max speed ability applying changes it too (Engine::Speed), and so do a class level (CR 717.2a), haste while
104
+ # controlled (CR 702.62a) and haste chosen with riot (CR 702.136a).
103
105
  def printed_board?
104
106
  speedy = state.players.each_index.any? { max_speed?(it) }
105
107
  state.battlefield.none? do |id|
106
108
  obj = object(id)
107
109
  !obj.counters.empty? || printed_noncreature_pt?(obj) || (speedy && !active_max_speed(obj, obj.controller).empty?) ||
108
- obj.memory.key?("class_level") || obj.memory.key?("haste_while_controlled_by") # CR 717.2a, 702.62a
110
+ obj.memory.key?("class_level") || obj.memory.key?("haste_while_controlled_by") || obj.memory.key?("riot_haste")
109
111
  end
110
112
  end
111
113
 
112
114
  def defined_on_battlefield? = state.battlefield.any? { definition(object(it)).defined_pt? }
113
115
 
114
- def facts(obj, current) = Mechanics::Filters::Facts.new(chars: current, counters: obj.counters, token: token?(obj))
115
-
116
116
  # ---- layer 1 (CR 613.2a-c, 707.2) ---------------------------------------------------------
117
117
 
118
118
  # The object's copiable values (CR 707.2): the printed characteristics of its card, which is the
@@ -27,7 +27,7 @@ module Enjine
27
27
  obj.controller == state.active && !obj.tapped && current.creature? &&
28
28
  (!current.keyword?(:defender) || current.keyword?(:attacks_despite_defender)) &&
29
29
  !current.keyword?(:cant_attack) && !attackers.key?(id) && !summoning_sick_for_tap?(obj) &&
30
- (only.nil? || only.match?(self, id, state.active))
30
+ (only.nil? || only.match?(self, id, state.active)) && !attack_targets_for(id).empty?
31
31
  end
32
32
  end
33
33
 
@@ -35,11 +35,28 @@ module Enjine
35
35
  # declaration may end only once every such requirement is obeyed (no attack has a cost yet).
36
36
  def unmet_attack_requirements = attack_candidates.select { chars(it).keyword?(:attacks_each_combat) }
37
37
 
38
- # CR 506.3, 508.1b: the defending player or a planeswalker they control.
38
+ # CR 506.3, 508.1b: the defending player, a planeswalker they control, or a battle they protect (CR 310.5,
39
+ # 310.9: its protector's opponents may attack it, whoever controls it).
39
40
  def attack_targets
40
41
  defender = defending_player
41
42
  [Mechanics::Filters.player_ref(self, defender)] +
42
- state.battlefield.select { |id| object(id).controller == defender && chars(id).planeswalker? }
43
+ state.battlefield.select do |id|
44
+ current = chars(id)
45
+ current.type?(:battle) ? protector(object(id)) == defender : object(id).controller == defender && current.planeswalker?
46
+ end
47
+ end
48
+
49
+ # CR 310.9: the player who protects a battle (nil for a permanent that isn't one or has none).
50
+ def protector(obj) = obj.memory["protector"]
51
+
52
+ # What creature `id` may attack: not a player with "creatures with flying can't attack you" matching it
53
+ # (CR 508.1c; their planeswalkers still can be attacked).
54
+ def attack_targets_for(id)
55
+ defender = defending_player
56
+ targets = attack_targets
57
+ return targets unless player_rule?(defender, "cant_be_attacked", object(id))
58
+
59
+ targets - [Mechanics::Filters.player_ref(self, defender)]
43
60
  end
44
61
 
45
62
  # Creatures that may be declared next. CR 506.5, 508.1c: one that can't attack alone is offered
@@ -66,13 +83,15 @@ module Enjine
66
83
  def withdraw_attacker!(id)
67
84
  attackers.delete(id)
68
85
  state.attacks_declared -= 1
86
+ touch! # statics reading combat status (CR 506.4)
69
87
  attack_withdrawn!(id) # Engine::TurnHistory
70
88
  state.pending_triggers.reject! { it["event"]["type"] == "attacker_declared" && it["event"]["object"] == id }
71
89
  end
72
90
 
73
- # CR 508.4: a creature put onto the battlefield attacking attacks the defending player. (Choosing one
74
- # of their planeswalkers instead isn't offered yet.) It was never declared, so it never "attacked".
75
- # Only called while its controller controls an attacking creature (see Abilities::EntersAttacking).
91
+ # CR 508.4: a creature put onto the battlefield attacking attacks `target` when one was chosen (a token's
92
+ # controller picks a planeswalker in Effects::CreateToken; ninjutsu keeps the attacker's), else the defending
93
+ # player. It was never declared, so it never "attacked". A permanent made to enter attacking by
94
+ # Abilities::EntersAttacking attacks the defending player (no choice can be asked mid-move).
76
95
  def enter_attacking!(obj, target = nil)
77
96
  target = Mechanics::Filters.player_ref(self, state.opponent(obj.controller)) unless target.is_a?(String) # CR 506.3a
78
97
  attackers[obj.id] = { "target" => target, "blocked" => false }
@@ -243,7 +262,10 @@ module Enjine
243
262
  end
244
263
  frame["queue"].shift
245
264
  end
246
- deal_combat_damage!(frame["assigned"])
265
+ hits = combat_hits(frame["assigned"])
266
+ return :wait if ask_damage_orders!(hits, frame, combat: true) == :wait # CR 616.1 (Engine::Damage)
267
+
268
+ with_damage_orders(frame["damage_orders"]) { deal_combat_damage!(hits) }
247
269
  :done
248
270
  end
249
271
 
@@ -269,8 +291,8 @@ module Enjine
269
291
  ask!(nil)
270
292
  end
271
293
 
272
- # CR 510.2: all combat damage in a step is dealt simultaneously.
273
- def deal_combat_damage!(assigned)
294
+ # The combat damage of this step, as assigned: [[source, recipient, amount]] (CR 510.1).
295
+ def combat_hits(assigned)
274
296
  hits = []
275
297
  attackers.each do |id, info|
276
298
  next unless deals_damage_now?(id)
@@ -286,11 +308,19 @@ module Enjine
286
308
  state.blockers.each do |blocker, attacker|
287
309
  hits << [blocker, attacker, combat_damage_amount(blocker)] if deals_damage_now?(blocker)
288
310
  end
289
- simultaneous_damage do # CR 510.2
290
- dealt = Hash.new(0)
291
- lifelinked = hits.map(&:first).uniq.select { damage_source_keyword?(it, :lifelink) }
292
- hits.each { |source, target, amount| dealt[source] += deal_damage!(source, target, amount, combat: true, lifelink: false) }
293
- lifelinked.each { lifelink!(it, dealt[it]) if dealt[it].positive? } # CR 120.3f, 119.9: one gain per source
311
+ hits
312
+ end
313
+
314
+ # CR 510.2: all combat damage in a step is dealt simultaneously.
315
+ def deal_combat_damage!(hits)
316
+ # CR 510.2, 603.2c: one event batch for "one or more creatures deal combat damage" triggers
317
+ in_batch("combat_damage:#{state.next_id}") do
318
+ simultaneous_damage do
319
+ dealt = Hash.new(0)
320
+ lifelinked = hits.map(&:first).uniq.select { damage_source_keyword?(it, :lifelink) }
321
+ hits.each { |source, target, amount| dealt[source] += deal_damage!(source, target, amount, combat: true, lifelink: false) }
322
+ lifelinked.each { lifelink!(it, dealt[it]) if dealt[it].positive? } # CR 120.3f, 119.9: one gain per source
323
+ end
294
324
  end
295
325
  turn_based_actions_done!
296
326
  end
@@ -308,6 +338,7 @@ module Enjine
308
338
  state.combat_damage_pass = nil
309
339
  attackers.clear
310
340
  state.blockers.clear
341
+ touch! # statics reading combat status (CR 506.4)
311
342
  end
312
343
  end
313
344
  include Combat
@@ -26,7 +26,8 @@ module Enjine
26
26
  module Copies
27
27
  # ---- reading -------------------------------------------------------------------------------
28
28
 
29
- def own_card(obj) = obj.memory["own_card"] || obj.card
29
+ # A face-down object is its hidden card (Engine::FaceDownPermanents).
30
+ def own_card(obj) = obj.memory["face_down_card"] || obj.memory["own_card"] || obj.card
30
31
 
31
32
  # A token (CR 111.1): created as one, or a copy of a permanent spell that resolved (CR 608.3f).
32
33
  def token?(obj) = obj.memory["token"] == true || catalog.fetch(own_card(obj)).token?
@@ -123,11 +124,10 @@ module Enjine
123
124
  copy.kind = "ability"
124
125
  copy.source = spell.source
125
126
  copy.ability = spell.ability
126
- copy.memory = Snapshot.deep_copy(spell.memory.except("trigger_id")) # the copy wasn't triggered
127
- else
128
- copy.memory = Marshal.load(Marshal.dump(spell.memory.slice("kicked", "kicked_with", "gift", "division"))).merge("copy" => "spell")
129
127
  end
128
+ copy.memory = copied_memory(spell)
130
129
  copy.memory["copy_except"] = except unless except.empty?
130
+ redivide!(copy.memory, spell.targets, targets) # CR 115.7f (Engine::TargetCounts)
131
131
  copy.targets = targets
132
132
  copy.modes = spell.modes&.dup
133
133
  copy.x = spell.x
@@ -137,9 +137,17 @@ module Enjine
137
137
  record_result!(copy.id)
138
138
  emit Events::SpellCopied.new(player: name(controller), object: copy.id, card: card, original: spell.id,
139
139
  targets: targets)
140
+ Array(targets).flatten.compact.uniq.each { became_target!(controller, copy.id, it) } # ward (CR 702.21a)
140
141
  copy
141
142
  end
142
143
 
144
+ # What a copy of a spell or ability knows: an ability's copy keeps what the ability knew, but wasn't triggered.
145
+ def copied_memory(spell)
146
+ return Snapshot.deep_copy(spell.memory.except("trigger_id", "ability_lki")) if spell.ability?
147
+
148
+ Snapshot.deep_copy(spell.memory.slice("kicked", "kicked_with", "gift", "division")).merge("copy" => "spell")
149
+ end
150
+
143
151
  # ---- zone changes and state-based actions ------------------------------------------------------
144
152
 
145
153
  # CR 400.7: the new object is the card itself again; a token or copy stays one. A copy of a permanent
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Committing a crime (CR 700.13): a player commits a crime as they cast a spell, activate an ability or put a
6
+ # triggered ability on the stack that targets at least one opponent, a permanent, spell or ability an opponent
7
+ # controls, or a card in an opponent's graveyard. One spell or ability is one crime, however many of its
8
+ # targets qualify. Checked once the spell is cast, the ability activated or the trigger put on the stack with
9
+ # its targets (Events::SpellCast, AbilityActivated, TriggerPutOnStack), so a cancelled cast is no crime; a copy
10
+ # put on the stack (CR 707.10) or new targets chosen later (CR 115.7) aren't cast or activated, so they aren't
11
+ # either. The turn log counts them ("crimes", amount `crimes_this_turn`), and Events::CrimeCommitted is what
12
+ # "whenever you commit a crime" (trigger `commits_crime`) watches.
13
+ module Crimes
14
+ CRIME_EVENTS = [Events::SpellCast, Events::AbilityActivated, Events::TriggerPutOnStack].freeze
15
+
16
+ # Emits the crime that `event` (a spell cast, an ability activated or a trigger put on the stack) commits.
17
+ def check_crime!(event)
18
+ return unless CRIME_EVENTS.include?(event.class)
19
+
20
+ index = names.index(event.player)
21
+ return unless index && Array(event.targets).flatten.compact.any? { crime_target?(index, it) }
22
+
23
+ emit Events::CrimeCommitted.new(player: event.player, object: event.object)
24
+ end
25
+
26
+ # CR 700.13: an opponent, a permanent, spell or ability an opponent controls, or a card in an opponent's graveyard.
27
+ def crime_target?(index, ref)
28
+ player = Mechanics::Filters.player_index(self, ref)
29
+ return player != index unless player.nil?
30
+
31
+ obj = state.objects[ref] or return false
32
+ case obj.zone
33
+ when :battlefield, :stack then obj.controller != index
34
+ when :graveyard then obj.owner != index
35
+ else false
36
+ end
37
+ end
38
+ end
39
+ include Crimes
40
+ end
41
+
42
+ module Events
43
+ # CR 700.13: `player` committed a crime with the spell or ability `object`.
44
+ CrimeCommitted = define(:crime_committed, :player, :object)
45
+ end
46
+ end