enjine 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -0
  3. data/SUPPORTED.md +31 -23
  4. data/docs/guides/card-data-format.md +106 -1
  5. data/docs/plans/dsl-gaps.md +23 -0
  6. data/docs/reference/abilities.md +46 -13
  7. data/docs/reference/costs.md +23 -6
  8. data/docs/reference/decisions.md +4 -0
  9. data/docs/reference/effects.md +108 -18
  10. data/docs/reference/filters.md +19 -2
  11. data/docs/reference/keywords.md +16 -2
  12. data/docs/reference/triggers.md +25 -6
  13. data/lib/enjine/actions/play_land.rb +3 -1
  14. data/lib/enjine/card_definition.rb +4 -3
  15. data/lib/enjine/cli/text.rb +10 -3
  16. data/lib/enjine/decisions/combat.rb +4 -2
  17. data/lib/enjine/decisions/damage_order.rb +18 -0
  18. data/lib/enjine/engine/ability_layers.rb +6 -1
  19. data/lib/enjine/engine/casting/alt_casting.rb +36 -4
  20. data/lib/enjine/engine/casting/cast_choices.rb +13 -1
  21. data/lib/enjine/engine/casting/casting.rb +24 -7
  22. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  23. data/lib/enjine/engine/casting/permissions.rb +13 -14
  24. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  25. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  26. data/lib/enjine/engine/characteristics.rb +3 -2
  27. data/lib/enjine/engine/combat.rb +26 -7
  28. data/lib/enjine/engine/copies.rb +10 -3
  29. data/lib/enjine/engine/damage.rb +49 -0
  30. data/lib/enjine/engine/entering.rb +36 -2
  31. data/lib/enjine/engine/face_down.rb +12 -3
  32. data/lib/enjine/engine/faces.rb +14 -2
  33. data/lib/enjine/engine/follow_ups.rb +4 -1
  34. data/lib/enjine/engine/resolution.rb +46 -1
  35. data/lib/enjine/engine/rules.rb +4 -3
  36. data/lib/enjine/engine/triggers.rb +5 -15
  37. data/lib/enjine/engine/turn_history.rb +16 -1
  38. data/lib/enjine/engine/turn_structure.rb +1 -0
  39. data/lib/enjine/engine/zones.rb +5 -2
  40. data/lib/enjine/events.rb +2 -0
  41. data/lib/enjine/frames.rb +2 -2
  42. data/lib/enjine/mana.rb +3 -0
  43. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  44. data/lib/enjine/mechanics/abilities/damage_replacements.rb +136 -64
  45. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  46. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -20
  47. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  48. data/lib/enjine/mechanics/abilities/static.rb +1 -1
  49. data/lib/enjine/mechanics/card_spec.rb +54 -11
  50. data/lib/enjine/mechanics/costs/base.rb +67 -9
  51. data/lib/enjine/mechanics/costs/behold.rb +21 -5
  52. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  53. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  54. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  55. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  56. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  57. data/lib/enjine/mechanics/effects/base.rb +10 -2
  58. data/lib/enjine/mechanics/effects/become.rb +29 -12
  59. data/lib/enjine/mechanics/effects/copy.rb +56 -19
  60. data/lib/enjine/mechanics/effects/counters.rb +8 -2
  61. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  62. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  63. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  64. data/lib/enjine/mechanics/effects/library.rb +76 -18
  65. data/lib/enjine/mechanics/effects/pay.rb +7 -4
  66. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  67. data/lib/enjine/mechanics/effects/search.rb +34 -6
  68. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  69. data/lib/enjine/mechanics/filters/base.rb +22 -12
  70. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  71. data/lib/enjine/mechanics/filters/stack.rb +14 -8
  72. data/lib/enjine/mechanics/keywords/alternative_costs.rb +10 -6
  73. data/lib/enjine/mechanics/keywords/cards_have.rb +65 -0
  74. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  75. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  76. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  77. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  78. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  79. data/lib/enjine/mechanics/linked.rb +32 -2
  80. data/lib/enjine/mechanics/selector.rb +32 -9
  81. data/lib/enjine/mechanics/triggers/casting.rb +15 -9
  82. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  83. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  84. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +20 -9
  85. data/lib/enjine/mechanics/values.rb +10 -3
  86. data/lib/enjine/replacements.rb +3 -2
  87. data/lib/enjine/rules_monitor.rb +13 -2
  88. data/lib/enjine/version.rb +1 -1
  89. data/lib/enjine/view.rb +1 -1
  90. metadata +6 -1
@@ -332,10 +332,11 @@ module Enjine
332
332
  end.uniq.freeze
333
333
  end
334
334
 
335
- # CR 202.2: a card's colors come from its mana cost, unless it has a color indicator (CR 204) or is a
336
- # token whose creating effect gives its colors (CR 111.4): `"colors": ["G"]` (`[]` for colorless).
335
+ # CR 202.2: a card's colors come from its mana cost (a hybrid symbol is each of its colors, CR 202.2d), unless it
336
+ # has a color indicator (CR 204) or is a token whose creating effect gives its colors (CR 111.4): `"colors": ["G"]`
337
+ # (`[]` for colorless).
337
338
  def read_colors(card, errors)
338
- return (@mana_cost.is_a?(Mana::Cost) ? Mana::COLORS.select { @mana_cost.colored.key?(it) } : []).freeze unless card.key?("colors")
339
+ return (@mana_cost.is_a?(Mana::Cost) ? @mana_cost.colors : []).freeze unless card.key?("colors")
339
340
 
340
341
  list = card["colors"]
341
342
  ok = list.is_a?(Array) && list.all? { Mana::COLORS.include?(it.to_s.upcase.to_sym) }
@@ -139,6 +139,8 @@ module Enjine
139
139
  when "assign_damage" then " — #{name_of(decision.details["attacker"])}: #{decision.details["remaining"]} damage left"
140
140
  when "choose_target" then " — target ##{decision.details["index"] + 1}"
141
141
  when "commander_zone" then " — #{name_of(decision.details["object"])} (your commander)"
142
+ when "damage_order"
143
+ " — damage #{decision.details["hit"].split(">").map { name_of(it) }.join(" → ")}"
142
144
  when "choose_target_count" then " — how many for target ##{decision.details["index"] + 1}"
143
145
  else ""
144
146
  end
@@ -161,22 +163,24 @@ module Enjine
161
163
  when "pay_mana"
162
164
  "Pay {#{opt[:mana]}} from mana pool#{" (restricted)" if opt[:restricted]}#{" (made by an artifact)" if opt[:from]}"
163
165
  when "target" then "Target #{name_of(opt[:target])}"
164
- when "cost" then "Use #{name_of(opt[:object])} to pay the cost"
166
+ when "cost" then opt[:creature_type] ? "Choose #{opt[:creature_type]}" : "Use #{name_of(opt[:object])} to pay the cost"
165
167
  when "behold" then "Behold #{name_of(opt[:object])}"
166
168
  when "pay" then opt[:cost] ? "Pay: #{opt[:cost]}" : "Pay"
167
169
  when "cost_option" then @game.pending_decision.details["costs"][opt[:option]]
168
170
  when "cancel" then "Cancel (rewind this cast/activation)"
169
- when "attack" then "Attack #{name_of(opt[:target])} with #{name_of(opt[:object])}"
171
+ when "attack" then "Attack #{name_of(opt[:target])}#{" with #{name_of(opt[:object])}" if opt[:object]}"
170
172
  when "block" then "Block #{name_of(opt[:attacker])} with #{name_of(opt[:object])}"
171
173
  when "assign" then "Assign 1 damage to #{name_of(opt[:object])}"
172
174
  when "done" then "Done"
173
175
  when "source" then "Choose #{name_of(opt[:object])} as the source"
176
+ when "order" then "Apply #{opt[:steps].join(", then ")} (#{opt[:amount]} damage)"
174
177
  when "devour" then "Devour #{name_of(opt[:object])}"
175
178
  when "discard", "bottom", "find" then "#{opt[:type].capitalize} #{name_of(opt[:object])}"
176
179
  when "keep" then "Keep hand"
177
180
  when "call" then "Call #{opt[:call]}"
178
181
  when "mulligan" then "Mulligan"
179
182
  when "play", "draw" then "#{opt[:type].capitalize} first"
183
+ when "card_name", "name" then "Name #{opt[:card_name] || opt[:name]}"
180
184
  else opt.inspect
181
185
  end
182
186
  end
@@ -234,6 +238,7 @@ module Enjine
234
238
  when "trigger_removed" then "#{card_name(ev["card"])}'s triggered ability is removed (#{ev["reason"]})"
235
239
  when "ability_countered" then "#{card_name(ev["card"])}'s ability is countered"
236
240
  when "spell_copied" then "#{ev["player"]} copies #{card_name(ev["card"])}#{targets(ev["targets"])}"
241
+ when "targets_changed" then "#{name_of(ev["object"])} has new targets: #{ev["targets"].map { name_of(it) }.join(", ")}"
237
242
  when "x_announced" then "#{ev["player"]} announces X = #{ev["value"]}"
238
243
  when "payment_finished" then "#{ev["player"]} #{ev["outcome"]}"
239
244
  when "attached" then "#{name_of(ev["object"])} is attached to #{name_of(ev["to"])}"
@@ -258,7 +263,9 @@ module Enjine
258
263
  when "speed_changed" then "#{ev["player"]}: speed #{ev["from"]} → #{ev["to"]}"
259
264
  when "coin_flipped"
260
265
  "#{ev["player"]} flips #{ev["heads"] ? "heads" : "tails"}#{{ true => " and wins", false => " and loses" }[ev["won"]]}"
261
- when "keyword_action" then "#{ev["player"]} #{ev["action"].to_s.tr("_", " ")}#{" #{ev["amount"]}" if ev["amount"]}"
266
+ when "keyword_action"
267
+ verb = ev["action"] == "give_gift" ? "gives a gift" : ev["action"].to_s.tr("_", " ")
268
+ "#{ev["player"]} #{verb}#{" #{ev["amount"]}" if ev["amount"]}"
262
269
  else "#{ev["type"]}: #{ev.except("type")}"
263
270
  end
264
271
  end
@@ -14,11 +14,13 @@ module Enjine
14
14
  end
15
15
 
16
16
  def self.options(engine, _pending)
17
- targets = engine.attack_targets
18
17
  legal = engine.attack_declaration_legal?
19
18
  done = engine.unmet_attack_requirements.empty? && legal ? [DONE] : [] # CR 508.1c-d
20
19
  withdraw = legal ? [] : engine.attackers.keys.map { { type: "withdraw", object: it } }
21
- done + engine.attack_candidates.flat_map { |id| targets.map { { type: "attack", object: id, target: it } } } + withdraw
20
+ attacks = engine.attack_candidates.flat_map do |id|
21
+ engine.attack_targets_for(id).map { { type: "attack", object: id, target: it } }
22
+ end
23
+ done + attacks + withdraw
22
24
  end
23
25
 
24
26
  def self.submit(engine, _pending, option)
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Decisions
5
+ # CR 616.1: the affected player orders the replacement and prevention effects that apply to one damage event
6
+ # (`hit`: "source>recipient"), asked only when orders lead to different results; one choice per result.
7
+ class DamageOrder < Base
8
+ def self.doc
9
+ "Order the effects that apply to damage dealt to you or a permanent you control (CR 616.1): submit one of " \
10
+ '`{type: "order", order: [effect keys], steps: [labels], amount: final damage}` exactly as listed.'
11
+ end
12
+
13
+ def self.options(_engine, pending) = pending["choices"].map { it.transform_keys(&:to_sym) }
14
+ def self.submit(engine, pending, option) = engine.damage_order_answer!(pending, option)
15
+ end
16
+ register("damage_order", DamageOrder)
17
+ end
18
+ end
@@ -18,6 +18,8 @@ module Enjine
18
18
  changes = Mechanics::Counters.keywords(obj.counters).map { |kw| [counter_timestamp(obj, kw.to_s), 0, [:keywords, [kw]]] }
19
19
  # A creature cast with suspend has haste while its caster controls it (CR 702.62a); since it was cast.
20
20
  changes << [0, 0, [:keywords, [:haste]]] if obj.memory["haste_while_controlled_by"] == obj.controller
21
+ # Riot: "if you don't, it gains haste" as it entered (CR 702.136a), an effect with that timestamp.
22
+ changes << [timestamp_of(obj), 0, [:keywords, [:haste]]] if obj.memory["riot_haste"]
21
23
  statics.each do |source, ability|
22
24
  next unless ability.ability_changes? && ability.affects?(obj, source, facts(obj, base))
23
25
 
@@ -94,9 +96,12 @@ module Enjine
94
96
  end
95
97
 
96
98
  # Abilities a resolved effect grants (layer 6, CR 613.1f): the effect's card holds them under its ref.
99
+ # What was chosen as the effect resolved is bound into them ("hexproof from that color", CR 607.2d).
97
100
  def effect_granted_instances(effect)
101
+ chosen = effect["chosen"]
98
102
  catalog.fetch(effect["card"]).effect_granted(effect["ref"]).map do |inst|
99
- AbilityInstance.new(ref: "granted:#{effect["card"]}:#{inst.ref}", ability: inst.ability)
103
+ ability = chosen && inst.ability.respond_to?(:with_chosen) ? inst.ability.with_chosen(chosen) : inst.ability
104
+ AbilityInstance.new(ref: "granted:#{effect["card"]}:#{inst.ref}", ability: ability)
100
105
  end
101
106
  end
102
107
 
@@ -21,8 +21,14 @@ module Enjine
21
21
 
22
22
  # ---- methods ------------------------------------------------------------------------------
23
23
 
24
- # The cards in a hand with an alternative cost (only those can be cast from it with a method).
25
- def alt_cost_hand(player) = player.hand.select { |id| chars(id).abilities.any? { it.ability.kind == :alternative_cost } }
24
+ # The cards in `index`'s hand with an alternative cost (only those can be cast from it with a method): all of
25
+ # them while a permanent of theirs gives cards in their hand one (Abilities::CardsHave).
26
+ def alt_cost_hand(index)
27
+ hand = player(index).hand
28
+ return hand if granted_alt_zones(index).include?(:hand)
29
+
30
+ hand.select { |id| chars(id).abilities.any? { it.ability.kind == :alternative_cost } }
31
+ end
26
32
 
27
33
  # A card in a graveyard or library, not a copy, with no face that has an ability to play itself
28
34
  # (CardDefinition#plays_itself?) has no play method (Engine::Permissions#play_methods): a quick no for most candidates.
@@ -41,7 +47,7 @@ module Enjine
41
47
  ability = inst.ability
42
48
  ability.method_for(inst.ref) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
43
49
  end
44
- own + warped_methods(index, obj) + plotted_methods(obj)
50
+ own + granted_alt_methods(index, obj) + warped_methods(index, obj) + plotted_methods(obj)
45
51
  end
46
52
 
47
53
  # CR 702.170d: a plotted card may be cast without paying its mana cost during its owner's main phase while
@@ -51,6 +57,32 @@ module Enjine
51
57
  turn && state.turn > turn ? [{ "via" => "plotted", "play" => "cast", "alt" => Permissions::FREE, "sorcery" => true }] : []
52
58
  end
53
59
 
60
+ GRANTED = "cards_have:"
61
+
62
+ # Alternative costs a permanent `index` controls gives their cards (Abilities::CardsHave, CR 611.3a): the ref
63
+ # "cards_have:<permanent>:<ref>" names the granting ability.
64
+ def granted_alt_methods(index, obj)
65
+ return [] if obj.zone == :outside
66
+
67
+ board_abilities(:cards_have).filter_map do |perm, grant|
68
+ next unless perm.controller == index && grant.functions?(self, obj, index)
69
+
70
+ inst = chars(perm).abilities.find { it.ability.equal?(grant) }
71
+ grant.granted.method_for("#{GRANTED}#{perm.id}:#{inst.ref}")
72
+ end
73
+ end
74
+
75
+ # The zones in which permanents `index` controls give cards an alternative cost (Abilities::CardsHave).
76
+ def granted_alt_zones(index) = board_abilities(:cards_have).filter_map { |perm, grant| grant.zone if perm.controller == index }
77
+
78
+ # The alternative cost ability a method's ref names: the card's own, or one a permanent grants.
79
+ def alt_cost_ability(obj, ref)
80
+ return chars(obj).ability(ref) unless ref.start_with?(GRANTED)
81
+
82
+ perm, inst = ref.delete_prefix(GRANTED).split(":", 2)
83
+ state.objects[perm] && chars(perm).ability(inst)&.granted
84
+ end
85
+
54
86
  # CR 702.185a: "Its owner may cast this card after the current turn has ended for as long as it remains
55
87
  # exiled." The exiled card remembers the turn it was warped in.
56
88
  def warped_methods(_index, obj)
@@ -72,7 +104,7 @@ module Enjine
72
104
  # The non-mana parts of the alternative cost being paid (a list of costs, CR 601.2h).
73
105
  def alt_cost_parts(obj, method)
74
106
  ref = method&.dig("alt", "ref") or return []
75
- chars(obj).ability(ref).choosing_costs
107
+ alt_cost_ability(obj, ref)&.choosing_costs || []
76
108
  end
77
109
 
78
110
  def alt_parts_payable?(obj, method) = alt_cost_parts(obj, method).all? { it.payable?(self, obj) }
@@ -40,10 +40,22 @@ module Enjine
40
40
  obj = object(ctx["object"])
41
41
  spell = spell_ability_of(obj)
42
42
  kick = kicked_castable?(ctx["player"], obj)
43
- plain = ability_targetable?(spell, ctx["player"], obj.id)
43
+ plain = !ctx["flash_by_cost"] && ability_targetable?(spell, ctx["player"], obj.id) # CR 601.3c
44
44
  (kick ? [{ type: "kick" }] : []) + (plain ? [{ type: "no_kick" }] : [])
45
45
  end
46
46
 
47
+ # CR 601.3c: "you may cast this spell as though it had flash if you [pay an optional additional cost]".
48
+ def flash_by_cost?(obj)
49
+ optional = spell_cost_abilities(obj, :kicker).first
50
+ optional.respond_to?(:flash?) && optional.flash?
51
+ end
52
+
53
+ # Whether casting `card` now relies on that cost rather than on its own timing.
54
+ def flash_cost_needed?(index, card)
55
+ c = chars(card)
56
+ !c.type?(:instant) && !c.keyword?(:flash) && !sorcery_timing?(index) && flash_by_cost?(card)
57
+ end
58
+
47
59
  # Whether the spell could be cast kicked: kicker payable, the kicked total affordable and its
48
60
  # kicked targets (or normal ones) available.
49
61
  def kicked_castable?(index, obj)
@@ -14,9 +14,10 @@ module Enjine
14
14
  obj = object(id)
15
15
  defn = definition(obj)
16
16
  return false unless defn.castable?
17
- return false unless defn.instant_speed? || sorcery_timing?(index)
17
+ return false unless defn.instant_speed? || sorcery_timing?(index) || flash_by_cost?(obj)
18
18
  return false if cast_forbidden?(index, obj) # CR 101.2 (Engine::Rules)
19
19
  return false unless additional_costs_payable?(obj) # CR 601.2f: e.g. "sacrifice a creature"
20
+ return kicked_castable?(index, obj) if flash_cost_needed?(index, obj) # CR 601.3c (Engine::CastChoices)
20
21
 
21
22
  if ability_targetable?(defn.spell_ability, index, id) && # CR 601.2b: some way of paying its costs (Engine::CostOptions)
22
23
  cost_variant_affordable?(index, spell_cost_list(obj, false), obj, defn.mana_cost, nil, { "spell" => id }) do
@@ -62,8 +63,9 @@ module Enjine
62
63
  end
63
64
 
64
65
  # CR 118.3, 601.2b: some way of paying its costs (Engine::CostOptions); waterbend: CR 701.67a
66
+ costs = granter_costs(ability.costs, AbilityLayers.granted_parts(ability_ref)&.last)
65
67
  ability_targetable?(ability, index, nil, id, ref: ability_ref) &&
66
- cost_variant_affordable?(index, ability.costs, obj, nil, needs_tap?(ability) ? id : nil, { "ability" => id }) do
68
+ cost_variant_affordable?(index, costs, obj, nil, needs_tap?(ability) ? id : nil, { "ability" => id }) do
67
69
  total_cost(index, it, ability: ability, source: id)
68
70
  end
69
71
  end
@@ -111,6 +113,14 @@ module Enjine
111
113
 
112
114
  def needs_tap?(ability) = ability.costs.any?(Mechanics::Costs::Tap)
113
115
 
116
+ # A granted ability's costs that name the granting permanent ("Tap Fishing Pole", CR 607.1a), bound to
117
+ # `granter` (the permanent whose static ability granted it).
118
+ def granter_costs(costs, granter)
119
+ return costs unless granter && costs.any? { it.respond_to?(:for_granter) }
120
+
121
+ costs.map { it.respond_to?(:for_granter) ? it.for_granter(granter) : it }
122
+ end
123
+
114
124
  # The spell ability of a spell (printed, CR 113.3a).
115
125
  def spell_ability_of(obj) = definition(obj).spell_ability
116
126
 
@@ -130,9 +140,11 @@ module Enjine
130
140
  "index" => state.zone_list(card.zone, card.owner).index(card_id) }
131
141
  origin["memory"] = card.memory.slice("face_down", "may_look") if face_down?(card) # turned face up (CR 406.3a)
132
142
  origin["memory"] = card.memory.slice("prepared_for") if card.memory["prepared_for"] # a prepare spell (CR 723.3c)
143
+ flash_cost = !via && !face && flash_cost_needed?(index, card) # CR 601.3c: the optional cost must be paid
133
144
  obj = move!(card_id, :stack, controller: index, reason: "cast")
134
145
  turn_spell_face!(obj, face) # CR 712.8b, 716.3b, 721.3b
135
146
  extra = method ? { "method" => method } : {}
147
+ extra["flash_by_cost"] = true if flash_cost
136
148
  extra["no_priority"] = true if %w[free resolving].include?(via) # cast while resolving (CR 608.2g)
137
149
  start_casting!(index, obj.id, "spell", origin: origin, extra: extra)
138
150
  end
@@ -248,14 +260,19 @@ module Enjine
248
260
  def choose_target!(ref)
249
261
  ctx = casting
250
262
  add_chosen_target!(ctx, ref)
251
- if ref
252
- queued = state.pending_triggers.size
253
- emit Events::TargetChosen.new(player: name(ctx["player"]), object: ctx["object"], target: ref)
254
- state.pending_triggers.drop(queued).each { it["memory"] = it["memory"].merge("targeted_by" => ctx["object"]) }
255
- end
263
+ became_target!(ctx["player"], ctx["object"], ref) if ref
256
264
  ask!(nil)
257
265
  end
258
266
 
267
+ # `ref` becomes a target of the spell or ability `object` controlled by `player`: as it's cast or put on the
268
+ # stack, when its targets change (CR 115.7) and when a copy is put on the stack with it (CR 707.10).
269
+ # Abilities that trigger then (ward, CR 702.21a) learn which spell or ability targeted it.
270
+ def became_target!(player, object, ref)
271
+ queued = state.pending_triggers.size
272
+ emit Events::TargetChosen.new(player: name(player), object: object, target: ref)
273
+ state.pending_triggers.drop(queued).each { it["memory"] = it["memory"].merge("targeted_by" => object) }
274
+ end
275
+
259
276
  # CR 601.2h-i / 602.2b: remaining costs are paid, the spell becomes cast.
260
277
  def finish_casting!
261
278
  ctx = casting
@@ -52,7 +52,9 @@ module Enjine
52
52
  # additional costs (and kicker's when kicked).
53
53
  def frame_cost_list(ctx)
54
54
  case ctx["kind"]
55
- when "ability" then stack_ability(object(ctx["object"])).costs
55
+ when "ability"
56
+ obj = object(ctx["object"])
57
+ granter_costs(stack_ability(obj).costs, obj.memory["granter"]) # "Tap Fishing Pole" (CR 607.1a)
56
58
  when "spell" then spell_cost_list(object(ctx["object"]), ctx["kicked"])
57
59
  else []
58
60
  end
@@ -30,8 +30,8 @@ module Enjine
30
30
  BEAM_COST_TEXT = "Return a creature you control to its owner's hand"
31
31
  OUTSIDE = "outside:"
32
32
  # Permission effect fields copied into the play method (see Effects::PlayPermission); "alt" is an
33
- # alternative cost, {"cost" => "{2}"} (airbend, CR 701.65a, 118.9).
34
- RIDERS = %w[cost_increase any_mana_type alt exile_instead].freeze
33
+ # alternative cost, {"cost" => "{2}"} (airbend, CR 701.65a, 118.9); "during" and "waterbend": Engine::Waterbending.
34
+ RIDERS = %w[cost_increase any_mana_type alt exile_instead during waterbend].freeze
35
35
 
36
36
  # ---- legal actions --------------------------------------------------------------------
37
37
 
@@ -41,7 +41,7 @@ module Enjine
41
41
  # distinct card) while something lets them play those.
42
42
  def permission_candidates(index, sources = permission_sources(index))
43
43
  pl = player(index)
44
- ids = alt_cost_hand(pl) + pl.graveyard + state.exile + commander_candidates(index)
44
+ ids = alt_cost_hand(index) + pl.graveyard + state.exile + commander_candidates(index)
45
45
  ids += [pl.library.first] unless pl.library.empty?
46
46
  return ids unless sources.any? { |_, inst| inst.ability.kind == :play_from && inst.ability.outside? }
47
47
 
@@ -65,10 +65,10 @@ module Enjine
65
65
 
66
66
  # The options the block makes of each [candidate ref, object, play method]. While no permanent lets `index`
67
67
  # play cards from other zones and no card was granted an ability, a card in a graveyard or library can only
68
- # be played by an ability of its own (#unplayable_elsewhere?).
68
+ # be played by an ability of its own (#unplayable_elsewhere?); nor while one gives cards an alternative cost.
69
69
  def candidate_methods(index, land: false, &)
70
70
  sources = permission_sources(index)
71
- plain = sources.empty? && own_abilities_only?
71
+ plain = sources.empty? && own_abilities_only? && granted_alt_zones(index).empty?
72
72
  permission_candidates(index, sources).flat_map do |ref|
73
73
  obj = candidate_object(index, ref)
74
74
  next [] if (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
@@ -172,8 +172,7 @@ module Enjine
172
172
  return false if returns_creature?(method["alt"]) && return_candidates(index, method["alt"]).empty?
173
173
  return false unless additional_costs_payable?(obj) && alt_parts_payable?(obj, method) # CR 601.2f
174
174
 
175
- # CR 609.4b; a stand-in for a card outside the game is passed itself (it isn't in state.objects).
176
- purpose = { "spell" => state.objects.key?(obj.id) ? obj.id : obj, "any_type" => method["any_mana_type"] }.compact
175
+ purpose = cast_purpose(obj, method) # Engine::Waterbending
177
176
  ability_targetable?(spell_ability_of(obj), index, obj.id) &&
178
177
  cost_variant_affordable?(index, spell_cost_list(obj, false), obj, method_cost(obj, method), nil, purpose) do
179
178
  harmonize_reduced(total_cost(index, it, spell: obj), best_harmonize_power(index, method)) # CR 601.2b
@@ -221,9 +220,9 @@ module Enjine
221
220
  def granted_methods(index, obj)
222
221
  state.effects.filter_map do |e|
223
222
  next unless e["kind"] == "permission" && e["controller"] == index && e["affected"].include?(obj.id)
224
- next unless obj.zone == :exile && may_look?(obj, index)
223
+ next unless obj.zone == :exile && may_look?(obj, index) && (e["during"] != "your_turn" || state.active == index)
225
224
 
226
- { "via" => "effect:#{e["timestamp"]}", "play" => e["play"], **e.slice(*RIDERS) }
225
+ with_waterbend_alt(obj, { "via" => "effect:#{e["timestamp"]}", "play" => e["play"], **e.slice(*RIDERS) })
227
226
  end
228
227
  end
229
228
 
@@ -291,13 +290,13 @@ module Enjine
291
290
 
292
291
  # Permission to play exiled cards for a duration (CR 611.2): a continuous effect for the exiled
293
292
  # objects (a card that leaves exile is a new object, CR 400.7, so the permission ends with it).
294
- # `riders` (RIDERS) change how a card is played with this permission, and only then.
295
- def grant_play_permission!(index, ids, duration:, play:, **riders)
293
+ # `riders` (RIDERS) change how a card is played with this permission, and only then (`source`: CR 611.2b).
294
+ def grant_play_permission!(index, ids, duration:, play:, source: nil, **riders)
296
295
  return if ids.empty?
297
296
 
298
- state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index,
299
- "affected" => ids, "duration" => duration, "turn" => state.turn, "play" => play,
300
- **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }
297
+ state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index, "affected" => ids,
298
+ "duration" => duration, "turn" => state.turn, "play" => play, "source" => source,
299
+ **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }.compact
301
300
  emit Events::EffectStarted.new(kind: "permission", affected: ids, details: { "duration" => duration, "play" => play })
302
301
  end
303
302
 
@@ -100,11 +100,22 @@ module Enjine
100
100
  template.map { it.is_a?(Array) ? flat.shift(it.size) : flat.shift }
101
101
  end
102
102
 
103
- # CR 115.7d: `player` chose new targets for the spell or ability `spell` (shaped like its old ones).
104
- def change_targets!(spell, targets, player)
103
+ # CR 115.7d: new targets for the spell or ability `spell` (shaped like its old ones). Each new target becomes a
104
+ # target of it (ward, "becomes the target", CR 702.21a, 603.2); a division keeps its amounts (CR 115.7f).
105
+ def change_targets!(spell, targets)
105
106
  added = targets.flatten.compact - Array(spell.targets).flatten
107
+ redivide!(spell.memory, spell.targets, targets)
106
108
  spell.targets = targets
107
- added.each { emit Events::TargetChosen.new(player: name(player), object: spell.id, target: it) }
109
+ added.each { became_target!(spell.controller, spell.id, it) }
110
+ emit Events::TargetsChanged.new(player: name(spell.controller), object: spell.id, targets: added) unless added.empty?
111
+ end
112
+
113
+ # CR 115.7f, 601.2d: the amount divided to each target goes to the target that replaced it (a copy with new
114
+ # targets, or new targets chosen for the spell).
115
+ def redivide!(memory, old, new)
116
+ division = memory["division"] or return
117
+ pairs = Array(old).flatten.zip(Array(new).flatten).select { |was, _| division.key?(was) }
118
+ memory["division"] = pairs.to_h { |was, now| [now, division[was]] }
108
119
  end
109
120
  end
110
121
 
@@ -26,10 +26,30 @@ module Enjine
26
26
  abilities.flat_map(&:costs)
27
27
  end
28
28
 
29
- # CR 601.2f: as the total cost is locked in, so is the waterbend cost's generic part.
29
+ # CR 601.2f: as the total cost is locked in, so is the waterbend cost's generic part (with an alternative cost
30
+ # that is a waterbend cost, "cast it by waterbending {X} rather than paying its mana cost").
30
31
  def lock_waterbend!(ctx)
31
32
  costs = frame_costs(ctx) # Engine::CostOptions
32
- ctx["waterbend"] = waterbend_generic(costs, ctx["x"].to_i) if costs.any?(WATERBEND)
33
+ alt = alt_waterbend(ctx["method"])
34
+ ctx["waterbend"] = waterbend_generic(costs, ctx["x"].to_i) + alt.to_i if alt || costs.any?(WATERBEND)
35
+ end
36
+
37
+ # The generic mana of a cast method's waterbend alternative cost (Engine::Permissions#granted_methods), or nil.
38
+ def alt_waterbend(method) = method&.dig("alt", "waterbend") ? Mana::Cost.parse(method["alt"]["cost"]).generic : nil
39
+
40
+ # What paying for `obj` cast with `method` may use: mana of any type (CR 609.4b), tapping for a waterbend
41
+ # alternative cost. A stand-in for a card outside the game is passed itself (it isn't in state.objects).
42
+ def cast_purpose(obj, method)
43
+ { "spell" => state.objects.key?(obj.id) ? obj.id : obj, "any_type" => method["any_mana_type"],
44
+ "waterbend" => alt_waterbend(method) }.compact
45
+ end
46
+
47
+ # A permission's method for `obj`; with "waterbend" => "mana_value" ("cast it by waterbending {X} rather than
48
+ # paying its mana cost, where X is its mana value", CR 118.9) its alternative cost is that waterbend cost.
49
+ def with_waterbend_alt(obj, method)
50
+ return method unless method.delete("waterbend")
51
+
52
+ method.merge("alt" => { "cost" => "{#{chars(obj).mana_cost&.mana_value.to_i}}", "waterbend" => true })
33
53
  end
34
54
 
35
55
  def waterbend_candidates(index, excluded = [])
@@ -99,13 +99,14 @@ module Enjine
99
99
 
100
100
  # Without effects, every permanent is as printed: none has counters or is a noncreature with printed
101
101
  # power and toughness (an uncrewed Vehicle has none, CR 208.3).
102
- # A max speed ability applying changes it too (Engine::Speed).
102
+ # A max speed ability applying changes it too (Engine::Speed), and so do a class level (CR 717.2a), haste while
103
+ # controlled (CR 702.62a) and haste chosen with riot (CR 702.136a).
103
104
  def printed_board?
104
105
  speedy = state.players.each_index.any? { max_speed?(it) }
105
106
  state.battlefield.none? do |id|
106
107
  obj = object(id)
107
108
  !obj.counters.empty? || printed_noncreature_pt?(obj) || (speedy && !active_max_speed(obj, obj.controller).empty?) ||
108
- obj.memory.key?("class_level") || obj.memory.key?("haste_while_controlled_by") # CR 717.2a, 702.62a
109
+ obj.memory.key?("class_level") || obj.memory.key?("haste_while_controlled_by") || obj.memory.key?("riot_haste")
109
110
  end
110
111
  end
111
112
 
@@ -27,7 +27,7 @@ module Enjine
27
27
  obj.controller == state.active && !obj.tapped && current.creature? &&
28
28
  (!current.keyword?(:defender) || current.keyword?(:attacks_despite_defender)) &&
29
29
  !current.keyword?(:cant_attack) && !attackers.key?(id) && !summoning_sick_for_tap?(obj) &&
30
- (only.nil? || only.match?(self, id, state.active))
30
+ (only.nil? || only.match?(self, id, state.active)) && !attack_targets_for(id).empty?
31
31
  end
32
32
  end
33
33
 
@@ -42,6 +42,16 @@ module Enjine
42
42
  state.battlefield.select { |id| object(id).controller == defender && chars(id).planeswalker? }
43
43
  end
44
44
 
45
+ # What creature `id` may attack: not a player with "creatures with flying can't attack you" matching it
46
+ # (CR 508.1c; their planeswalkers still can be attacked).
47
+ def attack_targets_for(id)
48
+ defender = defending_player
49
+ targets = attack_targets
50
+ return targets unless player_rule?(defender, "cant_be_attacked", object(id))
51
+
52
+ targets - [Mechanics::Filters.player_ref(self, defender)]
53
+ end
54
+
45
55
  # Creatures that may be declared next. CR 506.5, 508.1c: one that can't attack alone is offered
46
56
  # only while another creature attacks or could still be declared.
47
57
  def attack_candidates
@@ -70,9 +80,10 @@ module Enjine
70
80
  state.pending_triggers.reject! { it["event"]["type"] == "attacker_declared" && it["event"]["object"] == id }
71
81
  end
72
82
 
73
- # CR 508.4: a creature put onto the battlefield attacking attacks the defending player. (Choosing one
74
- # of their planeswalkers instead isn't offered yet.) It was never declared, so it never "attacked".
75
- # Only called while its controller controls an attacking creature (see Abilities::EntersAttacking).
83
+ # CR 508.4: a creature put onto the battlefield attacking attacks `target` when one was chosen (a token's
84
+ # controller picks a planeswalker in Effects::CreateToken; ninjutsu keeps the attacker's), else the defending
85
+ # player. It was never declared, so it never "attacked". A permanent made to enter attacking by
86
+ # Abilities::EntersAttacking attacks the defending player (no choice can be asked mid-move).
76
87
  def enter_attacking!(obj, target = nil)
77
88
  target = Mechanics::Filters.player_ref(self, state.opponent(obj.controller)) unless target.is_a?(String) # CR 506.3a
78
89
  attackers[obj.id] = { "target" => target, "blocked" => false }
@@ -243,7 +254,10 @@ module Enjine
243
254
  end
244
255
  frame["queue"].shift
245
256
  end
246
- deal_combat_damage!(frame["assigned"])
257
+ hits = combat_hits(frame["assigned"])
258
+ return :wait if ask_damage_orders!(hits, frame, combat: true) == :wait # CR 616.1 (Engine::Damage)
259
+
260
+ with_damage_orders(frame["damage_orders"]) { deal_combat_damage!(hits) }
247
261
  :done
248
262
  end
249
263
 
@@ -269,8 +283,8 @@ module Enjine
269
283
  ask!(nil)
270
284
  end
271
285
 
272
- # CR 510.2: all combat damage in a step is dealt simultaneously.
273
- def deal_combat_damage!(assigned)
286
+ # The combat damage of this step, as assigned: [[source, recipient, amount]] (CR 510.1).
287
+ def combat_hits(assigned)
274
288
  hits = []
275
289
  attackers.each do |id, info|
276
290
  next unless deals_damage_now?(id)
@@ -286,6 +300,11 @@ module Enjine
286
300
  state.blockers.each do |blocker, attacker|
287
301
  hits << [blocker, attacker, combat_damage_amount(blocker)] if deals_damage_now?(blocker)
288
302
  end
303
+ hits
304
+ end
305
+
306
+ # CR 510.2: all combat damage in a step is dealt simultaneously.
307
+ def deal_combat_damage!(hits)
289
308
  simultaneous_damage do # CR 510.2
290
309
  dealt = Hash.new(0)
291
310
  lifelinked = hits.map(&:first).uniq.select { damage_source_keyword?(it, :lifelink) }
@@ -123,11 +123,10 @@ module Enjine
123
123
  copy.kind = "ability"
124
124
  copy.source = spell.source
125
125
  copy.ability = spell.ability
126
- copy.memory = Snapshot.deep_copy(spell.memory.except("trigger_id")) # the copy wasn't triggered
127
- else
128
- copy.memory = Marshal.load(Marshal.dump(spell.memory.slice("kicked", "kicked_with", "gift", "division"))).merge("copy" => "spell")
129
126
  end
127
+ copy.memory = copied_memory(spell)
130
128
  copy.memory["copy_except"] = except unless except.empty?
129
+ redivide!(copy.memory, spell.targets, targets) # CR 115.7f (Engine::TargetCounts)
131
130
  copy.targets = targets
132
131
  copy.modes = spell.modes&.dup
133
132
  copy.x = spell.x
@@ -137,9 +136,17 @@ module Enjine
137
136
  record_result!(copy.id)
138
137
  emit Events::SpellCopied.new(player: name(controller), object: copy.id, card: card, original: spell.id,
139
138
  targets: targets)
139
+ Array(targets).flatten.compact.uniq.each { became_target!(controller, copy.id, it) } # ward (CR 702.21a)
140
140
  copy
141
141
  end
142
142
 
143
+ # What a copy of a spell or ability knows: an ability's copy keeps what the ability knew, but wasn't triggered.
144
+ def copied_memory(spell)
145
+ return Snapshot.deep_copy(spell.memory.except("trigger_id", "ability_lki")) if spell.ability?
146
+
147
+ Snapshot.deep_copy(spell.memory.slice("kicked", "kicked_with", "gift", "division")).merge("copy" => "spell")
148
+ end
149
+
143
150
  # ---- zone changes and state-based actions ------------------------------------------------------
144
151
 
145
152
  # CR 400.7: the new object is the card itself again; a token or copy stays one. A copy of a permanent
@@ -16,6 +16,55 @@ module Enjine
16
16
  dealt
17
17
  end
18
18
 
19
+ # ---- the order of replacement and prevention effects (CR 616.1) ------------------------------------------
20
+
21
+ # The key naming one damage event of an effect or combat in a chosen order.
22
+ def self.hit_key(source, target) = "#{source}>#{target}"
23
+
24
+ # Before damage is dealt (`hits`: [[source, recipient, amount]]), the affected player of each event whose
25
+ # result depends on the order of the effects that apply to it chooses one (CR 616.1), in APNAP order (CR
26
+ # 101.4). The chosen orders are kept in `store` ("damage_orders": the effect's locals, or the combat damage
27
+ # frame). Returns :wait while asking. Not asked while damage is being dealt (follow-ups): the default order.
28
+ def ask_damage_orders!(hits, store, combat: false)
29
+ return if hits.empty? || @damage_orders
30
+
31
+ orders = store["damage_orders"] || {}
32
+ asks = hits.filter_map do |source, ref, amount|
33
+ key = Damage.hit_key(source, ref)
34
+ found = !orders.key?(key) && Mechanics::DamageEvents.orders(self, source, ref, amount, combat)
35
+ [key, *found] if found
36
+ end
37
+ key, chooser, outcomes = asks.min_by { apnap_rank(it[1]) }
38
+ return unless key
39
+
40
+ ask!("kind" => "damage_order", "player" => chooser, "hit" => key,
41
+ "choices" => outcomes.map do |order, amount|
42
+ { "type" => "order", "order" => order.map(&:first), "steps" => order.map(&:last), "amount" => amount }
43
+ end)
44
+ :wait
45
+ end
46
+
47
+ def apnap_rank(index) = (index - state.active) % state.players.size
48
+
49
+ # The affected player answered: the order is kept where #ask_damage_orders! looks for it.
50
+ def damage_order_answer!(pending, option)
51
+ frame = state.frames.last
52
+ store = frame["type"] == "resolve" ? answering_locals : frame
53
+ (store["damage_orders"] ||= {})[pending["hit"]] = option[:order]
54
+ ask!(nil)
55
+ end
56
+
57
+ # Deals damage with the orders chosen for it (#damage_order).
58
+ def with_damage_orders(orders)
59
+ before = @damage_orders
60
+ @damage_orders = orders || {}
61
+ yield
62
+ ensure
63
+ @damage_orders = before
64
+ end
65
+
66
+ def damage_order(hit) = @damage_orders&.[](hit)
67
+
19
68
  # The damage event after replacement and prevention effects (CR 614, 615).
20
69
  def deal_proposed_damage!(source, data, combat, lifelink)
21
70
  amount = data["amount"]