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
@@ -30,6 +30,20 @@ module Enjine
30
30
  obj.ability? ? stack_ability(obj) : definition(obj).spell_ability
31
31
  end
32
32
 
33
+ # CR 608.2n, 400.7: a spell that leaves the stack as part of its own resolution ("exile this spell") becomes a
34
+ # new object, but its resolution goes on: its resolve frame keeps the spell as it last existed on the stack
35
+ # ("left_stack"), which stands in for it (Engine#object) for the rest of its effects (a choice, a payment, a
36
+ # reflexive trigger) and as it finishes resolving.
37
+ def note_left_stack!(old)
38
+ frame = state.frames.rfind { it["type"] == "resolve" && it["object"] == old.id } or return
39
+ frame["left_stack"] = old.to_h
40
+ end
41
+
42
+ def resolving_stand_in(id)
43
+ frame = state.frames.rfind { it["type"] == "resolve" && it["object"] == id }
44
+ frame&.key?("left_stack") ? Snapshot.build_object(frame["left_stack"]) : nil
45
+ end
46
+
33
47
  def step_resolution!(frame)
34
48
  obj = object(frame["object"])
35
49
  ability = resolving_ability(obj)
@@ -47,14 +61,24 @@ module Enjine
47
61
  frame["pc"] += 1
48
62
  end
49
63
  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
64
+ return ask_enter_choice!(obj.id, obj.controller, frame["enter"]) # CR 614.12: decided before it enters
51
65
  end
52
66
 
67
+ gift_given!(obj, ability)
53
68
  emit Events::Resolved.new(object: obj.id, card: obj.card, kind: obj.kind)
54
69
  finish_resolution!(obj, frame)
55
70
  after_resolution!
56
71
  end
57
72
 
73
+ # CR 702.174c: a player gives a gift as their instant or sorcery spell whose gift was promised resolves, or as
74
+ # the gift triggered ability of their permanent resolves (an enters trigger checking "if the gift was promised").
75
+ def gift_given!(obj, ability)
76
+ given = if obj.ability? then ability.respond_to?(:condition) && Mechanics::Condition::CastHow.gift?(ability.condition)
77
+ else obj.memory["kicked_with"] == "gift" && (chars(obj).type?(:instant) || chars(obj).type?(:sorcery))
78
+ end
79
+ emit Events::KeywordAction.new(player: name(obj.controller), action: "give_gift", amount: nil) if given
80
+ end
81
+
58
82
  # CR 608.2b: targets are checked once, as resolution begins.
59
83
  def start_resolution!(frame, obj, ability)
60
84
  specs = ability&.targets_for(obj.modes || [], kicked: obj.memory.key?("kicked_with")) || []
@@ -93,6 +117,23 @@ module Enjine
93
117
  # Called by zone changes and token creation while an effect runs.
94
118
  def record_result!(id) = @recorded&.push(id)
95
119
 
120
+ # Runs the block recording apart what it moves or creates and how much it changes (an effect of a nested
121
+ # list with results of its own, Effects::Repeat); returns [the block's value, those objects, that amount].
122
+ # They also count for the effect running the nested list.
123
+ def recording_apart
124
+ outer = @recorded
125
+ outer_amount = @recorded_amount
126
+ @recorded = []
127
+ @recorded_amount = 0
128
+ value = yield
129
+ [value, @recorded, @recorded_amount]
130
+ ensure
131
+ inner = @recorded
132
+ inner_amount = @recorded_amount
133
+ @recorded = outer && (outer + inner)
134
+ @recorded_amount = outer_amount && (outer_amount + inner_amount)
135
+ end
136
+
96
137
  # The context for one effect; a modal ability's effects see only their mode's targets.
97
138
  # CR 603.4: a triggered ability whose intervening "if" is false on resolution does nothing.
98
139
  def intervening_if_holds?(obj, ability)
@@ -102,12 +143,18 @@ module Enjine
102
143
  end
103
144
 
104
145
  # `base` is the plan position of the first effect of this effect's list: result n is at base + n.
105
- # A delayed trigger's effects see the results of the list that created it instead.
146
+ # A delayed or reflexive trigger's effects see the results (and amounts) of the earlier effects of the list
147
+ # that created it first, then their own (StackAbility.parse_effects numbers them on, CR 603.7c, 603.12).
106
148
  def effect_context(data, offset = 0, count = nil, base = 0)
107
149
  targets = count ? data["targets"][offset, count] || [] : data["targets"]
108
150
  own = data["results"] || {}
109
- results = data["linked"] || Array.new([own.size - base, 0].max) { own[(base + it).to_s] || [] }
110
- amounts = data["linked_amounts"] || Array.new(results.size) { data.fetch("amounts", {})[(base + it).to_s] || 0 }
151
+ results = Array.new([own.size - base, 0].max) { own[(base + it).to_s] || [] }
152
+ amounts = Array.new(results.size) { data.fetch("amounts", {})[(base + it).to_s] || 0 }
153
+ if (linked = data["linked"])
154
+ linked_amounts = Array.new(linked.size) { data["linked_amounts"]&.[](it).to_i }
155
+ results = linked + results
156
+ amounts = linked_amounts + amounts
157
+ end
111
158
  Mechanics::EffectContext.new(data["controller"], data["source"], data["object"], targets, results, amounts)
112
159
  end
113
160
 
@@ -126,8 +173,8 @@ module Enjine
126
173
  # Targets that are still legal; illegal ones become nil and are ignored (CR 608.2b).
127
174
  def legal_targets(obj, specs)
128
175
  legal = lambda { |ref, spec|
129
- spec&.match_for?(self, ref, obj.controller,
130
- obj.source) && targetable?(ref, obj.controller, obj.source, targeter: obj.source || obj.id)
176
+ spec&.match_for?(self, ref, obj.controller, obj.source, ctx: x_context(obj.controller, obj.source, obj)) &&
177
+ targetable?(ref, obj.controller, obj.source, targeter: obj.source || obj.id)
131
178
  }
132
179
  (obj.targets || []).each_with_index.map do |ref, i|
133
180
  ref.is_a?(Array) ? ref.select { legal.call(it, specs[i]) } : (ref if legal.call(ref, specs[i])) # a counted slot's list
@@ -159,9 +206,27 @@ module Enjine
159
206
 
160
207
  # Abilities on the stack aren't cards; they simply cease to exist.
161
208
  def remove_stack_object!(id)
209
+ remember_ability!(object(id))
162
210
  state.stack.delete(id)
163
211
  state.objects.delete(id)
164
212
  end
213
+
214
+ # "Copy that ability" (CR 707.10) after it has left the stack: the abilities that refer to it ({"triggering":
215
+ # "ability"}) remember it as it last existed on the stack, with its choices (CR 608.2h), to copy that.
216
+ def remember_ability!(obj)
217
+ refs = [obj.id, obj.memory["trigger_id"]].compact
218
+ holders = state.stack.map { object(it).memory } + state.pending_triggers.filter_map { it["memory"] }
219
+ holders.each do |memory|
220
+ triggering = memory["triggering"]
221
+ memory["ability_lki"] = obj.to_h if triggering.is_a?(Hash) && refs.include?(triggering["ability"]) && !memory.equal?(obj.memory)
222
+ end
223
+ end
224
+
225
+ # The ability `memory` remembers (see #remember_ability!), as a detached object that is never stored.
226
+ def remembered_ability(memory)
227
+ lki = memory["ability_lki"]
228
+ lki && Snapshot.build_object(lki)
229
+ end
165
230
  end
166
231
 
167
232
  include Resolution
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Room permanents (CR 709.5, CardDefinition::Rooms). Which doors are unlocked is the face the permanent has up:
6
+ # its card is the combined card with both doors unlocked, "<id>/1" with only the left one, "<id>/2" with only
7
+ # the right one and "<id>/3" with neither. So its name, mana cost, mana value and abilities are always those of
8
+ # its unlocked doors (CR 709.5) with no special case elsewhere.
9
+ #
10
+ # A door cast as a spell (CR 709.3) is the spell's face; the permanent it becomes has that door unlocked
11
+ # (CR 709.5d) and "when you unlock this door" triggers (CR 709.5h). A Room put onto the battlefield any other way
12
+ # enters with both doors locked (Engine::Faces#card_after_move). Unlocking is a special action (Actions::Unlock,
13
+ # CR 116.2m, 709.5e).
14
+ module Rooms
15
+ FACE_DOORS = { 0 => %w[left right], 1 => %w[left], 2 => %w[right], 3 => [] }.freeze
16
+ DOOR_FACE = { "left" => 1, "right" => 2 }.freeze
17
+
18
+ def room?(obj) = !obj.memory["own_card"] && catalog.fetch(obj.card).layout == "room"
19
+
20
+ # The doors of a Room permanent that are unlocked (CR 709.5c), and those that are locked.
21
+ def unlocked_doors(obj) = room?(obj) && obj.zone == :battlefield ? FACE_DOORS.fetch(catalog.fetch(obj.card).face_index) : []
22
+ def locked_doors(obj) = room?(obj) && obj.zone == :battlefield ? CardDefinition::Rooms::DOORS - unlocked_doors(obj) : []
23
+
24
+ # A door's unlock cost: its mana cost (CR 709.5e).
25
+ def door_cost(obj, door) = catalog.fetch(obj.card).card.face(DOOR_FACE.fetch(door)).mana_cost
26
+
27
+ # The face a Room card has when it enters the battlefield not as a resolving door spell: both doors locked
28
+ # (CR 709.5d).
29
+ def room_locked_face(card) = catalog.fetch(card).card.face(CardDefinition::Rooms::LOCKED_FACE).id
30
+
31
+ # CR 116.2m, 709.5e: in a main phase of their turn with an empty stack, the player may unlock each locked door
32
+ # of each Room they control that they can pay for.
33
+ def unlock_options(index)
34
+ return [] unless sorcery_timing?(index)
35
+
36
+ state.battlefield.flat_map do |id|
37
+ obj = object(id)
38
+ next [] unless obj.controller == index && room?(obj)
39
+
40
+ locked_doors(obj).filter_map do |door|
41
+ cost = door_cost(obj, door)
42
+ { type: "unlock", object: id, door: door } if cost && affordable?(index, cost, nil)
43
+ end
44
+ end
45
+ end
46
+
47
+ # The permanent gets that door's unlocked designation (CR 709.5c, 709.5f); "when you unlock this door" and "when
48
+ # you fully unlock" trigger (CR 709.5h-i). `player`: who unlocked it.
49
+ def unlock_door!(obj, door, player = obj.controller)
50
+ return false unless locked_doors(obj).include?(door)
51
+
52
+ open = unlocked_doors(obj) + [door]
53
+ set_room_doors!(obj, open)
54
+ emit Events::DoorUnlocked.new(player: name(player), object: obj.id, door: door, fully: open.size == 2)
55
+ true
56
+ end
57
+
58
+ # CR 709.5g: the permanent loses that door's unlocked designation.
59
+ def lock_door!(obj, door)
60
+ return false unless unlocked_doors(obj).include?(door)
61
+
62
+ set_room_doors!(obj, unlocked_doors(obj) - [door])
63
+ emit Events::DoorLocked.new(object: obj.id, door: door)
64
+ true
65
+ end
66
+
67
+ # CR 709.5d, 709.5h: the permanent a door spell became has that door unlocked, which triggers abilities.
68
+ def room_entered!(fresh, old)
69
+ return unless old.zone == :stack && fresh.zone == :battlefield && room?(fresh)
70
+
71
+ door = FACE_DOORS.fetch(catalog.fetch(fresh.card).face_index)
72
+ return unless door.size == 1
73
+
74
+ emit Events::DoorUnlocked.new(player: name(fresh.controller), object: fresh.id, door: door.first, fully: false)
75
+ end
76
+
77
+ private
78
+
79
+ def set_room_doors!(obj, open)
80
+ index = FACE_DOORS.key(CardDefinition::Rooms::DOORS & open)
81
+ obj.card = catalog.fetch(obj.card).card.face(index).id
82
+ end
83
+ end
84
+ include Rooms
85
+ end
86
+ end
@@ -31,14 +31,16 @@ module Enjine
31
31
  # CR 101.2: "can't cast" beats any permission to cast. `obj`: the card (or stand-in) to be cast. The card's own
32
32
  # "you can't cast this spell unless ..." too (CR 601.3).
33
33
  def cast_forbidden?(index, obj)
34
- player_rule?(index, "cant_cast", obj) || (obj.zone != :hand && player_rule?(index, "cant_cast_except_from_hand")) ||
34
+ Mechanics::Keywords::SplitSecond.active?(self) || # CR 702.61b
35
+ player_rule?(index, "cant_cast", obj) || (obj.zone != :hand && player_rule?(index, "cant_cast_except_from_hand")) ||
35
36
  chars(obj).abilities.any? { it.ability.kind == :cast_restriction && !it.ability.allows?(self, index, obj) }
36
37
  end
37
38
 
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?).
39
+ # CR 602.5, 101.2: abilities of a source a `cant_activate` rule is about can't be activated (a filter matches
40
+ # only permanents; "sources with the chosen name" are in any zone), nor any of a permanent whose activated
41
+ # abilities can't be activated (#mana_abilities_forbidden?).
40
42
  def activation_forbidden?(index, obj)
41
- obj.zone == :battlefield && (mana_abilities_forbidden?(obj) || player_rule?(index, "cant_activate", obj))
43
+ (obj.zone == :battlefield && mana_abilities_forbidden?(obj)) || player_rule?(index, "cant_activate", obj)
42
44
  end
43
45
 
44
46
  # CR 602.5, 605.3a: "its activated abilities can't be activated" covers its mana abilities too.
@@ -49,6 +49,7 @@ module Enjine
49
49
  state.result = { "winner" => winner, "reason" => reason }
50
50
  ask!(nil)
51
51
  state.frames.clear
52
+ reveal_face_down_at_end! # CR 708.9 (Engine::FaceDownPermanents)
52
53
  emit Events::GameEnded.new(winner: winner, reason: reason)
53
54
  end
54
55
 
@@ -64,19 +65,39 @@ module Enjine
64
65
  state.battlefield.each do |id|
65
66
  obj = object(id)
66
67
  defn = chars(obj)
67
- reason = if defn.creature? then creature_sba(obj)
68
- elsif defn.planeswalker? && loyalty(obj) <= 0 then "sba_loyalty"
69
- end
68
+ reason = defn.creature? ? creature_sba(obj) : noncreature_sba(obj, defn)
70
69
  reason ||= "sba_aura" if illegal_aura?(obj) # CR 704.5m
71
70
  reason ||= "sacrifice" if saga_complete?(obj) # CR 704.5s: its controller sacrifices it
72
71
  (doomed ||= []) << [id, reason] if reason
73
72
  end
74
73
  return ceased unless doomed
75
74
 
76
- simultaneously { doomed.each { |id, reason| move!(id, :graveyard, reason: reason) } } # CR 704.3, 603.10a
75
+ in_batch("sba:#{state.next_id}") do # CR 704.3, 603.2c, 603.10a: at once, one event batch
76
+ simultaneously { doomed.each { |id, reason| move!(id, :graveyard, reason: reason) } }
77
+ end
77
78
  true
78
79
  end
79
80
 
81
+ # CR 704.5i: a planeswalker with 0 loyalty is put into its owner's graveyard; a battle, see #battle_sba.
82
+ def noncreature_sba(obj, current)
83
+ return "sba_loyalty" if current.planeswalker? && loyalty(obj) <= 0
84
+
85
+ battle_sba(obj) if current.type?(:battle)
86
+ end
87
+
88
+ # CR 704.5v, 310.7: a battle with defense 0 is put into its owner's graveyard, unless it's the source of a
89
+ # triggered ability that has triggered but not yet left the stack (a Siege's defeat trigger, CR 310.12).
90
+ # CR 704.5x: a Siege its protector controls gets a new protector from among its controller's opponents (no
91
+ # choice in a two-player game).
92
+ def battle_sba(obj)
93
+ obj.memory["protector"] = state.opponent(obj.controller) if protector(obj) == obj.controller && chars(obj).subtypes.include?(:siege)
94
+ return nil if obj.counters.fetch("defense", 0).positive?
95
+
96
+ waiting = state.pending_triggers.any? { it["source"] == obj.id } ||
97
+ state.stack.any? { (ability = object(it)).ability? && ability.source == obj.id && ability.memory.key?("trigger_id") }
98
+ waiting ? nil : "sba_defense"
99
+ end
100
+
80
101
  # CR 704.5q, 122.3: N +1/+1 and N -1/-1 counters are removed, N the smaller count.
81
102
  def annihilate_counters!
82
103
  hit = state.battlefield.filter_map do |id|
@@ -10,20 +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, "owner" => obj.owner, "card" => obj.card, "types" => current.types,
19
- "subtypes" => current.subtypes,
20
- "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
21
- "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
22
- "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
23
- "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities }
24
- .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
25
- end
26
-
27
13
  def with_last_known(id, info)
28
14
  (@last_known ||= {})[id] = info
29
15
  yield
@@ -55,6 +41,7 @@ module Enjine
55
41
  watch_delayed!(event) unless state.delayed_triggers.empty?
56
42
  watch_speed!(event) # CR 702.179d (Engine::Speed)
57
43
  Mechanics::Keywords::Suspend.watch!(self, event) # CR 702.62a: suspended cards in exile
44
+ Mechanics::Abilities::Miracle.watch!(self, event) # CR 702.94a: the first card drawn this turn
58
45
  end
59
46
 
60
47
  # "For the first time each turn" (trigger counters_placed with first_time_this_turn): every placement of
@@ -85,13 +72,15 @@ module Enjine
85
72
 
86
73
  # CR 603.7: creates a delayed triggered ability. `entry` names the card and the ability ref
87
74
  # (see Effects::DelayedTrigger) plus what it remembers ("results", "watched" objects) and, for
88
- # one with a duration ("this turn"), the turn it lasts for ("turn").
75
+ # one with a duration ("this turn"), the turn it lasts for ("turn"). "while_watched": it can only ever
76
+ # trigger on its watched permanent, so it ends once that permanent has left the battlefield (earthbend).
89
77
  def create_delayed_trigger!(entry)
90
78
  state.delayed_triggers << entry.merge("id" => "d#{next_timestamp!}")
91
79
  end
92
80
 
93
81
  # CR 603.7b: a delayed triggered ability triggers only once, the next time its event occurs, unless
94
82
  # it has a stated duration ("whenever ... this turn"): then it triggers each time until the turn ends.
83
+ # CR 400.7, 603.7c: one "while_watched" ends when the permanent it watches leaves to any zone.
95
84
  def watch_delayed!(event)
96
85
  state.delayed_triggers.reject! { it["turn"] && it["turn"] != state.turn } # "this turn" has ended
97
86
  fired = []
@@ -107,6 +96,8 @@ module Enjine
107
96
  end
108
97
  end
109
98
  state.delayed_triggers -= fired.reject { repeats?(it) }
99
+ gone = event.old_id if event.is_a?(Events::ZoneChanged) && event.from == "battlefield"
100
+ state.delayed_triggers.reject! { it["while_watched"] && Array(it["watched"]).include?(gone) } if gone
110
101
  end
111
102
 
112
103
  # "Whenever ... this turn" triggers each time; "the next ... this turn" ("once") only the first time; one
@@ -216,19 +207,25 @@ module Enjine
216
207
  return if once_each_turn_used!(ability, inst.ref, source)
217
208
 
218
209
  memory = trigger_memory(source)
210
+ memory = memory.merge("source_moved_to" => event.new_id) if source_left?(trigger, event, source)
219
211
  batch = trigger.respond_to?(:batched?) && trigger.batched? ? event_batch : nil
220
212
  times = 1 + additional_triggers(event, source)
221
213
  card, ref, granter = AbilityLayers.granted_parts(inst.ref) # a granted ability lives in the granting card's data (CR 613.1f)
222
214
  queued = source.merge("ability" => ref || inst.ref, "card" => card || source["card"])
223
215
  memory = memory.merge("granter" => granter) if granter # CR 607.1a (Selector "granter")
224
216
  found.first(limited?(ability) ? 1 : found.size).each do |facts|
225
- next if batch && batched_pending!(source, queued["ability"], batch)
217
+ next if batch && batched_pending!(source, queued["ability"], batch, facts)
226
218
 
227
- facts = facts.merge("amount" => 1) if batch # "that many": the occurrences so far (batched_pending!)
228
- times.times { queue_pending_trigger!(queued, event, memory.merge("triggering" => facts), batch: batch) }
219
+ # "that many" / "those": the occurrences and their objects so far (batched_pending!)
220
+ facts = facts.merge("amount" => 1, "objects" => [facts["object"]].compact) if batch
221
+ times.times { queue_pending_trigger!(queued, event, memory.merge("triggering" => Snapshot.deep_copy(facts)), batch: batch) }
229
222
  end
230
223
  end
231
224
 
225
+ # CR 400.7e, 603.10a: a leaves-the-battlefield ability of the permanent that left ("when this dies, return it to
226
+ # its owner's hand") can find the new object it became; Selector "self" looks for it.
227
+ def source_left?(trig, event, src) = trig.leaves_battlefield? && event.is_a?(Events::ZoneChanged) && event.old_id == src["id"]
228
+
232
229
  # A once-each-turn limit: remembered on the source object, so the same card
233
230
  # as a new object (CR 400.7) may trigger again.
234
231
  def limited?(ability) = ability.respond_to?(:limit) && !ability.limit.nil?
@@ -266,18 +263,24 @@ module Enjine
266
263
  # The event batch an event belongs to, for "one or more" triggers (CR 603.2c): everything one effect
267
264
  # of a resolving spell or ability does, or one cast or activation (its costs). Outside those, each
268
265
  # event is its own batch.
266
+ # Events that happen at once outside those (state-based actions, CR 704.3) share the batch `in_batch` names.
269
267
  def event_batch
268
+ return @event_batch if @event_batch
269
+
270
270
  frame = state.frames.last or return "event:#{state.next_id}"
271
271
  "#{frame["type"]}:#{frame["object"]}:#{frame["pc"]}"
272
272
  end
273
273
 
274
274
  # Whether a "one or more" trigger already waits for this batch. If so, this occurrence joins it: its
275
- # "that many" counts the occurrences in the batch (CR 603.2c).
276
- def batched_pending!(source, ref, batch)
275
+ # "that many" counts the occurrences in the batch and its "those" ({"triggering": "objects"}) gains the
276
+ # occurrence's object (CR 603.2c).
277
+ def batched_pending!(source, ref, batch, found = {})
277
278
  waiting = state.pending_triggers.select { it["source"] == source["id"] && it["ability"] == ref && it["batch"] == batch }
278
279
  waiting.each do |trigger|
279
280
  facts = trigger["memory"]["triggering"]
280
281
  facts["amount"] = facts.fetch("amount", 1) + 1
282
+ objects = (facts["objects"] ||= [])
283
+ objects << found["object"] if found["object"] && !objects.include?(found["object"])
281
284
  end
282
285
  !waiting.empty?
283
286
  end
@@ -340,6 +343,8 @@ module Enjine
340
343
  # CR 107.3m: an enters-the-battlefield trigger uses the X its permanent was cast with.
341
344
  def entered_x(trigger)
342
345
  event = trigger["event"]
346
+ # "When you cycle this card, ... with mana value X": the X of the activated ability (CR 702.29c, 107.3).
347
+ return state.objects[event["object"]]&.x if event["type"] == "ability_activated"
343
348
  return nil unless event["type"] == "zone_changed" && event["to"] == "battlefield" &&
344
349
  event["new_id"] == trigger["source"]
345
350
 
@@ -25,6 +25,9 @@ module Enjine
25
25
  # "returned" permanents returned to their hand from the battlefield
26
26
  # "drawn" / "discarded" how many cards they drew (CR 121.2) / discarded (CR 701.9a)
27
27
  # "dilemmas" dilemmas they faced (CR 700.17)
28
+ # "crimes" crimes they committed (CR 700.13)
29
+ # "entered_face_down" / "turned_face_up" permanents that entered face down under their control / that they
30
+ # turned face up (CR 708.3, 708.8)
28
31
  # "noncombat_damage" noncombat damage dealt to them (CR 120.2b)
29
32
  # "coin_flips" coins they flipped (CR 705)
30
33
  # The game log also counts the turns each player has begun ("turns").
@@ -41,6 +44,8 @@ module Enjine
41
44
  zone_change_recorded!(event)
42
45
  discard_recorded!(event) # mayhem (Engine::AltCasting)
43
46
  when Events::DilemmaFaced then bump!(log_of(event.player), "dilemmas", 1)
47
+ when Events::CrimeCommitted then bump!(log_of(event.player), "crimes", 1) # CR 700.13 (Engine::Crimes)
48
+ when Events::TurnedFaceUp then bump!(log_of(event.player), "turned_face_up", 1) # CR 708.8
44
49
  when Events::AttackerDeclared then attack_recorded!(event)
45
50
  when Events::AttacksDeclared # the attacking creatures' total power, per combat (Triggers::PlayerAttacks)
46
51
  (log_of(event.player)["attack_powers"] ||= []) << event.attackers.sum { power(object(it)) }
@@ -106,15 +111,45 @@ module Enjine
106
111
  "mana_value" => Mechanics::Amount.mana_value(self, obj) }
107
112
  end
108
113
 
114
+ # What a permanent looked like as it last existed on the battlefield (CR 603.10a, 608.2h):
115
+ # controller and current characteristics, so "a creature you control dies" checks the
116
+ # types it had then, not its printed ones.
117
+ def last_known_info(obj)
118
+ current = chars(obj)
119
+ { "controller" => obj.controller, "owner" => obj.owner, "card" => obj.card, "types" => current.types,
120
+ "subtypes" => current.subtypes,
121
+ "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
122
+ "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
123
+ "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
124
+ "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities,
125
+ "attacking" => attackers.key?(obj.id), # "if it was attacking" (CR 506.4, 608.2h)
126
+ "memory" => cast_memory(obj) } # how it was cast, for its leaves-the-battlefield triggers (CR 400.7d)
127
+ .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
128
+ end
129
+
130
+ # What a permanent remembers of the spell it was (CR 400.7d): whether it was cast, kicked, how and from where,
131
+ # and the mana spent on it (CR 601.2h). Plain data; empty for a permanent that wasn't cast.
132
+ CAST_MEMORY = %w[cast kicked cast_from cast_with kicked_with mana_from].freeze
133
+
134
+ def cast_memory(obj)
135
+ memory = Snapshot.deep_copy(obj.memory.slice(*CAST_MEMORY))
136
+ memory["mana_spent"] = obj.mana_spent.dup if obj.mana_spent
137
+ memory
138
+ end
139
+
109
140
  # The part of last known information an ability keeps in its memory ("source_lki"): plain data.
110
141
  def last_known_memory(lki)
111
142
  info = { "controller" => lki["controller"], "power" => lki["power"], "toughness" => lki["toughness"],
112
143
  "mana_value" => lki["mana_value"], "counters" => lki["counters"].dup, "card" => lki["card"],
113
- "keywords" => lki["keywords"].dup }
144
+ "keywords" => lki["keywords"].dup, "attacking" => lki["attacking"] }
114
145
  info["except"] = lki["except"] if lki["except"] # what a copy of it copies (CR 707.2, Engine::Copies)
115
146
  info.merge(lki.slice(Mechanics::Linked::EXILED).transform_values(&:dup)) # CR 607.2a (Linked.exiled_with)
116
147
  end
117
148
 
149
+ # What a source that is being looked at while its leaves-the-battlefield trigger is checked remembered of the
150
+ # spell it was (CR 400.7d, 603.4): the ability isn't on the stack yet, and the permanent is gone.
151
+ def departed_cast_memory(id) = last_known(id)&.[]("memory")
152
+
118
153
  # What the resolving spell or ability remembers about an object that left the battlefield during it.
119
154
  def resolving_last_known(id) = state.frames.rfind { it["type"] == "resolve" && it["ctx"] }&.dig("ctx", "lki", id)
120
155
 
@@ -190,6 +225,7 @@ module Enjine
190
225
  def entered_recorded!(event)
191
226
  obj = state.objects[event.new_id] or return
192
227
  (turn_log(obj.controller)["entered"] ||= []) << history_entry(event.card, chars(obj))
228
+ bump!(turn_log(obj.controller), "entered_face_down", 1) if face_down_object?(obj) # CR 708.3
193
229
  end
194
230
 
195
231
  # CR 305.1: the player who plays a land controls it as it enters.
@@ -245,16 +281,18 @@ module Enjine
245
281
 
246
282
  # What a triggered ability remembers of its source: whether it was cast (CR 400.7d) and kicked (CR 702.33d),
247
283
  # how it was cast, the mana spent to cast it (CR 601.2h) and, for a source that just left the battlefield
248
- # ("when this leaves, put its counters on ..."), how it last existed (CR 603.10a, 608.2h).
284
+ # ("when this leaves, put its counters on ..."), how it last existed (CR 603.10a, 608.2h), the way it was cast
285
+ # included ("when this dies, if it was cast from your hand").
249
286
  def trigger_memory(source)
250
287
  obj = state.objects[source["id"]]
251
- source_memory = obj&.memory || {}
288
+ lki = last_known(source["id"])
289
+ source_memory = obj&.memory || lki&.[]("memory") || {}
252
290
  memory = source_memory["cast"] ? { "source_cast" => true } : {}
253
291
  memory["kicked"] = true if source_memory["kicked"] # CR 702.33d: a kicked permanent's "if it was kicked"
254
292
  memory.merge!(source_memory.slice("cast_from", "cast_with", "kicked_with")) # "if its evoke cost was paid" (Engine::AltCasting)
255
- memory["source_mana_spent"] = obj.mana_spent.dup if obj&.mana_spent
293
+ spent = obj ? obj.mana_spent : source_memory["mana_spent"]
294
+ memory["source_mana_spent"] = spent.dup if spent
256
295
  memory["source_mana_from"] = Snapshot.deep_copy(source_memory["mana_from"]) if source_memory["mana_from"]
257
- lki = last_known(source["id"])
258
296
  memory["source_lki"] = last_known_memory(lki) if lki
259
297
  memory
260
298
  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
@@ -82,9 +82,11 @@ module Enjine
82
82
  def propose(kind, data, applied = []) = Replacements.apply(self, Proposal.new(kind, data, applied.dup))
83
83
 
84
84
  # `face_down`: exile it face down (CR 406.3); the list of player indices who may look at it.
85
- def move!(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
85
+ # `face_down_as`: it goes to the battlefield or the stack face down, as "manifest", "cloak", "morph" or
86
+ # "disguise" (Engine::FaceDownPermanents).
87
+ def move!(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil, face_down_as: nil)
86
88
  data = plan_move(id, to, reason: reason, position: position, controller: controller, enters: enters,
87
- face_down: face_down)
89
+ face_down: face_down, face_down_as: face_down_as)
88
90
  data && execute_zone_change!(data)
89
91
  end
90
92
 
@@ -94,9 +96,10 @@ module Enjine
94
96
 
95
97
  # The zone change `move!` would make, after replacement effects (CR 614), not yet executed; nil if a
96
98
  # replacement cancelled it. Planning several before executing any lets them happen at once (CR 614.12).
97
- def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
99
+ def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil, face_down_as: nil)
98
100
  data = { "object" => id, "to" => to, "position" => position, "reason" => reason, "controller" => controller }
99
101
  data["face_down"] = face_down if face_down && to == :exile
102
+ data["face_down_as"] = face_down_as if face_down_as && %i[battlefield stack].include?(to)
100
103
  data["enters"] = { "tapped" => enters&.fetch("tapped", false) == true, "counters" => {} } if to == :battlefield
101
104
  data["enters"]["face"] = enters["face"] if data["enters"] && enters&.key?("face") # seen by its own replacements
102
105
  data = propose("zone_change", data).data
@@ -110,7 +113,10 @@ module Enjine
110
113
  def depart!(old)
111
114
  lki = old.zone == :battlefield ? last_known_info(old) : nil # before it leaves (CR 603.10a)
112
115
  remember_last_known!(old.id, lki) if lki # CR 608.2h (see Engine::TurnHistory)
113
- remember_spell!(old) if old.zone == :stack && !old.ability? # a countered spell's mana spent (Engine::TurnHistory)
116
+ if old.zone == :stack && !old.ability?
117
+ remember_spell!(old) # a countered spell's mana spent (Engine::TurnHistory)
118
+ note_left_stack!(old) # while it resolves (Engine::Resolution)
119
+ end
114
120
  state.zone_list(old.zone, old.owner).delete(old.id)
115
121
  state.objects.delete(old.id)
116
122
  lki
@@ -122,25 +128,45 @@ module Enjine
122
128
  old = object(id)
123
129
  lki = depart!(old)
124
130
  face_down = to == :exile ? data["face_down"] : nil
125
- fresh = create_object(card_after_move(old, to), old.owner, to, hidden: !face_down.nil?) # front face up (Engine::Faces)
131
+ as = face_down_as(old, to, data) # CR 708.3, 708.4 (Engine::FaceDownPermanents)
132
+ fresh = create_object(card_after_move(old, to), old.owner, to, hidden: !face_down.nil? || !as.nil?) # front face up (Engine::Faces)
126
133
  carry_copy_status!(fresh, old, to) # a token or copy stays one (Engine::Copies)
127
134
  left_battlefield!(fresh, old) if lki
128
135
  arrive!(fresh, old, data)
129
136
  fresh.memory.merge!("face_down" => true, "may_look" => face_down.uniq.sort) if face_down
137
+ turn_face_down!(fresh, as) if as
130
138
  place!(fresh, data)
131
139
  record_result!(fresh.id)
132
140
  note_commander_move!(fresh) # CR 903.9
133
141
  event = Events::ZoneChanged.new(card: old.card, old_id: id, new_id: fresh.id, owner: name(old.owner),
134
142
  from: old.zone.to_s, to: to.to_s, reason: data["reason"],
135
- lookers: face_down&.map { name(it) })
143
+ lookers: zone_change_lookers(fresh, face_down, as))
136
144
  lki ? with_last_known(id, lki) { emit event } : emit(event)
145
+ reveal_face_down_left!(old, fresh) # CR 708.9
137
146
  return_exiled_until_leaves!(old) if lki # CR 610.3
138
147
  unmeld!(old, to, data) if old.memory["melded"] # CR 713.8 (Engine::Faces)
139
148
  prepare!(fresh) if to == :battlefield && data["enters"]["prepared"] # "enters prepared" (CR 723.3a)
149
+ room_entered!(fresh, old) if to == :battlefield # CR 709.5d, 709.5h (Engine::Rooms)
140
150
  run_follow_ups!(data, "object" => fresh.id) # "exile it instead. When you do, ..." (Engine::FollowUps)
141
151
  fresh
142
152
  end
143
153
 
154
+ # What a moving object is face down as on arrival: as the move says, or as the face-down spell it was
155
+ # (CR 702.37c, 702.168b: the permanent has the spell's characteristics); nil when it's face up.
156
+ def face_down_as(old, to, data)
157
+ return data["face_down_as"] if data["face_down_as"]
158
+
159
+ old.memory["face_down_as"] if old.zone == :stack && to == :battlefield
160
+ end
161
+
162
+ # Who sees which card moved: the players who may look at a card exiled face down (CR 406.3), the controller of
163
+ # a face-down spell or permanent (CR 708.5); nil when everyone who sees the zones does.
164
+ def zone_change_lookers(fresh, face_down, kind)
165
+ return face_down.map { name(it) } if face_down
166
+
167
+ kind && [name(fresh.controller)]
168
+ end
169
+
144
170
  # Puts the new object into its zone's list; on the battlefield, as what it enters as (#enter_as!).
145
171
  def place!(fresh, data)
146
172
  list = state.zone_list(data["to"], fresh.owner)
@@ -189,6 +215,8 @@ module Enjine
189
215
  fresh.x = old.x
190
216
  fresh.memory.merge!(old.memory.slice("kicked", "kicked_with", "gift")) # gift: CR 702.174b
191
217
  fresh.mana_spent = old.mana_spent&.dup
218
+ # CR 609.7b: a prevention effect for a chosen permanent spell also applies to the permanent it becomes.
219
+ state.effects.each { it["by"] << fresh.id if it["kind"] == "prevent_damage" && it["by"]&.include?(old.id) }
192
220
  end
193
221
 
194
222
  # CR 111.1: a token enters the battlefield under its creator's control. Entering replacement
@@ -213,7 +241,7 @@ module Enjine
213
241
  obj.counters.merge!(enters["counters"])
214
242
  enter_as_copy!(obj, enters["copy"]) if enters["copy"] # CR 707.5 (Engine::Copies)
215
243
  state.battlefield.unshift(obj.id)
216
- enter_attacking!(obj) if enters["attacking"] # CR 508.4
244
+ enter_attacking!(obj, enters["attacking"]) if enters["attacking"] # CR 508.4
217
245
  record_result!(obj.id)
218
246
  emit Events::ZoneChanged.new(card: definition.id, old_id: nil, new_id: obj.id, owner: name(controller),
219
247
  from: "none", to: "battlefield", reason: "create_token")
@@ -263,9 +291,10 @@ module Enjine
263
291
  end
264
292
 
265
293
  # CR 701.26b: only tapped permanents can be untapped. Replacement effects (a stun counter,
266
- # CR 122.1d) may stop it.
294
+ # CR 122.1d) may stop it, and "can't become untapped" forbids it (CR 101.2).
267
295
  def untap!(object)
268
296
  return unless object.tapped
297
+ return if chars(object).keyword?(:cant_become_untapped)
269
298
  return if propose("untap", { "object" => object.id }).data["cancelled"]
270
299
 
271
300
  object.tapped = false