enjine 0.3.0 → 0.5.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 (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -1
  3. data/SUPPORTED.md +34 -26
  4. data/docs/guides/card-data-format.md +143 -1
  5. data/docs/plans/dsl-gaps.md +99 -0
  6. data/docs/reference/abilities.md +46 -13
  7. data/docs/reference/costs.md +23 -6
  8. data/docs/reference/decisions.md +4 -0
  9. data/docs/reference/effects.md +118 -25
  10. data/docs/reference/filters.md +19 -2
  11. data/docs/reference/keywords.md +16 -2
  12. data/docs/reference/triggers.md +28 -7
  13. data/lib/enjine/actions/cast.rb +10 -3
  14. data/lib/enjine/actions/play_land.rb +3 -1
  15. data/lib/enjine/card_definition.rb +19 -3
  16. data/lib/enjine/cli/text.rb +10 -3
  17. data/lib/enjine/decisions/combat.rb +4 -2
  18. data/lib/enjine/decisions/damage_order.rb +18 -0
  19. data/lib/enjine/engine/ability_layers.rb +6 -1
  20. data/lib/enjine/engine/casting/alt_casting.rb +44 -4
  21. data/lib/enjine/engine/casting/cast_choices.rb +13 -1
  22. data/lib/enjine/engine/casting/casting.rb +43 -7
  23. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  24. data/lib/enjine/engine/casting/permissions.rb +27 -23
  25. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  26. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  27. data/lib/enjine/engine/characteristics.rb +32 -14
  28. data/lib/enjine/engine/combat.rb +26 -7
  29. data/lib/enjine/engine/copies.rb +26 -12
  30. data/lib/enjine/engine/damage.rb +51 -1
  31. data/lib/enjine/engine/durations.rb +47 -0
  32. data/lib/enjine/engine/entering.rb +36 -2
  33. data/lib/enjine/engine/face_down.rb +12 -3
  34. data/lib/enjine/engine/faces.rb +16 -2
  35. data/lib/enjine/engine/follow_ups.rb +4 -1
  36. data/lib/enjine/engine/resolution.rb +46 -1
  37. data/lib/enjine/engine/rules.rb +6 -4
  38. data/lib/enjine/engine/state_based_actions.rb +8 -0
  39. data/lib/enjine/engine/triggers.rb +18 -21
  40. data/lib/enjine/engine/turn_history.rb +16 -1
  41. data/lib/enjine/engine/turn_structure.rb +1 -0
  42. data/lib/enjine/engine/zones.rb +23 -4
  43. data/lib/enjine/events.rb +6 -1
  44. data/lib/enjine/frames.rb +2 -2
  45. data/lib/enjine/mana.rb +3 -0
  46. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  47. data/lib/enjine/mechanics/abilities/damage_replacements.rb +136 -64
  48. data/lib/enjine/mechanics/abilities/double_counters.rb +1 -1
  49. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  50. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -19
  51. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  52. data/lib/enjine/mechanics/abilities/replacement_effects.rb +2 -1
  53. data/lib/enjine/mechanics/abilities/static.rb +8 -1
  54. data/lib/enjine/mechanics/card_spec.rb +99 -14
  55. data/lib/enjine/mechanics/costs/base.rb +67 -9
  56. data/lib/enjine/mechanics/costs/behold.rb +21 -5
  57. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  58. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  59. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  60. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  61. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  62. data/lib/enjine/mechanics/effects/base.rb +10 -2
  63. data/lib/enjine/mechanics/effects/become.rb +60 -21
  64. data/lib/enjine/mechanics/effects/copy.rb +63 -23
  65. data/lib/enjine/mechanics/effects/counters.rb +8 -2
  66. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  67. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  68. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  69. data/lib/enjine/mechanics/effects/gain_control.rb +6 -3
  70. data/lib/enjine/mechanics/effects/library.rb +76 -18
  71. data/lib/enjine/mechanics/effects/pay.rb +7 -4
  72. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  73. data/lib/enjine/mechanics/effects/return_to_battlefield.rb +25 -6
  74. data/lib/enjine/mechanics/effects/search.rb +34 -6
  75. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  76. data/lib/enjine/mechanics/filters/base.rb +40 -13
  77. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  78. data/lib/enjine/mechanics/filters/stack.rb +15 -9
  79. data/lib/enjine/mechanics/keywords/alternative_costs.rb +10 -6
  80. data/lib/enjine/mechanics/keywords/cards_have.rb +65 -0
  81. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  82. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  83. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  84. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  85. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  86. data/lib/enjine/mechanics/linked.rb +32 -2
  87. data/lib/enjine/mechanics/selector.rb +32 -9
  88. data/lib/enjine/mechanics/triggers/base.rb +14 -3
  89. data/lib/enjine/mechanics/triggers/casting.rb +16 -10
  90. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  91. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  92. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +38 -11
  93. data/lib/enjine/mechanics/triggers/zone_changes.rb +1 -1
  94. data/lib/enjine/mechanics/values.rb +20 -10
  95. data/lib/enjine/mechanics.rb +5 -0
  96. data/lib/enjine/replacements.rb +3 -2
  97. data/lib/enjine/rules_monitor.rb +17 -4
  98. data/lib/enjine/steps.rb +10 -1
  99. data/lib/enjine/version.rb +1 -1
  100. data/lib/enjine/view.rb +1 -1
  101. metadata +7 -1
@@ -13,7 +13,8 @@ module Enjine
13
13
  # resolve against that card's data)
14
14
  # memory["own_card"] the card the object really is, while a copy effect changed obj.card
15
15
  # memory["copy_effects"] copy effects on a permanent, in timestamp order (CR 613.7): each
16
- # {"card", "except", "duration" ("permanent" | "end_of_turn"), "timestamp"}
16
+ # {"card", "except", "duration" ("permanent" | "end_of_turn" |
17
+ # "until_your_next_turn", with its "controller"), "timestamp"}
17
18
  # memory["copy_except"] the exceptions of an object created as a copy (a token copy, CR 707.9)
18
19
  # memory["token"] true for a token that is a copy of a card (CR 111.1, 608.3f)
19
20
  # memory["copy"] "spell" for a copy of a spell (CR 707.10), "card" for a copy of a card
@@ -79,11 +80,13 @@ module Enjine
79
80
 
80
81
  # CR 707.4, 613.2a: `obj` becomes a copy of [card, except]; no enter or leave triggers. A
81
82
  # "permanent" copy effect lasts as long as the object stays on the battlefield.
82
- def become_copy!(obj, values, duration: "permanent")
83
+ # `controller`: whose next turn ends an "until your next turn" copy effect (CR 611.2a).
84
+ def become_copy!(obj, values, duration: "permanent", controller: nil)
83
85
  card, except = values
84
86
  obj.memory["own_card"] ||= obj.card
85
- (obj.memory["copy_effects"] ||= []) << { "card" => card, "except" => except, "duration" => duration,
86
- "timestamp" => next_timestamp! }
87
+ entry = { "card" => card, "except" => except, "duration" => duration, "timestamp" => next_timestamp! }
88
+ entry["controller"] = controller if duration == "until_your_next_turn"
89
+ (obj.memory["copy_effects"] ||= []) << entry
87
90
  obj.card = card
88
91
  emit Events::EffectStarted.new(kind: "copy", affected: [obj.id], details: { "card" => card })
89
92
  end
@@ -120,11 +123,10 @@ module Enjine
120
123
  copy.kind = "ability"
121
124
  copy.source = spell.source
122
125
  copy.ability = spell.ability
123
- copy.memory = Snapshot.deep_copy(spell.memory.except("trigger_id")) # the copy wasn't triggered
124
- else
125
- copy.memory = Marshal.load(Marshal.dump(spell.memory.slice("kicked", "kicked_with", "gift", "division"))).merge("copy" => "spell")
126
126
  end
127
+ copy.memory = copied_memory(spell)
127
128
  copy.memory["copy_except"] = except unless except.empty?
129
+ redivide!(copy.memory, spell.targets, targets) # CR 115.7f (Engine::TargetCounts)
128
130
  copy.targets = targets
129
131
  copy.modes = spell.modes&.dup
130
132
  copy.x = spell.x
@@ -134,9 +136,17 @@ module Enjine
134
136
  record_result!(copy.id)
135
137
  emit Events::SpellCopied.new(player: name(controller), object: copy.id, card: card, original: spell.id,
136
138
  targets: targets)
139
+ Array(targets).flatten.compact.uniq.each { became_target!(controller, copy.id, it) } # ward (CR 702.21a)
137
140
  copy
138
141
  end
139
142
 
143
+ # What a copy of a spell or ability knows: an ability's copy keeps what the ability knew, but wasn't triggered.
144
+ def copied_memory(spell)
145
+ return Snapshot.deep_copy(spell.memory.except("trigger_id", "ability_lki")) if spell.ability?
146
+
147
+ Snapshot.deep_copy(spell.memory.slice("kicked", "kicked_with", "gift", "division")).merge("copy" => "spell")
148
+ end
149
+
140
150
  # ---- zone changes and state-based actions ------------------------------------------------------
141
151
 
142
152
  # CR 400.7: the new object is the card itself again; a token or copy stays one. A copy of a permanent
@@ -165,15 +175,19 @@ module Enjine
165
175
  end
166
176
  end
167
177
 
168
- # CR 514.2: "until end of turn" copy effects end; the permanent has the copiable values of the
169
- # newest copy effect left, or its own.
170
- def end_copy_effects!
178
+ # CR 514.2: "until end of turn" copy effects end (with `controller`: that player's "until your next turn"
179
+ # ones, as their turn begins, CR 611.2a); the permanent has the copiable values of the newest copy effect
180
+ # left, or its own.
181
+ def end_copy_effects!(controller: nil)
182
+ ending = lambda do |e|
183
+ controller.nil? ? e["duration"] == "end_of_turn" : e["duration"] == "until_your_next_turn" && e["controller"] == controller
184
+ end
171
185
  state.battlefield.each do |id|
172
186
  obj = object(id)
173
187
  effects = obj.memory["copy_effects"] or next
174
- next unless effects.any? { it["duration"] == "end_of_turn" }
188
+ next unless effects.any?(&ending)
175
189
 
176
- effects.reject! { it["duration"] == "end_of_turn" }
190
+ effects.reject!(&ending)
177
191
  obj.card = effects.last&.fetch("card") || obj.memory["own_card"]
178
192
  obj.memory.delete("copy_effects") if effects.empty?
179
193
  obj.memory.delete("own_card") if effects.empty?
@@ -16,6 +16,55 @@ module Enjine
16
16
  dealt
17
17
  end
18
18
 
19
+ # ---- the order of replacement and prevention effects (CR 616.1) ------------------------------------------
20
+
21
+ # The key naming one damage event of an effect or combat in a chosen order.
22
+ def self.hit_key(source, target) = "#{source}>#{target}"
23
+
24
+ # Before damage is dealt (`hits`: [[source, recipient, amount]]), the affected player of each event whose
25
+ # result depends on the order of the effects that apply to it chooses one (CR 616.1), in APNAP order (CR
26
+ # 101.4). The chosen orders are kept in `store` ("damage_orders": the effect's locals, or the combat damage
27
+ # frame). Returns :wait while asking. Not asked while damage is being dealt (follow-ups): the default order.
28
+ def ask_damage_orders!(hits, store, combat: false)
29
+ return if hits.empty? || @damage_orders
30
+
31
+ orders = store["damage_orders"] || {}
32
+ asks = hits.filter_map do |source, ref, amount|
33
+ key = Damage.hit_key(source, ref)
34
+ found = !orders.key?(key) && Mechanics::DamageEvents.orders(self, source, ref, amount, combat)
35
+ [key, *found] if found
36
+ end
37
+ key, chooser, outcomes = asks.min_by { apnap_rank(it[1]) }
38
+ return unless key
39
+
40
+ ask!("kind" => "damage_order", "player" => chooser, "hit" => key,
41
+ "choices" => outcomes.map do |order, amount|
42
+ { "type" => "order", "order" => order.map(&:first), "steps" => order.map(&:last), "amount" => amount }
43
+ end)
44
+ :wait
45
+ end
46
+
47
+ def apnap_rank(index) = (index - state.active) % state.players.size
48
+
49
+ # The affected player answered: the order is kept where #ask_damage_orders! looks for it.
50
+ def damage_order_answer!(pending, option)
51
+ frame = state.frames.last
52
+ store = frame["type"] == "resolve" ? answering_locals : frame
53
+ (store["damage_orders"] ||= {})[pending["hit"]] = option[:order]
54
+ ask!(nil)
55
+ end
56
+
57
+ # Deals damage with the orders chosen for it (#damage_order).
58
+ def with_damage_orders(orders)
59
+ before = @damage_orders
60
+ @damage_orders = orders || {}
61
+ yield
62
+ ensure
63
+ @damage_orders = before
64
+ end
65
+
66
+ def damage_order(hit) = @damage_orders&.[](hit)
67
+
19
68
  # The damage event after replacement and prevention effects (CR 614, 615).
20
69
  def deal_proposed_damage!(source, data, combat, lifelink)
21
70
  amount = data["amount"]
@@ -136,7 +185,8 @@ module Enjine
136
185
  # CR 613.7c: keyword counters of this kind get the new counter's timestamp (Engine::Characteristics#ability_layers).
137
186
  # The next timestamp isn't taken: an effect created later gets this number too and sorts after it.
138
187
  (object.memory["counter_timestamps"] ||= {})[kind] = state.next_id if Mechanics::Counters.keyword?(kind)
139
- emit Events::CountersChanged.new(object: object.id, counter: kind, from: before, to: before + amount)
188
+ emit Events::CountersChanged.new(object: object.id, counter: kind, from: before, to: before + amount,
189
+ by: name(data["player"]))
140
190
  end
141
191
 
142
192
  # Counters on a player (CR 122.1): poison (ten or more lose the game, CR 122.1f, 704.5c), experience, rad, ...
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Durations measured in a player's own turns (CR 611.2a): "until the end of your next turn" control effects
6
+ # and "until your next end step" permissions. "Until your next turn" ends as that turn begins
7
+ # (Engine::Rules#end_effects_until_turn_of!).
8
+ module Durations
9
+ # At cleanup of its controller's next turn (CR 514.2), an "until the end of your next turn" control effect
10
+ # ends and control returns (Engine::Rules#revert_control!).
11
+ def end_next_turn_control!
12
+ ending = state.effects.select do |e|
13
+ e["kind"] == "control" && e["duration"] == "end_of_your_next_turn" && e["controller"] == state.active &&
14
+ state.turn > e["turn"]
15
+ end
16
+ return if ending.empty?
17
+
18
+ revert_control!(ending)
19
+ state.effects.reject! { ending.include?(it) }
20
+ emit Events::EffectsEnded.new(count: ending.size)
21
+ end
22
+
23
+ # What an effect lasting "until your next end step" remembers: an effect made during its controller's end
24
+ # step or cleanup (`late`) lasts until the end step of their next turn; otherwise this turn's end step ends
25
+ # it on their own turn.
26
+ def end_step_timing(index, duration)
27
+ return {} unless duration == "until_your_next_end_step"
28
+
29
+ { "late" => state.active == index && %i[end cleanup].include?(state.step) }
30
+ end
31
+
32
+ # CR 513.1: as the active player's end step begins, their "until your next end step" effects end.
33
+ def expire_end_step_effects!
34
+ ending = state.effects.select do |e|
35
+ e["duration"] == "until_your_next_end_step" && e["controller"] == state.active &&
36
+ (state.turn > e["turn"] || !e["late"])
37
+ end
38
+ return if ending.empty?
39
+
40
+ state.effects.reject! { ending.include?(it) }
41
+ emit Events::EffectsEnded.new(count: ending.size)
42
+ end
43
+ end
44
+
45
+ include Durations
46
+ end
47
+ end
@@ -21,7 +21,33 @@ module Enjine
21
21
  abilities = if id.is_a?(GameObject) || state.objects.key?(id) then chars(id).abilities
22
22
  else token_to_create(id).printed_characteristics.abilities
23
23
  end
24
- abilities.map(&:ability).select { it.kind == :entering_choice }
24
+ abilities.map(&:ability).select { it.kind == :entering_choice } + granted_entering_choices(id)
25
+ end
26
+
27
+ # CR 614.12: "as this enters" choices of keywords that static abilities on the battlefield would grant the
28
+ # permanent once it's there ("Other Spiders you control have riot"), judged as it would exist there, under
29
+ # its controller (or its owner's, for a card that has none). A token about to be created isn't judged yet.
30
+ def granted_entering_choices(id)
31
+ obj = id.is_a?(GameObject) ? id : state.objects[id]
32
+ return [] if obj.nil? || obj.zone == :battlefield
33
+
34
+ granting = board_abilities(:static).select { |_, ability| ability.keywords.any? { Entering.entering_keyword?(it) } }
35
+ return [] if granting.empty?
36
+
37
+ stand_in = obj.dup.tap { it.controller ||= it.owner }
38
+ current = chars(obj)
39
+ granting.flat_map do |source, ability|
40
+ next [] unless ability.active?(self, source) && ability.affects?(stand_in, source, facts(obj, current))
41
+
42
+ ability.keywords.flat_map { CardDefinition.keyword_instances(it) }.map(&:ability).select { it.kind == :entering_choice }
43
+ end
44
+ end
45
+
46
+ # Whether a keyword brings an "as this enters" choice (riot).
47
+ def self.entering_keyword?(keyword)
48
+ (@entering_keywords ||= {}).fetch(keyword) do
49
+ @entering_keywords[keyword] = CardDefinition.keyword_instances(keyword).any? { it.ability.kind == :entering_choice }
50
+ end
25
51
  end
26
52
 
27
53
  def entering_choice(id) = entering_choices(id).first
@@ -51,11 +77,18 @@ module Enjine
51
77
  ask!(nil)
52
78
  end
53
79
 
54
- def ask_enter_choice!(id, controller)
80
+ def ask_enter_choice!(id, controller, given = nil)
81
+ before_entering_choice!(id, controller, given)
55
82
  ask!("kind" => "enter_choice", "player" => controller, "object" => id)
56
83
  :wait
57
84
  end
58
85
 
86
+ # What happens just before a choice is asked ("look at an opponent's hand, then choose", CR 701.20e).
87
+ def before_entering_choice!(id, controller, given)
88
+ choice = entering_choices(id)[Entering.answers(given).size]
89
+ choice.before_choice(self, controller) if choice.respond_to?(:before_choice)
90
+ end
91
+
59
92
  def enters_from_answer(id, frame) = entering_statuses(id, Entering.answers(frame["enter"]))
60
93
 
61
94
  # What a permanent enters with given its "as this enters" answers, combined (memories merged, counters
@@ -101,6 +134,7 @@ module Enjine
101
134
  return nil unless id
102
135
 
103
136
  token = state.objects.key?(id) ? {} : { "card" => token_to_create(id).id }
137
+ before_entering_choice!(id, controller, answers[id])
104
138
  ask!({ "kind" => "enter_choice", "player" => controller, "object" => id, "effect" => true }.merge(token))
105
139
  :wait
106
140
  end
@@ -6,14 +6,23 @@ module Enjine
6
6
  FACE_DOWN_ID = "face_down"
7
7
 
8
8
  # Cards exiled face down (CR 406.3, 406.3a-b). Such a card has no characteristics (Engine#chars) and
9
- # only the players in its memory "may_look" see which card it is (View, Events::ZoneChanged). The effect
9
+ # only the players in its memory "may_look" see which card it is (View, Events::ZoneChanged); a hidden-away
10
+ # card (memory "looker_source", CR 702.75a), the player who controls that permanent now. The effect
10
11
  # that exiled it may let a player play it; the card is turned face up just before it's played, so
11
12
  # whether it can be played is judged face up, and only for a player who may look at it.
12
13
  module FaceDown
13
14
  def face_down?(obj) = obj.zone == :exile && obj.memory["face_down"] == true
14
15
 
15
- # Whether `index` may look at the face-down card (always true for a face-up card).
16
- def may_look?(obj, index) = !face_down?(obj) || obj.memory.fetch("may_look", []).include?(index)
16
+ # Whether `index` may look at the face-down card (always true for a face-up card). A hidden-away card's
17
+ # looker follows its permanent's controller while that permanent is on the battlefield (CR 702.75a).
18
+ def may_look?(obj, index)
19
+ return true unless face_down?(obj)
20
+
21
+ source = state.objects[obj.memory["looker_source"]]
22
+ return source.controller == index if source&.zone == :battlefield
23
+
24
+ obj.memory.fetch("may_look", []).include?(index)
25
+ end
17
26
 
18
27
  # Evaluates the block with the face-down card `id` seen face up (CR 406.3a: "turned face up just
19
28
  # before the player announces that they are playing the card"). Nothing in the block changes state.
@@ -103,8 +103,20 @@ module Enjine
103
103
 
104
104
  state.exile.delete(second.id)
105
105
  state.objects.delete(second.id)
106
- move!(first.id, :battlefield, controller: controller, reason: "meld",
107
- enters: { "face" => 1, "memory" => { "melded" => second.card } })
106
+ melded = move!(first.id, :battlefield, controller: controller, reason: "meld",
107
+ enters: { "face" => 1, "memory" => { "melded" => second.card } })
108
+ # The second card leaves exile too; it's part of the melded permanent, not an object of its own.
109
+ emit Events::ZoneChanged.new(card: second.card, old_id: second.id, new_id: nil, owner: name(second.owner),
110
+ from: "exile", to: "battlefield", reason: "meld")
111
+ melded
112
+ end
113
+
114
+ # CR 713.5c, 202.3c: a melded permanent's mana value is the sum of its front faces' mana values. Nil for any
115
+ # other object (a copy of a melded permanent has the back face's copiable values, so its mana value is 0).
116
+ def melded_mana_value(obj)
117
+ return nil unless obj.zone == :battlefield && obj.memory["melded"] && !obj.memory["own_card"]
118
+
119
+ [obj.card, obj.memory["melded"]].sum { catalog.fetch(it).card.mana_cost&.mana_value.to_i }
108
120
  end
109
121
 
110
122
  # CR 713.8, 713.8c: a melded permanent that leaves the battlefield puts its two cards into the new zone;
@@ -201,6 +213,8 @@ module Enjine
201
213
  def unprepare!(obj)
202
214
  return false unless obj.memory.delete("prepared")
203
215
 
216
+ rescan_tokens! # its prepare spell copy ceases to exist (CR 723.3c)
217
+
204
218
  emit Events::PreparedChanged.new(object: obj.id, prepared: false)
205
219
  true
206
220
  end
@@ -17,7 +17,10 @@ module Enjine
17
17
  effects = catalog.fetch(entry["card"]).ability(entry["ref"]).effects
18
18
  memory = { "triggering" => seen, "source_card" => entry["card"] }
19
19
  ctx = Mechanics::EffectContext.new(entry["controller"], entry["source"], entry["source"], [], [], [], memory)
20
- effects.each { it.run(self, ctx, {}) } # effects that need no choice (CR 615.5)
20
+ # Effects that need no choice (CR 615.5); with nothing prevented (CR 615.12) no "when damage is prevented
21
+ # this way" triggers.
22
+ effects = effects.grep_v(Mechanics::Effects::ReflexiveTrigger) if entry["unprevented"]
23
+ with_damage_orders(nil) { effects.each { it.run(self, ctx, {}) } }
21
24
  end
22
25
  end
23
26
  end
@@ -47,14 +47,24 @@ module Enjine
47
47
  frame["pc"] += 1
48
48
  end
49
49
  if !obj.ability? && definition(obj).permanent? && entering_choice_pending?(obj.id, frame["enter"])
50
- return ask_enter_choice!(obj.id, obj.controller) # CR 614.12: decided before it enters
50
+ return ask_enter_choice!(obj.id, obj.controller, frame["enter"]) # CR 614.12: decided before it enters
51
51
  end
52
52
 
53
+ gift_given!(obj, ability)
53
54
  emit Events::Resolved.new(object: obj.id, card: obj.card, kind: obj.kind)
54
55
  finish_resolution!(obj, frame)
55
56
  after_resolution!
56
57
  end
57
58
 
59
+ # CR 702.174c: a player gives a gift as their instant or sorcery spell whose gift was promised resolves, or as
60
+ # the gift triggered ability of their permanent resolves (an enters trigger checking "if the gift was promised").
61
+ def gift_given!(obj, ability)
62
+ given = if obj.ability? then ability.respond_to?(:condition) && Mechanics::Condition::CastHow.gift?(ability.condition)
63
+ else obj.memory["kicked_with"] == "gift" && (chars(obj).type?(:instant) || chars(obj).type?(:sorcery))
64
+ end
65
+ emit Events::KeywordAction.new(player: name(obj.controller), action: "give_gift", amount: nil) if given
66
+ end
67
+
58
68
  # CR 608.2b: targets are checked once, as resolution begins.
59
69
  def start_resolution!(frame, obj, ability)
60
70
  specs = ability&.targets_for(obj.modes || [], kicked: obj.memory.key?("kicked_with")) || []
@@ -93,6 +103,23 @@ module Enjine
93
103
  # Called by zone changes and token creation while an effect runs.
94
104
  def record_result!(id) = @recorded&.push(id)
95
105
 
106
+ # Runs the block recording apart what it moves or creates and how much it changes (an effect of a nested
107
+ # list with results of its own, Effects::Repeat); returns [the block's value, those objects, that amount].
108
+ # They also count for the effect running the nested list.
109
+ def recording_apart
110
+ outer = @recorded
111
+ outer_amount = @recorded_amount
112
+ @recorded = []
113
+ @recorded_amount = 0
114
+ value = yield
115
+ [value, @recorded, @recorded_amount]
116
+ ensure
117
+ inner = @recorded
118
+ inner_amount = @recorded_amount
119
+ @recorded = outer && (outer + inner)
120
+ @recorded_amount = outer_amount && (outer_amount + inner_amount)
121
+ end
122
+
96
123
  # The context for one effect; a modal ability's effects see only their mode's targets.
97
124
  # CR 603.4: a triggered ability whose intervening "if" is false on resolution does nothing.
98
125
  def intervening_if_holds?(obj, ability)
@@ -159,9 +186,27 @@ module Enjine
159
186
 
160
187
  # Abilities on the stack aren't cards; they simply cease to exist.
161
188
  def remove_stack_object!(id)
189
+ remember_ability!(object(id))
162
190
  state.stack.delete(id)
163
191
  state.objects.delete(id)
164
192
  end
193
+
194
+ # "Copy that ability" (CR 707.10) after it has left the stack: the abilities that refer to it ({"triggering":
195
+ # "ability"}) remember it as it last existed on the stack, with its choices (CR 608.2h), to copy that.
196
+ def remember_ability!(obj)
197
+ refs = [obj.id, obj.memory["trigger_id"]].compact
198
+ holders = state.stack.map { object(it).memory } + state.pending_triggers.filter_map { it["memory"] }
199
+ holders.each do |memory|
200
+ triggering = memory["triggering"]
201
+ memory["ability_lki"] = obj.to_h if triggering.is_a?(Hash) && refs.include?(triggering["ability"]) && !memory.equal?(obj.memory)
202
+ end
203
+ end
204
+
205
+ # The ability `memory` remembers (see #remember_ability!), as a detached object that is never stored.
206
+ def remembered_ability(memory)
207
+ lki = memory["ability_lki"]
208
+ lki && Snapshot.build_object(lki)
209
+ end
165
210
  end
166
211
 
167
212
  include Resolution
@@ -35,10 +35,11 @@ module Enjine
35
35
  chars(obj).abilities.any? { it.ability.kind == :cast_restriction && !it.ability.allows?(self, index, obj) }
36
36
  end
37
37
 
38
- # CR 602.5, 101.2: abilities of a permanent matching a `cant_activate` filter can't be activated, nor any of a
39
- # permanent whose activated abilities can't be activated (#mana_abilities_forbidden?).
38
+ # CR 602.5, 101.2: abilities of a source a `cant_activate` rule is about can't be activated (a filter matches
39
+ # only permanents; "sources with the chosen name" are in any zone), nor any of a permanent whose activated
40
+ # abilities can't be activated (#mana_abilities_forbidden?).
40
41
  def activation_forbidden?(index, obj)
41
- obj.zone == :battlefield && (mana_abilities_forbidden?(obj) || player_rule?(index, "cant_activate", obj))
42
+ (obj.zone == :battlefield && mana_abilities_forbidden?(obj)) || player_rule?(index, "cant_activate", obj)
42
43
  end
43
44
 
44
45
  # CR 602.5, 605.3a: "its activated abilities can't be activated" covers its mana abilities too.
@@ -83,6 +84,7 @@ module Enjine
83
84
 
84
85
  # "Until your next turn" effects end as that player's next turn begins (CR 611.2a, 500.1).
85
86
  def end_effects_until_turn_of!(index)
87
+ end_copy_effects!(controller: index) # Engine::Copies
86
88
  ending = state.effects.count { it["duration"] == "until_your_next_turn" && it["controller"] == index }
87
89
  return if ending.zero?
88
90
 
@@ -202,7 +204,7 @@ module Enjine
202
204
  gain_control!(obj, controller, timestamp)
203
205
  state.effects << { "kind" => "control", "timestamp" => timestamp, "controller" => ctx.controller,
204
206
  "affected" => [obj.id], "duration" => duration, "previous" => previous,
205
- "source" => source }.compact
207
+ "source" => source, "turn" => duration == "end_of_your_next_turn" ? state.turn : nil }.compact
206
208
  emit Events::EffectStarted.new(kind: "control", affected: [obj.id], details: { "controller" => controller })
207
209
  end
208
210
 
@@ -93,16 +93,24 @@ module Enjine
93
93
 
94
94
  # CR 704.5d / 111.7: a token in a zone other than the battlefield ceases to exist. Phased-out tokens are
95
95
  # still on the battlefield (CR 702.26d), see Engine::Copies#ceases_to_exist?.
96
+ # Skipped while the zones are as last scanned (Engine::Zones#zones_version), unless a prepared copy lost its
97
+ # permanent since (Engine::Faces#unprepare!).
96
98
  def remove_tokens_outside_battlefield!
99
+ return false if @tokens_scanned == zones_version
100
+
97
101
  gone = state.objects.values.select { ceases_to_exist?(it) } # and copies, CR 707.10a (Engine::Copies)
98
102
  gone.each do |obj|
99
103
  state.zone_list(obj.zone, obj.owner).delete(obj.id)
100
104
  state.objects.delete(obj.id)
101
105
  emit Events::TokenCeased.new(object: obj.id, card: obj.card, zone: obj.zone.to_s)
102
106
  end
107
+ @tokens_scanned = zones_version
103
108
  !gone.empty?
104
109
  end
105
110
 
111
+ # The next state-based action check looks for tokens and copies to remove again.
112
+ def rescan_tokens! = @tokens_scanned = nil
113
+
106
114
  # CR 704.5j: the legend rule needs a choice, so it runs as a frame before priority.
107
115
  def legend_rule_first!(index)
108
116
  return false if state.frames.any? { it["type"] == "legend_rule" }
@@ -10,19 +10,6 @@ module Enjine
10
10
  # A permanent that left earlier in the same simultaneous zone change is remembered too (#simultaneously).
11
11
  def last_known(id) = @last_known&.[](id) || @departed_together&.dig(id, "lki")
12
12
 
13
- # What a permanent looked like as it last existed on the battlefield (CR 603.10a, 608.2h):
14
- # controller and current characteristics, so "a creature you control dies" checks the
15
- # types it had then, not its printed ones.
16
- def last_known_info(obj)
17
- current = chars(obj)
18
- { "controller" => obj.controller, "card" => obj.card, "types" => current.types, "subtypes" => current.subtypes,
19
- "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
20
- "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
21
- "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
22
- "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities }
23
- .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
24
- end
25
-
26
13
  def with_last_known(id, info)
27
14
  (@last_known ||= {})[id] = info
28
15
  yield
@@ -84,13 +71,15 @@ module Enjine
84
71
 
85
72
  # CR 603.7: creates a delayed triggered ability. `entry` names the card and the ability ref
86
73
  # (see Effects::DelayedTrigger) plus what it remembers ("results", "watched" objects) and, for
87
- # one with a duration ("this turn"), the turn it lasts for ("turn").
74
+ # one with a duration ("this turn"), the turn it lasts for ("turn"). "while_watched": it can only ever
75
+ # trigger on its watched permanent, so it ends once that permanent has left the battlefield (earthbend).
88
76
  def create_delayed_trigger!(entry)
89
77
  state.delayed_triggers << entry.merge("id" => "d#{next_timestamp!}")
90
78
  end
91
79
 
92
80
  # CR 603.7b: a delayed triggered ability triggers only once, the next time its event occurs, unless
93
81
  # it has a stated duration ("whenever ... this turn"): then it triggers each time until the turn ends.
82
+ # CR 400.7, 603.7c: one "while_watched" ends when the permanent it watches leaves to any zone.
94
83
  def watch_delayed!(event)
95
84
  state.delayed_triggers.reject! { it["turn"] && it["turn"] != state.turn } # "this turn" has ended
96
85
  fired = []
@@ -106,6 +95,8 @@ module Enjine
106
95
  end
107
96
  end
108
97
  state.delayed_triggers -= fired.reject { repeats?(it) }
98
+ gone = event.old_id if event.is_a?(Events::ZoneChanged) && event.from == "battlefield"
99
+ state.delayed_triggers.reject! { it["while_watched"] && Array(it["watched"]).include?(gone) } if gone
109
100
  end
110
101
 
111
102
  # "Whenever ... this turn" triggers each time; "the next ... this turn" ("once") only the first time; one
@@ -178,14 +169,20 @@ module Enjine
178
169
 
179
170
  # CR 113.6k: triggered abilities that function from a graveyard, controlled by the card's owner.
180
171
  def watch_graveyards!(event)
181
- state.players.each_with_index do |pl, owner|
182
- pl.graveyard.each do |id|
183
- instances = graveyard_triggers(object(id).card)
184
- next if instances.empty?
172
+ graveyard_trigger_holders.each do |id, owner, instances|
173
+ source = { "id" => id, "card" => object(id).card, "controller" => owner }
174
+ instances.each { queue_trigger(it, event, source) }
175
+ end
176
+ end
185
177
 
186
- source = { "id" => id, "card" => object(id).card, "controller" => owner }
187
- instances.each { queue_trigger(it, event, source) }
188
- end
178
+ # [[id, owner, instances]] of the cards in graveyards with such abilities, in graveyard order; kept while
179
+ # no object appears, moves or ceases to exist (Engine::Zones#zones_version).
180
+ def graveyard_trigger_holders
181
+ return @graveyard_holders if @graveyard_holders_version == zones_version
182
+
183
+ @graveyard_holders_version = zones_version
184
+ @graveyard_holders = state.players.each_with_index.flat_map do |pl, owner|
185
+ pl.graveyard.map { [it, owner, graveyard_triggers(object(it).card)] }.reject { it[2].empty? }
189
186
  end
190
187
  end
191
188
 
@@ -106,11 +106,26 @@ module Enjine
106
106
  "mana_value" => Mechanics::Amount.mana_value(self, obj) }
107
107
  end
108
108
 
109
+ # What a permanent looked like as it last existed on the battlefield (CR 603.10a, 608.2h):
110
+ # controller and current characteristics, so "a creature you control dies" checks the
111
+ # types it had then, not its printed ones.
112
+ def last_known_info(obj)
113
+ current = chars(obj)
114
+ { "controller" => obj.controller, "owner" => obj.owner, "card" => obj.card, "types" => current.types,
115
+ "subtypes" => current.subtypes,
116
+ "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
117
+ "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
118
+ "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
119
+ "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities,
120
+ "attacking" => attackers.key?(obj.id) } # "if it was attacking" (CR 506.4, 608.2h)
121
+ .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
122
+ end
123
+
109
124
  # The part of last known information an ability keeps in its memory ("source_lki"): plain data.
110
125
  def last_known_memory(lki)
111
126
  info = { "controller" => lki["controller"], "power" => lki["power"], "toughness" => lki["toughness"],
112
127
  "mana_value" => lki["mana_value"], "counters" => lki["counters"].dup, "card" => lki["card"],
113
- "keywords" => lki["keywords"].dup }
128
+ "keywords" => lki["keywords"].dup, "attacking" => lki["attacking"] }
114
129
  info["except"] = lki["except"] if lki["except"] # what a copy of it copies (CR 707.2, Engine::Copies)
115
130
  info.merge(lki.slice(Mechanics::Linked::EXILED).transform_values(&:dup)) # CR 607.2a (Linked.exiled_with)
116
131
  end
@@ -44,6 +44,7 @@ module Enjine
44
44
  obj = object(id)
45
45
  current = chars(obj)
46
46
  obj.tapped && obj.controller == index && !current.keyword?(:doesnt_untap) && !obj.memory["exerted"] &&
47
+ !current.keyword?(:cant_become_untapped) &&
47
48
  current.abilities.any? { it.ability.kind == :may_not_untap }
48
49
  end
49
50
  end