enjine 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -1
  3. data/SUPPORTED.md +34 -26
  4. data/docs/guides/card-data-format.md +143 -1
  5. data/docs/plans/dsl-gaps.md +99 -0
  6. data/docs/reference/abilities.md +46 -13
  7. data/docs/reference/costs.md +23 -6
  8. data/docs/reference/decisions.md +4 -0
  9. data/docs/reference/effects.md +118 -25
  10. data/docs/reference/filters.md +19 -2
  11. data/docs/reference/keywords.md +16 -2
  12. data/docs/reference/triggers.md +28 -7
  13. data/lib/enjine/actions/cast.rb +10 -3
  14. data/lib/enjine/actions/play_land.rb +3 -1
  15. data/lib/enjine/card_definition.rb +19 -3
  16. data/lib/enjine/cli/text.rb +10 -3
  17. data/lib/enjine/decisions/combat.rb +4 -2
  18. data/lib/enjine/decisions/damage_order.rb +18 -0
  19. data/lib/enjine/engine/ability_layers.rb +6 -1
  20. data/lib/enjine/engine/casting/alt_casting.rb +44 -4
  21. data/lib/enjine/engine/casting/cast_choices.rb +13 -1
  22. data/lib/enjine/engine/casting/casting.rb +43 -7
  23. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  24. data/lib/enjine/engine/casting/permissions.rb +27 -23
  25. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  26. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  27. data/lib/enjine/engine/characteristics.rb +32 -14
  28. data/lib/enjine/engine/combat.rb +26 -7
  29. data/lib/enjine/engine/copies.rb +26 -12
  30. data/lib/enjine/engine/damage.rb +51 -1
  31. data/lib/enjine/engine/durations.rb +47 -0
  32. data/lib/enjine/engine/entering.rb +36 -2
  33. data/lib/enjine/engine/face_down.rb +12 -3
  34. data/lib/enjine/engine/faces.rb +16 -2
  35. data/lib/enjine/engine/follow_ups.rb +4 -1
  36. data/lib/enjine/engine/resolution.rb +46 -1
  37. data/lib/enjine/engine/rules.rb +6 -4
  38. data/lib/enjine/engine/state_based_actions.rb +8 -0
  39. data/lib/enjine/engine/triggers.rb +18 -21
  40. data/lib/enjine/engine/turn_history.rb +16 -1
  41. data/lib/enjine/engine/turn_structure.rb +1 -0
  42. data/lib/enjine/engine/zones.rb +23 -4
  43. data/lib/enjine/events.rb +6 -1
  44. data/lib/enjine/frames.rb +2 -2
  45. data/lib/enjine/mana.rb +3 -0
  46. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  47. data/lib/enjine/mechanics/abilities/damage_replacements.rb +136 -64
  48. data/lib/enjine/mechanics/abilities/double_counters.rb +1 -1
  49. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  50. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -19
  51. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  52. data/lib/enjine/mechanics/abilities/replacement_effects.rb +2 -1
  53. data/lib/enjine/mechanics/abilities/static.rb +8 -1
  54. data/lib/enjine/mechanics/card_spec.rb +99 -14
  55. data/lib/enjine/mechanics/costs/base.rb +67 -9
  56. data/lib/enjine/mechanics/costs/behold.rb +21 -5
  57. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  58. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  59. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  60. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  61. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  62. data/lib/enjine/mechanics/effects/base.rb +10 -2
  63. data/lib/enjine/mechanics/effects/become.rb +60 -21
  64. data/lib/enjine/mechanics/effects/copy.rb +63 -23
  65. data/lib/enjine/mechanics/effects/counters.rb +8 -2
  66. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  67. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  68. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  69. data/lib/enjine/mechanics/effects/gain_control.rb +6 -3
  70. data/lib/enjine/mechanics/effects/library.rb +76 -18
  71. data/lib/enjine/mechanics/effects/pay.rb +7 -4
  72. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  73. data/lib/enjine/mechanics/effects/return_to_battlefield.rb +25 -6
  74. data/lib/enjine/mechanics/effects/search.rb +34 -6
  75. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  76. data/lib/enjine/mechanics/filters/base.rb +40 -13
  77. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  78. data/lib/enjine/mechanics/filters/stack.rb +15 -9
  79. data/lib/enjine/mechanics/keywords/alternative_costs.rb +10 -6
  80. data/lib/enjine/mechanics/keywords/cards_have.rb +65 -0
  81. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  82. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  83. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  84. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  85. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  86. data/lib/enjine/mechanics/linked.rb +32 -2
  87. data/lib/enjine/mechanics/selector.rb +32 -9
  88. data/lib/enjine/mechanics/triggers/base.rb +14 -3
  89. data/lib/enjine/mechanics/triggers/casting.rb +16 -10
  90. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  91. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  92. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +38 -11
  93. data/lib/enjine/mechanics/triggers/zone_changes.rb +1 -1
  94. data/lib/enjine/mechanics/values.rb +20 -10
  95. data/lib/enjine/mechanics.rb +5 -0
  96. data/lib/enjine/replacements.rb +3 -2
  97. data/lib/enjine/rules_monitor.rb +17 -4
  98. data/lib/enjine/steps.rb +10 -1
  99. data/lib/enjine/version.rb +1 -1
  100. data/lib/enjine/view.rb +1 -1
  101. metadata +7 -1
@@ -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,22 @@ 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
32
+
33
+ # A card in a graveyard or library, not a copy, with no face that has an ability to play itself
34
+ # (CardDefinition#plays_itself?) has no play method (Engine::Permissions#play_methods): a quick no for most candidates.
35
+ # Exiled cards (permissions, plot, warp, foretell) and a commander always get the full look.
36
+ def unplayable_elsewhere?(obj)
37
+ %i[graveyard library].include?(obj.zone) && !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
38
+ !card_off_board(obj.card)[:plays_itself]
39
+ end
26
40
 
27
41
  # The alternative-cost methods of `obj` (a card `index` owns) that function now. A face-down card its owner
28
42
  # may look at is seen face up (a foretold card, CR 702.143a, 406.3a).
@@ -33,7 +47,7 @@ module Enjine
33
47
  ability = inst.ability
34
48
  ability.method_for(inst.ref) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
35
49
  end
36
- own + warped_methods(index, obj) + plotted_methods(obj)
50
+ own + granted_alt_methods(index, obj) + warped_methods(index, obj) + plotted_methods(obj)
37
51
  end
38
52
 
39
53
  # CR 702.170d: a plotted card may be cast without paying its mana cost during its owner's main phase while
@@ -43,6 +57,32 @@ module Enjine
43
57
  turn && state.turn > turn ? [{ "via" => "plotted", "play" => "cast", "alt" => Permissions::FREE, "sorcery" => true }] : []
44
58
  end
45
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
+
46
86
  # CR 702.185a: "Its owner may cast this card after the current turn has ended for as long as it remains
47
87
  # exiled." The exiled card remembers the turn it was warped in.
48
88
  def warped_methods(_index, obj)
@@ -64,7 +104,7 @@ module Enjine
64
104
  # The non-mana parts of the alternative cost being paid (a list of costs, CR 601.2h).
65
105
  def alt_cost_parts(obj, method)
66
106
  ref = method&.dig("alt", "ref") or return []
67
- chars(obj).ability(ref).choosing_costs
107
+ alt_cost_ability(obj, ref)&.choosing_costs || []
68
108
  end
69
109
 
70
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
@@ -28,6 +29,25 @@ module Enjine
28
29
  kicked_castable?(index, obj) # CR 702.33g: only the kicked spell has legal targets
29
30
  end
30
31
 
32
+ # No effect gives a card off the battlefield an ability (CR 113.6b): each has only its own (and its copiable
33
+ # values'), so the quick nos below hold.
34
+ def own_abilities_only? = state.effects.none? { it["kind"] == "card_ability" }
35
+
36
+ # A card that isn't a copy, none of whose faces has an activated ability functioning from the zone it's in
37
+ # (CardDefinition#activation_zones, CR 113.6): nothing of it can be activated there.
38
+ def no_activations_here?(obj)
39
+ !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
40
+ !card_off_board(obj.card)[:activation_zones].include?(obj.zone)
41
+ end
42
+
43
+ # What a card's faces can do off the battlefield (CardDefinition#plays_itself?, #activation_zones), once per
44
+ # card: printed facts that never change.
45
+ def card_off_board(card)
46
+ (@card_off_board ||= {})[card] ||= catalog.fetch(card).faces.then do |faces|
47
+ { plays_itself: faces.any?(&:plays_itself?), activation_zones: faces.flat_map(&:activation_zones).uniq }
48
+ end
49
+ end
50
+
31
51
  def activatable?(index, id, ability_ref)
32
52
  obj = object(id)
33
53
  ability = chars(obj).ability(ability_ref)
@@ -43,8 +63,9 @@ module Enjine
43
63
  end
44
64
 
45
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)
46
67
  ability_targetable?(ability, index, nil, id, ref: ability_ref) &&
47
- 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
48
69
  total_cost(index, it, ability: ability, source: id)
49
70
  end
50
71
  end
@@ -92,6 +113,14 @@ module Enjine
92
113
 
93
114
  def needs_tap?(ability) = ability.costs.any?(Mechanics::Costs::Tap)
94
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
+
95
124
  # The spell ability of a spell (printed, CR 113.3a).
96
125
  def spell_ability_of(obj) = definition(obj).spell_ability
97
126
 
@@ -111,9 +140,11 @@ module Enjine
111
140
  "index" => state.zone_list(card.zone, card.owner).index(card_id) }
112
141
  origin["memory"] = card.memory.slice("face_down", "may_look") if face_down?(card) # turned face up (CR 406.3a)
113
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
114
144
  obj = move!(card_id, :stack, controller: index, reason: "cast")
115
145
  turn_spell_face!(obj, face) # CR 712.8b, 716.3b, 721.3b
116
146
  extra = method ? { "method" => method } : {}
147
+ extra["flash_by_cost"] = true if flash_cost
117
148
  extra["no_priority"] = true if %w[free resolving].include?(via) # cast while resolving (CR 608.2g)
118
149
  start_casting!(index, obj.id, "spell", origin: origin, extra: extra)
119
150
  end
@@ -229,14 +260,19 @@ module Enjine
229
260
  def choose_target!(ref)
230
261
  ctx = casting
231
262
  add_chosen_target!(ctx, ref)
232
- if ref
233
- queued = state.pending_triggers.size
234
- emit Events::TargetChosen.new(player: name(ctx["player"]), object: ctx["object"], target: ref)
235
- state.pending_triggers.drop(queued).each { it["memory"] = it["memory"].merge("targeted_by" => ctx["object"]) }
236
- end
263
+ became_target!(ctx["player"], ctx["object"], ref) if ref
237
264
  ask!(nil)
238
265
  end
239
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
+
240
276
  # CR 601.2h-i / 602.2b: remaining costs are paid, the spell becomes cast.
241
277
  def finish_casting!
242
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
 
@@ -50,25 +50,30 @@ module Enjine
50
50
 
51
51
  # Priority options: `{type: "cast", object: id, via: method}` for every castable card and method.
52
52
  def permission_cast_options(index)
53
- sources = permission_sources(index)
54
- permission_candidates(index, sources).flat_map do |ref|
55
- obj = candidate_object(index, ref)
56
- play_methods(index, obj, sources).filter_map do |method|
57
- { type: "cast", object: ref, via: method["via"] } if castable_via?(index, obj, method)
58
- end
53
+ candidate_methods(index) do |ref, obj, method|
54
+ { type: "cast", object: ref, via: method["via"] } if castable_via?(index, obj, method)
59
55
  end
60
56
  end
61
57
 
62
- # Priority options: lands `index` may play from outside their hand (CR 305.1, 305.2).
58
+ # Priority options: lands `index` may play from outside their hand (CR 305.1, 305.2). A face-down card is
59
+ # played face up (CR 406.3a).
63
60
  def permission_land_options(index)
61
+ candidate_methods(index, land: true) do |ref, _obj, method|
62
+ { type: "play_land", object: ref, via: method["via"] } if method["play"] == "play"
63
+ end
64
+ end
65
+
66
+ # The options the block makes of each [candidate ref, object, play method]. While no permanent lets `index`
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?); nor while one gives cards an alternative cost.
69
+ def candidate_methods(index, land: false, &)
64
70
  sources = permission_sources(index)
71
+ plain = sources.empty? && own_abilities_only? && granted_alt_zones(index).empty?
65
72
  permission_candidates(index, sources).flat_map do |ref|
66
73
  obj = candidate_object(index, ref)
67
- next [] unless face_up(obj.id) { chars(obj).land? } # a face-down card is played face up (CR 406.3a)
74
+ next [] if (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
68
75
 
69
- play_methods(index, obj, sources).filter_map do |method|
70
- { type: "play_land", object: ref, via: method["via"] } if method["play"] == "play"
71
- end
76
+ play_methods(index, obj, sources).filter_map { yield ref, obj, it }
72
77
  end
73
78
  end
74
79
 
@@ -167,8 +172,7 @@ module Enjine
167
172
  return false if returns_creature?(method["alt"]) && return_candidates(index, method["alt"]).empty?
168
173
  return false unless additional_costs_payable?(obj) && alt_parts_payable?(obj, method) # CR 601.2f
169
174
 
170
- # CR 609.4b; a stand-in for a card outside the game is passed itself (it isn't in state.objects).
171
- 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
172
176
  ability_targetable?(spell_ability_of(obj), index, obj.id) &&
173
177
  cost_variant_affordable?(index, spell_cost_list(obj, false), obj, method_cost(obj, method), nil, purpose) do
174
178
  harmonize_reduced(total_cost(index, it, spell: obj), best_harmonize_power(index, method)) # CR 601.2b
@@ -216,9 +220,9 @@ module Enjine
216
220
  def granted_methods(index, obj)
217
221
  state.effects.filter_map do |e|
218
222
  next unless e["kind"] == "permission" && e["controller"] == index && e["affected"].include?(obj.id)
219
- 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)
220
224
 
221
- { "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) })
222
226
  end
223
227
  end
224
228
 
@@ -286,13 +290,13 @@ module Enjine
286
290
 
287
291
  # Permission to play exiled cards for a duration (CR 611.2): a continuous effect for the exiled
288
292
  # objects (a card that leaves exile is a new object, CR 400.7, so the permission ends with it).
289
- # `riders` (RIDERS) change how a card is played with this permission, and only then.
290
- 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)
291
295
  return if ids.empty?
292
296
 
293
- state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index,
294
- "affected" => ids, "duration" => duration, "turn" => state.turn, "play" => play,
295
- **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
296
300
  emit Events::EffectStarted.new(kind: "permission", affected: ids, details: { "duration" => duration, "play" => play })
297
301
  end
298
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 = [])
@@ -24,12 +24,13 @@ module Enjine
24
24
 
25
25
  # layer 1 (CR 613.2a-c): its copiable values
26
26
  return board_characteristics.fetch(object.id) { copy_base(object) } if object.zone == :battlefield
27
- return @options_memo[object.id] ||= off_board_chars(object) if @options_memo && object.zone == :hand
27
+ return @options_memo[object.id] ||= off_board_chars(object) if @options_memo # the state holds still meanwhile
28
28
 
29
29
  off_board_chars(object)
30
30
  end
31
31
 
32
- # Off the battlefield. The options of one decision ask about each card in hand often (Engine#options).
32
+ # Off the battlefield. The options of one decision ask about each card in hand, graveyard and exile often
33
+ # (Engine#options).
33
34
  def off_board_chars(object)
34
35
  defn = definition(object)
35
36
  base = copy_base(object)
@@ -98,13 +99,14 @@ module Enjine
98
99
 
99
100
  # Without effects, every permanent is as printed: none has counters or is a noncreature with printed
100
101
  # power and toughness (an uncrewed Vehicle has none, CR 208.3).
101
- # 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).
102
104
  def printed_board?
103
105
  speedy = state.players.each_index.any? { max_speed?(it) }
104
106
  state.battlefield.none? do |id|
105
107
  obj = object(id)
106
108
  !obj.counters.empty? || printed_noncreature_pt?(obj) || (speedy && !active_max_speed(obj, obj.controller).empty?) ||
107
- 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")
108
110
  end
109
111
  end
110
112
 
@@ -152,7 +154,8 @@ module Enjine
152
154
  base = with_added_types(base, ability.card_types) unless ability.card_types.empty?
153
155
  subtypes |= ability.added_subtypes(source)
154
156
  end
155
- effects.each { types = it["types"].map(&:to_sym) if it["kind"] == "creature_types" && it["affected"].include?(obj.id) }
157
+ setting = effects.select { it["kind"] == "creature_types" && it["affected"].include?(obj.id) }.last
158
+ types = Mechanics::Effects::Become.creature_types_of(setting) if setting
156
159
  base = base.with(subtypes: ((base.subtypes & Characteristics::NON_CREATURE_SUBTYPES) | types).freeze) if types
157
160
  base = with_gained_subtypes(base, subtypes - base.subtypes) unless (subtypes - base.subtypes).empty?
158
161
  base.creature? || base.power.nil? ? base : base.with(power: nil, toughness: nil)
@@ -178,12 +181,16 @@ module Enjine
178
181
  # "Is a black Skeleton creature" (CR 205.1a): the card types are exactly these, and subtypes correlated with
179
182
  # a card type it no longer has are lost (creature types without creature, an Equipment without artifact).
180
183
  def with_set_types(base, set)
181
- kept = base.subtypes.select do |sub|
184
+ base = base.with(types: set, subtypes: subtypes_of_types(base.subtypes, set))
185
+ base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
186
+ end
187
+
188
+ # The subtypes still correlated with one of the card types `set` (CR 205.1a).
189
+ def subtypes_of_types(subtypes, set)
190
+ subtypes.select do |sub|
182
191
  correlated = CORRELATED_SUBTYPES.find { |_, list| list.include?(sub) }&.first || :creature
183
192
  set.include?(correlated)
184
- end
185
- base = base.with(types: set, subtypes: kept.freeze)
186
- base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
193
+ end.freeze
187
194
  end
188
195
 
189
196
  def printed_noncreature_pt?(obj) = definition(obj).then { !it.creature? && !it.power.nil? }
@@ -284,6 +291,8 @@ module Enjine
284
291
  urzas]
285
292
  }.freeze
286
293
  NON_CREATURE_SUBTYPES = CORRELATED_SUBTYPES.values.flatten.freeze
294
+ # Resolved effects that change card types in layer 4, applied in timestamp order (CR 613.7a).
295
+ TYPE_EFFECTS = %w[add_types set_types].freeze
287
296
 
288
297
  # ---- layers 4 and 7b from the object's own state ------------------------------------
289
298
 
@@ -314,7 +323,7 @@ module Enjine
314
323
  symbols += active_max_speed(obj, obj.controller) + active_class_levels(obj)
315
324
  assimilated = !effects.empty? && effects.any? { it["kind"] == "assimilate" && it["affected"].include?(obj.id) }
316
325
  added = effects.empty? ? [] : added_subtypes(obj, effects)
317
- becomes = effects.empty? ? [] : effects.select { it["kind"] == "add_types" && it["affected"].include?(obj.id) }
326
+ becomes = effects.empty? ? [] : effects.select { TYPE_EFFECTS.include?(it["kind"]) && it["affected"].include?(obj.id) }
318
327
  return printed if symbols.empty? && !assimilated && added.empty? && becomes.empty?
319
328
 
320
329
  attrs = printed.to_h
@@ -326,15 +335,24 @@ module Enjine
326
335
  end
327
336
 
328
337
  # "Becomes an artifact creature", "becomes a legendary Spider Hero in addition to its other types" (CR 205.1b):
329
- # card types, supertypes and subtypes are added, none lost. Power/toughness: see Characteristics#with_added_types.
338
+ # card types, supertypes and subtypes are added, none lost. "It's an enchantment. (It's not a creature.)"
339
+ # (CR 205.1a): the card types are set, losing the subtypes of the others. In timestamp order (CR 613.7a).
340
+ # Power/toughness: see Characteristics#with_added_types.
330
341
  def added_type_layers(attrs, effect)
342
+ if effect["kind"] == "set_types"
343
+ attrs[:types] = effect["types"].map(&:to_sym)
344
+ attrs[:subtypes] = subtypes_of_types(attrs[:subtypes], attrs[:types])
345
+ return become_creature_pt(attrs)
346
+ end
331
347
  attrs[:types] = attrs[:types] | effect["types"].map(&:to_sym)
332
348
  attrs[:supertypes] = attrs[:supertypes] | effect["supertypes"].map(&:to_sym)
333
349
  attrs[:subtypes] = attrs[:subtypes] | effect["subtypes"].map(&:to_sym)
334
- return unless attrs[:types].include?(:creature) && attrs[:power].nil?
350
+ become_creature_pt(attrs)
351
+ end
335
352
 
336
- attrs[:power] = 0
337
- attrs[:toughness] = 0
353
+ # A permanent that becomes a creature without power and toughness is 0/0 (CR 301.7b).
354
+ def become_creature_pt(attrs)
355
+ attrs.merge!(power: 0, toughness: 0) if attrs[:types].include?(:creature) && attrs[:power].nil?
338
356
  end
339
357
 
340
358
  def station_symbol_layers(attrs, inst, defn)
@@ -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) }