enjine 0.4.1 → 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 (90) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -0
  3. data/SUPPORTED.md +31 -23
  4. data/docs/guides/card-data-format.md +106 -1
  5. data/docs/plans/dsl-gaps.md +23 -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 +108 -18
  10. data/docs/reference/filters.md +19 -2
  11. data/docs/reference/keywords.md +16 -2
  12. data/docs/reference/triggers.md +25 -6
  13. data/lib/enjine/actions/play_land.rb +3 -1
  14. data/lib/enjine/card_definition.rb +4 -3
  15. data/lib/enjine/cli/text.rb +10 -3
  16. data/lib/enjine/decisions/combat.rb +4 -2
  17. data/lib/enjine/decisions/damage_order.rb +18 -0
  18. data/lib/enjine/engine/ability_layers.rb +6 -1
  19. data/lib/enjine/engine/casting/alt_casting.rb +36 -4
  20. data/lib/enjine/engine/casting/cast_choices.rb +13 -1
  21. data/lib/enjine/engine/casting/casting.rb +24 -7
  22. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  23. data/lib/enjine/engine/casting/permissions.rb +13 -14
  24. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  25. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  26. data/lib/enjine/engine/characteristics.rb +3 -2
  27. data/lib/enjine/engine/combat.rb +26 -7
  28. data/lib/enjine/engine/copies.rb +10 -3
  29. data/lib/enjine/engine/damage.rb +49 -0
  30. data/lib/enjine/engine/entering.rb +36 -2
  31. data/lib/enjine/engine/face_down.rb +12 -3
  32. data/lib/enjine/engine/faces.rb +14 -2
  33. data/lib/enjine/engine/follow_ups.rb +4 -1
  34. data/lib/enjine/engine/resolution.rb +46 -1
  35. data/lib/enjine/engine/rules.rb +4 -3
  36. data/lib/enjine/engine/triggers.rb +5 -15
  37. data/lib/enjine/engine/turn_history.rb +16 -1
  38. data/lib/enjine/engine/turn_structure.rb +1 -0
  39. data/lib/enjine/engine/zones.rb +5 -2
  40. data/lib/enjine/events.rb +2 -0
  41. data/lib/enjine/frames.rb +2 -2
  42. data/lib/enjine/mana.rb +3 -0
  43. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  44. data/lib/enjine/mechanics/abilities/damage_replacements.rb +136 -64
  45. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  46. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -20
  47. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  48. data/lib/enjine/mechanics/abilities/static.rb +1 -1
  49. data/lib/enjine/mechanics/card_spec.rb +54 -11
  50. data/lib/enjine/mechanics/costs/base.rb +67 -9
  51. data/lib/enjine/mechanics/costs/behold.rb +21 -5
  52. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  53. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  54. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  55. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  56. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  57. data/lib/enjine/mechanics/effects/base.rb +10 -2
  58. data/lib/enjine/mechanics/effects/become.rb +29 -12
  59. data/lib/enjine/mechanics/effects/copy.rb +56 -19
  60. data/lib/enjine/mechanics/effects/counters.rb +8 -2
  61. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  62. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  63. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  64. data/lib/enjine/mechanics/effects/library.rb +76 -18
  65. data/lib/enjine/mechanics/effects/pay.rb +7 -4
  66. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  67. data/lib/enjine/mechanics/effects/search.rb +34 -6
  68. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  69. data/lib/enjine/mechanics/filters/base.rb +22 -12
  70. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  71. data/lib/enjine/mechanics/filters/stack.rb +14 -8
  72. data/lib/enjine/mechanics/keywords/alternative_costs.rb +10 -6
  73. data/lib/enjine/mechanics/keywords/cards_have.rb +65 -0
  74. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  75. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  76. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  77. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  78. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  79. data/lib/enjine/mechanics/linked.rb +32 -2
  80. data/lib/enjine/mechanics/selector.rb +32 -9
  81. data/lib/enjine/mechanics/triggers/casting.rb +15 -9
  82. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  83. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  84. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +20 -9
  85. data/lib/enjine/mechanics/values.rb +10 -3
  86. data/lib/enjine/replacements.rb +3 -2
  87. data/lib/enjine/rules_monitor.rb +13 -2
  88. data/lib/enjine/version.rb +1 -1
  89. data/lib/enjine/view.rb +1 -1
  90. metadata +6 -1
@@ -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
@@ -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
@@ -206,32 +206,44 @@ module Enjine
206
206
  # `to_player` "controller" (default), "owner" (each card's owner, CR 108.3) or a player selector
207
207
  # `cost_increase` generic mana added to the total cost of a spell cast with this permission (601.2f)
208
208
  # `any_mana_type` mana of any type may be spent to cast it (CR 609.4b)
209
+ # `during` "your_turn": only during the permission's player's turn
210
+ # `waterbend` "mana_value": cast by waterbending {X} rather than paying its mana cost, X its mana
211
+ # value (an alternative cost, CR 118.9, 701.67a)
209
212
  # Riders like these are stored on the permission (`state.effects` entry) and copied into the play
210
- # method, so only casts that use this permission (`via: "effect:<timestamp>"`) see them.
213
+ # method, so only casts that use this permission (`via: "effect:<timestamp>"`) see them. A
214
+ # `while_you_control_source` permission ends when its source leaves or changes control (CR 611.2b).
211
215
  class PlayPermission < ChoiceEffect
212
- DURATIONS = %w[end_of_turn end_of_your_next_turn until_your_next_end_step while_exiled].freeze
216
+ DURATIONS = %w[end_of_turn end_of_your_next_turn until_your_next_end_step while_exiled
217
+ while_you_control_source].freeze
213
218
  PLAYERS = %w[controller owner].freeze
214
219
 
215
220
  primitive :effect, :play_permission,
216
221
  description: "A player may play (`play: \"play\"`, default) or cast (`\"cast\"`) each referenced " \
217
222
  "exiled card matching `for`/`not_types`, paying its costs and following timing rules, " \
218
- "for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step " \
219
- "or while_exiled. With " \
223
+ "for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step, " \
224
+ "while_exiled or while_you_control_source (\"for as long as you control this creature\"). " \
225
+ "With " \
220
226
  "`choose: \"one_per_owner\"` only one chosen card per owner. `to_player`: who may " \
221
227
  "play it, \"controller\" (default, the effect's controller), \"owner\" (the card's " \
222
228
  "owner) or a player selector (a face-down card: only someone who may look at it). " \
223
229
  "`cost_increase`: spells cast this way cost that much generic mana more. " \
224
- "`any_mana_type: true`: mana of any type can be spent to cast those spells.",
225
- rules: %w[611.2a 601.3 305.1 400.7 514.2 601.2f 108.3 406.3b 609.4b],
230
+ "`any_mana_type: true`: mana of any type can be spent to cast those spells. " \
231
+ "`during: \"your_turn\"`: only during your turn. `waterbend: \"mana_value\"`: cast it by " \
232
+ "waterbending {X} rather than paying its mana cost, where X is its mana value.",
233
+ rules: %w[611.2a 611.2b 601.3 305.1 400.7 514.2 601.2f 108.3 406.3b 609.4b 118.9 701.67a],
226
234
  params: { "to" => "selector (usually {\"result\": n})", "duration" => DURATIONS.join(" | "),
227
235
  "play" => "play | cast", "for" => "card spec", "not_types" => "list of card types",
228
236
  "choose" => "one_per_owner", "to_player" => "controller | owner | player selector",
229
237
  "cost_increase" => "integer >= 1", "any_mana_type" => "boolean",
230
238
  "exile_instead" => "true or a card spec: if a spell cast this way (matching it) would be put " \
231
- "into a graveyard, it's exiled instead (CR 614.1a)" },
239
+ "into a graveyard, it's exiled instead (CR 614.1a)",
240
+ "during" => "your_turn", "waterbend" => "mana_value" },
232
241
  example: { "play_permission" => { "to" => { "result" => 0 }, "duration" => "end_of_your_next_turn" } }
233
242
 
234
- def self.keys = %w[to duration play for not_types choose to_player cost_increase any_mana_type exile_instead if]
243
+ def self.keys
244
+ %w[to duration play for not_types choose to_player cost_increase any_mana_type exile_instead during
245
+ waterbend if]
246
+ end
235
247
 
236
248
  def setup(params, errors, path)
237
249
  @duration = Mechanics.fetch_param(params, :duration) || "end_of_turn"
@@ -251,18 +263,23 @@ module Enjine
251
263
  more = @riders["cost_increase"] ? ", costs {#{@riders["cost_increase"]}} more" : ""
252
264
  more += ", mana of any type" if @riders["any_mana_type"]
253
265
  more += ", #{ExileInstead.words(@riders["exile_instead"])}" if @riders["exile_instead"]
266
+ more += ", during your turn" if @riders["during"]
267
+ more += ", by waterbending {X} (X: its mana value)" if @riders["waterbend"]
254
268
  "#{who} may #{@play} #{@filter} (#{@duration.tr("_", " ")}#{more}) → #{to}"
255
269
  end
256
270
 
257
271
  def run(engine, ctx, locals)
258
272
  return :done unless locals["cards"] || condition.nil? || condition.true?(engine, ctx)
273
+ # CR 611.2b: "for as long as you control [this]" that has already ended never starts.
274
+ return :done unless engine.source_duration_holds?(@duration, ctx.source, ctx.controller)
259
275
 
260
276
  cards = (locals["cards"] ||= refs(engine, ctx).select { exiled_match?(engine, it) })
261
277
  picks = @choose ? choose(engine, ctx, locals, cards) : cards
262
278
  return :wait if picks == :wait
263
279
 
280
+ source = ctx.source if Engine::Rules::WHILE_SOURCE.include?(@duration)
264
281
  picks.flat_map { |id| players_for(engine, ctx, id).map { [it, id] } }.group_by(&:first).each do |index, pairs|
265
- engine.grant_play_permission!(index, pairs.map(&:last), duration: @duration, play: @play, **@riders)
282
+ engine.grant_play_permission!(index, pairs.map(&:last), duration: @duration, play: @play, source: source, **@riders)
266
283
  end
267
284
  :done
268
285
  end
@@ -281,7 +298,15 @@ module Enjine
281
298
  errors << "#{path}.cost_increase: must be an integer >= 1" unless ok
282
299
  any_type = Mechanics.flag_param(params, :any_mana_type, errors, path)
283
300
  { "cost_increase" => increase, "any_mana_type" => (true if any_type),
284
- "exile_instead" => ExileInstead.build(params, errors, path) }.compact
301
+ "exile_instead" => ExileInstead.build(params, errors, path),
302
+ "during" => fixed_word(params, :during, "your_turn", errors, path),
303
+ "waterbend" => fixed_word(params, :waterbend, "mana_value", errors, path) }.compact
304
+ end
305
+
306
+ def fixed_word(params, key, word, errors, path)
307
+ value = Mechanics.fetch_param(params, key)
308
+ errors << "#{path}.#{key}: must be \"#{word}\"" unless value.nil? || value == word
309
+ value
285
310
  end
286
311
 
287
312
  # The players who may play `id`: the effect's controller, the card's owner, or the selected players.
@@ -319,23 +344,27 @@ module Enjine
319
344
  # the controller picks a card, casts it right away (a cast frame on top of the resolving one; nobody
320
345
  # gets priority), then the resolution goes on. `count: "any"` repeats until they stop.
321
346
  class CastFree < ChoiceEffect
347
+ FROM = %w[hand graveyard].freeze
348
+
322
349
  primitive :effect, :cast_free,
323
350
  description: "The controller may cast referenced cards without paying their mana costs while this " \
324
351
  "resolves. `to` names the cards ({\"result\": n}), or a player for the cards in their " \
325
- "hand (default: your hand). Only cards matching `for`/`not_types` with mana value up to " \
326
- "`max_mana_value` (optional amount) that could be cast now (legal targets). `count`: 1 " \
327
- "(default) or \"any\" (any number, one at a time). X is 0 (CR 107.3b). `play: true` " \
352
+ "hand (default: your hand), or in the zone `from` (hand | graveyard). Only cards " \
353
+ "matching `for`/`not_types` with mana value up to `max_mana_value` (optional amount) " \
354
+ "that could be cast now (legal targets). `count`: 1 (default), up to N (an integer), or " \
355
+ "\"any\" (any number, one at a time). X is 0 (CR 107.3b). `play: true` " \
328
356
  "(\"you may play\"): a land among them may be played, on your turn with a land play " \
329
357
  "left (`{type: \"play_land\"}`). A face-down card is judged face up.",
330
358
  rules: %w[608.2g 118.9 601.2a 107.3b 118.6a 305.2a 305.3 406.3a],
331
359
  params: { "to" => "selector", "for" => "card spec", "not_types" => "list of card types",
332
- "max_mana_value" => "amount", "count" => "1 or \"any\"", "play" => "boolean",
360
+ "max_mana_value" => "amount", "count" => "integer >= 1 (default 1) or \"any\"",
361
+ "from" => FROM.join(" | "), "play" => "boolean",
333
362
  "exile_instead" => "true or a card spec: if a spell cast this way (matching it) would be put " \
334
363
  "into a graveyard, it's exiled instead (CR 614.1a)",
335
364
  "any_mana_type" => "boolean: mana of any type can be spent to cast it (CR 609.4b)" },
336
365
  example: { "cast_free" => { "to" => { "result" => 0 }, "max_mana_value" => 3, "count" => "any" } }
337
366
 
338
- def self.keys = %w[to for not_types max_mana_value count play exile_instead any_mana_type if]
367
+ def self.keys = %w[to from for not_types max_mana_value count play exile_instead any_mana_type if]
339
368
  def self.default_to = "you"
340
369
 
341
370
  def setup(params, errors, path)
@@ -345,14 +374,17 @@ module Enjine
345
374
  raw = Mechanics.fetch_param(params, :max_mana_value)
346
375
  @max = raw.nil? ? nil : Amount.build(raw, errors, "#{path}.max_mana_value", targets_count: @targets_count)
347
376
  @count = Mechanics.fetch_param(params, :count) || 1
348
- errors << "#{path}.count: must be 1 or \"any\"" unless [1, "any"].include?(@count)
377
+ errors << "#{path}.count: must be an integer >= 1 or \"any\"" unless @count == "any" || (@count.is_a?(Integer) && @count >= 1)
378
+ @from = Mechanics.fetch_param(params, :from) || "hand"
379
+ errors << "#{path}.from: must be one of #{FROM.join(", ")}" unless FROM.include?(@from)
349
380
  @play = Mechanics.flag_param(params, :play, errors, path)
350
381
  end
351
382
 
352
383
  def to_s
353
384
  more = @riders["any_mana_type"] ? ", mana of any type" : ""
354
385
  more += ", #{ExileInstead.words(@riders["exile_instead"])}" if @riders["exile_instead"]
355
- "you may cast #{@count == "any" ? "any number of" : "a"} #{@filter} free#{more} → #{to}"
386
+ how_many = { "any" => "any number of", 1 => "a" }.fetch(@count) { "up to #{@count}" }
387
+ "you may cast #{how_many} #{@filter}#{" from #{@from}" unless @from == "hand"} free#{more} → #{to}"
356
388
  end
357
389
 
358
390
  def run(engine, ctx, locals)
@@ -372,7 +404,7 @@ module Enjine
372
404
  locals["playing"] = answer["object"]
373
405
  return :wait if play_land!(engine, index, locals) == :wait
374
406
  end
375
- return :done if @count == 1 && locals["cast"].to_i >= 1
407
+ return :done if @count != "any" && locals["cast"].to_i >= @count
376
408
 
377
409
  choices = candidates(engine, ctx, locals)
378
410
  return :done if choices.empty?
@@ -433,11 +465,11 @@ module Enjine
433
465
  :done
434
466
  end
435
467
 
436
- # Referenced cards still in the zone they were put in; a player stands for their hand.
468
+ # Referenced cards still in the zone they were put in; a player stands for their hand (or graveyard).
437
469
  def cards(engine, ctx)
438
470
  refs(engine, ctx).flat_map do |ref|
439
471
  index = Filters.player_index(engine, ref)
440
- next engine.player(index).hand if index
472
+ next engine.player(index).public_send(@from).dup if index
441
473
  next [] unless engine.state.objects.key?(ref)
442
474
 
443
475
  %i[stack battlefield].include?(engine.object(ref).zone) ? [] : [ref]
@@ -14,8 +14,10 @@ module Enjine
14
14
  # spells_cant_be_countered spells the player controls (matching `spells`) can't be countered (101.2, 701.6a)
15
15
  # abilities_cant_be_countered activated and triggered abilities the player controls can't be countered (101.2)
16
16
  # cant_gain_life the player can't gain life (119.7)
17
- # cant_activate the player can't activate abilities of sources matching `filter`, except mana
18
- # abilities (602.5)
17
+ # cant_activate the player can't activate abilities of sources matching `filter` (or, with `name:
18
+ # "chosen"`, with the name its source chose, in any zone), except mana abilities (602.5)
19
+ # cant_be_attacked creatures matching `filter` can't attack the player (their planeswalkers still can be)
20
+ # (508.1c)
19
21
  # protection_from_opponents the player has protection from each of their opponents: opponents' spells
20
22
  # and abilities can't target them and damage from opponents' sources is prevented
21
23
  # (702.16b, 702.16e, 702.16k)
@@ -30,11 +32,13 @@ module Enjine
30
32
  "abilities_cant_be_countered" => %w[101.2 701.6a],
31
33
  "cant_gain_life" => %w[119.7], "cant_activate" => %w[101.2 602.5],
32
34
  "damage_cant_be_prevented" => %w[615.12], "combat_damage_cant_be_prevented" => %w[615.12],
33
- "protection_from_opponents" => %w[702.16b 702.16e 702.16k]
35
+ "protection_from_opponents" => %w[702.16b 702.16e 702.16k],
36
+ "cant_be_attacked" => %w[508.1c 506.3]
34
37
  }.freeze
35
- # Rules that take a `filter` of permanents (required for cant_sacrifice) or a card spec of `spells`.
36
- FILTERED = %w[cant_sacrifice cant_activate].freeze
37
- REQUIRED_FILTER = %w[cant_sacrifice].freeze
38
+ # Rules that take a `filter` of permanents (required for cant_sacrifice and cant_be_attacked) or a card
39
+ # spec of `spells`.
40
+ FILTERED = %w[cant_sacrifice cant_activate cant_be_attacked].freeze
41
+ REQUIRED_FILTER = %w[cant_sacrifice cant_be_attacked].freeze
38
42
  SPELLS = %w[cant_cast spells_cant_be_countered].freeze
39
43
 
40
44
  def self.rule(params, errors, path)
@@ -69,34 +73,43 @@ module Enjine
69
73
  "applies to the players in `affects` (you | opponents | each; default you). Rules: " \
70
74
  "#{PlayerRules::RULES.keys.join(", ")}. `cant_sacrifice` takes a `filter` of the " \
71
75
  "permanents that can't be sacrificed, `cant_activate` may take a `filter` of the " \
72
- "sources whose abilities can't be activated (mana abilities still can), and " \
76
+ "sources whose abilities can't be activated (mana abilities still can) or `name: " \
77
+ "\"chosen\"` (sources with the name this permanent chose, in any zone), " \
78
+ "`cant_be_attacked` takes a `filter` of the creatures that can't attack them, and " \
73
79
  "`cant_cast` and `spells_cant_be_countered` may take a card spec of the `spells`. " \
74
80
  "The damage rules apply to all damage whichever players they name.",
75
81
  rules: PlayerRules::RULES.values.flatten.uniq + %w[604.1 604.2 611.3a],
76
82
  params: { "rule" => PlayerRules::RULES.keys.join(" | "), "affects" => AFFECTS.join(" | "),
77
83
  "filter" => "permanent filter (#{PlayerRules::FILTERED.join(", ")})",
78
84
  "spells" => "card spec of the spells (#{PlayerRules::SPELLS.join(", ")})",
85
+ "name" => "\"chosen\" (cant_activate: sources with the chosen name)",
79
86
  "if" => "condition (\"during your turn\": {\"your_turn\": true})" },
80
87
  example: { "player_rule" => { "rule" => "cant_cast", "affects" => "opponents", "if" => { "your_turn" => true } } }
81
88
 
82
89
  attr_reader :rule, :affects, :filter, :spells, :condition
83
90
 
84
91
  def self.build(params, errors, path, **)
85
- Mechanics.check_keys(params, %w[rule affects filter spells if], errors, path)
92
+ Mechanics.check_keys(params, %w[rule affects filter spells name if], errors, path)
86
93
  rule = PlayerRules.rule(params, errors, path)
87
94
  affects = Mechanics.fetch_param(params, :affects) || "you"
88
95
  errors << "#{path}.affects: must be one of #{AFFECTS.join(", ")}" unless AFFECTS.include?(affects)
89
96
  filter, spells = PlayerRules.qualifiers(params, rule, errors, path)
97
+ named = Mechanics.fetch_param(params, :name)
98
+ unless named.nil? || (named == "chosen" && rule == "cant_activate")
99
+ errors << "#{path}.name: must be \"chosen\", and only for cant_activate"
100
+ end
90
101
  raw_if = Mechanics.fetch_param(params, :if)
91
- new(rule, affects, filter, spells: spells, condition: raw_if && Condition.build(raw_if, errors, "#{path}.if"))
102
+ new(rule, affects, filter, spells: spells, chosen_name: !named.nil?,
103
+ condition: raw_if && Condition.build(raw_if, errors, "#{path}.if"))
92
104
  end
93
105
 
94
- def initialize(rule, affects, filter, spells: nil, condition: nil)
106
+ def initialize(rule, affects, filter, spells: nil, chosen_name: false, condition: nil)
95
107
  super()
96
108
  @rule = rule
97
109
  @affects = affects
98
110
  @filter = filter
99
111
  @spells = spells
112
+ @chosen_name = chosen_name
100
113
  @condition = condition
101
114
  freeze
102
115
  end
@@ -116,14 +129,18 @@ module Enjine
116
129
  condition.nil? || condition.true?(engine, EffectContext.new(source.controller, source.id, source.id, [], []))
117
130
  end
118
131
 
119
- # Whether the object asked about (a permanent for `filter`, a card for `spells`) is one the rule is about.
132
+ # Whether the object asked about (a permanent for `filter`, a card for `spells`, a source in any zone with
133
+ # the name its source chose for `name`, CR 201.4) is one the rule is about.
120
134
  def matches?(engine, object, source)
121
- (filter.nil? || filter.match?(engine, object.id, source.controller)) && (spells.nil? || spells.match?(engine, object))
135
+ return false if @chosen_name && engine.chars(object).name != source.memory["chosen_name"]
136
+
137
+ (filter.nil? || filter.match_for?(engine, object.id, source.controller, source.id)) &&
138
+ (spells.nil? || spells.match?(engine, object))
122
139
  end
123
140
 
124
141
  def to_s
125
142
  who = { "you" => "you", "opponents" => "your opponents", "each" => "each player" }.fetch(affects)
126
- about = filter || spells
143
+ about = filter || spells || ("sources with the chosen name" if @chosen_name)
127
144
  "#{who}: #{rule.tr("_", " ")}#{" (#{about.is_a?(Class) ? about.primitive_name : about})" if about}" \
128
145
  "#{" as long as #{condition}" if condition}"
129
146
  end