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
@@ -45,28 +45,39 @@ module Enjine
45
45
 
46
46
  # Choosing new targets for a spell or ability on the stack, one target at a time: keep the old one (even if
47
47
  # it's illegal now) or pick a legal new one (CR 115.7d, 707.10c). `legal_for`: whose targets they are
48
- # (legality, CR 115.7); `chooser`: who decides.
48
+ # (legality, CR 115.7); `chooser`: who decides. `change: true` is "change the target(s)" (CR 115.7a): each
49
+ # target must change to another legal target; if one can't, it stays, and then none of them change.
49
50
  module NewTargets
50
- def choose_new_targets(engine, spell, legal_for, locals, chooser: legal_for)
51
+ def choose_new_targets(engine, spell, legal_for, locals, chooser: legal_for, change: false)
51
52
  old = spell.targets || []
52
53
  specs = engine.resolving_ability(spell)&.targets_for(spell.modes || [], kicked: spell.memory.key?("kicked_with")) || []
53
54
  slots = engine.target_slots(old, specs) # each target of a counted slot in turn; same number (CR 707.10c)
54
- chosen = answers(locals).map { it["target"] }
55
- return engine.regroup_targets(chosen, old) if chosen.size >= slots.size
56
-
57
- i = chosen.size
58
- current, spec = slots[i]
59
- keep = [{ "type" => "target", "target" => current }]
60
- others = spec ? new_target_choices(engine, spec, legal_for, spell, current) : []
61
- ask(engine, locals, chooser, "Choose target ##{i + 1} for #{engine.catalog.fetch(spell.card).name}", keep + others)
55
+ loop do
56
+ chosen = answers(locals).map { it["target"] }
57
+ return locals["unchanged"] ? old : engine.regroup_targets(chosen, old) if chosen.size >= slots.size
58
+
59
+ i = chosen.size
60
+ current, spec = slots[i]
61
+ keep = [{ "type" => "target", "target" => current }]
62
+ # A divided spell's targets stay distinct, so each still receives at least one (CR 115.7f, 601.2d).
63
+ taken = spell.memory.key?("division") ? chosen + slots.drop(i + 1).map(&:first) : []
64
+ others = spec ? new_target_choices(engine, spec, legal_for, spell, [current, *taken]) : []
65
+ unless change && others.empty?
66
+ return ask(engine, locals, chooser, "Choose target ##{i + 1} for #{engine.catalog.fetch(spell.card).name}",
67
+ change ? others : keep + others)
68
+ end
69
+
70
+ locals["unchanged"] = true # CR 115.7a: no other legal target
71
+ answers(locals).concat(keep)
72
+ end
62
73
  end
63
74
 
64
75
  private
65
76
 
66
- def new_target_choices(engine, spec, controller, spell, current)
77
+ def new_target_choices(engine, spec, controller, spell, taken)
67
78
  source = spell.ability? ? spell.source : nil # an ability's copy has the same source (CR 707.10b)
68
79
  spec.candidates_for(engine, controller, source).filter_map do |ref|
69
- next if ref == current || ref == spell.id || !engine.targetable?(ref, controller, source, targeter: source || spell.id)
80
+ next if taken.include?(ref) || ref == spell.id || !engine.targetable?(ref, controller, source, targeter: source || spell.id)
70
81
 
71
82
  { "type" => "target", "target" => ref }
72
83
  end
@@ -125,12 +136,13 @@ module Enjine
125
136
  class BecomeCopy < Effect
126
137
  include CopyOf
127
138
 
128
- DURATIONS = %w[end_of_turn permanent].freeze
139
+ DURATIONS = %w[end_of_turn until_your_next_turn permanent].freeze
129
140
 
130
141
  primitive :effect, :become_copy,
131
142
  description: "Each referenced permanent becomes a copy of the (first) object `of` refers to, with the " \
132
- "`except` modifications, until end of turn (default) or for as long as it stays on the " \
133
- "battlefield (`duration: \"permanent\"`). It keeps its counters, status and other " \
143
+ "`except` modifications, until end of turn (default), until your next turn " \
144
+ "(`until_your_next_turn`) or for as long as it stays on the battlefield " \
145
+ "(`duration: \"permanent\"`). It keeps its counters, status and other " \
134
146
  "effects; nothing enters or leaves, so no enter or leave abilities trigger. Several copy " \
135
147
  "effects apply in timestamp order.",
136
148
  rules: %w[707.2 707.4 613.2a 613.7 611.2a 514.2],
@@ -152,7 +164,9 @@ module Enjine
152
164
  def apply(engine, ctx)
153
165
  first = copy_values(engine, ctx).first or return
154
166
  values = [first[0], Engine::Copies.merge_except(first[1], @except)]
155
- objects(engine, ctx).each { engine.become_copy!(engine.object(it), values, duration: @duration) }
167
+ objects(engine, ctx).each do
168
+ engine.become_copy!(engine.object(it), values, duration: @duration, controller: ctx.controller)
169
+ end
156
170
  end
157
171
  end
158
172
 
@@ -200,7 +214,7 @@ module Enjine
200
214
 
201
215
  locals["plan"] ||= plan(engine, ctx)
202
216
  while (spell_id, controller = locals["plan"].first)
203
- spell = engine.state.objects[spell_id]
217
+ spell = spell_id == REMEMBERED ? engine.remembered_ability(Selector.memory(engine, ctx)) : engine.state.objects[spell_id]
204
218
  if spell&.zone == :stack
205
219
  targets = @new_targets ? choose_new_targets(engine, spell, controller, locals) : spell.targets&.dup
206
220
  return :wait if targets == :wait
@@ -214,11 +228,18 @@ module Enjine
214
228
  :done
215
229
  end
216
230
 
231
+ # "Copy that ability" when it has already left the stack copies it as it last existed there, with the
232
+ # choices made for it (CR 707.10, 608.2h): the engine's reading, since the copy needs no object on the stack.
233
+ REMEMBERED = "remembered"
234
+
217
235
  private
218
236
 
219
237
  def plan(engine, ctx)
220
238
  n = amount_for(engine, ctx)
221
239
  spells = of_refs(engine, ctx).select { engine.state.objects[it]&.zone == :stack }
240
+ if spells.empty? && @of.kind == :triggering && @of.value == "ability" && engine.remembered_ability(Selector.memory(engine, ctx))
241
+ spells = [REMEMBERED]
242
+ end
222
243
  players(engine, ctx).flat_map { |index| spells.flat_map { |id| Array.new(n) { [id, index] } } }
223
244
  end
224
245
  end
@@ -242,6 +263,7 @@ module Enjine
242
263
  def self.default_to = "you"
243
264
  def setup(params, errors, path) = @of = setup_of(params, errors, path)
244
265
  def to_s = "you may choose new targets for #{@of}"
266
+ def change? = false
245
267
 
246
268
  def run(engine, ctx, locals)
247
269
  return :done unless locals["spells"] || condition.nil? || condition.true?(engine, ctx)
@@ -250,18 +272,34 @@ module Enjine
250
272
  while (id = locals["spells"].first)
251
273
  spell = engine.state.objects[id]
252
274
  if spell&.zone == :stack && !Array(spell.targets).flatten.compact.empty?
253
- targets = choose_new_targets(engine, spell, spell.controller, locals, chooser: ctx.controller)
275
+ targets = choose_new_targets(engine, spell, spell.controller, locals, chooser: ctx.controller, change: change?)
254
276
  return :wait if targets == :wait
255
277
 
256
- engine.change_targets!(spell, targets, ctx.controller)
278
+ engine.change_targets!(spell, targets)
257
279
  end
258
280
  locals["spells"].shift
259
281
  locals.delete("answers")
282
+ locals.delete("unchanged")
260
283
  end
261
284
  :done
262
285
  end
263
286
  end
264
287
 
288
+ # "Change the target of target spell or ability" (CR 115.7a): its controller must change each target to
289
+ # another legal target (legal for that spell's controller); a target with no other legal target stays, and
290
+ # then none change.
291
+ class ChangeTarget < ChooseNewTargets
292
+ primitive :effect, :change_target,
293
+ description: "Change the target(s) of each spell or ability on the stack `of` refers to: each target " \
294
+ "becomes another legal target you choose for that spell; if one can't, none change.",
295
+ rules: %w[115.7 115.7a 115.7e],
296
+ params: { "of" => "selector (spells or abilities on the stack)" },
297
+ example: { "change_target" => { "of" => { "target" => 0 } } }
298
+
299
+ def to_s = "change the target of #{@of}"
300
+ def change? = true
301
+ end
302
+
265
303
  # "Copy that card" / "create a copy of this card" (CR 707.12): copies of cards, in the zone the card is in.
266
304
  class CopyCard < Effect
267
305
  include CopyOf
@@ -303,11 +341,13 @@ module Enjine
303
341
  class Cast < CastFree
304
342
  primitive :effect, :cast,
305
343
  description: "The controller may cast referenced cards (or card copies) now, while this resolves, " \
306
- "paying their costs; timing restrictions don't apply. `to`, `for`, `not_types`, " \
307
- "`max_mana_value`, `count`, `exile_instead` and `any_mana_type` work as for `cast_free`.",
344
+ "paying their costs; timing restrictions don't apply. `to`, `from`, `for`, `not_types`, " \
345
+ "`max_mana_value`, `count`, `exile_instead` and `any_mana_type` work as for `cast_free` " \
346
+ "(\"you may cast an artifact spell from your graveyard\": `from: \"graveyard\"`).",
308
347
  rules: %w[608.2g 707.12 707.12a 601.2a 601.2f],
309
- params: { "to" => "selector", "for" => "card spec", "not_types" => "list of card types",
310
- "max_mana_value" => "amount", "count" => "1 or \"any\"",
348
+ params: { "to" => "selector", "from" => "hand | graveyard", "for" => "card spec",
349
+ "not_types" => "list of card types",
350
+ "max_mana_value" => "amount", "count" => "integer >= 1 (default 1) or \"any\"",
311
351
  "exile_instead" => "true or a card spec (as for cast_free)",
312
352
  "any_mana_type" => "boolean: mana of any type can be spent to cast it (CR 609.4b)" },
313
353
  example: { "cast" => { "to" => { "result" => 0 } } }
@@ -36,7 +36,8 @@ module Enjine
36
36
  # "Remove two +1/+1 counters from target creature." (CR 122.8)
37
37
  class RemoveCounters < Effect
38
38
  primitive :effect, :remove_counters,
39
- description: "Remove up to `amount` counters named `counter` from each referenced permanent.",
39
+ description: "Remove up to `amount` counters named `counter` from each referenced permanent. How " \
40
+ "many were removed is {\"this_way\": n} (\"remove a bait counter ... If you do, ...\").",
40
41
  rules: %w[122.8],
41
42
  params: { "counter" => "counter name", "amount" => "amount", "to" => "selector" },
42
43
  example: { "remove_counters" => { "counter" => "+1/+1", "amount" => 2, "to" => { "target" => 0 } } }
@@ -51,7 +52,12 @@ module Enjine
51
52
 
52
53
  def apply(engine, ctx)
53
54
  n = amount_for(engine, ctx)
54
- objects(engine, ctx).each { engine.remove_counters!(engine.object(it), counter, n) }
55
+ objects(engine, ctx).each do
56
+ perm = engine.object(it)
57
+ before = perm.counters.fetch(counter, 0)
58
+ engine.remove_counters!(perm, counter, n)
59
+ engine.record_amount!(before - perm.counters.fetch(counter, 0)) # CR 608.2c: "if you do"
60
+ end
55
61
  end
56
62
 
57
63
  def to_s = "remove #{amount} #{counter} counter(s) → #{to}"
@@ -16,6 +16,11 @@ module Enjine
16
16
 
17
17
  # The excess damage it deals (beyond lethal damage to a creature, or a planeswalker's loyalty) is
18
18
  # what {"this_way": n} reads ("if excess damage was dealt this way", CR 120.4a, 120.10).
19
+ def damage_hits(engine, ctx)
20
+ n = amount_for(engine, ctx)
21
+ refs(engine, ctx).map { [ctx.source || ctx.object, it, n] }
22
+ end
23
+
19
24
  def apply(engine, ctx)
20
25
  n = amount_for(engine, ctx)
21
26
  source = ctx.source || ctx.object
@@ -43,6 +48,12 @@ module Enjine
43
48
 
44
49
  def to_s = "deal the divided damage to the targets"
45
50
 
51
+ def damage_hits(engine, ctx)
52
+ engine.object(ctx.object).memory.fetch("division", {}).filter_map do |ref, n|
53
+ [ctx.source || ctx.object, ref, n] if ctx.targets.flatten.include?(ref)
54
+ end
55
+ end
56
+
46
57
  def apply(engine, ctx)
47
58
  source = ctx.source || ctx.object
48
59
  excess = engine.object(ctx.object).memory.fetch("division", {}).sum do |ref, n|
@@ -48,7 +48,8 @@ module Enjine
48
48
  engine.record_result!(id)
49
49
  engine.add_counters!(engine.object(id), "+1/+1", n, by_player: ctx.controller)
50
50
  engine.create_delayed_trigger!("controller" => ctx.controller, "source" => ctx.source,
51
- "card" => engine.object(ctx.object).card, "ability" => ref, "watched" => [id])
51
+ "card" => engine.object(ctx.object).card, "ability" => ref, "watched" => [id],
52
+ "while_watched" => true) # gone with the land (any zone)
52
53
  engine.emit Events::KeywordAction.new(player: engine.name(ctx.controller), action: "earthbend", amount: n)
53
54
  end
54
55
  end
@@ -40,6 +40,13 @@ module Enjine
40
40
 
41
41
  def self.other_key = "with"
42
42
 
43
+ def damage_hits(engine, ctx)
44
+ pair = [refs(engine, ctx).first, other.resolve(engine, ctx).first]
45
+ return [] unless pair.all? { engine.state.battlefield.include?(it) && engine.chars(it).creature? }
46
+
47
+ [[pair[0], pair[1], engine.power(engine.object(pair[0]))], [pair[1], pair[0], engine.power(engine.object(pair[1]))]].uniq
48
+ end
49
+
43
50
  def apply(engine, ctx)
44
51
  one = refs(engine, ctx).first
45
52
  other_one = other.resolve(engine, ctx).first
@@ -63,6 +70,10 @@ module Enjine
63
70
 
64
71
  def self.other_key = "from"
65
72
 
73
+ def damage_hits(engine, ctx)
74
+ other_creatures(engine, ctx).product(refs(engine, ctx)).map { |source, ref| [source, ref, engine.power(engine.object(source))] }
75
+ end
76
+
66
77
  def apply(engine, ctx)
67
78
  sources = other_creatures(engine, ctx)
68
79
  powers = sources.to_h { [it, engine.power(engine.object(it))] } # determined before any is dealt
@@ -6,7 +6,8 @@ module Enjine
6
6
  # "Gain control of target permanent" / "... until end of turn" / "Target opponent gains control of
7
7
  # target permanent you control" (CR 613.1b, 108.4, 506.4, 302.6).
8
8
  class GainControl < Effect
9
- DURATIONS = %w[permanent end_of_turn while_source_on_battlefield while_source_tapped while_you_control_source].freeze
9
+ DURATIONS = %w[permanent end_of_turn end_of_your_next_turn while_source_on_battlefield while_source_tapped
10
+ while_you_control_source].freeze
10
11
 
11
12
  primitive :effect, :gain_control,
12
13
  description: "The player referenced by `gains` (default you) gains control of each referenced " \
@@ -40,11 +41,13 @@ module Enjine
40
41
  next engine.gain_control!(obj, player) if duration == "permanent"
41
42
 
42
43
  engine.gain_control_for!(obj, player, ctx, duration: duration,
43
- source: duration == "end_of_turn" ? nil : ctx.source)
44
+ source: %w[end_of_turn end_of_your_next_turn].include?(duration) ? nil : ctx.source)
44
45
  end
45
46
  end
46
47
 
47
- def to_s = "#{gains} gains control#{" until end of turn" if duration == "end_of_turn"} → #{to}"
48
+ UNTIL = { "end_of_turn" => " until end of turn", "end_of_your_next_turn" => " until the end of your next turn" }.freeze
49
+
50
+ def to_s = "#{gains} gains control#{UNTIL[duration]} → #{to}"
48
51
  end
49
52
 
50
53
  # "Exchange control of target artifact you control and target artifact an opponent controls" (CR 701.12a-b):
@@ -68,22 +68,27 @@ module Enjine
68
68
  "`optional`: you may take fewer. `reveal: \"chosen\"` reveals the cards taken. The rest go " \
69
69
  "to `rest`: \"bottom_random\" (default), \"bottom_any\" (in an order you choose) or \"graveyard\". " \
70
70
  "`put: \"exile\"` takes `face_down: true` (only you may look at them) and `link: true` " \
71
- "(exiled with the source, CR 607.2a: hideaway).",
72
- rules: %w[701.20a 701.20e 401.4 400.7j 406.3 607.2a],
71
+ "(exiled with the source, CR 607.2a); `looker: \"source_controller\"`: whoever controls " \
72
+ "the source may look at them instead of you (hideaway, CR 702.75a).",
73
+ rules: %w[701.20a 701.20e 401.4 400.7j 406.3 607.2a 702.75a],
73
74
  params: { "amount" => "amount (how many cards)", "for" => "card spec (default any card)",
74
75
  "count" => "integer, \"all\" or \"any\"", "optional" => "boolean", "put" => PUT.join(" | "),
75
76
  "tapped" => "boolean", "reveal" => REVEAL.join(" | "), "rest" => RestOfCards::REST.join(" | "),
76
- "face_down" => "boolean (put exile)", "link" => "boolean (put exile)" },
77
+ "face_down" => "boolean (put exile)", "link" => "boolean (put exile)",
78
+ "looker" => "\"source_controller\" (face_down)" },
77
79
  example: { "dig" => { "amount" => 6, "for" => { "types" => ["artifact"] }, "optional" => true,
78
80
  "reveal" => "chosen", "put" => "hand" } }
79
81
 
80
82
  attr_reader :spec, :count, :put
81
83
 
82
- def self.keys = %w[amount for count optional put tapped reveal rest face_down link if]
84
+ def self.keys = %w[amount for count optional put tapped reveal rest face_down link looker if]
83
85
  def self.default_to = "you"
84
86
 
85
87
  def setup(params, errors, path)
86
88
  @spec = CardSpec.build(Mechanics.fetch_param(params, :for), errors, "#{path}.for")
89
+ looker = Mechanics.fetch_param(params, :looker)
90
+ @source_looks = looker == "source_controller"
91
+ errors << "#{path}.looker: must be \"source_controller\"" unless looker.nil? || @source_looks
87
92
  @count = Mechanics.fetch_param(params, :count) || 1
88
93
  unless %w[all any].include?(@count) || (@count.is_a?(Integer) && @count.positive?)
89
94
  errors << "#{path}.count: must be a positive integer, \"all\" or \"any\""
@@ -97,6 +102,7 @@ module Enjine
97
102
  @rest = parse_rest(params, errors, path)
98
103
  @face_down, @link = %i[face_down link].map { Mechanics.flag_param(params, it, errors, path) }
99
104
  errors << "#{path}: face_down and link need put: \"exile\"" if (@face_down || @link) && @put != "exile"
105
+ errors << "#{path}.looker: needs face_down: true" if @source_looks && !@face_down
100
106
  end
101
107
 
102
108
  def to_s
@@ -148,11 +154,12 @@ module Enjine
148
154
  put_cards!(engine, locals, taken, ctx.controller, reason: "put", enters: @tapped ? { "tapped" => true } : nil)
149
155
  end
150
156
 
151
- # CR 406.3, 607.2a: face down (only you may look), linked to the source.
157
+ # CR 406.3, 607.2a: face down (only you may look, or the source's controller: CR 702.75a), linked to the source.
152
158
  def exile!(engine, ctx, index, taken)
153
159
  taken.each do |id|
154
- fresh = engine.move!(id, :exile, reason: "exile", face_down: @face_down ? [index] : nil)
155
- engine.link_exiled!(ctx.source, fresh.id) if fresh && @link
160
+ fresh = engine.move!(id, :exile, reason: "exile", face_down: @face_down ? [index] : nil) or next
161
+ fresh.memory["looker_source"] = ctx.source if @source_looks
162
+ engine.link_exiled!(ctx.source, fresh.id) if @link
156
163
  end
157
164
  end
158
165
  end
@@ -227,22 +234,31 @@ module Enjine
227
234
 
228
235
  # Exile the top N cards of a library (CR 406.1). What was exiled is the effect's result ({"result": n}),
229
236
  # for later effects of the list (returning the permanent cards among them, permissions to play them);
230
- # `link: true` exiles them with the source (CR 607.2a).
237
+ # `link: true` exiles them with the source (CR 607.2a). `until` exiles one card at a time instead, until
238
+ # the cards exiled this way have a total mana value of N or more, or until a card matching a spec is exiled.
231
239
  class ExileTop < Effect
240
+ UNTIL = %w[total_mana_value card].freeze
241
+
232
242
  primitive :effect, :exile_top,
233
243
  description: "Each referenced player (default: you) exiles the top `amount` cards of their library " \
234
244
  "(face up). Later effects name them with {\"result\": n}; `link: true` exiles them with " \
235
245
  "the source. `face_down: true` exiles them face down: only the `looker` players " \
236
- "(default: you) may look at them.",
237
- rules: %w[406.1 400.7j 607.2a 406.3 406.3a],
246
+ "(default: you) may look at them. `until` instead of `amount`: exile cards from the top " \
247
+ "one at a time until {\"total_mana_value\": N}: those cards have a total mana value of N " \
248
+ "or more, or {\"card\": card spec}: a matching card is exiled (or the library is empty).",
249
+ rules: %w[406.1 400.7j 607.2a 406.3 406.3a 202.3 608.2c],
238
250
  params: { "amount" => "amount", "to" => "selector of players", "link" => "boolean",
239
- "face_down" => "boolean", "looker" => "selector of players who may look (default \"you\")" },
251
+ "face_down" => "boolean", "looker" => "selector of players who may look (default \"you\")",
252
+ "until" => "{\"total_mana_value\": amount} | {\"card\": card spec}" },
240
253
  example: { "exile_top" => { "amount" => 4 } }
241
254
 
242
- def self.keys = %w[amount to link face_down looker if]
255
+ def self.keys = %w[amount to link face_down looker until if]
243
256
  def self.default_to = "you"
257
+ def self.amount_optional?(params) = !Mechanics.fetch_param(params, :until).nil?
244
258
 
245
259
  def setup(params, errors, path)
260
+ @until = build_until(Mechanics.fetch_param(params, :until), errors, "#{path}.until")
261
+ errors << "#{path}: amount or until, not both" if @until && Mechanics.fetch_param(params, :amount)
246
262
  @link = Mechanics.flag_param(params, "link", errors, path)
247
263
  @face_down = Mechanics.flag_param(params, :face_down, errors, path)
248
264
  raw = Mechanics.fetch_param(params, :looker)
@@ -251,18 +267,60 @@ module Enjine
251
267
  results_count: @results_count)
252
268
  end
253
269
 
254
- def to_s = @face_down ? super.sub(" → ", " face down → ") : super
270
+ def to_s
271
+ text = @until ? "exile top cards until #{@until.keys.first.tr("_", " ")} #{@until.values.first} → #{to}" : super
272
+ @face_down ? text.sub(" → ", " face down → ") : text
273
+ end
255
274
 
256
275
  def apply(engine, ctx)
257
- n = amount_for(engine, ctx)
258
276
  lookers = @face_down ? @looker.resolve(engine, ctx).filter_map { Filters.player_index(engine, it) } : nil
259
277
  players(engine, ctx).each do |index|
260
- engine.player(index).library.first(n).each do |id|
261
- fresh = engine.move!(id, :exile, reason: "exile", face_down: lookers)
262
- engine.link_exiled!(ctx.source, fresh.id) if fresh && @link
263
- end
278
+ library = engine.player(index).library
279
+ next library.first(amount_for(engine, ctx)).each { exile!(engine, ctx, it, lookers) } unless @until
280
+
281
+ exile_until!(engine, ctx, library, lookers)
264
282
  end
265
283
  end
284
+
285
+ def exile_until!(engine, ctx, library, lookers)
286
+ exiled = []
287
+ while (id = library.first) && !enough?(engine, ctx, exiled)
288
+ fresh = exile!(engine, ctx, id, lookers)
289
+ break if fresh.nil? && library.first == id # a replacement left it where it was
290
+
291
+ exiled << fresh if fresh&.zone == :exile
292
+ end
293
+ end
294
+
295
+ private
296
+
297
+ def build_until(raw, errors, path)
298
+ return nil if raw.nil?
299
+ return (errors << "#{path}: must be one of {#{UNTIL.join("|")}: ...}") && nil unless raw.is_a?(Hash) && raw.size == 1 &&
300
+ UNTIL.include?(raw.keys.first.to_s)
301
+
302
+ kind, value = raw.first
303
+ kind = kind.to_s
304
+ { kind => if kind == "card" then CardSpec.build(value, errors, "#{path}.card")
305
+ else Amount.build(value, errors, "#{path}.#{kind}", targets_count: @targets_count, results_count: @results_count)
306
+ end }
307
+ end
308
+
309
+ def exile!(engine, ctx, id, lookers)
310
+ fresh = engine.move!(id, :exile, reason: "exile", face_down: lookers)
311
+ engine.link_exiled!(ctx.source, fresh.id) if fresh && @link
312
+ fresh
313
+ end
314
+
315
+ # CR 202.3: the cards exiled so far have a total mana value of N or more; or the last one matches the spec.
316
+ def enough?(engine, ctx, exiled)
317
+ return false if exiled.empty?
318
+
319
+ spec = @until["card"]
320
+ return spec.match?(engine, exiled.last, ctx) if spec
321
+
322
+ exiled.sum { Amount.mana_value(engine, it) } >= @until["total_mana_value"].value(engine, ctx)
323
+ end
266
324
  end
267
325
 
268
326
  # Explore (CR 701.44a): reveal the top card of your library; a land card goes to your hand,
@@ -31,6 +31,9 @@ module Enjine
31
31
  end
32
32
  end
33
33
 
34
+ # The costs with amounts computed as this resolves ("pay life equal to its power", Costs::PayLife#fixed).
35
+ def costs_now(engine, ctx) = costs.map { it.respond_to?(:fixed) ? it.fixed(engine, ctx) : it }
36
+
34
37
  # Each way of paying `costs` open to the payer now: its other parts payable for `payer_obj` (an object
35
38
  # the payer controls, CR 118.3) and its mana affordable.
36
39
  def open_variants(engine, payer_obj, costs)
@@ -174,12 +177,12 @@ module Enjine
174
177
  def decide(engine, ctx, locals)
175
178
  payer = engine.object(ctx.object)
176
179
  unless locals["paying"] || answers(locals).first
177
- choices = pay_choices(engine, payer, costs) + [{ "type" => "decline" }]
180
+ choices = pay_choices(engine, payer, costs_now(engine, ctx)) + [{ "type" => "decline" }]
178
181
  return ask(engine, locals, payer.controller, "Pay #{what}?", choices)
179
182
  end
180
183
  return locals["outcome"] = "unpaid" if answers(locals).first["type"] == "decline"
181
184
 
182
- result = pay_costs(engine, ctx, locals, payer, costs)
185
+ result = pay_costs(engine, ctx, locals, payer, costs_now(engine, ctx))
183
186
  result == :wait ? :wait : (locals["outcome"] = result)
184
187
  end
185
188
  end
@@ -214,10 +217,10 @@ module Enjine
214
217
 
215
218
  payer = engine.object(target)
216
219
  unless locals["paying"] || answers(locals).first
217
- choices = pay_choices(engine, payer, costs) + [{ "type" => "decline" }]
220
+ choices = pay_choices(engine, payer, costs_now(engine, ctx)) + [{ "type" => "decline" }]
218
221
  return ask(engine, locals, payer.controller, "Pay #{what} or #{payer.card} is countered?", choices)
219
222
  end
220
- paid = answers(locals).first["type"] == "pay" && pay_costs(engine, ctx, locals, payer, costs)
223
+ paid = answers(locals).first["type"] == "pay" && pay_costs(engine, ctx, locals, payer, costs_now(engine, ctx))
221
224
  return :wait if paid == :wait
222
225
 
223
226
  engine.counter!(target) unless paid == "paid"
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Mechanics
5
+ module Effects
6
+ # "[Effects]. If [condition], repeat this process." (CR 608.2c): the effects run in order, then, while
7
+ # `while` holds, they run again. Each pass is a fresh process with results of its own: {"result": n} inside
8
+ # the list (and in `while`) names what effect n of the list did during this pass. What every pass moved or
9
+ # created is also the result of the `repeat` effect itself.
10
+ class Repeat < ChoiceEffect
11
+ # A mandatory loop that never ends would be a draw (CR 104.4b); the engine stops after this many passes.
12
+ MAX_PASSES = 100
13
+
14
+ primitive :effect, :repeat,
15
+ description: "Run `effects`, then run them again for as long as `while` (a condition) holds after a " \
16
+ "pass (\"if the exiled card is a land card, repeat this process\"). {\"result\": n} in " \
17
+ "the list and in `while` names what effect n did during the current pass. At most " \
18
+ "#{MAX_PASSES} passes.",
19
+ rules: %w[608.2c 400.7j 104.4b],
20
+ params: { "effects" => "list of effects (one pass)", "while" => "condition, checked after each pass" },
21
+ example: { "repeat" => { "effects" => [{ "mill" => { "amount" => 1 } }],
22
+ "while" => { "amount" => { "count" => { "result" => 0, "for" => { "types" => ["land"] } } },
23
+ "at_least" => 1 } } }
24
+
25
+ attr_reader :effects
26
+
27
+ def self.keys = %w[effects while if]
28
+ def self.default_to = "you"
29
+
30
+ def setup(params, errors, path)
31
+ @effects = Abilities::StackAbility.parse_effects(params, errors, path, @targets_count) # results of its own
32
+ errors << "#{path}.effects: needs at least one effect" if @effects.empty?
33
+ raw = Mechanics.fetch_param(params, :while)
34
+ errors << "#{path}.while: required" if raw.nil?
35
+ @while = raw && Condition.build(raw, errors, "#{path}.while", targets_count: @targets_count,
36
+ results_count: @effects.size)
37
+ end
38
+
39
+ def nested_effects = @effects
40
+ def to_s = "#{@effects.join("; ")} — repeat while #{@while}"
41
+
42
+ # Progress in `locals`: "pass" (1, 2, ...), "next" (the effect of this pass to run), "results" / "amounts"
43
+ # (what this pass's effects did so far) and the running effect's own locals under "child".
44
+ def run(engine, ctx, locals)
45
+ return :done unless locals["pass"] || condition.nil? || condition.true?(engine, ctx)
46
+
47
+ locals["pass"] ||= 1
48
+ loop do
49
+ return :wait if run_pass(engine, ctx, locals) == :wait
50
+ return :done if locals["pass"] >= MAX_PASSES || !@while&.true?(engine, pass_context(ctx, locals))
51
+
52
+ locals["pass"] += 1
53
+ %w[next results amounts cards].each { locals.delete(it) }
54
+ end
55
+ end
56
+
57
+ private
58
+
59
+ def run_pass(engine, ctx, locals)
60
+ locals["next"] ||= 0
61
+ while (i = locals["next"]) < @effects.size
62
+ status, ids, amount = engine.recording_apart { @effects[i].run(engine, pass_context(ctx, locals), locals["child"] ||= {}) }
63
+ (locals["results"] ||= [])[i] = Array(locals["results"][i]) + ids
64
+ remember_cards!(engine, ids, locals)
65
+ (locals["amounts"] ||= [])[i] = locals["amounts"][i].to_i + amount
66
+ return :wait if status == :wait
67
+
68
+ locals.delete("child")
69
+ locals["next"] += 1
70
+ end
71
+ :done
72
+ end
73
+
74
+ # The card each new result is, so `while` can still ask "was it a land card?" after a later effect of the pass
75
+ # moved it (Selector "for"). A face-down card is remembered as nothing (its card isn't known, CR 708.2).
76
+ def remember_cards!(engine, ids, locals)
77
+ ids.each do |id|
78
+ obj = engine.state.objects[id]
79
+ (locals["cards"] ||= {})[id] = obj.card if obj && obj.kind == "card" && !obj.memory["face_down"]
80
+ end
81
+ end
82
+
83
+ # This pass's results, one list per effect of the list (CR 400.7j).
84
+ def pass_context(ctx, locals)
85
+ results = Array.new(@effects.size) { Array(locals.dig("results", it)) }
86
+ amounts = Array.new(@effects.size) { locals.dig("amounts", it).to_i }
87
+ EffectContext.new(ctx.controller, ctx.source, ctx.object, ctx.targets, results, amounts, ctx.memory, locals["cards"])
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end