enjine 0.6.3 → 0.6.5

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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -1
  3. data/SUPPORTED.md +10 -9
  4. data/docs/guides/api.md +3 -0
  5. data/docs/guides/card-data-format.md +41 -2
  6. data/docs/plans/dsl-gaps.md +12 -12
  7. data/docs/reference/abilities.md +25 -11
  8. data/docs/reference/decisions.md +1 -1
  9. data/docs/reference/effects.md +15 -11
  10. data/lib/enjine/actions/activate_mana_ability.rb +3 -2
  11. data/lib/enjine/cli/text.rb +2 -1
  12. data/lib/enjine/decisions/casting.rb +1 -1
  13. data/lib/enjine/engine/casting/casting.rb +1 -0
  14. data/lib/enjine/engine/casting/payment.rb +20 -13
  15. data/lib/enjine/engine/casting/permissions.rb +11 -9
  16. data/lib/enjine/engine/copies.rb +8 -0
  17. data/lib/enjine/engine/damage.rb +1 -0
  18. data/lib/enjine/engine/mana_helpers.rb +75 -0
  19. data/lib/enjine/engine/mana_sources.rb +19 -8
  20. data/lib/enjine/engine/options_memo.rb +15 -2
  21. data/lib/enjine/engine/turn_history.rb +8 -0
  22. data/lib/enjine/engine/zones.rb +10 -0
  23. data/lib/enjine/mechanics/abilities/cost_changes.rb +62 -17
  24. data/lib/enjine/mechanics/abilities/entering_copy.rb +45 -16
  25. data/lib/enjine/mechanics/abilities/mana_ability.rb +54 -9
  26. data/lib/enjine/mechanics/abilities/play_permissions.rb +28 -9
  27. data/lib/enjine/mechanics/abilities/replacement_effects.rb +40 -11
  28. data/lib/enjine/mechanics/card_spec.rb +28 -2
  29. data/lib/enjine/mechanics/effects/choose_cards.rb +30 -15
  30. data/lib/enjine/mechanics/effects/counter_spell.rb +12 -5
  31. data/lib/enjine/mechanics/effects/damage.rb +24 -4
  32. data/lib/enjine/mechanics/effects/delayed_triggers.rb +3 -2
  33. data/lib/enjine/mechanics/effects/draw.rb +1 -1
  34. data/lib/enjine/mechanics/effects/loot.rb +1 -1
  35. data/lib/enjine/mechanics/effects/mana.rb +4 -1
  36. data/lib/enjine/mechanics/effects/pay.rb +14 -8
  37. data/lib/enjine/mechanics/keywords/alternative_costs.rb +3 -2
  38. data/lib/enjine/mechanics/keywords/bargain.rb +39 -0
  39. data/lib/enjine/mechanics/selector.rb +29 -8
  40. data/lib/enjine/replacements.rb +23 -5
  41. data/lib/enjine/steps.rb +1 -1
  42. data/lib/enjine/version.rb +1 -1
  43. metadata +4 -2
@@ -90,27 +90,33 @@ module Enjine
90
90
  class CostModifier < Primitive
91
91
  TYPES = %w[artifact creature enchantment land planeswalker instant sorcery].freeze
92
92
  CASTERS = %w[you opponent any].freeze
93
- SPEC_KEYS = %w[subtypes colors name].freeze
93
+ SPEC_KEYS = %w[subtypes colors name keywords not_subtypes].freeze
94
+ # "The first ... spell you cast each turn / during each of your turns" (CR 601.2f): only a spell no earlier
95
+ # matching spell of its caster this turn came before.
96
+ FIRSTS = %w[each_turn each_of_your_turns].freeze
94
97
 
95
98
  primitive :ability, :cost_modifier,
96
99
  description: "While on the battlefield: spells cast by `caster` (you, opponent or any; default you) " \
97
100
  "whose card types match `spells` ({\"any_of\": [types], \"not\": [types]}, default all " \
98
101
  "spells; `subtypes`, `colors` and `name` narrow it: \"Dragon spells\", \"red spells\"; " \
99
102
  "`\"subtypes\": \"chosen\"`: of the type chosen for this permanent, `\"name\": \"chosen\"`: with the " \
100
- "name its source chose) cost " \
103
+ "name its source chose; `keywords` / `not_subtypes`: \"non-Lemur creature spells with " \
104
+ "flying\") cost " \
101
105
  "`reduce` less or `increase` more generic mana. `from` / `not_from`: only " \
102
- "spells cast from (not from) that zone (hand | graveyard | exile | library | outside).",
103
- rules: %w[601.2f 118.7a 604.1 601.2a],
106
+ "spells cast from (not from) that zone (hand | graveyard | exile | library | outside). " \
107
+ "`first`: only the first matching spell its caster casts `each_turn` or " \
108
+ "`each_of_your_turns` (spells cast before this permanent was there count too).",
109
+ rules: %w[601.2f 118.7a 604.1 601.2a 601.2i],
104
110
  params: { "spells" => "{\"any_of\": [types], \"not\": [types], \"subtypes\": [subtypes], \"colors\": [colors]} " \
105
111
  "(optional)",
106
112
  "caster" => "you | opponent | any", "reduce" => "amount", "increase" => "amount",
107
- "from" => "zone", "not_from" => "zone" },
113
+ "from" => "zone", "not_from" => "zone", "first" => FIRSTS.join(" | ") },
108
114
  example: { "cost_modifier" => { "spells" => { "not" => ["creature"] }, "reduce" => 1 } }
109
115
 
110
116
  attr_reader :caster, :any_of, :not_types, :amount, :sign
111
117
 
112
118
  def self.build(params, errors, path, **)
113
- Mechanics.check_keys(params, %w[spells caster reduce increase] + CastFrom::KEYS, errors, path)
119
+ Mechanics.check_keys(params, %w[spells caster reduce increase first] + CastFrom::KEYS, errors, path)
114
120
  spells = Mechanics.fetch_param(params, :spells) || {}
115
121
  unless spells.is_a?(Hash)
116
122
  errors << "#{path}.spells: must be an object"
@@ -124,8 +130,10 @@ module Enjine
124
130
  end
125
131
  caster = Mechanics.fetch_param(params, :caster) || "you"
126
132
  errors << "#{path}.caster: must be one of #{CASTERS.join(", ")}" unless CASTERS.include?(caster)
133
+ first = Mechanics.fetch_param(params, :first)
134
+ errors << "#{path}.first: must be one of #{FIRSTS.join(", ")}" unless first.nil? || FIRSTS.include?(first)
127
135
  new(caster, lists["any_of"], lists["not"], *build_amount(params, errors, path),
128
- zones: CastFrom.build(params, errors, path), spec: build_spec(spells, errors, path))
136
+ zones: CastFrom.build(params, errors, path), spec: build_spec(spells, errors, path), first: first)
129
137
  end
130
138
 
131
139
  # "Dragon spells", "red spells": the subtypes and colors in `spells`, matched as a card spec.
@@ -143,8 +151,9 @@ module Enjine
143
151
  [Amount.build(params[keys.first], errors, "#{path}.#{keys.first}", targets_count: 0), keys.first == "reduce" ? -1 : 1]
144
152
  end
145
153
 
146
- def initialize(caster, any_of, not_types, amount, sign, zones: CastFrom.new(nil, nil), spec: nil)
154
+ def initialize(caster, any_of, not_types, amount, sign, zones: CastFrom.new(nil, nil), spec: nil, first: nil)
147
155
  super()
156
+ @first = first
148
157
  @spec = spec
149
158
  @caster = caster
150
159
  @any_of = any_of.freeze
@@ -164,24 +173,60 @@ module Enjine
164
173
  def change_for(engine, permanent, spell, caster_index)
165
174
  return 0 unless caster == "any" || (caster == "you") == (caster_index == permanent.controller)
166
175
 
167
- chars = engine.chars(spell)
168
- types = chars.types
169
- return 0 if types.intersect?(not_types) || !(any_of.empty? || types.intersect?(any_of))
170
-
171
176
  ctx = EffectContext.new(permanent.controller, permanent.id, permanent.id, [])
172
- return 0 if @spec && !@spec.chars_match?(engine, chars, ctx) # the source's choices: type, name (CR 201.4, 607.2d)
173
- return 0 unless @zones.match?(engine.cast_origin(spell))
177
+ return 0 unless spell_matches?(engine, engine.chars(spell), engine.cast_origin(spell), ctx)
178
+ return 0 if @first && !first_spell?(engine, caster_index, ctx)
174
179
 
175
180
  sign * amount.value(engine, ctx)
176
181
  end
177
182
 
183
+ # Whether a spell with these characteristics, cast from `zone`, is one it changes.
184
+ def spell_matches?(engine, chars, zone, ctx)
185
+ types = chars.types
186
+ return false if types.intersect?(not_types) || !(any_of.empty? || types.intersect?(any_of))
187
+ return false if @spec && !@spec.chars_match?(engine, chars, ctx) # the source's choices: type, name (CR 201.4, 607.2d)
188
+
189
+ @zones.match?(zone)
190
+ end
191
+
192
+ # "The first ... spell you cast each turn": no spell its caster cast this turn matched, as it was cast
193
+ # (Engine::TurnHistory "spells_as_cast"; a cancelled cast never counts, CR 601.2i); "during each of your
194
+ # turns": and it's the caster's turn.
195
+ def first_spell?(engine, caster_index, ctx)
196
+ return false if @first == "each_of_your_turns" && engine.state.active != caster_index
197
+
198
+ log = engine.turn_log(caster_index)
199
+ facts = Array(log["spells_as_cast"])
200
+ zones = Array(log["spells_from"])
201
+ Array(log["spells"]).each_with_index.none? do |card, i|
202
+ spell_matches?(engine, CostModifier.as_cast(engine, card, facts[i]), zones[i] || "hand", ctx)
203
+ end
204
+ end
205
+
206
+ # A spell's characteristics as it was cast (types, subtypes, keywords and colors of the face cast, CR 601.2a);
207
+ # its printed ones if they weren't recorded.
208
+ def self.as_cast(engine, card, facts)
209
+ chars = engine.catalog.fetch(card).printed_characteristics
210
+ return chars unless facts
211
+
212
+ types, subtypes, keywords, colors = facts.map { |list| list.map(&:to_sym) }
213
+ chars.with(types: types, subtypes: subtypes, keywords: keywords, colors: colors)
214
+ end
215
+
216
+ FIRST_TEXT = { "each_turn" => " each turn", "each_of_your_turns" => " during each of your turns" }.freeze
217
+
178
218
  def to_s
179
- narrow = @spec ? [@spec.colors.map(&:to_s), @spec.subtypes.map { it.to_s.capitalize }] : []
219
+ narrow = []
220
+ if @spec
221
+ narrow = [@spec.colors.map(&:to_s), @spec.not_subtypes.map { "non-#{it.to_s.capitalize}" },
222
+ @spec.subtypes.map { it.to_s.capitalize }]
223
+ end
180
224
  narrow << "chosen-type" if @spec&.relations&.[]("chosen_subtype")
181
225
  kinds = [not_types.map { "non#{it}" }, narrow, any_of.join(" or ")].flatten.reject(&:empty?).join(" ")
182
226
  whose = { "you" => "you cast", "opponent" => "your opponents cast", "any" => "" }[caster]
183
- "#{[kinds, "spells", whose].reject(&:empty?).join(" ")}#{@zones} cost {#{amount}} " \
184
- "#{sign.negative? ? "less" : "more"}"
227
+ with = " with #{@spec.keywords.join(" or ")}" if @spec && !@spec.keywords.empty?
228
+ "#{"the first " if @first}#{[kinds, "spells#{with}", whose].reject(&:empty?).join(" ")}#{@zones}" \
229
+ "#{FIRST_TEXT[@first]} cost {#{amount}} #{sign.negative? ? "less" : "more"}"
185
230
  end
186
231
  end
187
232
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "entering_choices"
4
4
  require_relative "../copy_except"
5
+ require_relative "../follow_up"
5
6
 
6
7
  module Enjine
7
8
  module Mechanics
@@ -9,56 +10,84 @@ module Enjine
9
10
  # "You may have this creature enter as a copy of any artifact or creature on the battlefield" (CR 707.5,
10
11
  # 614.1c, 614.12): as it would enter, its controller chooses a permanent matching `of` (or none); it
11
12
  # enters as a copy of it, with the `except` modifications, and with `with_counters: true` also with
12
- # the same number and kinds of counters the copied permanent has.
13
+ # the same number and kinds of counters the copied permanent has. `of` may name cards in a graveyard
14
+ # instead ("enter as a copy of any creature card in a graveyard", {"graveyard_card": ...}): the copy has
15
+ # the card's copiable values (CR 707.2). `then`: effects right after it entered as a copy, usually a
16
+ # reflexive_trigger ("When you do, exile that card", CR 603.12), reading {"triggering": "object"} (the
17
+ # copied object) and "player" (its owner).
13
18
  class EnterAsCopy < EnteringChoice
19
+ # Where the copied object may be.
20
+ ZONES = %i[battlefield graveyard].freeze
21
+
14
22
  primitive :ability, :enter_as_copy,
15
23
  description: "As this permanent enters, its controller may choose a permanent on the battlefield " \
16
- "matching `of`; it enters as a copy of that permanent (its copiable values, with the " \
17
- "`except` modifications) and its enter abilities trigger. `with_counters: true`: it " \
18
- "also enters with the counters the copied permanent has. Choosing none: it enters as " \
19
- "itself.",
20
- rules: %w[707.5 707.9b 205.1a 614.1c 614.12],
21
- params: { "of" => "filter (the permanents it may copy)", "except" => Mechanics::CopyExcept::PARAM,
22
- "with_counters" => "boolean" },
24
+ "matching `of` (or, with a `graveyard_card` filter, a card in a graveyard); it enters " \
25
+ "as a copy of it (its copiable values, with the `except` modifications) and its enter " \
26
+ "abilities trigger. `with_counters: true`: it also enters with the counters the copied " \
27
+ "permanent has. `then`: effects once it entered as a copy, usually a reflexive_trigger " \
28
+ "(\"When you do, exile that card\"), reading {\"triggering\": \"object\"} (what it " \
29
+ "copied) and \"player\" (its owner). Choosing none: it enters as itself.",
30
+ rules: %w[707.5 707.2 707.9b 205.1a 614.1c 614.12 603.12],
31
+ params: { "of" => "filter (the permanents, or graveyard cards, it may copy)",
32
+ "except" => Mechanics::CopyExcept::PARAM, "with_counters" => "boolean",
33
+ "then" => "list of effects (a reflexive_trigger for \"When you do, ...\")" },
23
34
  example: { "enter_as_copy" => { "of" => { "permanent" => { "any_of" => %w[artifact creature] } },
24
35
  "except" => { "legendary" => false }, "with_counters" => true } }
25
36
 
26
- attr_reader :filter, :except, :with_counters
37
+ attr_reader :filter, :except, :with_counters, :follow_up
27
38
 
28
39
  def self.build(params, errors, path, **)
29
- Mechanics.check_keys(params, %w[of except with_counters], errors, path)
40
+ Mechanics.check_keys(params, %w[of except with_counters then], errors, path)
30
41
  raw = Mechanics.fetch_param(params, :of)
31
42
  filter = raw.nil? ? (errors << "#{path}.of: required") && nil : Mechanics.build_entry(:filter, raw, errors, "#{path}.of")
43
+ zones = filter ? zones(filter) : []
44
+ errors << "#{path}.of: must name permanents or graveyard cards" unless (zones - ZONES).empty?
32
45
  except = Mechanics::CopyExcept.build(Mechanics.fetch_param(params, :except), errors, "#{path}.except")
33
- new(filter, except, Mechanics.flag_param(params, :with_counters, errors, path))
46
+ with_counters = Mechanics.flag_param(params, :with_counters, errors, path)
47
+ errors << "#{path}.with_counters: a card in a graveyard has no counters" if with_counters && zones.include?(:graveyard)
48
+ new(filter, except, with_counters, FollowUp.build(params, errors, path))
34
49
  end
35
50
 
36
- def initialize(filter, except, with_counters)
51
+ # The zones a filter's objects are in.
52
+ def self.zones(filter)
53
+ return filter.filters.flat_map { zones(it) }.uniq if filter.respond_to?(:filters)
54
+
55
+ [(filter.respond_to?(:base) ? filter.base : filter).zone]
56
+ end
57
+
58
+ def initialize(filter, except, with_counters, follow_up = nil)
37
59
  super()
38
60
  @filter = filter
39
61
  @except = except
40
62
  @with_counters = with_counters
63
+ @follow_up = follow_up
41
64
  freeze
42
65
  end
43
66
 
67
+ def try_effects = [follow_up].compact
68
+
44
69
  def to_s
45
70
  what = filter.is_a?(Class) ? filter.primitive_name : filter
46
- "you may have it enter as a copy of a #{what}#{Mechanics::CopyExcept.to_s(except)}#{" with its counters" if with_counters}"
71
+ what = "#{what} card in a graveyard" if filter.is_a?(Filters::Restricted) && filter.base == Filters::GraveyardCard
72
+ "you may have it enter as a copy of a #{what}#{Mechanics::CopyExcept.to_s(except)}" \
73
+ "#{" with its counters" if with_counters}#{"; then #{follow_up}" if follow_up}"
47
74
  end
48
75
 
49
76
  def options(engine, controller)
50
77
  candidates = filter ? filter.candidates_for(engine, controller, nil) : []
51
- candidates.select { engine.state.battlefield.include?(it) }.map { { type: "copy", object: it } } +
78
+ candidates.select { ZONES.include?(engine.state.objects[it]&.zone) }.map { { type: "copy", object: it } } +
52
79
  [{ type: "dont_copy" }]
53
80
  end
54
81
 
55
- # What it enters with (Engine#enters_from_answer): the copy, and the copied permanent's counters.
82
+ # What it enters with (Engine#enters_from_answer): the copy, the copied permanent's counters, and the
83
+ # follow-up to run once it entered (Engine::Copies#copy_follow_up!).
56
84
  def enters_with(engine, answer)
57
85
  obj = answer[:type] == "copy" && engine.state.objects[answer[:object]]
58
- return nil unless obj && obj.zone == :battlefield
86
+ return nil unless obj && ZONES.include?(obj.zone)
59
87
 
60
88
  card, except = engine.copiable_values(obj)
61
89
  enters = { "copy" => { "card" => card, "except" => Engine::Copies.merge_except(except, @except) } }
90
+ enters["copy_then"] = { "ref" => follow_up.ref, "facts" => { "object" => obj.id, "player" => obj.owner } } if follow_up
62
91
  with_counters && !obj.counters.empty? ? enters.merge("counters" => obj.counters.dup) : enters
63
92
  end
64
93
 
@@ -11,8 +11,12 @@ module Enjine
11
11
  # paid for a cost while a spell or ability resolves (CR 118.12) is neither, so restricted mana can't pay it.
12
12
  # `from` / `not_from` a zone limit the spells to those cast from (not from) it ("spend this mana only to cast
13
13
  # a spell from anywhere other than your hand": {"not_from": "hand"}; CR 601.2a); alone, they mean spells.
14
+ # A spec of `"subtypes": "chosen"` reads the creature type chosen for the mana's source (CR 607.2d) as the mana is
15
+ # made (#bound), so the mana keeps that restriction once in the pool, wherever the source goes (CR 106.6).
16
+ # `"cant_be_countered": true`: a spell cast with this mana can't be countered (Cavern of Souls, CR 106.6, 101.2).
14
17
  class SpendOnly
15
- KEYS = (%w[spells abilities] + CastFrom::KEYS).freeze
18
+ KEYS = (%w[spells abilities cant_be_countered] + CastFrom::KEYS).freeze
19
+ SPECS = %w[spells abilities].freeze
16
20
 
17
21
  attr_reader :data
18
22
 
@@ -24,11 +28,19 @@ module Enjine
24
28
  end
25
29
  data = data.transform_keys(&:to_s)
26
30
  zones = CastFrom.build(data, errors, path)
27
- specs = data.slice("spells", "abilities").to_h { |key, spec| [key, CardSpec.build(spec, errors, "#{path}.#{key}")] }
31
+ specs = data.slice(*SPECS).to_h { |key, spec| [key, CardSpec.build(spec, errors, "#{path}.#{key}")] }
28
32
  specs["spells"] ||= CardSpec.build("card", errors, path) if data.keys.intersect?(CastFrom::KEYS)
33
+ check_rider(data, specs, errors, path)
29
34
  new(data, specs, zones)
30
35
  end
31
36
 
37
+ def self.check_rider(data, specs, errors, path)
38
+ return unless data.key?("cant_be_countered")
39
+
40
+ errors << "#{path}.cant_be_countered: must be true" unless data["cant_be_countered"] == true
41
+ errors << "#{path}.cant_be_countered: needs \"spells\" (it applies to a spell cast with the mana)" unless specs["spells"]
42
+ end
43
+
32
44
  # The restriction kept on pool mana (plain data, CR 106.6), rebuilt once per distinct data.
33
45
  def self.from_data(data)
34
46
  (@cache ||= {})[data] ||= build(data, [], "spend_only")
@@ -38,9 +50,30 @@ module Enjine
38
50
  @data = Snapshot.deep_copy(data).freeze
39
51
  @specs = specs.freeze
40
52
  @zones = zones
53
+ @chosen = specs.values.any? { it.relations["chosen_subtype"] }
41
54
  freeze
42
55
  end
43
56
 
57
+ # "A spell cast with this mana can't be countered" (CR 106.6, 101.2): Engine::Payment#pay_mana! marks the spell.
58
+ def cant_be_countered? = @data["cant_be_countered"] == true
59
+
60
+ # Whether a spent pool entry (restricted mana, or nil) carries that rider.
61
+ def self.uncounterable?(entry) = !entry&.[]("spend_only").nil? && from_data(entry["spend_only"]).cant_be_countered?
62
+
63
+ # The restriction of mana made by `source`: "of the chosen type" becomes the creature type chosen for it now
64
+ # (CR 607.2d), so mana in the pool keeps it (CR 106.6). With no type chosen, "chosen" stays and matches nothing
65
+ # (CardSpec reads no choice without a context).
66
+ def bound(engine, source)
67
+ return self unless @chosen
68
+
69
+ type = engine.state.objects[source]&.memory&.[]("chosen_type") or return self
70
+ SpendOnly.from_data(@data.to_h do |key, spec|
71
+ next [key, spec] unless SPECS.include?(key) && spec.is_a?(Hash) && spec["subtypes"] == "chosen"
72
+
73
+ [key, spec.merge("subtypes" => [type])]
74
+ end)
75
+ end
76
+
44
77
  # `purpose`: {"spell" => id} for a spell being cast, {"ability" => source id} for an ability being
45
78
  # activated, nil for anything else.
46
79
  def allows?(engine, purpose)
@@ -57,7 +90,7 @@ module Enjine
57
90
  parts = []
58
91
  parts << "cast #{"#{@specs["spells"]} " unless @specs["spells"].any?}spells#{@zones}" if @specs["spells"]
59
92
  parts << "activate abilities of #{@specs["abilities"]}s" if @specs["abilities"]
60
- "spend this mana only to #{parts.join(" or ")}"
93
+ "spend this mana only to #{parts.join(" or ")}#{", and that spell can't be countered" if cant_be_countered?}"
61
94
  end
62
95
  end
63
96
 
@@ -76,15 +109,20 @@ module Enjine
76
109
  "`amount` mana (default 1) of one color you choose as you activate it " \
77
110
  "(`\"any_one\"`) or in any combination of colors (`\"any\"`); `colors` limits " \
78
111
  "the choice. `\"chosen\"`: of the color chosen as this entered (choose_color). " \
79
- "`spend_only` restricts how the mana can be spent. `only_if`: \"Activate only if ...\". " \
112
+ "`spend_only` restricts how the mana can be spent (a spec of `\"subtypes\": \"chosen\"`: the creature " \
113
+ "type chosen as this entered; `\"cant_be_countered\": true`: a spell cast with it can't be " \
114
+ "countered). `only_if`: \"Activate only if ...\". " \
80
115
  "`limit: \"once_each_turn\"`: \"Activate only once each turn.\" `add_counters`: it also " \
81
- "puts counters on its own source (\"Add {C}. Put a point counter on this\").",
82
- rules: %w[605.1a 605.3a 605.3b 106.1a 106.4 106.6 607.2d 602.5b 122.1],
116
+ "puts counters on its own source (\"Add {C}. Put a point counter on this\"). A " \
117
+ "`tap_permanents` cost (count 1) taps another permanent you choose as you activate it " \
118
+ "(\"{T}, Tap an untapped creature you control\"): each activation option names it (`tap`).",
119
+ rules: %w[605.1a 605.3a 605.3b 106.1a 106.4 106.6 607.2d 602.5b 122.1 101.2 602.2b 302.6],
83
120
  params: { "cost" => "list of costs (e.g. [\"tap\"])",
84
121
  "produce" => "mana symbols added, e.g. \"{G}\" or \"{C}{C}\"",
85
122
  "amount" => "amount (default 1; with produce: how many times)",
86
123
  "color" => CHOICES.join(" | "), "colors" => "list of colors to choose from (default all five)",
87
- "spend_only" => "{\"spells\": card spec, \"abilities\": card spec, \"from\" | \"not_from\": zone}",
124
+ "spend_only" => "{\"spells\": card spec, \"abilities\": card spec, \"from\" | \"not_from\": zone, " \
125
+ "\"cant_be_countered\": true}",
88
126
  "only_if" => "condition: it can be activated only while it holds (CR 602.5b)",
89
127
  "limit" => "\"once_each_turn\" (CR 602.5b)",
90
128
  "add_counters" => "{\"counter\": name, \"amount\": integer (default 1)}: put on this permanent" },
@@ -141,6 +179,9 @@ module Enjine
141
179
  if cost.is_a?(Costs::OneOf)
142
180
  errors << "#{path}.cost[#{i}]: a mana ability's cost can't be a one_of (a choice between costs, CR 601.2b, " \
143
181
  "isn't supported for mana abilities, which are paid for at once, CR 605.3a)"
182
+ elsif cost.is_a?(Costs::TapPermanents)
183
+ # "Tap an untapped creature you control": the permanent is named by the activation (Engine::ManaHelpers)
184
+ errors << "#{path}.cost[#{i}]: a mana ability can tap only one other permanent (count 1)" unless cost.count == 1
144
185
  elsif choosing_cost?(cost)
145
186
  errors << "#{path}.cost[#{i}]: a mana ability's cost can't need a choice, X or {2/B}"
146
187
  end
@@ -203,16 +244,20 @@ module Enjine
203
244
  def activatable?(engine, object, bound = costs)
204
245
  return false if @only_if && !@only_if.true?(engine, EffectContext.new(object.controller, object.id, nil, nil))
205
246
 
206
- bound.all? { |c| c.payable?(engine, object) } && (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
247
+ bound.all? { |c| c.is_a?(Costs::TapPermanents) || c.payable?(engine, object) } && engine.mana_helper?(object, bound) &&
248
+ (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
207
249
  end
208
250
 
209
251
  # [counter, amount] it puts on its source as it resolves, or nil.
210
252
  attr_reader :add_counters
211
253
 
254
+ # Tapping its source, the granter or another permanent (Engine::ManaHelpers) can be rewound (CR 734.1).
255
+ def self.rewindable?(cost) = [Costs::Tap, Costs::TapGranter, Costs::TapPermanents].any? { cost.is_a?(it) }
256
+
212
257
  # One whose costs include more than {T} and mana (a sacrifice, life, a discard, removing counters) or that puts
213
258
  # counters on its source can't be undone (CR 734.1 rewinds only tapping and mana).
214
259
  def irreversible?
215
- !add_counters.nil? || costs.any? { !it.is_a?(Costs::Tap) && !it.is_a?(Costs::TapGranter) && !it.mana? }
260
+ !add_counters.nil? || costs.any? { !ManaAbility.rewindable?(it) && !it.mana? }
216
261
  end
217
262
 
218
263
  # How many times it could be activated in a row now, for affordability: once, unless every cost is removing
@@ -200,7 +200,9 @@ module Enjine
200
200
  end
201
201
 
202
202
  # Permission to play exiled cards for a duration (CR 611.2, 601.3; see Engine::Permissions). With
203
- # `choose`, the controller first chooses one matching card per owner among them.
203
+ # `choose`, the controller first chooses one matching card per owner among them. `zone: "graveyard"`: the
204
+ # referenced cards in a graveyard instead ("mill a card. You may play that card this turn"); the permission
205
+ # ends once the card leaves it (a new object, CR 400.7).
204
206
  #
205
207
  # Who may play them and how (riders):
206
208
  # `to_player` "controller" (default), "owner" (each card's owner, CR 108.3) or a player selector
@@ -216,10 +218,12 @@ module Enjine
216
218
  DURATIONS = %w[end_of_turn end_of_your_next_turn until_your_next_end_step while_exiled
217
219
  while_you_control_source].freeze
218
220
  PLAYERS = %w[controller owner].freeze
221
+ ZONES = %w[exile graveyard].freeze
219
222
 
220
223
  primitive :effect, :play_permission,
221
224
  description: "A player may play (`play: \"play\"`, default) or cast (`\"cast\"`) each referenced " \
222
- "exiled card matching `for`/`not_types`, paying its costs and following timing rules, " \
225
+ "exiled card (`zone: \"graveyard\"`: card in a graveyard) matching `for`/`not_types`, " \
226
+ "paying its costs and following timing rules (a land uses a land play), " \
223
227
  "for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step, " \
224
228
  "while_exiled or while_you_control_source (\"for as long as you control this creature\"). " \
225
229
  "With " \
@@ -230,19 +234,20 @@ module Enjine
230
234
  "`any_mana_type: true`: mana of any type can be spent to cast those spells. " \
231
235
  "`during: \"your_turn\"`: only during your turn. `waterbend: \"mana_value\"`: cast it by " \
232
236
  "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],
237
+ rules: %w[611.2a 611.2b 601.3 305.1 305.2 400.7 514.2 601.2f 108.3 406.3b 609.4b 118.9 701.67a],
234
238
  params: { "to" => "selector (usually {\"result\": n})", "duration" => DURATIONS.join(" | "),
235
239
  "play" => "play | cast", "for" => "card spec", "not_types" => "list of card types",
236
240
  "choose" => "one_per_owner", "to_player" => "controller | owner | player selector",
237
241
  "cost_increase" => "integer >= 1", "any_mana_type" => "boolean",
238
242
  "exile_instead" => "true or a card spec: if a spell cast this way (matching it) would be put " \
239
243
  "into a graveyard, it's exiled instead (CR 614.1a)",
240
- "during" => "your_turn", "waterbend" => "mana_value" },
244
+ "during" => "your_turn", "waterbend" => "mana_value",
245
+ "zone" => "exile (default) | graveyard: where the referenced cards are" },
241
246
  example: { "play_permission" => { "to" => { "result" => 0 }, "duration" => "end_of_your_next_turn" } }
242
247
 
243
248
  def self.keys
244
249
  %w[to duration play for not_types choose to_player cost_increase any_mana_type exile_instead during
245
- waterbend if]
250
+ waterbend zone if]
246
251
  end
247
252
 
248
253
  def setup(params, errors, path)
@@ -256,6 +261,8 @@ module Enjine
256
261
  @filter = CardFilter.build(params, errors, path)
257
262
  @to_player = player_param(Mechanics.fetch_param(params, :to_player) || "controller", errors, path)
258
263
  @riders = riders(params, errors, path)
264
+ @zone = zone_param(params, errors, path)
265
+ @riders["zone"] = @zone if @zone == "graveyard"
259
266
  end
260
267
 
261
268
  def to_s
@@ -265,7 +272,8 @@ module Enjine
265
272
  more += ", #{ExileInstead.words(@riders["exile_instead"])}" if @riders["exile_instead"]
266
273
  more += ", during your turn" if @riders["during"]
267
274
  more += ", by waterbending {X} (X: its mana value)" if @riders["waterbend"]
268
- "#{who} may #{@play} #{@filter} (#{@duration.tr("_", " ")}#{more}) → #{to}"
275
+ where = @zone == "graveyard" ? " in a graveyard" : ""
276
+ "#{who} may #{@play} #{@filter}#{where} (#{@duration.tr("_", " ")}#{more}) → #{to}"
269
277
  end
270
278
 
271
279
  def run(engine, ctx, locals)
@@ -273,7 +281,7 @@ module Enjine
273
281
  # CR 611.2b: "for as long as you control [this]" that has already ended never starts.
274
282
  return :done unless engine.source_duration_holds?(@duration, ctx.source, ctx.controller)
275
283
 
276
- cards = (locals["cards"] ||= refs(engine, ctx).select { exiled_match?(engine, it) })
284
+ cards = (locals["cards"] ||= refs(engine, ctx).select { card_match?(engine, it) })
277
285
  picks = @choose ? choose(engine, ctx, locals, cards) : cards
278
286
  return :wait if picks == :wait
279
287
 
@@ -286,6 +294,17 @@ module Enjine
286
294
 
287
295
  private
288
296
 
297
+ # CR 400.7: a card in a graveyard keeps its permission only while it stays there ("while_exiled" is exile's).
298
+ def zone_param(params, errors, path)
299
+ zone = Mechanics.fetch_param(params, :zone) || "exile"
300
+ return zone if ZONES.include?(zone) && !(zone == "graveyard" && @duration == "while_exiled")
301
+
302
+ errors << if ZONES.include?(zone) then "#{path}.duration: while_exiled needs zone exile"
303
+ else "#{path}.zone: must be one of #{ZONES.join(", ")}"
304
+ end
305
+ "exile"
306
+ end
307
+
289
308
  def player_param(raw, errors, path)
290
309
  return raw if PLAYERS.include?(raw)
291
310
 
@@ -319,9 +338,9 @@ module Enjine
319
338
  end
320
339
 
321
340
  # A face-down card is judged face up (the permission is to play it face up, CR 406.3a).
322
- def exiled_match?(engine, id)
341
+ def card_match?(engine, id)
323
342
  obj = engine.state.objects[id]
324
- obj && obj.zone == :exile && engine.face_up(id) { @filter.match?(engine, obj) }
343
+ obj && obj.zone.to_s == @zone && engine.face_up(id) { @filter.match?(engine, obj) }
325
344
  end
326
345
 
327
346
  # One card per owner, in seat order; asked only when there's a choice.
@@ -59,32 +59,61 @@ module Enjine
59
59
  def try_effects = []
60
60
  end
61
61
 
62
- # "If you would draw a card, draw two cards instead." (CR 614.11)
62
+ # "If you would draw a card, draw two cards instead." (CR 614.11) / "As long as you have one or fewer cards in
63
+ # hand, if you would draw one or more cards, you draw that many cards plus one instead." (CR 614.11, 121.2)
63
64
  class DrawReplacement < StaticReplacement
64
65
  primitive :ability, :draw_replacement,
65
- description: "While this permanent is on the battlefield, each time its controller would draw a " \
66
- "card, they draw `amount` cards instead (even with an empty library). The draws it " \
67
- "makes aren't replaced by it again, but another such effect applies to each of them.",
68
- rules: %w[614.11 614.11a 614.5 121.2 616.1],
69
- params: { "amount" => "integer >= 2" },
66
+ description: "While this permanent is on the battlefield (and its `if` condition holds as the draw " \
67
+ "would happen), each time its controller would draw: with `amount`, each card they " \
68
+ "would draw becomes `amount` cards (even with an empty library; the draws it makes " \
69
+ "aren't replaced by it again, but another such effect applies to each of them); with " \
70
+ "`plus`, an instruction to draw one or more cards draws that many plus `plus` " \
71
+ "instead, once for the whole instruction (\"draw two\" becomes three, not four). " \
72
+ "The affected player's best order is used: adding before multiplying each card.",
73
+ rules: %w[614.11 614.11a 614.5 121.2 616.1 604.2],
74
+ params: { "amount" => "integer >= 2 (each card drawn: that many instead)",
75
+ "plus" => "amount (\"that many cards plus one\"), instead of amount",
76
+ "if" => "condition, e.g. {\"hand_size\": \"you\", \"at_most\": 1}" },
70
77
  example: { "draw_replacement" => { "amount" => 2 } }
71
78
 
72
- attr_reader :amount
79
+ attr_reader :amount, :plus, :condition
73
80
 
74
81
  def self.build(params, errors, path, **)
75
- Mechanics.check_keys(params, %w[amount], errors, path)
76
- new(Mechanics.integer_param(params, :amount, errors, path, min: 2))
82
+ Mechanics.check_keys(params, %w[amount plus if], errors, path)
83
+ errors << "#{path}: needs exactly one of amount, plus" unless %w[amount plus].one? { params.key?(it) }
84
+ amount = params.key?("amount") ? Mechanics.integer_param(params, :amount, errors, path, min: 2) : nil
85
+ plus = params.key?("plus") ? Amount.build(params["plus"], errors, "#{path}.plus", targets_count: 0) : nil
86
+ raw_if = Mechanics.fetch_param(params, :if)
87
+ new(amount, plus, raw_if && Condition.build(raw_if, errors, "#{path}.if"))
77
88
  end
78
89
 
79
- def initialize(amount)
90
+ def initialize(amount, plus = nil, condition = nil)
80
91
  super()
81
92
  @amount = amount
93
+ @plus = plus
94
+ @condition = condition
82
95
  freeze
83
96
  end
84
97
 
85
98
  def kind = :draw_replacement
86
99
  def replace_draw = true
87
- def to_s = "if you would draw a card, draw #{amount} instead"
100
+
101
+ # Whether it applies to a draw of `index` now: its controller's draw while its "as long as" condition
102
+ # holds (CR 604.2), checked as the draw would happen (CR 614.11).
103
+ def applies?(engine, index, source)
104
+ index == source.controller &&
105
+ (condition.nil? || condition.true?(engine, EffectContext.new(source.controller, source.id, source.id, [], [])))
106
+ end
107
+
108
+ # The extra cards an instruction to draw gets ("that many plus one"), at least 0.
109
+ def extra(engine, source) = [plus.value(engine, EffectContext.new(source.controller, source.id, source.id, [], [])), 0].max
110
+
111
+ def to_s
112
+ instead = if plus then "if you would draw one or more cards, draw that many plus #{plus} instead"
113
+ else "if you would draw a card, draw #{amount} instead"
114
+ end
115
+ condition ? "as long as #{condition}, #{instead}" : instead
116
+ end
88
117
  end
89
118
 
90
119
  # "If another creature you control with a +1/+1 counter on it would be destroyed, instead remove all
@@ -23,6 +23,8 @@ module Enjine
23
23
  # {"subtypes": "chosen"} of the creature type chosen for the source (CR 607.2d)
24
24
  # {"name": "chosen"} with the card name chosen for the source or the resolving
25
25
  # spell (choose_card_name, CR 201.4, 607.2d)
26
+ # {"same_name_as": {"result": n}} the same name as a card effect n of the list moved ("cards
27
+ # with that name", CR 201.2)
26
28
  # {"same_name_as": filter} the same name as a permanent the filter matches, e.g. "a
27
29
  # legendary permanent you control" (CR 201.2a)
28
30
  # The chosen ones and same_name_as read the context (an EffectContext): the source's choices and its controller.
@@ -67,9 +69,19 @@ module Enjine
67
69
  # What the spec compares with its context: the chosen creature type, permanents to share a name with.
68
70
  def self.relations_param(data, chosen, errors, path)
69
71
  raw = data["same_name_as"]
70
- same = raw && Mechanics.build_entry(:filter, raw, errors, "#{path}.same_name_as")
72
+ result = raw.is_a?(Hash) && raw.key?("result")
73
+ same = raw && !result && Mechanics.build_entry(:filter, raw, errors, "#{path}.same_name_as")
71
74
  { "chosen_subtype" => (true if chosen), "chosen_name" => (true if data["name"] == "chosen"),
72
- "same_name_as" => same }.compact
75
+ "same_name_as" => same || nil, "same_name_as_result" => (result_index(raw, errors, path) if result) }.compact
76
+ end
77
+
78
+ # {"same_name_as": {"result": n}}: the name of a card an earlier effect of the list moved (CR 201.2, 400.7j).
79
+ # Whether n names an earlier effect is known only where the spec is used; a later one matches nothing.
80
+ def self.result_index(raw, errors, path)
81
+ Mechanics.check_keys(raw, %w[result], errors, "#{path}.same_name_as")
82
+ index = raw["result"]
83
+ errors << "#{path}.same_name_as.result: must be an effect index (0 or more)" unless index.is_a?(Integer) && index >= 0
84
+ index.to_i
73
85
  end
74
86
 
75
87
  def self.colors_param(data, errors, path)
@@ -206,6 +218,7 @@ module Enjine
206
218
 
207
219
  text = (type_words.map { it.to_s.tr("_", " ") } + ["card"]).join(" ") + quality_words
208
220
  text += " with the same name as a #{relations["same_name_as"]}" if relations["same_name_as"]
221
+ text += " with the same name as the card from effect ##{relations["same_name_as_result"] + 1}" if relations["same_name_as_result"]
209
222
  text += " with the chosen name" if relations["chosen_name"]
210
223
  bounds = { "mana value" => mana_value, "number of colors" => color_count, "power" => stats["power"] || {},
211
224
  "toughness" => stats["toughness"] || {} }.reject { |_, b| b.empty? }
@@ -245,12 +258,25 @@ module Enjine
245
258
  named = Filters.chosen_memory(engine, ctx.source, ctx)["chosen_name"]
246
259
  return false unless named && chars.name == named
247
260
  end
261
+ return result_names(engine, ctx).include?(chars.name) if relations["same_name_as_result"]
262
+
248
263
  filter = relations["same_name_as"] or return true
249
264
  !chars.name.to_s.empty? && engine.state.battlefield.any? do
250
265
  filter.match_for?(engine, it, ctx.controller, ctx.source) && engine.chars(it).name == chars.name
251
266
  end
252
267
  end
253
268
 
269
+ # The names of the cards effect n moved, as they are now, or as the card they were once they've moved again
270
+ # (CR 400.7); an object with no name shares none (CR 201.2a).
271
+ def result_names(engine, ctx)
272
+ Array(ctx.results&.[](relations["same_name_as_result"])).filter_map do |id|
273
+ obj = engine.state.objects[id]
274
+ card = obj ? nil : ctx.result_cards&.[](id)
275
+ name = obj ? engine.chars(obj).name : card && engine.catalog.fetch(card).printed_characteristics.name
276
+ name unless name.to_s.empty?
277
+ end
278
+ end
279
+
254
280
  # CR 202.3: a card's mana value (0 without a mana cost, CR 202.3a), or its number of colors (CR 105.2), within
255
281
  # the bounds.
256
282
  def bounded?(bounds, value, engine, ctx)