enjine 0.5.0 → 0.6.1

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 (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +156 -1
  3. data/README.md +12 -3
  4. data/SUPPORTED.md +44 -17
  5. data/docs/ARCHITECTURE.md +7 -2
  6. data/docs/MECHANICS_COVERAGE.md +10 -8
  7. data/docs/guides/api.md +2 -1
  8. data/docs/guides/card-data-format.md +40 -8
  9. data/docs/reference/abilities.md +254 -13
  10. data/docs/reference/costs.md +36 -0
  11. data/docs/reference/decisions.md +3 -1
  12. data/docs/reference/effects.md +93 -10
  13. data/docs/reference/filters.md +11 -1
  14. data/docs/reference/keywords.md +42 -0
  15. data/docs/reference/subtypes.md +18 -0
  16. data/docs/reference/triggers.md +69 -8
  17. data/docs/reference/types.md +20 -0
  18. data/lib/enjine/actions/special_action.rb +4 -0
  19. data/lib/enjine/actions/turn_face_up.rb +25 -0
  20. data/lib/enjine/actions/unlock.rb +23 -0
  21. data/lib/enjine/card_definition.rb +50 -12
  22. data/lib/enjine/card_face_down.rb +31 -0
  23. data/lib/enjine/card_faces.rb +4 -2
  24. data/lib/enjine/card_rooms.rb +86 -0
  25. data/lib/enjine/catalog.rb +9 -3
  26. data/lib/enjine/cli/text.rb +1 -0
  27. data/lib/enjine/color_identity.rb +34 -1
  28. data/lib/enjine/decisions/casting.rb +6 -3
  29. data/lib/enjine/engine/ability_layers.rb +8 -0
  30. data/lib/enjine/engine/casting/alt_casting.rb +12 -4
  31. data/lib/enjine/engine/casting/cast_choices.rb +8 -1
  32. data/lib/enjine/engine/casting/casting.rb +18 -22
  33. data/lib/enjine/engine/casting/costs.rb +8 -1
  34. data/lib/enjine/engine/casting/payment.rb +47 -9
  35. data/lib/enjine/engine/casting/permissions.rb +6 -3
  36. data/lib/enjine/engine/characteristics.rb +8 -9
  37. data/lib/enjine/engine/combat.rb +19 -7
  38. data/lib/enjine/engine/copies.rb +2 -1
  39. data/lib/enjine/engine/crimes.rb +46 -0
  40. data/lib/enjine/engine/damage.rb +36 -1
  41. data/lib/enjine/engine/face_down_permanents.rb +108 -0
  42. data/lib/enjine/engine/faces.rb +6 -3
  43. data/lib/enjine/engine/mana_sources.rb +18 -3
  44. data/lib/enjine/engine/options_memo.rb +140 -0
  45. data/lib/enjine/engine/permanent_designations.rb +29 -0
  46. data/lib/enjine/engine/resolution.rb +25 -5
  47. data/lib/enjine/engine/rooms.rb +86 -0
  48. data/lib/enjine/engine/rules.rb +2 -1
  49. data/lib/enjine/engine/state_based_actions.rb +25 -4
  50. data/lib/enjine/engine/triggers.rb +20 -5
  51. data/lib/enjine/engine/turn_history.rb +28 -5
  52. data/lib/enjine/engine/zones.rb +32 -6
  53. data/lib/enjine/engine.rb +9 -1
  54. data/lib/enjine/events.rb +9 -0
  55. data/lib/enjine/frames.rb +3 -0
  56. data/lib/enjine/fuzz.rb +3 -0
  57. data/lib/enjine/game.rb +3 -1
  58. data/lib/enjine/mechanics/abilities/cost_changes.rb +32 -10
  59. data/lib/enjine/mechanics/abilities/damage_replacements.rb +1 -1
  60. data/lib/enjine/mechanics/abilities/designated.rb +57 -0
  61. data/lib/enjine/mechanics/abilities/life_replacements.rb +74 -0
  62. data/lib/enjine/mechanics/abilities/mana_ability.rb +10 -4
  63. data/lib/enjine/mechanics/abilities/player_rules.rb +1 -1
  64. data/lib/enjine/mechanics/abilities/stack_abilities.rb +12 -7
  65. data/lib/enjine/mechanics/abilities/static.rb +18 -5
  66. data/lib/enjine/mechanics/card_spec.rb +12 -3
  67. data/lib/enjine/mechanics/costs/base.rb +3 -2
  68. data/lib/enjine/mechanics/costs/behold.rb +10 -3
  69. data/lib/enjine/mechanics/costs/choose_creature_type.rb +3 -3
  70. data/lib/enjine/mechanics/costs/collect_evidence.rb +60 -0
  71. data/lib/enjine/mechanics/costs/exile_permanent.rb +41 -0
  72. data/lib/enjine/mechanics/effects/base.rb +26 -5
  73. data/lib/enjine/mechanics/effects/choose_cards.rb +44 -14
  74. data/lib/enjine/mechanics/effects/copy.rb +2 -2
  75. data/lib/enjine/mechanics/effects/counters.rb +12 -6
  76. data/lib/enjine/mechanics/effects/delayed_triggers.rb +13 -6
  77. data/lib/enjine/mechanics/effects/may.rb +4 -2
  78. data/lib/enjine/mechanics/effects/pay.rb +20 -6
  79. data/lib/enjine/mechanics/filters/any_target.rb +6 -3
  80. data/lib/enjine/mechanics/filters/base.rb +14 -5
  81. data/lib/enjine/mechanics/filters/permanents.rb +7 -0
  82. data/lib/enjine/mechanics/keywords/alternative_costs.rb +70 -16
  83. data/lib/enjine/mechanics/keywords/cards_have.rb +4 -2
  84. data/lib/enjine/mechanics/keywords/craft.rb +132 -0
  85. data/lib/enjine/mechanics/keywords/cycling.rb +46 -7
  86. data/lib/enjine/mechanics/keywords/extort.rb +2 -0
  87. data/lib/enjine/mechanics/keywords/face_down.rb +165 -0
  88. data/lib/enjine/mechanics/keywords/impending.rb +75 -0
  89. data/lib/enjine/mechanics/keywords/increment.rb +2 -0
  90. data/lib/enjine/mechanics/keywords/infinity.rb +46 -0
  91. data/lib/enjine/mechanics/keywords/miracle.rb +142 -0
  92. data/lib/enjine/mechanics/keywords/ninjutsu.rb +101 -0
  93. data/lib/enjine/mechanics/keywords/offspring.rb +48 -0
  94. data/lib/enjine/mechanics/keywords/persist_and_undying.rb +42 -0
  95. data/lib/enjine/mechanics/keywords/split_second.rb +29 -0
  96. data/lib/enjine/mechanics/keywords/storm_and_cascade.rb +5 -0
  97. data/lib/enjine/mechanics/keywords/void.rb +34 -0
  98. data/lib/enjine/mechanics/linked.rb +2 -2
  99. data/lib/enjine/mechanics/mana_spent.rb +1 -1
  100. data/lib/enjine/mechanics/selector.rb +30 -9
  101. data/lib/enjine/mechanics/subtypes/case.rb +68 -0
  102. data/lib/enjine/mechanics/triggers/base.rb +13 -4
  103. data/lib/enjine/mechanics/triggers/crime.rb +28 -0
  104. data/lib/enjine/mechanics/triggers/damage.rb +33 -18
  105. data/lib/enjine/mechanics/triggers/draw_and_discard.rb +19 -6
  106. data/lib/enjine/mechanics/triggers/rooms.rb +49 -0
  107. data/lib/enjine/mechanics/triggers/zone_changes.rb +24 -9
  108. data/lib/enjine/mechanics/types/battle.rb +130 -0
  109. data/lib/enjine/mechanics/values.rb +74 -27
  110. data/lib/enjine/replacements.rb +18 -0
  111. data/lib/enjine/rules_monitor.rb +49 -75
  112. data/lib/enjine/snapshot/deep_copy.rb +23 -0
  113. data/lib/enjine/snapshot/player_checks.rb +10 -2
  114. data/lib/enjine/snapshot.rb +2 -1
  115. data/lib/enjine/state.rb +2 -2
  116. data/lib/enjine/verify.rb +10 -3
  117. data/lib/enjine/version.rb +1 -1
  118. data/lib/enjine/view.rb +49 -13
  119. data/lib/enjine.rb +1 -1
  120. metadata +29 -1
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Mechanics
5
+ module Costs
6
+ # "Exile a creature you control" / "Exile another artifact you control" as a cost (CR 406.1, 601.2h, 602.2b).
7
+ # The permanent is chosen while casting or activating and exiled as the spell or ability becomes cast. It's not
8
+ # a sacrifice (nothing watching sacrifices sees it). What it was is kept like a sacrificed permanent's (types,
9
+ # subtypes, power, toughness, mana value: amount `sacrificed`), and the card in exile is remembered by the
10
+ # spell or ability (selector "exiled_for_cost").
11
+ class ExilePermanent < Choosing
12
+ primitive :cost, :exile_permanent,
13
+ description: "Exile `count` permanents you control matching `filter` (`other: true`: not the source). " \
14
+ "Chosen while casting or activating, exiled as it becomes cast; the exiled cards are " \
15
+ "`exiled_for_cost`, and their last known power, toughness and mana value are amount " \
16
+ "`sacrificed`.",
17
+ rules: %w[406.1 601.2h 602.2b 118.3 608.2h],
18
+ params: { "filter" => "filter (default permanent)", "count" => "integer (default 1)",
19
+ "other" => "true: not the source itself" },
20
+ example: { "exile_permanent" => { "filter" => "creature" } }
21
+
22
+ def pay_chosen!(engine, _object, entries)
23
+ entries.each do |entry|
24
+ perm = engine.state.objects[entry["object"]]
25
+ next unless perm&.zone == :battlefield
26
+
27
+ facts = engine.chars(perm)
28
+ entry.merge!("types" => facts.types.map(&:to_s), "subtypes" => facts.subtypes.map(&:to_s),
29
+ "power" => engine.power(perm), "toughness" => engine.toughness(perm),
30
+ "mana_value" => Amount.mana_value(engine, perm))
31
+ fresh = engine.move!(perm.id, :exile, reason: "cost") or next
32
+ holder = engine.casting && engine.state.objects[engine.casting["object"]]
33
+ (holder.memory[CardsCost::EXILED] ||= []) << fresh.id if holder && fresh.zone == :exile
34
+ end
35
+ end
36
+
37
+ def to_s = "Exile #{amount_words} #{what} you control"
38
+ end
39
+ end
40
+ end
41
+ end
@@ -133,10 +133,19 @@ module Enjine
133
133
 
134
134
  # Runs a nested effect list one effect at a time (`may`, `pay`, `choose_cards`); a waiting effect keeps its locals
135
135
  # under "child", where Engine#effect_answer! delivers answers.
136
+ # The nested list numbers its results after the enclosing list's earlier effects (StackAbility.parse_effects):
137
+ # {"result": n} below this effect's `results_count` is one of those, above it one of the nested list's own
138
+ # (CR 608.2c: "if you do, ... the creature sacrificed this way"). What the nested effects move, create or change
139
+ # also counts for this effect in the enclosing list.
136
140
  module NestedList
137
141
  def run_list(engine, ctx, locals, list)
138
- while locals["next"] < list.size
139
- return :wait if list[locals["next"]].run(engine, ctx, locals["child"] ||= {}) == :wait
142
+ while (i = locals["next"]) < list.size
143
+ status, ids, amount = engine.recording_apart do
144
+ list[i].run(engine, nested_context(ctx, locals), locals["child"] ||= {})
145
+ end
146
+ (locals["own_results"] ||= [])[i] = Array(locals["own_results"][i]) + ids
147
+ (locals["own_amounts"] ||= [])[i] = locals["own_amounts"][i].to_i + amount
148
+ return :wait if status == :wait
140
149
 
141
150
  locals.delete("child")
142
151
  locals["next"] += 1
@@ -144,12 +153,24 @@ module Enjine
144
153
  :done
145
154
  end
146
155
 
147
- def parse_lists(params, errors, path, keys)
156
+ # `chain`: lists that run one after the other in one numbering (a "may"'s `effects`, then its `then`).
157
+ def parse_lists(params, errors, path, keys, chain: [])
158
+ offset = 0
148
159
  keys.to_h do |key|
149
- [key, Abilities::StackAbility.parse_effects(params, errors, path, @targets_count, key: key.to_sym,
150
- results_count: @results_count)]
160
+ list = Abilities::StackAbility.parse_effects(params, errors, path, @targets_count, key: key.to_sym,
161
+ results_count: @results_count,
162
+ offset: chain.include?(key) ? offset : 0)
163
+ offset += list.size if chain.include?(key)
164
+ [key, list]
151
165
  end.freeze
152
166
  end
167
+
168
+ # The enclosing list's results before this effect, then the nested list's own so far.
169
+ def nested_context(ctx, locals)
170
+ results = Array.new(@results_count) { Array(ctx.results&.[](it)) } + Array(locals["own_results"]).map { Array(it) }
171
+ amounts = Array.new(@results_count) { ctx.amounts&.[](it).to_i } + Array(locals["own_amounts"]).map(&:to_i)
172
+ EffectContext.new(ctx.controller, ctx.source, ctx.object, ctx.targets, results, amounts, ctx.memory, ctx.result_cards)
173
+ end
153
174
  end
154
175
  end
155
176
  end
@@ -16,43 +16,53 @@ module Enjine
16
16
  LISTS = %w[then otherwise].freeze
17
17
 
18
18
  primitive :effect, :choose_cards,
19
- description: "You choose `count` (default 1; \"any\": any number) cards matching `for` from `from`: a " \
19
+ description: "You choose `count` (default 1; \"any\": any number; \"all\": every matching card, no " \
20
+ "choice) cards matching `for` from `from`: a " \
20
21
  "selector (e.g. {\"result\": 0}, the cards an earlier effect milled) or a player's zone, " \
21
22
  "{\"hand\": selector} / {\"graveyard\": selector}. `optional`: you may choose fewer. Then " \
22
23
  "they are put into `put` (`discard`: from a hand, its owner discards them; `tapped` onto the " \
23
24
  "battlefield, under your control; exiled cards `link`ed to the source). `look`: you look at the " \
24
25
  "whole zone first; `reveal`: \"chosen\" reveals what you chose, \"all\" the whole set. " \
25
26
  "`then` runs if a card was chosen, `otherwise` if none was (\"if you can't\"). `random: true`: the " \
26
- "cards are picked at random (the game's random number generator) instead of chosen.",
27
- rules: %w[701.20a 701.20e 400.7j 608.2c 607.2a 118.12 701.9a 701.9b],
27
+ "cards are picked at random (the game's random number generator) instead of chosen. " \
28
+ "`chooser`: the player who chooses (a player selector, default \"you\"; e.g. " \
29
+ "\"each_opponent\" or {\"target\": 0}: \"target opponent chooses a card from among " \
30
+ "them\"); they look at the cards they choose from, and the cards still go where `put` " \
31
+ "says under your control.",
32
+ rules: %w[701.20a 701.20e 400.7j 608.2c 607.2a 118.12 701.9a 701.9b 608.2d],
28
33
  params: { "from" => "selector or {\"hand\"|\"graveyard\": player selector}", "for" => "card spec",
29
- "count" => "integer or \"any\"", "optional" => "boolean", "put" => PUT.join(" | "),
34
+ "count" => "integer, \"any\" or \"all\"", "optional" => "boolean", "put" => PUT.join(" | "),
30
35
  "tapped" => "boolean", "link" => "boolean", "look" => "boolean", "random" => "boolean",
31
- "reveal" => REVEAL.join(" | "), "then" => "list of effects", "otherwise" => "list of effects" },
36
+ "reveal" => REVEAL.join(" | "), "then" => "list of effects", "otherwise" => "list of effects",
37
+ "chooser" => "player selector (default \"you\")" },
32
38
  example: { "choose_cards" => { "from" => { "result" => 0 }, "for" => { "permanent" => true },
33
39
  "optional" => true, "put" => "hand" } }
34
40
 
35
41
  attr_reader :spec, :count, :put
36
42
 
37
- def self.keys = %w[from for count optional put tapped link look random reveal then otherwise if]
43
+ def self.keys = %w[from for count optional put tapped link look random reveal then otherwise chooser if]
38
44
  def self.default_to = "you"
39
45
 
40
46
  def setup(params, errors, path)
41
47
  @from_zone, @from = parse_from(Mechanics.fetch_param(params, :from), errors, path)
42
48
  @spec = CardSpec.build(Mechanics.fetch_param(params, :for), errors, "#{path}.for")
43
49
  @count = Mechanics.fetch_param(params, :count) || 1
44
- unless @count == "any" || (@count.is_a?(Integer) && @count.positive?)
45
- errors << "#{path}.count: must be a positive integer or \"any\""
50
+ unless %w[any all].include?(@count) || (@count.is_a?(Integer) && @count.positive?)
51
+ errors << "#{path}.count: must be a positive integer, \"any\" or \"all\""
46
52
  end
47
53
  @optional = Mechanics.flag_param(params, "optional", errors, path)
48
54
  @put = Mechanics.fetch_param(params, :put).to_s
49
55
  errors << "#{path}.put: must be one of #{PUT.join(", ")}" unless PUT.include?(@put)
50
56
  errors << "#{path}.put: discard takes cards from a hand" if @put == "discard" && @from_zone != "hand"
51
57
  @flags = %w[tapped link look random].to_h { [it, Mechanics.flag_param(params, it, errors, path)] }
52
- errors << "#{path}.count: must be a number to pick at random" if @flags["random"] && @count == "any"
58
+ errors << "#{path}.count: must be a number to pick at random" if @flags["random"] && !@count.is_a?(Integer)
53
59
  @reveal = Mechanics.fetch_param(params, :reveal)
54
60
  errors << "#{path}.reveal: must be one of #{REVEAL.join(", ")}" unless @reveal.nil? || REVEAL.include?(@reveal)
55
61
  @lists = parse_lists(params, errors, path, LISTS)
62
+ raw = Mechanics.fetch_param(params, :chooser)
63
+ errors << "#{path}.chooser: random cards have no chooser" if raw && @flags["random"]
64
+ @chooser = raw && Selector.build(raw, errors, "#{path}.chooser", targets_count: @targets_count,
65
+ results_count: @results_count)
56
66
  end
57
67
 
58
68
  def parse_from(raw, errors, path)
@@ -67,13 +77,13 @@ module Enjine
67
77
  def nested_effects = @lists.values.flatten
68
78
 
69
79
  def to_s
70
- many = count == "any" ? "any number of" : "#{"up to " if @optional}#{count}"
80
+ many = { "any" => "any number of", "all" => "all" }.fetch(count) { "#{"up to " if @optional}#{count}" }
71
81
  "choose #{many} #{spec}#{" at random" if @flags["random"]} from #{"the #{@from_zone} of " if @from_zone}#{@from} " \
72
- "→ #{put.tr("_", " ")}"
82
+ "→ #{put.tr("_", " ")}#{" (#{@chooser} chooses)" if @chooser}"
73
83
  end
74
84
 
75
85
  # CR 118.3: as the optional part of a "may", the full number of cards must be available.
76
- def possible?(engine, ctx) = pool(engine, ctx).size >= (count == "any" ? 1 : count)
86
+ def possible?(engine, ctx) = pool(engine, ctx).size >= (count.is_a?(Integer) ? count : 1)
77
87
 
78
88
  def run(engine, ctx, locals)
79
89
  return :done unless locals["asked"] || locals.key?("chose") || condition.nil? || condition.true?(engine, ctx)
@@ -81,8 +91,8 @@ module Enjine
81
91
  unless locals.key?("chose")
82
92
  show!(engine, ctx, locals)
83
93
  chosen = picked(engine, ctx, locals)
84
- choices = @flags["random"] || stop?(locals, chosen) ? [] : choices(engine, ctx, chosen)
85
- return ask(engine, locals, ctx.controller, "Choose #{spec}", choices) unless choices.empty?
94
+ choices = @flags["random"] || count == "all" || stop?(locals, chosen) ? [] : choices(engine, ctx, chosen)
95
+ return ask(engine, locals, chooser(engine, ctx, locals), "Choose #{spec}", choices) unless choices.empty?
86
96
 
87
97
  return :wait if put == "battlefield" && engine.ask_entering_choices!(locals, chosen.map { [it, ctx.controller] }) == :wait
88
98
 
@@ -94,8 +104,18 @@ module Enjine
94
104
 
95
105
  private
96
106
 
107
+ # Who chooses (CR 608.2d): `chooser`'s first player, resolved once; the controller without one (or when it
108
+ # names no player any more).
109
+ def chooser(engine, ctx, locals)
110
+ return ctx.controller unless @chooser
111
+
112
+ locals["chooser"] ||= @chooser.resolve(engine, ctx).filter_map { Filters.player_index(engine, it) }.first ||
113
+ ctx.controller
114
+ end
115
+
97
116
  # The cards chosen so far, or picked at random once (as in CR 701.9b, through the game's RNG).
98
117
  def picked(engine, ctx, locals)
118
+ return locals["picked"] ||= pool(engine, ctx) if count == "all" # "all cards with that name": no choice
99
119
  return answers(locals).select { it["type"] == "choose" }.map { it["object"] } unless @flags["random"]
100
120
 
101
121
  locals["picked"] ||= engine.state.rng.shuffle!(pool(engine, ctx)).first(count)
@@ -125,6 +145,16 @@ module Enjine
125
145
  elsif @flags["look"]
126
146
  ids.group_by { engine.object(it).owner }.each { |owner, list| engine.look_at!(ctx.controller, owner, list) }
127
147
  end
148
+ look_for_chooser!(engine, ctx, locals)
149
+ end
150
+
151
+ # Another player choosing among cards they can't see (a hand, a library) looks at them first (CR 701.20e).
152
+ def look_for_chooser!(engine, ctx, locals)
153
+ index = chooser(engine, ctx, locals)
154
+ return if index == ctx.controller || @reveal == "all"
155
+
156
+ hidden = pool(engine, ctx).select { %i[hand library].include?(engine.object(it).zone) || engine.face_down?(engine.object(it)) }
157
+ hidden.group_by { engine.object(it).owner }.each { |owner, list| engine.look_at!(index, owner, list) unless owner == index }
128
158
  end
129
159
 
130
160
  def stop?(locals, chosen)
@@ -400,8 +400,8 @@ module Enjine
400
400
  def to_s = "gains \"#{@granted_ability}\"#{" until end of turn" if @duration == "end_of_turn"} → #{to}"
401
401
 
402
402
  def apply(engine, ctx)
403
- card = engine.state.objects[ctx.object]&.card or return
404
- affected = refs(engine, ctx).select { (obj = engine.state.objects[it]) && @for.match?(engine, obj) }
403
+ card = engine.find_object(ctx.object)&.card or return
404
+ affected = refs(engine, ctx).select { (obj = engine.state.objects[it]) && @for.match?(engine, obj, ctx) }
405
405
  engine.grant_card_ability!(ctx, affected, card, @ref, @duration) unless affected.empty?
406
406
  end
407
407
  end
@@ -36,9 +36,10 @@ 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. How " \
40
- "many were removed is {\"this_way\": n} (\"remove a bait counter ... If you do, ...\").",
41
- rules: %w[122.8],
39
+ description: "Remove up to `amount` counters named `counter` from each referenced permanent or " \
40
+ "player (poison, experience, ...). How many were removed is {\"this_way\": n} " \
41
+ "(\"remove a bait counter ... If you do, ...\").",
42
+ rules: %w[122.8 122.1],
42
43
  params: { "counter" => "counter name", "amount" => "amount", "to" => "selector" },
43
44
  example: { "remove_counters" => { "counter" => "+1/+1", "amount" => 2, "to" => { "target" => 0 } } }
44
45
 
@@ -58,6 +59,7 @@ module Enjine
58
59
  engine.remove_counters!(perm, counter, n)
59
60
  engine.record_amount!(before - perm.counters.fetch(counter, 0)) # CR 608.2c: "if you do"
60
61
  end
62
+ players(engine, ctx).each { engine.record_amount!(engine.remove_player_counters!(it, counter, n)) } # CR 122.1
61
63
  end
62
64
 
63
65
  def to_s = "remove #{amount} #{counter} counter(s) → #{to}"
@@ -67,8 +69,8 @@ module Enjine
67
69
  class RemoveAllCounters < Effect
68
70
  primitive :effect, :remove_all_counters,
69
71
  description: "Remove every counter named `counter` (every counter, if no `counter` is given) from " \
70
- "each referenced permanent.",
71
- rules: %w[122.8],
72
+ "each referenced permanent or player (\"you lose all poison counters\").",
73
+ rules: %w[122.8 122.1],
72
74
  params: { "counter" => "optional counter name", "to" => "selector" },
73
75
  example: { "remove_all_counters" => { "counter" => "+1/+1", "to" => { "target" => 0 } } }
74
76
 
@@ -81,7 +83,11 @@ module Enjine
81
83
  @counter = raw && Counters.parse(raw, errors, "#{path}.counter")
82
84
  end
83
85
 
84
- def apply(engine, ctx) = objects(engine, ctx).each { engine.remove_all_counters!(engine.object(it), counter) }
86
+ def apply(engine, ctx)
87
+ objects(engine, ctx).each { engine.remove_all_counters!(engine.object(it), counter) }
88
+ players(engine, ctx).each { engine.remove_all_player_counters!(it, counter) } # CR 122.1: poison, experience, ...
89
+ end
90
+
85
91
  def to_s = "remove all #{counter || "counters"} → #{to}"
86
92
  end
87
93
 
@@ -11,7 +11,8 @@ module Enjine
11
11
  "spell or ability. It triggers only once, the next time `when` happens (e.g. " \
12
12
  "{\"step_begins\": {\"step\": \"end\", \"whose\": \"each\"}} for the next end step). Its " \
13
13
  "`effects` may use {\"result\": n} for what earlier effects of the creating list moved or " \
14
- "created; those objects are affected only if they are still where they were put.",
14
+ "created (n below its position); those objects are affected only if they are still " \
15
+ "where they were put. Its own effects are numbered on from there.",
15
16
  rules: %w[603.7a 603.7b 603.7c 603.7d 603.7e],
16
17
  params: { "when" => "a trigger condition", "effects" => "list of effects",
17
18
  "watch" => "selector resolved now (e.g. {\"target\": 0}): the objects its trigger subject " \
@@ -27,6 +28,10 @@ module Enjine
27
28
  def self.keys = %w[when effects watch this_turn]
28
29
  def self.default_to = "you"
29
30
 
31
+ # What the earlier effects of the creating list did (results or amounts), exactly `count` of them, so the
32
+ # created ability's own effects are numbered right after them (StackAbility.parse_effects).
33
+ def self.linked(values, count, blank) = Array.new(count) { values&.[](it) || blank }
34
+
30
35
  def setup(params, errors, path)
31
36
  @ref = "delayed:#{path}"
32
37
  raw = Mechanics.fetch_param(params, :when)
@@ -48,7 +53,7 @@ module Enjine
48
53
  # remembers the results it may name and the objects it watches (CR 603.7c).
49
54
  def apply(engine, ctx)
50
55
  entry = { "controller" => ctx.controller, "source" => ctx.source, "card" => engine.object(ctx.object).card,
51
- "ability" => ref, "results" => Snapshot.deep_copy(ctx.results || []) }
56
+ "ability" => ref, "results" => Snapshot.deep_copy(DelayedTrigger.linked(ctx.results, @results_count, [])) }
52
57
  entry["watched"] = @watch.resolve(engine, ctx) if @watch
53
58
  entry["turn"] = engine.state.turn if @this_turn
54
59
  entry["once"] = true if @this_turn == "once" # CR 603.7b: the next time only, and only this turn
@@ -64,7 +69,8 @@ module Enjine
64
69
  description: "Creates a reflexive triggered ability (\"when you do, ...\") that triggers immediately, " \
65
70
  "with the controller and source of the resolving spell or ability. Its `targets` are " \
66
71
  "chosen as it's put on the stack; its `effects` may name the results of earlier effects " \
67
- "of the creating list. With `if`, it triggers only when the condition holds " \
72
+ "of the creating list ({\"result\": n} / {\"this_way\": n} with n below its position) and " \
73
+ "their own, numbered on from there. With `if`, it triggers only when the condition holds " \
68
74
  "(\"when excess damage is dealt this way\").",
69
75
  rules: %w[603.12 603.12a 603.7d 603.7e 603.3d],
70
76
  params: { "targets" => "list of target filters", "effects" => "list of effects", "if" => "condition",
@@ -100,10 +106,11 @@ module Enjine
100
106
  def apply(engine, ctx)
101
107
  # Created by a replacement's follow-up (Engine::FollowUps), its spell may be long gone: its card is remembered.
102
108
  memory = Selector.memory(engine, ctx)
103
- card = engine.state.objects[ctx.object]&.card || memory["source_card"]
109
+ card = engine.find_object(ctx.object)&.card || memory["source_card"]
104
110
  source = { "id" => ctx.source, "card" => card, "controller" => ctx.controller, "ability" => ref }
105
- engine.queue_pending_trigger!(source, nil, { "results" => Snapshot.deep_copy(ctx.results || []),
106
- "amounts" => (ctx.amounts || []).dup,
111
+ results = Snapshot.deep_copy(DelayedTrigger.linked(ctx.results, @results_count, []))
112
+ engine.queue_pending_trigger!(source, nil, { "results" => results,
113
+ "amounts" => DelayedTrigger.linked(ctx.amounts, @results_count, 0),
107
114
  "triggering" => memory["triggering"]&.dup,
108
115
  "departed" => engine.departed_snapshot }.compact)
109
116
  end
@@ -16,7 +16,9 @@ module Enjine
16
16
  description: "An optional effect. The controller chooses yes or no as it resolves; yes is offered only " \
17
17
  "if every effect in `effects` can be done fully. On yes, `effects` then `then` (\"if you " \
18
18
  "do\") happen; on no, `otherwise` (\"if you don't\"). Nested effects may name the results " \
19
- "of earlier effects of the enclosing list.",
19
+ "of earlier effects of the enclosing list ({\"result\": n} with n below this effect's " \
20
+ "position) and their own, numbered on from there: `effects` then `then` in one " \
21
+ "numbering, `otherwise` in its own (\"if you do, ... the creature sacrificed this way\").",
20
22
  rules: %w[118.12 118.3 608.2d 608.2e],
21
23
  params: { "effects" => "list of effects (the optional part)", "then" => "list of effects",
22
24
  "otherwise" => "list of effects",
@@ -30,7 +32,7 @@ module Enjine
30
32
  def self.default_to = "you"
31
33
 
32
34
  def setup(params, errors, path)
33
- @lists = parse_lists(params, errors, path, LISTS)
35
+ @lists = parse_lists(params, errors, path, LISTS, chain: %w[effects then])
34
36
  errors << "#{path}.effects: needs at least one effect" if @lists["effects"].empty?
35
37
  raw = Mechanics.fetch_param(params, :chooser)
36
38
  @chooser = if raw.nil? || raw == "active_player" then raw
@@ -75,7 +75,9 @@ module Enjine
75
75
 
76
76
  def take_choice(engine, paying, variant, answer)
77
77
  i = paying.delete("cost")
78
- (paying["entries"][i.to_s] ||= []) << variant[i].choose!(engine, { object: answer["object"] })
78
+ # Every key of the option (the counter's kind, the creature type), as when casting.
79
+ option = answer.except("type").transform_keys(&:to_sym)
80
+ (paying["entries"][i.to_s] ||= []) << variant[i].choose!(engine, option)
79
81
  end
80
82
 
81
83
  # Asks for the next choice a cost needs (CR 601.2h, as for casting); nil when none is left.
@@ -88,7 +90,8 @@ module Enjine
88
90
  next if chosen.size >= cost.choices_needed || options.empty?
89
91
 
90
92
  paying["cost"] = i
91
- return ask(engine, locals, payer_obj.controller, cost.to_s, options.map { { "type" => "cost", "object" => it[:object] } })
93
+ return ask(engine, locals, payer_obj.controller, cost.to_s,
94
+ options.map { { "type" => "cost" }.merge(it.transform_keys(&:to_s)) })
92
95
  end
93
96
  nil
94
97
  end
@@ -104,9 +107,8 @@ module Enjine
104
107
  variant.each_with_index do |cost, i|
105
108
  next if cost.mana?
106
109
 
107
- if cost.respond_to?(:choices_needed)
108
- cost.pay_chosen!(engine, payer_obj,
109
- paying["entries"].fetch(i.to_s, []))
110
+ if cost.respond_to?(:choices_needed) # a chosen creature type was "paid" as it was chosen
111
+ cost.pay_chosen!(engine, payer_obj, paying["entries"].fetch(i.to_s, [])) if cost.respond_to?(:pay_chosen!)
110
112
  else
111
113
  cost.pay!(engine, payer_obj)
112
114
  end
@@ -175,7 +177,7 @@ module Enjine
175
177
 
176
178
  # Asks pay or decline, then pays; returns :wait while a decision or the payment is pending.
177
179
  def decide(engine, ctx, locals)
178
- payer = engine.object(ctx.object)
180
+ payer = payer_object(engine, ctx)
179
181
  unless locals["paying"] || answers(locals).first
180
182
  choices = pay_choices(engine, payer, costs_now(engine, ctx)) + [{ "type" => "decline" }]
181
183
  return ask(engine, locals, payer.controller, "Pay #{what}?", choices)
@@ -185,6 +187,18 @@ module Enjine
185
187
  result = pay_costs(engine, ctx, locals, payer, costs_now(engine, ctx))
186
188
  result == :wait ? :wait : (locals["outcome"] = result)
187
189
  end
190
+
191
+ # The object the costs are paid for. A resolving ability's "this permanent" (remove counters from it,
192
+ # sacrifice it, "another") is its source (CR 113.7a), while that is still on the battlefield under the
193
+ # ability's controller; once it has left it is a new object (CR 400.7), and such a cost can't be paid
194
+ # (CR 118.3). Either way the ability's controller pays.
195
+ def payer_object(engine, ctx)
196
+ resolving = engine.object(ctx.object)
197
+ return resolving unless resolving.ability?
198
+
199
+ source = engine.state.objects[ctx.source]
200
+ source&.zone == :battlefield && source.controller == resolving.controller ? source : resolving
201
+ end
188
202
  end
189
203
 
190
204
  # "Counter target spell unless its controller pays {3}." (CR 701.6a, 118.12a): the spell's (or
@@ -3,12 +3,15 @@
3
3
  module Enjine
4
4
  module Mechanics
5
5
  module Filters
6
- # "Any target": a creature, player or planeswalker (CR 115.4).
6
+ # "Any target": a creature, player, planeswalker or battle (CR 115.4).
7
7
  class AnyTarget < Filter
8
- primitive :filter, :any_target, description: "A creature, player or planeswalker (battles: later).",
8
+ primitive :filter, :any_target, description: "A creature, player, planeswalker or battle.",
9
9
  rules: %w[115.4], example: "any_target"
10
10
  def self.players?(_engine, index, _controller) = !index.nil?
11
- def self.match_object?(engine, object, controller) = CreatureOrPlaneswalker.match_object?(engine, object, controller)
11
+
12
+ def self.match_object?(engine, object, controller)
13
+ CreatureOrPlaneswalker.match_object?(engine, object, controller) || type?(engine, object, :battle)
14
+ end
12
15
  end
13
16
  end
14
17
  end
@@ -29,15 +29,17 @@ module Enjine
29
29
  filter
30
30
  end
31
31
 
32
- Facts = Data.define(:chars, :counters, :token, :chosen) do
33
- def initialize(chars:, counters:, token:, chosen: nil) = super
32
+ # `status`: {"attacking" =>, "blocking" =>, "tapped" => bool} for a permanent on the battlefield, nil where unknown
33
+ # (then a filter's status keys aren't checked).
34
+ Facts = Data.define(:chars, :counters, :token, :chosen, :status) do
35
+ def initialize(chars:, counters:, token:, chosen: nil, status: nil) = super
34
36
  end
35
37
 
36
38
  # The choices "the chosen ..." can refer to (CR 607.2d): the resolving spell's or ability's own
37
39
  # (an effect's "choose a creature type"), else its source's (an "as this enters" choice, CR 614.12).
38
40
  def self.chosen_memory(engine, source, ctx)
39
41
  own = engine.state.objects[source]&.memory || {}
40
- resolving = ctx && ctx.object != source ? engine.state.objects[ctx.object]&.memory : nil
42
+ resolving = ctx && ctx.object != source ? engine.find_object(ctx.object)&.memory : nil
41
43
  resolving ? own.merge(resolving.select { |k, _| k.start_with?("chosen_") }) : own
42
44
  end
43
45
 
@@ -106,7 +108,7 @@ module Enjine
106
108
  # {"creature": {"entered_this_turn": true}} entered the battlefield this turn
107
109
  # {"spell": {"single_target": true}} a spell with a single target (CR 115.7)
108
110
  class Restricted
109
- TYPES = %w[artifact creature enchantment land planeswalker instant sorcery].freeze
111
+ TYPES = %w[artifact battle creature enchantment kindred land planeswalker instant sorcery].freeze
110
112
  BOOLEANS = %w[other attacking blocking tapped token modified transformed prepared saddled entered_this_turn
111
113
  single_target].freeze
112
114
  RANGES = %w[power toughness mana_value].freeze
@@ -118,6 +120,8 @@ module Enjine
118
120
  # "chosen" ("with the chosen name", CR 201.4).
119
121
  CHOSEN = { "colors" => "chosen_color", "types" => "chosen_card_type", "not" => "chosen_card_type",
120
122
  "subtypes" => "chosen_type", "not_subtypes" => "chosen_type", "name" => "chosen_name" }.freeze
123
+ # Status, not characteristics: a static ability may read them (they never depend on the layer pass, CR 613.8).
124
+ STATUS = %w[attacking blocking tapped].freeze
121
125
  # Keys that need current characteristics or combat/tapped status: not usable in the layer pass.
122
126
  LIVE = %w[power toughness attacking blocking tapped attached_subtypes transformed prepared saddled
123
127
  entered_this_turn single_target].freeze
@@ -240,7 +244,12 @@ module Enjine
240
244
  (@lists["any_of"].empty? || types.intersect?(@lists["any_of"])) && (@lists["types"] - types).empty?
241
245
  end
242
246
 
243
- def matches_facts?(facts) = base.matches_facts?(facts) && characteristics_ok?(facts)
247
+ def matches_facts?(facts) = base.matches_facts?(facts) && characteristics_ok?(facts) && status_facts_ok?(facts.status)
248
+
249
+ # Attacking, blocking and tapped status from Facts (CR 506.4), when known.
250
+ def status_facts_ok?(status)
251
+ status.nil? || STATUS.all? { @params[it].nil? || status[it] == @params[it] }
252
+ end
244
253
 
245
254
  def to_s
246
255
  words = []
@@ -18,6 +18,13 @@ module Enjine
18
18
  def self.card_types = [:planeswalker]
19
19
  end
20
20
 
21
+ # A battle on the battlefield (CR 310).
22
+ class Battle < Filter
23
+ primitive :filter, :battle, description: "A battle on the battlefield.", rules: %w[310.5], example: "battle"
24
+ def self.match_object?(engine, object, _controller) = type?(engine, object, :battle)
25
+ def self.card_types = [:battle]
26
+ end
27
+
21
28
  # A creature or planeswalker on the battlefield.
22
29
  class CreatureOrPlaneswalker < Filter
23
30
  primitive :filter, :creature_or_planeswalker, description: "A creature or planeswalker on the battlefield.",