enjine 0.5.0 → 0.6.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 (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +146 -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 +5 -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
data/lib/enjine/events.rb CHANGED
@@ -136,6 +136,15 @@ module Enjine
136
136
  SpeedChanged = define(:speed_changed, :player, :from, :to)
137
137
  # A player got a designation for the rest of the game, e.g. an enduring story (CR 702.195b).
138
138
  DesignationGained = define(:designation_gained, :player, :designation)
139
+ # A permanent got a designation it keeps until it leaves the battlefield: "solved" (CR 720.3b), "harnessed"
140
+ # (CR 701.64b), see Engine::PermanentDesignations.
141
+ PermanentDesignated = define(:permanent_designated, :object, :designation)
142
+ # CR 709.5c, 709.5h-i: a Room permanent got a door's unlocked designation; `fully`: it now has both.
143
+ DoorUnlocked = define(:door_unlocked, :player, :object, :door, :fully)
144
+ # CR 709.5g: a Room permanent lost a door's unlocked designation.
145
+ DoorLocked = define(:door_locked, :object, :door)
146
+ # CR 708.8, 116.2b: a face-down permanent was turned face up; `card` is the card it is (Engine::FaceDownPermanents).
147
+ TurnedFaceUp = define(:turned_face_up, :player, :object, :card)
139
148
  # A permanent's class level became `level` (CR 717.2a).
140
149
  ClassLevelChanged = define(:class_level_changed, :object, :level)
141
150
  # CR 701.27a: a double-faced permanent turned over; `card` names the face now up (CR 712).
data/lib/enjine/frames.rb CHANGED
@@ -48,6 +48,9 @@ module Enjine
48
48
  def self.decisions = %w[effect_choice enter_choice damage_order]
49
49
 
50
50
  def self.validate(frame, data, errors)
51
+ # A spell that left the stack while resolving is kept by the frame (CR 608.2n, Engine::Resolution).
52
+ return if frame["left_stack"].is_a?(Hash) && frame["left_stack"]["id"] == frame["object"]
53
+
51
54
  errors << "frames: resolving object #{frame["object"]} is not on the stack" unless data["stack"].include?(frame["object"])
52
55
  end
53
56
  end
data/lib/enjine/fuzz.rb CHANGED
@@ -117,6 +117,9 @@ module Enjine
117
117
 
118
118
  def check!(game, seed, count)
119
119
  errors = Snapshot.validate(game.state.to_h, game.catalog)
120
+ # A pending decision always has a legal answer (CR 734.1: a payment that can't be finished is rewound).
121
+ decision = game.over? ? nil : game.pending_decision
122
+ errors << "pending #{decision.kind} decision has no options" if decision && decision.options.empty?
120
123
  raise Failure.new("invariant broken: #{errors.join("; ")}", seed: seed, decisions: count) unless errors.empty?
121
124
  end
122
125
 
data/lib/enjine/game.rb CHANGED
@@ -134,7 +134,9 @@ module Enjine
134
134
  self
135
135
  end
136
136
 
137
- def view_for(viewer) = View.build(@engine, viewer_key(viewer))
137
+ # The pending decision's options come from #pending_decision (memoized until the next submission), not generated
138
+ # once more for the view.
139
+ def view_for(viewer) = View.build(@engine, viewer_key(viewer), options: method(:legal_options))
138
140
  def history_for(viewer) = @history.map { it.for_viewer(viewer_key(viewer)) }
139
141
 
140
142
  # Ids of every decision submitted so far: with the seed this replays the game.
@@ -8,7 +8,10 @@ module Enjine
8
8
  class Reduction
9
9
  attr_reader :amount, :condition
10
10
 
11
- def self.build(data, errors, path)
11
+ # `targets_count`: the targets of the ability it reduces, which the amount may name ({"target": 0}): "costs {1}
12
+ # less for each +1/+1 counter on the target creature" (the total cost is determined after targets are chosen,
13
+ # CR 601.2f).
14
+ def self.build(data, errors, path, targets_count: 0)
12
15
  unless data.is_a?(Hash)
13
16
  errors << "#{path}: must be {\"amount\": n, \"if\": condition}"
14
17
  return new(Amount::Fixed.new(0), nil)
@@ -16,22 +19,36 @@ module Enjine
16
19
  data = data.transform_keys(&:to_s)
17
20
  Mechanics.check_keys(data, %w[amount if], errors, path)
18
21
  amount = if data.key?("amount")
19
- Amount.build(data["amount"], errors, "#{path}.amount", targets_count: 0)
22
+ Amount.build(data["amount"], errors, "#{path}.amount", targets_count: targets_count)
20
23
  else
21
24
  (errors << "#{path}.amount: required") && Amount::Fixed.new(0)
22
25
  end
23
26
  condition = data["if"] && Condition.build(data["if"], errors, "#{path}.if")
24
- new(amount, condition)
27
+ new(amount, condition, targeted: targets_count.positive? && names_targets?(data["amount"], path))
25
28
  end
26
29
 
27
- def initialize(amount, condition)
30
+ # Whether the amount names a target: it is valid only with targets to name.
31
+ def self.names_targets?(raw, path)
32
+ probe = []
33
+ Amount.build(raw, probe, path, targets_count: 0)
34
+ !probe.empty?
35
+ end
36
+
37
+ def initialize(amount, condition, targeted: false)
28
38
  @amount = amount
29
39
  @condition = condition
40
+ @targeted = targeted
30
41
  freeze
31
42
  end
32
43
 
33
- # The generic mana it takes off now (0 when the condition doesn't hold).
34
- def reduction(engine, ctx) = condition.nil? || condition.true?(engine, ctx) ? amount.value(engine, ctx) : 0
44
+ # The generic mana it takes off now (0 when the condition doesn't hold). An amount naming a target, before the
45
+ # targets are chosen (ctx targets nil): any amount, so the total cost found is a lower bound (Engine::Costs).
46
+ def reduction(engine, ctx)
47
+ return 0 unless condition.nil? || condition.true?(engine, ctx)
48
+ return Float::INFINITY if @targeted && ctx.targets.nil?
49
+
50
+ amount.value(engine, ctx)
51
+ end
35
52
 
36
53
  def to_s = "costs {#{amount}} less#{" if #{condition}" if condition}"
37
54
  end
@@ -73,12 +90,14 @@ module Enjine
73
90
  class CostModifier < Primitive
74
91
  TYPES = %w[artifact creature enchantment land planeswalker instant sorcery].freeze
75
92
  CASTERS = %w[you opponent any].freeze
76
- SPEC_KEYS = %w[subtypes colors].freeze
93
+ SPEC_KEYS = %w[subtypes colors name].freeze
77
94
 
78
95
  primitive :ability, :cost_modifier,
79
96
  description: "While on the battlefield: spells cast by `caster` (you, opponent or any; default you) " \
80
97
  "whose card types match `spells` ({\"any_of\": [types], \"not\": [types]}, default all " \
81
- "spells; `subtypes` and `colors` narrow it: \"Dragon spells\", \"red spells\") cost " \
98
+ "spells; `subtypes`, `colors` and `name` narrow it: \"Dragon spells\", \"red spells\"; " \
99
+ "`\"subtypes\": \"chosen\"`: of the type chosen for this permanent, `\"name\": \"chosen\"`: with the " \
100
+ "name its source chose) cost " \
82
101
  "`reduce` less or `increase` more generic mana. `from` / `not_from`: only " \
83
102
  "spells cast from (not from) that zone (hand | graveyard | exile | library | outside).",
84
103
  rules: %w[601.2f 118.7a 604.1 601.2a],
@@ -148,14 +167,17 @@ module Enjine
148
167
  chars = engine.chars(spell)
149
168
  types = chars.types
150
169
  return 0 if types.intersect?(not_types) || !(any_of.empty? || types.intersect?(any_of))
151
- return 0 if @spec && !@spec.chars_match?(engine, chars)
170
+
171
+ 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)
152
173
  return 0 unless @zones.match?(engine.cast_origin(spell))
153
174
 
154
- sign * amount.value(engine, EffectContext.new(permanent.controller, permanent.id, permanent.id, []))
175
+ sign * amount.value(engine, ctx)
155
176
  end
156
177
 
157
178
  def to_s
158
179
  narrow = @spec ? [@spec.colors.map(&:to_s), @spec.subtypes.map { it.to_s.capitalize }] : []
180
+ narrow << "chosen-type" if @spec&.relations&.[]("chosen_subtype")
159
181
  kinds = [not_types.map { "non#{it}" }, narrow, any_of.join(" or ")].flatten.reject(&:empty?).join(" ")
160
182
  whose = { "you" => "you cast", "opponent" => "your opponents cast", "any" => "" }[caster]
161
183
  "#{[kinds, "spells", whose].reject(&:empty?).join(" ")}#{@zones} cost {#{amount}} " \
@@ -556,7 +556,7 @@ module Enjine
556
556
  details["to"] = nil if to.nil? # "to": nil means any recipient
557
557
  details["by"] = nil if by.nil?
558
558
  details["remaining"] = shield.value(engine, ctx) if shield
559
- card = engine.state.objects[ctx.object]&.card
559
+ card = engine.find_object(ctx.object)&.card
560
560
  details["follow_up"] = follow_up.entry(card, ctx.controller, ctx.source, {}) if follow_up && card
561
561
  engine.add_continuous_effect!("prevent_damage", ctx, (to || []) + (by || []), details)
562
562
  :done
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Mechanics
5
+ module Abilities
6
+ # Abilities that work only while their permanent has a designation (Engine::PermanentDesignations): a Case's
7
+ # "Solved — [ability]" (CR 702.169, 720.3c) and an Infinity card's "∞ — [ability]" (CR 702.186). The wrapped
8
+ # ability is built with the designation as its condition, by kind:
9
+ # static "as long as it's solved/harnessed" (`if`, CR 702.169b, 702.186b)
10
+ # triggered "triggers only if it's solved" (`while`: checked as it triggers, CR 702.169c)
11
+ # activated "activate only if it's solved" (`only_if`, CR 702.169d)
12
+ # joined with any condition of its own. The result is the wrapped ability itself.
13
+ module DesignatedAbility
14
+ CONDITION_KEYS = { "static" => "if", "triggered" => "while", "activated" => "only_if" }.freeze
15
+
16
+ def self.build(designation, params, errors, path)
17
+ kind, body = Mechanics.split_entry(params)
18
+ key = CONDITION_KEYS[kind.to_s]
19
+ unless key && body.is_a?(Hash)
20
+ errors << "#{path}: must be one static, triggered or activated ability, e.g. {\"static\": {...}}"
21
+ return nil
22
+ end
23
+ mark = { designation => true }
24
+ body = body.transform_keys(&:to_s)
25
+ condition = body.key?(key) ? { "all" => [mark, body[key]] } : mark
26
+ Mechanics.build_entry(:ability, { kind.to_s => body.merge(key => condition) }, errors, path)
27
+ end
28
+ end
29
+ end
30
+
31
+ class Condition
32
+ # "If this Case is solved" / "as long as this permanent is harnessed": the source permanent has that
33
+ # designation (CR 720.3b, 701.64b). {"solved": true} / {"harnessed": true}.
34
+ class PermanentDesignation
35
+ def self.build(data, errors, path)
36
+ key = (Engine::PermanentDesignations::NAMES & data.keys).first
37
+ Mechanics.check_keys(data, [key], errors, path)
38
+ errors << "#{path}.#{key}: must be true or false" unless [true, false].include?(data[key])
39
+ new(key, data[key] != false)
40
+ end
41
+
42
+ def initialize(designation, value)
43
+ @designation = designation
44
+ @value = value
45
+ freeze
46
+ end
47
+
48
+ def true?(engine, ctx)
49
+ obj = engine.state.objects[ctx.source]
50
+ (obj ? engine.designated?(obj, @designation) : false) == @value
51
+ end
52
+
53
+ def to_s = "this permanent is #{"not " unless @value}#{@designation}"
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "replacement_effects"
4
+
5
+ module Enjine
6
+ module Mechanics
7
+ module Abilities
8
+ # "If you would gain life, you gain twice that much life instead" / "... that much life plus 1 instead" /
9
+ # "If an opponent would gain life, that player loses that much life instead" (CR 614.1a, 119.10): a
10
+ # static replacement effect of a permanent that changes a life gain event. Replacements.gaining_life!
11
+ # applies them.
12
+ class LifeGainReplacement < StaticReplacement
13
+ PLAYERS = %w[you opponent any].freeze
14
+
15
+ primitive :ability, :life_gain_replacement,
16
+ description: "While this permanent is on the battlefield, each time `player` (you (default) | " \
17
+ "opponent | any, relative to its controller) would gain life, instead: `multiply` " \
18
+ "(2 = \"twice that much\"), `plus` an amount (\"that much life plus 1\"), or `lose: " \
19
+ "true` (\"that player loses that much life instead\"). Each applies once to an event; " \
20
+ "the affected player's best order is used: losing instead first, then adding, then " \
21
+ "multiplying. Gaining 0 life is no event (nothing applies).",
22
+ rules: %w[614.1a 614.5 616.1 119.10],
23
+ params: { "player" => PLAYERS.join(" | "), "multiply" => "integer >= 2", "plus" => "amount",
24
+ "lose" => "true" },
25
+ example: { "life_gain_replacement" => { "player" => "you", "plus" => 1 } }
26
+
27
+ attr_reader :player, :multiply, :plus
28
+
29
+ def self.build(params, errors, path, **)
30
+ Mechanics.check_keys(params, %w[player multiply plus lose], errors, path)
31
+ player = params.fetch("player", "you")
32
+ errors << "#{path}.player: must be one of #{PLAYERS.join(", ")}" unless PLAYERS.include?(player)
33
+ modes = %w[multiply plus lose].select { params.key?(it) }
34
+ errors << "#{path}: needs exactly one of multiply, plus, lose" unless modes.size == 1
35
+ errors << "#{path}.lose: must be true" if params.key?("lose") && params["lose"] != true
36
+ multiply = params.key?("multiply") ? Mechanics.integer_param(params, :multiply, errors, path, min: 2) : nil
37
+ plus = params.key?("plus") ? Amount.build(params["plus"], errors, "#{path}.plus", targets_count: 0) : nil
38
+ new(player, multiply, plus, params["lose"] == true)
39
+ end
40
+
41
+ def initialize(player, multiply, plus, lose)
42
+ super()
43
+ @player = player
44
+ @multiply = multiply
45
+ @plus = plus
46
+ @lose = lose
47
+ freeze
48
+ end
49
+
50
+ def kind = :life_gain_replacement
51
+ def lose? = @lose
52
+
53
+ # Whether it applies to `index` gaining life (CR 614.1a), relative to the holder's controller.
54
+ def replaces_gain?(index, holder) = player == "any" || (player == "you") == (index == holder.controller)
55
+
56
+ # The changed amount of life gained (not used for `lose`).
57
+ def gained(engine, amount, holder)
58
+ return amount * multiply if multiply
59
+
60
+ amount + [plus.value(engine, EffectContext.new(holder.controller, holder.id, holder.id, [], [])), 0].max
61
+ end
62
+
63
+ def to_s
64
+ who = { "you" => "you", "opponent" => "an opponent", "any" => "a player" }.fetch(player)
65
+ instead = if multiply then "gain #{multiply} times that much"
66
+ elsif plus then "gain that much plus #{plus}"
67
+ else "lose that much"
68
+ end
69
+ "if #{who} would gain life, #{instead} instead"
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -119,7 +119,12 @@ module Enjine
119
119
 
120
120
  raw.each_with_index.map do |c, i|
121
121
  cost = Mechanics.build_entry(:cost, c, errors, "#{path}.cost[#{i}]")
122
- errors << "#{path}.cost[#{i}]: a mana ability's cost can't need a choice, X or {2/B}" if choosing_cost?(cost)
122
+ if cost.is_a?(Costs::OneOf)
123
+ errors << "#{path}.cost[#{i}]: a mana ability's cost can't be a one_of (a choice between costs, CR 601.2b, " \
124
+ "isn't supported for mana abilities, which are paid for at once, CR 605.3a)"
125
+ elsif choosing_cost?(cost)
126
+ errors << "#{path}.cost[#{i}]: a mana ability's cost can't need a choice, X or {2/B}"
127
+ end
123
128
  cost
124
129
  end
125
130
  end
@@ -169,11 +174,12 @@ module Enjine
169
174
  def allowed_types = nil
170
175
 
171
176
  # A mana cost ("{1}, {T}: Add …") is paid from the mana already in the pool (CR 605.3a, 601.2g-h).
172
- # "Activate only if ..." (CR 602.5b) is checked for its controller.
173
- def activatable?(engine, object)
177
+ # "Activate only if ..." (CR 602.5b) is checked for its controller. `bound`: its costs as they apply to this
178
+ # instance (a granted ability's "tap the granter", Engine#mana_ability_costs).
179
+ def activatable?(engine, object, bound = costs)
174
180
  return false if @only_if && !@only_if.true?(engine, EffectContext.new(object.controller, object.id, nil, nil))
175
181
 
176
- costs.all? { |c| c.payable?(engine, object) } && (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
182
+ bound.all? { |c| c.payable?(engine, object) } && (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
177
183
  end
178
184
 
179
185
  # How many times it may be activated each turn (nil: no limit, CR 602.5b); kept by Engine#record_activation!.
@@ -135,7 +135,7 @@ module Enjine
135
135
  return false if @chosen_name && engine.chars(object).name != source.memory["chosen_name"]
136
136
 
137
137
  (filter.nil? || filter.match_for?(engine, object.id, source.controller, source.id)) &&
138
- (spells.nil? || spells.match?(engine, object))
138
+ (spells.nil? || spells.match?(engine, object, EffectContext.new(source.controller, source.id, source.id, [], [])))
139
139
  end
140
140
 
141
141
  def to_s
@@ -186,13 +186,16 @@ module Enjine
186
186
  end.freeze
187
187
  end
188
188
 
189
- # Effect i may name the results of effects 0...i ({"result": n}). A nested list (`results_count`
190
- # given) sees only its parent's earlier results.
191
- def self.parse_effects(params, errors, path, targets_count, key: :effects, results_count: nil)
189
+ # Effect i may name the results of effects 0...i ({"result": n}, {"this_way": n}). A nested list
190
+ # (`results_count` given: how many earlier effects of the enclosing list it may name) continues that
191
+ # numbering: n below `results_count` is the enclosing list's effect n, `results_count + offset + j` the
192
+ # nested list's own effect j (CR 608.2c). `offset`: effects of a list that runs just before this one in
193
+ # the same numbering (a "may"'s `then` follows its `effects`).
194
+ def self.parse_effects(params, errors, path, targets_count, key: :effects, results_count: nil, offset: 0)
192
195
  list = Mechanics.list_param(params, key, errors, path)
193
196
  list.each_with_index.filter_map do |entry, i|
194
- Mechanics.build_entry(:effect, entry, errors, "#{path}.#{key}[#{i}]", targets_count: targets_count,
195
- results_count: results_count || i)
197
+ Mechanics.build_entry(:effect, entry, errors, "#{path}.#{key}[#{i}]",
198
+ targets_count: targets_count, results_count: results_count ? results_count + offset + i : i)
196
199
  end.freeze
197
200
  end
198
201
 
@@ -320,7 +323,7 @@ module Enjine
320
323
  "zone" => "\"exile\" | \"graveyard\" | \"hand\" (CR 113.6b; default: the battlefield, or the " \
321
324
  "zone a cost moves the card from)",
322
325
  "cost_reduction" => "{\"amount\": amount, \"if\": condition}: \"this ability costs {N} less " \
323
- "to activate\" (CR 601.2f, 602.2b)" },
326
+ "to activate\" (CR 601.2f, 602.2b); the amount may name its targets ({\"target\": 0})" },
324
327
  example: { "activated" => { "cost" => ["tap"], "targets" => ["any_target"],
325
328
  "effects" => [{ "deal_damage" => { "amount" => 1, "to" => { "target" => 0 } } }] } }
326
329
 
@@ -332,7 +335,9 @@ module Enjine
332
335
  costs = parse_costs(params, errors, path)
333
336
  errors << "#{path}.cost: must be a non-empty list" if costs.empty? && errors.none? { it.start_with?("#{path}.cost") }
334
337
  raw = Mechanics.fetch_param(params, :cost_reduction)
335
- reduction = raw && Reduction.build(raw, errors, "#{path}.cost_reduction")
338
+ targets = Mechanics.fetch_param(params, :targets)
339
+ reduction = raw && Reduction.build(raw, errors, "#{path}.cost_reduction",
340
+ targets_count: targets.is_a?(Array) ? targets.size : 0) # CR 601.2f
336
341
  check_cost_zones(costs, errors, path)
337
342
  zone = parse_zone(params, costs, errors, path)
338
343
  body = parse_body(params, errors, path)
@@ -23,8 +23,11 @@ module Enjine
23
23
  "`affects` is " \
24
24
  "{\"each\": filter, " \
25
25
  "\"controller\": you|opponent|any, \"other\": true} (relative to the source's " \
26
- "controller), \"self\", or \"attached\" (\"equipped/enchanted creature\").",
27
- rules: %w[604.1 604.2 611.3a 612.8 613.1c 613.1d 613.1e 613.1f 613.4b 613.4c 613.7a 613.8a 205.1a 205.1b 301.5f
26
+ "controller), \"self\", or \"attached\" (\"equipped/enchanted creature\"). The filter " \
27
+ "and the `if` condition may read combat and tapped status (\"attacking creatures you " \
28
+ "control have first strike\", {\"if\": {\"attacking\": \"attached\"}}), never power " \
29
+ "or toughness.",
30
+ rules: %w[604.1 604.2 611.3a 506.4 612.8 613.1c 613.1d 613.1e 613.1f 613.4b 613.4c 613.7a 613.8a 205.1a 205.1b 301.5f
28
31
  303.4m],
29
32
  params: { "affects" => "{\"each\": filter, \"controller\": ..., \"other\": bool}, \"self\" or \"attached\"",
30
33
  "if" => "condition (\"as long as ...\", \"during your turn\")",
@@ -44,7 +47,9 @@ module Enjine
44
47
 
45
48
  GRANTABLE = %i[triggered mana activated loyalty hexproof_from protection_from tapping_power cant_be_blocked_by].freeze
46
49
  # Data that would make the layer pass depend on its own result (CR 613.8).
47
- LIVE = %w[power toughness greatest_power attacking blocking tapped].freeze
50
+ # Combat and tapped status may be read (CR 506.4): they aren't characteristics, so they never depend on it.
51
+ LIVE = %w[power toughness greatest_power].freeze
52
+ STATUS = Filters::Restricted::STATUS
48
53
  KEYS = %w[affects if pump keywords creature_types abilities types subtypes loses_abilities colors
49
54
  base_power_toughness set_types name].freeze
50
55
 
@@ -56,7 +61,7 @@ module Enjine
56
61
  affects = Mechanics.fetch_param(params, :affects)
57
62
  filter, controller, other = parse_affects(affects, errors, path)
58
63
  raw_if = Mechanics.fetch_param(params, :if)
59
- errors << "#{path}.if: can't depend on power, toughness or combat status (CR 613.8)" if live?(raw_if)
64
+ errors << "#{path}.if: can't depend on power or toughness (CR 613.8)" if live?(raw_if)
60
65
  condition = raw_if && Condition.build(raw_if, errors, "#{path}.if")
61
66
  pump = parse_pump(params, errors, path)
62
67
  keywords = parse_keywords(params, errors, path)
@@ -111,7 +116,7 @@ module Enjine
111
116
  end
112
117
  Mechanics.check_keys(affects, %w[each controller other], errors, "#{path}.affects")
113
118
  filter = Mechanics.build_entry(:filter, affects["each"], errors, "#{path}.affects.each")
114
- live = filter ? filter.live_keys : []
119
+ live = filter ? filter.live_keys - STATUS : []
115
120
  # CR 613.8: these would make the layer pass depend on its own result.
116
121
  errors << "#{path}.affects.each: #{live.join(", ")} can't be used in a static ability yet" unless live.empty?
117
122
  [filter, affects.fetch("controller", "any"), affects["other"] == true]
@@ -207,6 +212,14 @@ module Enjine
207
212
  def ability_changes? = @loses_abilities || !@keywords.empty? || !@granted.empty?
208
213
  def computed? = @pump.values.any? { !it.is_a?(Amount::Fixed) }
209
214
 
215
+ # Whether which permanents it affects depends on combat or tapped status ("attacking creatures you control
216
+ # have first strike", CR 506.4): the layer pass is then redone after every event.
217
+ def combat_status? = @filter.respond_to?(:live_keys) && @filter.live_keys.intersect?(STATUS)
218
+
219
+ # Whether any event may change what it does (a condition, a computed bonus, combat status): then the layer
220
+ # pass isn't cached between events (Engine::Characteristics#apply_layers).
221
+ def volatile? = !@condition.nil? || computed? || combat_status?
222
+
210
223
  # The fixed bonus, for display and for data readers (computed bonuses are Amounts).
211
224
  def power = fixed(@pump["power"])
212
225
  def toughness = fixed(@pump["toughness"])
@@ -21,9 +21,11 @@ module Enjine
21
21
  # {"layout": "adventure"} "a card that has an Adventure": the card's layout (CR 716,
22
22
  # CardDefinition::Faces)
23
23
  # {"subtypes": "chosen"} of the creature type chosen for the source (CR 607.2d)
24
+ # {"name": "chosen"} with the card name chosen for the source or the resolving
25
+ # spell (choose_card_name, CR 201.4, 607.2d)
24
26
  # {"same_name_as": filter} the same name as a permanent the filter matches, e.g. "a
25
27
  # legendary permanent you control" (CR 201.2a)
26
- # The last two read the context (an EffectContext): the source's choices and its controller.
28
+ # The chosen ones and same_name_as read the context (an EffectContext): the source's choices and its controller.
27
29
  class CardSpec
28
30
  KEYS = %w[types not_types subtypes supertypes name any_of permanent mana_value colors color_count keywords
29
31
  not_subtypes power toughness layout same_name_as].freeze
@@ -43,8 +45,9 @@ module Enjine
43
45
  Mechanics.check_keys(data, KEYS, errors, path)
44
46
  errors << "#{path}: needs at least one of #{KEYS.join(", ")}" if data.empty?
45
47
  chosen = data["subtypes"] == "chosen"
48
+ named = data["name"] == "chosen"
46
49
  new(types: names(data, "types", :type, errors, path), supertypes: names(data, "supertypes", :supertype, errors, path),
47
- subtypes: chosen ? [] : subtype_list(data, errors, path), name: name_param(data, errors, path),
50
+ subtypes: chosen ? [] : subtype_list(data, errors, path), name: named ? nil : name_param(data, errors, path),
48
51
  any_of: alternatives(data, errors, path), not_types: names(data, "not_types", :type, errors, path),
49
52
  permanent: permanent_param(data, errors, path), mana_value: bounds_param(data, "mana_value", errors, path),
50
53
  colors: colors_param(data, errors, path), color_count: bounds_param(data, "color_count", errors, path),
@@ -65,7 +68,8 @@ module Enjine
65
68
  def self.relations_param(data, chosen, errors, path)
66
69
  raw = data["same_name_as"]
67
70
  same = raw && Mechanics.build_entry(:filter, raw, errors, "#{path}.same_name_as")
68
- { "chosen_subtype" => (true if chosen), "same_name_as" => same }.compact
71
+ { "chosen_subtype" => (true if chosen), "chosen_name" => (true if data["name"] == "chosen"),
72
+ "same_name_as" => same }.compact
69
73
  end
70
74
 
71
75
  def self.colors_param(data, errors, path)
@@ -202,6 +206,7 @@ module Enjine
202
206
 
203
207
  text = (type_words.map { it.to_s.tr("_", " ") } + ["card"]).join(" ") + quality_words
204
208
  text += " with the same name as a #{relations["same_name_as"]}" if relations["same_name_as"]
209
+ text += " with the chosen name" if relations["chosen_name"]
205
210
  bounds = { "mana value" => mana_value, "number of colors" => color_count, "power" => stats["power"] || {},
206
211
  "toughness" => stats["toughness"] || {} }.reject { |_, b| b.empty? }
207
212
  return text if bounds.empty?
@@ -236,6 +241,10 @@ module Enjine
236
241
  chosen = Filters.chosen_memory(engine, ctx.source, ctx)["chosen_type"]
237
242
  return false unless chosen && chars.subtypes.include?(chosen.to_sym)
238
243
  end
244
+ if relations["chosen_name"] # "a card with the chosen name" (CR 201.4): nothing matches before a name is chosen
245
+ named = Filters.chosen_memory(engine, ctx.source, ctx)["chosen_name"]
246
+ return false unless named && chars.name == named
247
+ end
239
248
  filter = relations["same_name_as"] or return true
240
249
  !chars.name.to_s.empty? && engine.state.battlefield.any? do
241
250
  filter.match_for?(engine, it, ctx.controller, ctx.source) && engine.chars(it).name == chars.name
@@ -155,10 +155,11 @@ module Enjine
155
155
  entries.map { it["object"] }.select { engine.state.objects[it]&.zone == self.class.zone }.each { pay_card!(engine, it) }
156
156
  end
157
157
 
158
- # An exiled card is remembered by the spell or ability being cast ("copy those exiled cards").
158
+ # An exiled card is remembered by the spell or ability being cast, or resolving for a cost paid then (CR 118.12):
159
+ # "copy those exiled cards".
159
160
  def pay_card!(engine, id)
160
161
  fresh = engine.move!(id, :exile, reason: "cost") or return
161
- holder = engine.casting && engine.state.objects[engine.casting["object"]]
162
+ holder = engine.cost_holder
162
163
  (holder.memory[EXILED] ||= []) << fresh.id if holder
163
164
  end
164
165
 
@@ -55,15 +55,22 @@ module Enjine
55
55
  end
56
56
 
57
57
  # Not the card being cast (it is on the stack once casting begins). "Of the chosen type" reads the type chosen
58
- # for it (Costs::ChooseCreatureType).
58
+ # for the spell or ability being paid for (Costs::ChooseCreatureType, Engine#cost_holder).
59
59
  def candidates(engine, object)
60
- ctx = EffectContext.new(object.controller, object.id, object.id, [])
60
+ ctx = EffectContext.new(object.controller, object.id, holder(engine, object).id, [])
61
61
  Beholding.candidates(engine, object.controller, filter, ctx) - [object.id]
62
62
  end
63
63
 
64
+ # The spell or ability being paid for, when `object` is it or its source (an ability's costs are paid for its
65
+ # source); otherwise `object`.
66
+ def holder(engine, object)
67
+ held = engine.cost_holder
68
+ held && (held.id == object.id || held.source == object.id) ? held : object
69
+ end
70
+
64
71
  # Before a type is chosen for "behold two creatures of that type", whether some type would do (CR 601.2b).
65
72
  def payable?(engine, object)
66
- return super unless filter.relations["chosen_subtype"] && !object.memory["chosen_type"]
73
+ return super unless filter.relations["chosen_subtype"] && !holder(engine, object).memory["chosen_type"]
67
74
 
68
75
  others = Beholding.candidates(engine, object.controller, filter.unrelated) - [object.id]
69
76
  others.flat_map { engine.chars(it).subtypes.uniq }.tally.any? do |type, n|
@@ -28,11 +28,11 @@ module Enjine
28
28
 
29
29
  def choice_options(_engine, _object, _chosen) = Chosen.values("creature_type", []).map { { creature_type: it } }
30
30
 
31
- # The spell being cast remembers the type now, so a later cost of "that type" can be chosen (CR 601.2b).
31
+ # The spell or ability being cast (or resolving, for a cost paid then, CR 118.12) remembers the type now, so a
32
+ # later cost of "that type" can be chosen (CR 601.2b).
32
33
  def choose!(engine, option)
33
34
  type = option[:creature_type].to_s
34
- spell = engine.casting && engine.state.objects[engine.casting["object"]]
35
- spell&.memory&.store("chosen_type", type)
35
+ engine.cost_holder&.memory&.store("chosen_type", type)
36
36
  { "creature_type" => type }
37
37
  end
38
38
 
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Mechanics
5
+ module Costs
6
+ # Collect evidence N (CR 701.59a): "exile any number of cards from your graveyard with total mana value N or
7
+ # greater" (CR 202.3), never the card the spell or ability belongs to. The player chooses cards one at a time
8
+ # (`choose_cost`) and may stop (`done`) once they total N; the cards are exiled as the spell becomes cast
9
+ # (CR 601.2h). It can't be paid without enough mana value in the graveyard (CR 701.59b, 118.3). As an
10
+ # optional additional cost (`additional_cost` with `optional: true`), "if evidence was collected" is
11
+ # `{"cast_with": "additional_cost"}`; inside `pay` (and so ward) it is "you may collect evidence N. If you do".
12
+ class CollectEvidence < CardsCost
13
+ primitive :cost, :collect_evidence,
14
+ description: "Collect evidence `N`: exile any number of other cards from your graveyard with total " \
15
+ "mana value N or greater, chosen one at a time (`choose_cost`; `done` once they total " \
16
+ "N). Not payable without that much mana value in your graveyard. \"If evidence was " \
17
+ "collected\": make it an optional `additional_cost` and read `{\"cast_with\": " \
18
+ "\"additional_cost\"}`.",
19
+ rules: %w[701.59a 701.59b 701.59c 202.3 601.2h 118.3],
20
+ params: { "(value)" => "integer >= 1: N" },
21
+ example: { "collect_evidence" => 6 }
22
+
23
+ attr_reader :evidence
24
+
25
+ def self.scalar_params? = true
26
+ def self.zone = :graveyard
27
+
28
+ def self.build(params, errors, path, **)
29
+ errors << "#{path}: must be an integer >= 1" unless params.is_a?(Integer) && params.positive?
30
+ new(nil, "any", false, { "evidence" => params.is_a?(Integer) ? params : 1 }, errors, path)
31
+ end
32
+
33
+ def initialize(filter, count, other, params, errors, path)
34
+ @evidence = params["evidence"]
35
+ super(filter, count, other, {}, errors, path)
36
+ end
37
+
38
+ # CardsCost's "any number" check reads `symbols`; collect evidence reads mana value instead.
39
+ def symbols_param(_raw, _errors, _path) = { "evidence" => true }
40
+
41
+ def mana_value_among(engine, ids) = ids.sum { engine.chars(it).mana_cost&.mana_value.to_i }
42
+
43
+ def payable?(engine, object) = mana_value_among(engine, candidates(engine, object)) >= evidence
44
+
45
+ # Each chosen card remembers its mana value, so the total is known without the engine.
46
+ def choose!(engine, option) = { "object" => option[:object], "mana_value" => mana_value_among(engine, [option[:object]]) }
47
+
48
+ # Engine::CastChoices: `done` is offered once the chosen cards total N; with nothing left to choose it's done.
49
+ def finishable?(entries) = entries.sum { it["mana_value"].to_i } >= evidence
50
+
51
+ def chosen?(engine, object, entries, done)
52
+ finishable?(entries) && (done || choice_options(engine, object, entries).empty?)
53
+ end
54
+
55
+ def cards_text = "cards with total mana value #{evidence} or greater"
56
+ def to_s = "Collect evidence #{evidence}"
57
+ end
58
+ end
59
+ end
60
+ end