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
@@ -88,6 +88,10 @@ module Enjine
88
88
  data && execute_zone_change!(data)
89
89
  end
90
90
 
91
+ # Changes whenever an object appears or moves (as a new object, CR 400.7, advancing state.next_id) or ceases
92
+ # to exist, and when the whole state is replaced: what is in which zone holds while it stays the same.
93
+ def zones_version = [state.object_id, state.next_id, state.objects.size]
94
+
91
95
  # The zone change `move!` would make, after replacement effects (CR 614), not yet executed; nil if a
92
96
  # replacement cancelled it. Planning several before executing any lets them happen at once (CR 614.12).
93
97
  def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
@@ -123,8 +127,7 @@ module Enjine
123
127
  left_battlefield!(fresh, old) if lki
124
128
  arrive!(fresh, old, data)
125
129
  fresh.memory.merge!("face_down" => true, "may_look" => face_down.uniq.sort) if face_down
126
- list = state.zone_list(to, old.owner)
127
- data["position"] == :bottom ? list.push(fresh.id) : list.unshift(fresh.id)
130
+ place!(fresh, data)
128
131
  record_result!(fresh.id)
129
132
  note_commander_move!(fresh) # CR 903.9
130
133
  event = Events::ZoneChanged.new(card: old.card, old_id: id, new_id: fresh.id, owner: name(old.owner),
@@ -138,6 +141,19 @@ module Enjine
138
141
  fresh
139
142
  end
140
143
 
144
+ # Puts the new object into its zone's list; on the battlefield, as what it enters as (#enter_as!).
145
+ def place!(fresh, data)
146
+ list = state.zone_list(data["to"], fresh.owner)
147
+ data["position"] == :bottom ? list.push(fresh.id) : list.unshift(fresh.id)
148
+ enter_as!(fresh, data["enters"]["as"]) if data["to"] == :battlefield && data["enters"]["as"]
149
+ end
150
+
151
+ # "Return it to the battlefield. It's an enchantment. (It's not a creature.)": what it is from the moment it
152
+ # enters (CR 614.1c, 205.1a), applied before the event, so abilities triggering on it entering see it so.
153
+ def enter_as!(obj, become)
154
+ become.apply(self, Mechanics::EffectContext.new(obj.controller, obj.id, obj.id, [], []))
155
+ end
156
+
141
157
  # A permanent that left the battlefield: the resolving spell or ability links the new object to it (CR 400.7,
142
158
  # 608.2h; Engine::TurnHistory), it leaves combat, and effects lasting while it stays end (CR 611.2b).
143
159
  def left_battlefield!(fresh, old)
@@ -173,6 +189,8 @@ module Enjine
173
189
  fresh.x = old.x
174
190
  fresh.memory.merge!(old.memory.slice("kicked", "kicked_with", "gift")) # gift: CR 702.174b
175
191
  fresh.mana_spent = old.mana_spent&.dup
192
+ # CR 609.7b: a prevention effect for a chosen permanent spell also applies to the permanent it becomes.
193
+ state.effects.each { it["by"] << fresh.id if it["kind"] == "prevent_damage" && it["by"]&.include?(old.id) }
176
194
  end
177
195
 
178
196
  # CR 111.1: a token enters the battlefield under its creator's control. Entering replacement
@@ -197,7 +215,7 @@ module Enjine
197
215
  obj.counters.merge!(enters["counters"])
198
216
  enter_as_copy!(obj, enters["copy"]) if enters["copy"] # CR 707.5 (Engine::Copies)
199
217
  state.battlefield.unshift(obj.id)
200
- enter_attacking!(obj) if enters["attacking"] # CR 508.4
218
+ enter_attacking!(obj, enters["attacking"]) if enters["attacking"] # CR 508.4
201
219
  record_result!(obj.id)
202
220
  emit Events::ZoneChanged.new(card: definition.id, old_id: nil, new_id: obj.id, owner: name(controller),
203
221
  from: "none", to: "battlefield", reason: "create_token")
@@ -247,9 +265,10 @@ module Enjine
247
265
  end
248
266
 
249
267
  # CR 701.26b: only tapped permanents can be untapped. Replacement effects (a stun counter,
250
- # CR 122.1d) may stop it.
268
+ # CR 122.1d) may stop it, and "can't become untapped" forbids it (CR 101.2).
251
269
  def untap!(object)
252
270
  return unless object.tapped
271
+ return if chars(object).keyword?(:cant_become_untapped)
253
272
  return if propose("untap", { "object" => object.id }).data["cancelled"]
254
273
 
255
274
  object.tapped = false
data/lib/enjine/events.rb CHANGED
@@ -76,7 +76,10 @@ module Enjine
76
76
  def gain = [to - from, 0].max
77
77
  def loss = [from - to, 0].max
78
78
  end
79
- CountersChanged = define(:counters_changed, :object, :counter, :from, :to)
79
+ # `by`: the player who put the counters on (CR 122.6a), nil for removals; absent in older histories.
80
+ CountersChanged = define(:counters_changed, :object, :counter, :from, :to, :by) do
81
+ def initialize(by: nil, **) = super # rubocop:disable Naming/MethodParameterName -- the event field
82
+ end
80
83
  PlayerCountersChanged = define(:player_counters_changed, :player, :counter, :from, :to) # poison, rad, ... (CR 122.1)
81
84
  EmblemCreated = define(:emblem_created, :player, :object, :card) # CR 114.2
82
85
  # CR 705: a coin flip; `won` is nil for a flip no one wins or loses (CR 705.2).
@@ -85,6 +88,8 @@ module Enjine
85
88
  RolledDie = define(:rolled_die, :player, :sides, :result)
86
89
  # CR 707.10: a copy of a spell put on the stack (not cast).
87
90
  SpellCopied = define(:spell_copied, :player, :object, :card, :original, :targets)
91
+ # New targets chosen for a spell or ability (CR 115.7); `player`: its controller, `targets`: the added ones.
92
+ TargetsChanged = define(:targets_changed, :player, :object, :targets)
88
93
  EffectStarted = define(:effect_started, :kind, :affected, :details)
89
94
  EffectsEnded = define(:effects_ended, :count)
90
95
  AttackerDeclared = define(:attacker_declared, :object, :target)
data/lib/enjine/frames.rb CHANGED
@@ -45,7 +45,7 @@ module Enjine
45
45
  # Resolving the top object of the stack, one effect at a time (CR 608).
46
46
  class Resolve < Base
47
47
  def self.step(engine, frame) = engine.step_resolution!(frame)
48
- def self.decisions = %w[effect_choice enter_choice]
48
+ def self.decisions = %w[effect_choice enter_choice damage_order]
49
49
 
50
50
  def self.validate(frame, data, errors)
51
51
  errors << "frames: resolving object #{frame["object"]} is not on the stack" unless data["stack"].include?(frame["object"])
@@ -56,7 +56,7 @@ module Enjine
56
56
  # Assigning and dealing combat damage (CR 510).
57
57
  class CombatDamage < Base
58
58
  def self.step(engine, frame) = engine.step_combat_damage!(frame)
59
- def self.decisions = %w[assign_damage]
59
+ def self.decisions = %w[assign_damage damage_order]
60
60
  end
61
61
  register("combat_damage", CombatDamage)
62
62
 
data/lib/enjine/mana.rb CHANGED
@@ -33,6 +33,9 @@ module Enjine
33
33
  # The cost with X replaced by `value` (CR 107.3a): each {X} adds that much generic mana.
34
34
  def with_x(value) = with(generic: generic + (x_symbols * value), x_symbols: 0)
35
35
 
36
+ # How many of its mana symbols are of `color`: colored ones and hybrid ones with that color (CR 107.4e).
37
+ def symbols_of(color) = colored.fetch(color, 0) + hybrid.count { it.include?(color) }
38
+
36
39
  # The colors of the cost's colored and hybrid symbols, in WUBRG order (CR 202.2, 202.2d, 107.4e).
37
40
  def colors = COLORS.select { |c| colored.key?(c) || hybrid.any? { it.include?(c) } }
38
41
 
@@ -12,7 +12,7 @@ module Enjine
12
12
  module Chosen
13
13
  # What is chosen -> [memory key, option key].
14
14
  MEMORY = { "color" => "chosen_color", "creature_type" => "chosen_type", "card_type" => "chosen_card_type",
15
- "basic_land_type" => "chosen_type", "option" => "chosen_option" }.freeze
15
+ "basic_land_type" => "chosen_type", "option" => "chosen_option", "card_name" => "chosen_name" }.freeze
16
16
  # CR 105.4: one of the five colors.
17
17
  COLORS = %w[W U B R G].freeze
18
18
  # CR 205.2a: the card types of traditional Magic cards.
@@ -124,14 +124,23 @@ module Enjine
124
124
  module Effects
125
125
  # "Choose a creature type." while resolving: the choice is remembered on the resolving spell or
126
126
  # ability, so its later effects' filters ("of the chosen type") and conditions read it (CR 607.2d).
127
+ # `remember: "source"` also remembers it on the source permanent, for its other abilities ("When this
128
+ # land enters, choose a land card name. ... Lands with the chosen name have ...", CR 607.2d).
127
129
  class ResolvingChosen < ChoiceEffect
128
130
  def self.kind_name = raise(NotImplementedError)
129
131
  def self.default_to = "you"
130
- def self.keys = kind_name == "option" ? %w[options to if] : %w[to if]
132
+ def self.keys = (kind_name == "option" ? %w[options] : []) + %w[remember to if]
131
133
 
132
- def setup(params, errors, path) = @words = Chosen.words(self.class.kind_name, params, errors, path)
134
+ def setup(params, errors, path)
135
+ @words = Chosen.words(self.class.kind_name, params, errors, path)
136
+ @remember = Mechanics.fetch_param(params, :remember)
137
+ errors << "#{path}.remember: must be \"source\"" unless [nil, "source"].include?(@remember)
138
+ end
139
+
140
+ def to_s = "choose #{Chosen.words_text(self.class.kind_name, @words)}#{" (remembered by the source)" if @remember}"
133
141
 
134
- def to_s = "choose #{Chosen.words_text(self.class.kind_name, @words)}"
142
+ # The values offered.
143
+ def choice_values(_engine) = Chosen.values(self.class.kind_name, @words)
135
144
 
136
145
  def run(engine, ctx, locals)
137
146
  return :done unless locals["asked"] || condition.nil? || condition.true?(engine, ctx)
@@ -141,11 +150,22 @@ module Enjine
141
150
  unless answer
142
151
  chooser = players(engine, ctx).first || ctx.controller
143
152
  return ask(engine, locals, chooser, "Choose #{Chosen.words_text(kind, @words)}",
144
- Chosen.values(kind, @words).map { { "type" => kind, kind => it } })
153
+ choice_values(engine).map { { "type" => kind, kind => it } })
145
154
  end
146
- engine.state.objects[ctx.object]&.memory&.merge!(Chosen.memory(kind, answer[kind]))
155
+ remember!(engine, ctx, Chosen.memory(kind, answer[kind]))
147
156
  :done
148
157
  end
158
+
159
+ private
160
+
161
+ def remember!(engine, ctx, memory)
162
+ engine.state.objects[ctx.object]&.memory&.merge!(memory)
163
+ source = @remember && engine.state.objects[ctx.source]
164
+ return unless source&.zone == :battlefield
165
+
166
+ source.memory.merge!(memory)
167
+ engine.touch! # its static abilities may now apply to other permanents (the layer pass is cached)
168
+ end
149
169
  end
150
170
 
151
171
  # "Choose a color."
@@ -178,6 +198,29 @@ module Enjine
178
198
  def self.kind_name = "card_type"
179
199
  end
180
200
 
201
+ # "Choose a land card name." among the cards in the game (CR 201.4, as Abilities::ChooseCardName).
202
+ class ChooseCardNameEffect < ResolvingChosen
203
+ primitive :effect, :choose_card_name,
204
+ description: "The player (`to`, default you) chooses a card name among the cards in the game (`types`: " \
205
+ "the named card has one of these; `not`: it has none of these); \"the chosen name\" " \
206
+ "(`name: \"chosen\"` in filters) reads it. `remember: \"source\"`: the source permanent " \
207
+ "remembers it for its other abilities.",
208
+ rules: %w[201.4 607.2d 608.2c],
209
+ params: { "types" => "list of card types", "not" => "list of card types",
210
+ "remember" => "\"source\"", "to" => "player selector (default you)" },
211
+ example: { "choose_card_name" => { "types" => ["land"], "remember" => "source" } }
212
+ def self.kind_name = "card_name"
213
+ def self.keys = super + %w[types not]
214
+
215
+ def setup(params, errors, path)
216
+ super
217
+ @types = Abilities::ChooseCardName.type_list(params, :types, errors, path)
218
+ @excluded = Abilities::ChooseCardName.type_list(params, :not, errors, path)
219
+ end
220
+
221
+ def choice_values(engine) = Abilities::ChooseCardName.names(engine, @types, @excluded)
222
+ end
223
+
181
224
  # "Choose odd or even." Later effects check the word with {"if": {"chosen": word}}.
182
225
  class ChooseOptionEffect < ResolvingChosen
183
226
  primitive :effect, :choose_option,
@@ -67,17 +67,124 @@ module Enjine
67
67
  # The damage pass of the replacement step (CR 614.1a, 614.9, 615, 616.1): redirection, prevention and
68
68
  # damage modification, from static abilities of permanents and from resolved prevention effects.
69
69
  #
70
- # The affected player (or the affected permanent's controller) chooses the order (CR 616.1). The engine
71
- # applies them in the order that player would choose to take the least damage: redirections first (the
72
- # damage then affects the new recipient), then prevention, then multiplying, then adding.
70
+ # Redirections apply first (the damage then affects the new recipient, whose controller chooses the rest). The
71
+ # other effects apply one at a time, each once, rechecking which still apply after each (CR 616.1e-f, 616.2),
72
+ # in the order the affected player (or the affected permanent's controller) chose (CR 616.1): Engine::Damage
73
+ # asks before the damage is dealt when two orders lead to different results (#orders), and otherwise applies
74
+ # them in the order that takes the least damage: prevention, then multiplying, then adding; static abilities
75
+ # before resolved effects.
73
76
  module DamageEvents
74
77
  module_function
75
78
 
79
+ # One prevention or modification effect that applies to the damage: `key` names it in proposal.applied and
80
+ # in a chosen order. kind: :rule (a game rule or protection), :prevent / :modify (a static ability of
81
+ # `holder`), :shield / :effect (a resolved effect, `effect` in state.effects).
82
+ Candidate = Data.define(:key, :kind, :holder, :ability, :effect)
83
+
76
84
  def replace!(engine, proposal)
85
+ hit = Engine::Damage.hit_key(proposal.data["source"], proposal.data["target"])
77
86
  redirect!(engine, proposal)
78
87
  proposal.data["unpreventable"] = true if unpreventable?(engine, proposal.data) # CR 615.12 (also shield counters)
79
- prevent!(engine, proposal)
80
- modify!(engine, proposal)
88
+ apply_in_order!(engine, proposal, engine.damage_order(hit))
89
+ end
90
+
91
+ # CR 616.1e-f: the effect chosen next is the first one of `order` that applies now, else the default first.
92
+ def apply_in_order!(engine, proposal, order)
93
+ until (found = candidates(engine, proposal)).empty?
94
+ chosen = Array(order).lazy.filter_map { |key| found.find { it.key == key } }.first || found.first
95
+ apply!(engine, proposal, chosen)
96
+ end
97
+ end
98
+
99
+ # The effects that apply to the damage now and haven't applied to it yet (CR 614.5), in the default order.
100
+ def candidates(engine, proposal)
101
+ data = proposal.data
102
+ return [] if data["amount"].zero?
103
+
104
+ applied = proposal.applied
105
+ rule = !data["unpreventable"] && !applied.include?("rule") &&
106
+ (engine.damage_prevented?(data["target"]) || protected?(engine, data)) # "prevent all damage to you", CR 702.16e
107
+ shields = engine.state.effects.select do
108
+ it["kind"] == "prevent_damage" && !applied.include?("effect:#{it["timestamp"]}") && PreventionEffect.applies?(engine, it, data)
109
+ end
110
+ modifiers = applicable(engine, proposal, :damage_replacement).reject { |_, ability| ability.redirect }
111
+ effects = engine.state.effects.select do
112
+ it["kind"] == "damage_replacement" && !applied.include?("effect:#{it["timestamp"]}") && ModifyingEffect.applies?(engine, it, data)
113
+ end
114
+ [*(Candidate.new("rule", :rule, nil, nil, nil) if rule),
115
+ *applicable(engine, proposal, :prevent_damage).map { |h, a| Candidate.new("#{h.id}:prevent_damage", :prevent, h, a, nil) },
116
+ *shields.map { Candidate.new("effect:#{it["timestamp"]}", :shield, nil, nil, it) },
117
+ *modifiers.sort_by { |_, a| a.multiply ? 0 : 1 }.map { |h, a| Candidate.new("#{h.id}:damage_replacement", :modify, h, a, nil) },
118
+ *effects.sort_by { it["multiply"] ? 0 : 1 }.map { Candidate.new("effect:#{it["timestamp"]}", :effect, nil, nil, it) }]
119
+ end
120
+
121
+ # CR 615.12: damage that can't be prevented still passes through prevention effects: their additional effects
122
+ # happen, nothing is prevented and shields aren't used up.
123
+ def apply!(engine, proposal, candidate)
124
+ data = proposal.data
125
+ proposal.applied << candidate.key
126
+ case candidate.kind
127
+ when :rule then data["amount"] = 0
128
+ when :prevent
129
+ prevented = data["unpreventable"] ? 0 : data["amount"]
130
+ holder = candidate.holder
131
+ follow_up!(engine, data, candidate.ability.follow_up&.entry(holder.card, holder.controller, holder.id, {}), prevented)
132
+ data["amount"] -= prevented
133
+ when :shield
134
+ before = data["amount"]
135
+ PreventionEffect.use!(engine, candidate.effect, data) unless data["unpreventable"]
136
+ follow_up!(engine, data, candidate.effect["follow_up"], before - data["amount"])
137
+ when :modify then data["amount"] = candidate.ability.modified(engine, data["amount"], candidate.holder)
138
+ else
139
+ effect = candidate.effect
140
+ data["amount"] = effect["multiply"] ? data["amount"] * effect["multiply"] : data["amount"] + effect["plus"]
141
+ end
142
+ end
143
+
144
+ # The affected player and the distinct results they can get by ordering the effects that apply to `source`'s
145
+ # damage to `target` (CR 616.1): [player, [[[[key, label], ...], final amount], ...]], one order per distinct
146
+ # result (the final recipient, amount, follow-ups and the shields left); nil when the order can't matter.
147
+ # A dry run: nothing changes.
148
+ def orders(engine, source, target, amount, combat)
149
+ probe = Proposal.new("damage", { "source" => source, "target" => target, "amount" => amount, "combat" => combat }, [])
150
+ redirect!(engine, probe)
151
+ probe.data["unpreventable"] = true if unpreventable?(engine, probe.data)
152
+ return if candidates(engine, probe).size < 2
153
+
154
+ outcomes = {}
155
+ explore(engine, probe, [], outcomes)
156
+ return if outcomes.size < 2
157
+
158
+ affected = probe.data["target"]
159
+ chooser = Filters.player_index(engine, affected) || engine.state.objects[affected]&.controller
160
+ chooser && [chooser, outcomes.values]
161
+ end
162
+
163
+ def explore(engine, proposal, path, outcomes)
164
+ keys = candidates(engine, proposal).map(&:key)
165
+ if keys.empty?
166
+ result = [proposal.data.slice("target", "amount", "follow_ups"), engine.state.effects]
167
+ outcomes[Marshal.dump(result)] ||= [path, proposal.data["amount"]]
168
+ return
169
+ end
170
+ saved = Snapshot.deep_copy(engine.state.effects)
171
+ labels = candidates(engine, proposal).to_h { [it.key, label(engine, it)] }
172
+ keys.each do |key|
173
+ engine.state.effects.replace(Snapshot.deep_copy(saved))
174
+ branch = Proposal.new("damage", Snapshot.deep_copy(proposal.data), proposal.applied.dup)
175
+ apply!(engine, branch, candidates(engine, branch).find { it.key == key })
176
+ explore(engine, branch, path + [[key, labels[key]]], outcomes)
177
+ end
178
+ engine.state.effects.replace(saved)
179
+ end
180
+
181
+ # What a player sees of an effect in the order they choose.
182
+ def label(engine, candidate)
183
+ return "the rules (prevent all)" if candidate.kind == :rule
184
+
185
+ card = candidate.holder ? candidate.holder.card : engine.state.objects[candidate.effect["source"]]&.card
186
+ name = card ? engine.catalog.fetch(card).name : "an effect"
187
+ "#{name}: #{%i[prevent shield].include?(candidate.kind) ? "prevent" : "modify"}"
81
188
  end
82
189
 
83
190
  def statics(engine, kind)
@@ -108,37 +215,16 @@ module Enjine
108
215
  to && to != from && engine.state.battlefield.include?(to) && (engine.chars(to).creature? || engine.chars(to).planeswalker?)
109
216
  end
110
217
 
111
- # CR 615: prevention effects of static abilities, then shields from resolved effects (CR 615.7).
112
- # Damage that can't be prevented still passes through them without being prevented (CR 615.12).
113
- def prevent!(engine, proposal)
114
- data = proposal.data
115
- return if data["amount"].zero? || data["unpreventable"]
116
-
117
- data["amount"] = 0 if engine.damage_prevented?(data["target"]) # "prevent all damage to you" (player_rule)
118
- data["amount"] = 0 if protected?(engine, data) # CR 702.16e
119
- applicable(engine, proposal, :prevent_damage).each do |holder, ability|
120
- break if data["amount"].zero?
121
-
122
- follow_up!(engine, data, ability.follow_up&.entry(holder.card, holder.controller, holder.id, {}), data["amount"])
123
- data["amount"] = 0
124
- end
125
- engine.state.effects.select { it["kind"] == "prevent_damage" }.each do |effect|
126
- break if data["amount"].zero?
127
- next unless PreventionEffect.applies?(engine, effect, data)
128
-
129
- before = data["amount"]
130
- PreventionEffect.use!(engine, effect, data)
131
- follow_up!(engine, data, effect["follow_up"], before - data["amount"])
132
- end
133
- end
134
-
135
218
  # CR 615.5: the rest of a prevention effect happens right after the event (Engine#run_follow_ups!), seeing
136
- # the damage prevented, its source and the source's controller.
219
+ # the damage prevented, its source and the source's controller. For damage that can't be prevented it happens
220
+ # too, with 0 prevented, except a reflexive "when damage is prevented this way" (CR 615.12).
137
221
  def follow_up!(engine, data, entry, prevented)
138
- return unless entry && prevented.positive?
222
+ return unless entry && (prevented.positive? || data["unpreventable"])
139
223
 
140
224
  facts = { "amount" => prevented, "object" => data["source"], "player" => engine.damage_source_controller(data["source"]) }
141
- (data["follow_ups"] ||= []) << entry.merge("facts" => facts.compact)
225
+ entry = entry.merge("facts" => facts.compact)
226
+ entry["unprevented"] = true unless prevented.positive?
227
+ (data["follow_ups"] ||= []) << entry
142
228
  end
143
229
 
144
230
  # Protection from the source's quality prevents the damage (CR 702.16e), also a player's protection from each
@@ -163,33 +249,6 @@ module Enjine
163
249
  end
164
250
  end
165
251
 
166
- # "Deals double that damage instead" and "that much damage plus N instead" (CR 614.1a).
167
- def modify!(engine, proposal)
168
- data = proposal.data
169
- return if data["amount"].zero?
170
-
171
- found = applicable(engine, proposal, :damage_replacement).reject { |_, ability| ability.redirect }
172
- found.sort_by { |_, ability| ability.multiply ? 0 : 1 }.each do |holder, ability|
173
- proposal.applied << "#{holder.id}:damage_replacement"
174
- data["amount"] = ability.modified(engine, data["amount"], holder)
175
- end
176
- modify_by_effects!(engine, proposal)
177
- end
178
-
179
- # Resolved "until your next turn, if a source would deal damage to that player or a permanent that player
180
- # controls, it deals double that damage instead" effects (Effects::DamageReplacementEffect): doubling first.
181
- def modify_by_effects!(engine, proposal)
182
- data = proposal.data
183
- found = engine.state.effects.select do |effect|
184
- effect["kind"] == "damage_replacement" && !proposal.applied.include?("effect:#{effect["timestamp"]}") &&
185
- ModifyingEffect.applies?(engine, effect, data)
186
- end
187
- found.sort_by { it["multiply"] ? 0 : 1 }.each do |effect|
188
- proposal.applied << "effect:#{effect["timestamp"]}"
189
- data["amount"] = effect["multiply"] ? data["amount"] * effect["multiply"] : data["amount"] + effect["plus"]
190
- end
191
- end
192
-
193
252
  # Damage replacement effects of resolved spells and abilities (state.effects, kind "damage_replacement"):
194
253
  # {"to": [refs], "permanents": bool, "combat": ..., "multiply": n | nil, "plus": n | nil}. A player in `to`
195
254
  # with "permanents" also covers the permanents they control as the damage is dealt (CR 611.2c).
@@ -296,8 +355,9 @@ module Enjine
296
355
  "to instead). A scope is \"self\", \"attached\" or {\"each\": filter, \"controller\": " \
297
356
  "you|opponent|any, \"other\": bool}; `each` is optional and players match too, so " \
298
357
  "{\"controller\": \"opponent\"} is \"an opponent or a permanent an opponent controls\". " \
299
- "Several apply in the order the affected player would pick: redirections, then " \
300
- "prevention, then multiplying, then adding.",
358
+ "Redirections apply first; when the order of the others changes the result, the " \
359
+ "affected player chooses it (a damage_order decision), else prevention, then " \
360
+ "multiplying, then adding.",
301
361
  rules: %w[614.1a 614.5 614.9 616.1 616.1e 616.1f 120.2b],
302
362
  params: { "by" => "damage scope", "to" => "damage scope", "combat" => "combat | noncombat",
303
363
  "multiply" => "integer >= 2", "plus" => "amount", "redirect" => "\"self\" | \"attached\"" },
@@ -460,7 +520,7 @@ module Enjine
460
520
 
461
521
  def nested_effects = [follow_up].compact
462
522
 
463
- # A source of the controller's choice (CR 609.7a): a permanent or a spell on the stack, chosen as it resolves.
523
+ # A source of the controller's choice, chosen as it resolves (CR 609.7a).
464
524
  def run(engine, ctx, locals)
465
525
  return :done unless locals["asked"] || condition.nil? || condition.true?(engine, ctx)
466
526
  return start(engine, ctx, nil) unless @chosen_source
@@ -468,12 +528,23 @@ module Enjine
468
528
  answer = answers(locals).first
469
529
  return start(engine, ctx, [answer["object"]]) if answer
470
530
 
471
- sources = engine.state.battlefield + engine.state.stack.reject { it == ctx.object }
531
+ sources = self.class.sources(engine, ctx.object)
472
532
  return :done if sources.empty?
473
533
 
474
534
  ask(engine, locals, ctx.controller, "Choose a source of damage", sources.map { { "type" => "source", "object" => it } })
475
535
  end
476
536
 
537
+ # CR 609.7a: a permanent, a spell on the stack, an object a spell or ability on the stack refers to (its
538
+ # targets, an ability's source; even one that has left its zone) or a face-up object in the command zone.
539
+ def self.sources(engine, resolving)
540
+ stack = engine.state.stack.reject { it == resolving }
541
+ referred = stack.flat_map do |id|
542
+ obj = engine.object(id)
543
+ Array(obj.targets).flatten.compact.reject { Filters.player_index(engine, it) } + (obj.ability? ? [obj.source] : [])
544
+ end
545
+ (engine.state.battlefield + stack + referred.compact + engine.state.command).uniq - [resolving]
546
+ end
547
+
477
548
  def start(engine, ctx, chosen)
478
549
  # CR 611.2b: "for as long as" a source that has already left never starts.
479
550
  return :done if duration == "while_source_on_battlefield" && !engine.state.battlefield.include?(ctx.source)
@@ -536,7 +607,8 @@ module Enjine
536
607
 
537
608
  def apply(engine, ctx)
538
609
  to = refs(engine, ctx)
539
- details = { "to" => to, "permanents" => @permanents == true, "combat" => combat, "duration" => duration }
610
+ details = { "to" => to, "permanents" => @permanents == true, "combat" => combat, "duration" => duration,
611
+ "source" => ctx.source }
540
612
  multiply ? details["multiply"] = multiply : details["plus"] = [plus.value(engine, ctx), 0].max
541
613
  engine.add_continuous_effect!("damage_replacement", ctx, to, details)
542
614
  end
@@ -28,7 +28,7 @@ module Enjine
28
28
  affects = { "each" => "permanent" }
29
29
  end
30
30
  Mechanics.check_keys(affects, %w[each controller], errors, "#{path}.affects")
31
- filter = Mechanics.build_entry(:filter, affects["each"], errors, "#{path}.affects.each")
31
+ filter = Mechanics.characteristic_filter(affects["each"], errors, "#{path}.affects.each")
32
32
  live = filter ? filter.live_keys : []
33
33
  errors << "#{path}.affects.each: #{live.join(", ")} can't be used here yet" unless live.empty?
34
34
  controller = affects.fetch("controller", "any")
@@ -46,44 +46,63 @@ module Enjine
46
46
 
47
47
  # "As this enters, choose a nonland card name." The names offered are those of the cards in the game's
48
48
  # decklists (CR 201.4: a player chooses a card name; names of cards outside the game can't matter).
49
+ # "As this artifact enters, look at an opponent's hand, then choose any card name" (`look_at_hand`).
49
50
  class ChooseCardName < EnteringChoice
50
51
  primitive :ability, :choose_card_name,
51
52
  description: "As this permanent enters, its controller chooses a card name among the cards in the " \
52
- "game (`not`: card types the named card mustn't have, e.g. [\"land\"]); abilities of it " \
53
- "that say \"the chosen name\" use it.",
54
- rules: %w[614.12 614.12a 201.4 201.4a 607.2],
55
- params: { "not" => "list of card types" },
53
+ "game (`not`: card types the named card mustn't have, e.g. [\"land\"]; `types`: it must " \
54
+ "have one of these, [\"land\"] for \"a land card name\"); abilities of it that say \"the " \
55
+ "chosen name\" use it. `look_at_hand: \"opponent\"`: first they look at an opponent's hand.",
56
+ rules: %w[614.12 614.12a 201.4 201.4a 607.2 701.20e],
57
+ params: { "not" => "list of card types", "types" => "list of card types",
58
+ "look_at_hand" => "\"opponent\"" },
56
59
  example: { "choose_card_name" => { "not" => ["land"] } }
57
60
 
58
- attr_reader :excluded
61
+ attr_reader :excluded, :types
59
62
 
60
63
  def self.build(params, errors, path, **)
61
- Mechanics.check_keys(params, %w[not], errors, path)
62
- excluded = Mechanics.fetch_param(params, :not) || []
63
- types = Filters::Restricted::TYPES
64
- unless excluded.is_a?(Array) && (excluded - types).empty?
65
- errors << "#{path}.not: must be a list of card types (#{types.join(", ")})"
66
- excluded = []
67
- end
68
- new(excluded.map(&:to_sym))
64
+ Mechanics.check_keys(params, %w[not types look_at_hand], errors, path)
65
+ look = Mechanics.fetch_param(params, :look_at_hand)
66
+ errors << "#{path}.look_at_hand: must be \"opponent\"" unless [nil, "opponent"].include?(look)
67
+ new(type_list(params, :not, errors, path), type_list(params, :types, errors, path), look: !look.nil?)
69
68
  end
70
69
 
71
- def initialize(excluded)
70
+ def self.type_list(params, key, errors, path)
71
+ list = Mechanics.fetch_param(params, key) || []
72
+ known = Filters::Restricted::TYPES
73
+ return list.map(&:to_sym) if list.is_a?(Array) && (list - known).empty?
74
+
75
+ errors << "#{path}.#{key}: must be a list of card types (#{known.join(", ")})"
76
+ []
77
+ end
78
+
79
+ # The names of the cards in the game matching the type restrictions, sorted.
80
+ def self.names(engine, types, excluded)
81
+ engine.state.decklists.flatten.uniq.filter_map do |card|
82
+ defn = engine.catalog.fetch(card)
83
+ defn.name if !defn.types.intersect?(excluded) && (types.empty? || defn.types.intersect?(types))
84
+ end.uniq.sort
85
+ end
86
+
87
+ def initialize(excluded, types = [], look: false)
72
88
  super()
73
89
  @excluded = excluded.freeze
90
+ @types = types.freeze
91
+ @look = look
74
92
  freeze
75
93
  end
76
94
 
77
- def to_s = "as this enters, choose a #{excluded.map { "non#{it}" }.join(" ")} card name".squeeze(" ")
95
+ def to_s
96
+ "as this enters, #{"look at an opponent's hand, then " if @look}choose a " \
97
+ "#{(excluded.map { "non#{it}" } + types).join(" ")} card name".squeeze(" ")
98
+ end
78
99
 
79
- def options(engine, _controller)
80
- names = engine.state.decklists.flatten.uniq.filter_map do |card|
81
- defn = engine.catalog.fetch(card)
82
- defn.name unless defn.types.intersect?(excluded)
83
- end
84
- names.uniq.sort.map { { type: "name", name: it } }
100
+ # CR 701.20e: looking at an opponent's hand comes before the choice.
101
+ def before_choice(engine, controller)
102
+ engine.look_at!(controller, engine.state.opponent(controller), engine.player(engine.state.opponent(controller)).hand) if @look
85
103
  end
86
104
 
105
+ def options(engine, _controller) = ChooseCardName.names(engine, types, excluded).map { { type: "name", name: it } }
87
106
  def enters_for(answer) = { "memory" => { "chosen_name" => answer[:name] } }
88
107
  end
89
108
  end