enjine 0.4.1 → 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 (158) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +196 -1
  3. data/README.md +12 -3
  4. data/SUPPORTED.md +73 -38
  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 +146 -9
  9. data/docs/plans/dsl-gaps.md +23 -0
  10. data/docs/reference/abilities.md +299 -25
  11. data/docs/reference/costs.md +59 -6
  12. data/docs/reference/decisions.md +7 -1
  13. data/docs/reference/effects.md +200 -27
  14. data/docs/reference/filters.md +30 -3
  15. data/docs/reference/keywords.md +58 -2
  16. data/docs/reference/subtypes.md +18 -0
  17. data/docs/reference/triggers.md +94 -14
  18. data/docs/reference/types.md +20 -0
  19. data/lib/enjine/actions/play_land.rb +3 -1
  20. data/lib/enjine/actions/special_action.rb +4 -0
  21. data/lib/enjine/actions/turn_face_up.rb +25 -0
  22. data/lib/enjine/actions/unlock.rb +23 -0
  23. data/lib/enjine/card_definition.rb +54 -15
  24. data/lib/enjine/card_face_down.rb +31 -0
  25. data/lib/enjine/card_faces.rb +4 -2
  26. data/lib/enjine/card_rooms.rb +86 -0
  27. data/lib/enjine/catalog.rb +9 -3
  28. data/lib/enjine/cli/text.rb +11 -3
  29. data/lib/enjine/color_identity.rb +34 -1
  30. data/lib/enjine/decisions/casting.rb +6 -3
  31. data/lib/enjine/decisions/combat.rb +4 -2
  32. data/lib/enjine/decisions/damage_order.rb +18 -0
  33. data/lib/enjine/engine/ability_layers.rb +14 -1
  34. data/lib/enjine/engine/casting/alt_casting.rb +45 -5
  35. data/lib/enjine/engine/casting/cast_choices.rb +21 -2
  36. data/lib/enjine/engine/casting/casting.rb +42 -29
  37. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  38. data/lib/enjine/engine/casting/costs.rb +8 -1
  39. data/lib/enjine/engine/casting/payment.rb +47 -9
  40. data/lib/enjine/engine/casting/permissions.rb +19 -17
  41. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  42. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  43. data/lib/enjine/engine/characteristics.rb +11 -11
  44. data/lib/enjine/engine/combat.rb +45 -14
  45. data/lib/enjine/engine/copies.rb +12 -4
  46. data/lib/enjine/engine/crimes.rb +46 -0
  47. data/lib/enjine/engine/damage.rb +85 -1
  48. data/lib/enjine/engine/entering.rb +36 -2
  49. data/lib/enjine/engine/face_down.rb +12 -3
  50. data/lib/enjine/engine/face_down_permanents.rb +108 -0
  51. data/lib/enjine/engine/faces.rb +20 -5
  52. data/lib/enjine/engine/follow_ups.rb +4 -1
  53. data/lib/enjine/engine/mana_sources.rb +18 -3
  54. data/lib/enjine/engine/options_memo.rb +140 -0
  55. data/lib/enjine/engine/permanent_designations.rb +29 -0
  56. data/lib/enjine/engine/resolution.rb +71 -6
  57. data/lib/enjine/engine/rooms.rb +86 -0
  58. data/lib/enjine/engine/rules.rb +6 -4
  59. data/lib/enjine/engine/state_based_actions.rb +25 -4
  60. data/lib/enjine/engine/triggers.rb +25 -20
  61. data/lib/enjine/engine/turn_history.rb +43 -5
  62. data/lib/enjine/engine/turn_structure.rb +1 -0
  63. data/lib/enjine/engine/zones.rb +37 -8
  64. data/lib/enjine/engine.rb +5 -1
  65. data/lib/enjine/events.rb +11 -0
  66. data/lib/enjine/frames.rb +5 -2
  67. data/lib/enjine/fuzz.rb +3 -0
  68. data/lib/enjine/game.rb +3 -1
  69. data/lib/enjine/mana.rb +3 -0
  70. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  71. data/lib/enjine/mechanics/abilities/cost_changes.rb +32 -10
  72. data/lib/enjine/mechanics/abilities/damage_replacements.rb +137 -65
  73. data/lib/enjine/mechanics/abilities/designated.rb +57 -0
  74. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  75. data/lib/enjine/mechanics/abilities/life_replacements.rb +74 -0
  76. data/lib/enjine/mechanics/abilities/mana_ability.rb +10 -4
  77. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -20
  78. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  79. data/lib/enjine/mechanics/abilities/stack_abilities.rb +12 -7
  80. data/lib/enjine/mechanics/abilities/static.rb +19 -6
  81. data/lib/enjine/mechanics/card_spec.rb +63 -11
  82. data/lib/enjine/mechanics/costs/base.rb +68 -9
  83. data/lib/enjine/mechanics/costs/behold.rb +28 -5
  84. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  85. data/lib/enjine/mechanics/costs/collect_evidence.rb +60 -0
  86. data/lib/enjine/mechanics/costs/exile_permanent.rb +41 -0
  87. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  88. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  89. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  90. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  91. data/lib/enjine/mechanics/effects/base.rb +36 -7
  92. data/lib/enjine/mechanics/effects/become.rb +29 -12
  93. data/lib/enjine/mechanics/effects/choose_cards.rb +44 -14
  94. data/lib/enjine/mechanics/effects/copy.rb +58 -21
  95. data/lib/enjine/mechanics/effects/counters.rb +18 -6
  96. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  97. data/lib/enjine/mechanics/effects/delayed_triggers.rb +13 -6
  98. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  99. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  100. data/lib/enjine/mechanics/effects/library.rb +76 -18
  101. data/lib/enjine/mechanics/effects/may.rb +4 -2
  102. data/lib/enjine/mechanics/effects/pay.rb +27 -10
  103. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  104. data/lib/enjine/mechanics/effects/search.rb +34 -6
  105. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  106. data/lib/enjine/mechanics/filters/any_target.rb +6 -3
  107. data/lib/enjine/mechanics/filters/base.rb +36 -17
  108. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  109. data/lib/enjine/mechanics/filters/permanents.rb +7 -0
  110. data/lib/enjine/mechanics/filters/stack.rb +14 -8
  111. data/lib/enjine/mechanics/keywords/alternative_costs.rb +80 -22
  112. data/lib/enjine/mechanics/keywords/cards_have.rb +67 -0
  113. data/lib/enjine/mechanics/keywords/craft.rb +132 -0
  114. data/lib/enjine/mechanics/keywords/cycling.rb +46 -7
  115. data/lib/enjine/mechanics/keywords/extort.rb +2 -0
  116. data/lib/enjine/mechanics/keywords/face_down.rb +165 -0
  117. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  118. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  119. data/lib/enjine/mechanics/keywords/impending.rb +75 -0
  120. data/lib/enjine/mechanics/keywords/increment.rb +2 -0
  121. data/lib/enjine/mechanics/keywords/infinity.rb +46 -0
  122. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  123. data/lib/enjine/mechanics/keywords/miracle.rb +142 -0
  124. data/lib/enjine/mechanics/keywords/ninjutsu.rb +101 -0
  125. data/lib/enjine/mechanics/keywords/offspring.rb +48 -0
  126. data/lib/enjine/mechanics/keywords/persist_and_undying.rb +42 -0
  127. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  128. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  129. data/lib/enjine/mechanics/keywords/split_second.rb +29 -0
  130. data/lib/enjine/mechanics/keywords/storm_and_cascade.rb +5 -0
  131. data/lib/enjine/mechanics/keywords/void.rb +34 -0
  132. data/lib/enjine/mechanics/linked.rb +33 -3
  133. data/lib/enjine/mechanics/mana_spent.rb +1 -1
  134. data/lib/enjine/mechanics/selector.rb +62 -18
  135. data/lib/enjine/mechanics/subtypes/case.rb +68 -0
  136. data/lib/enjine/mechanics/triggers/base.rb +13 -4
  137. data/lib/enjine/mechanics/triggers/casting.rb +15 -9
  138. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  139. data/lib/enjine/mechanics/triggers/crime.rb +28 -0
  140. data/lib/enjine/mechanics/triggers/damage.rb +33 -18
  141. data/lib/enjine/mechanics/triggers/draw_and_discard.rb +19 -6
  142. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  143. data/lib/enjine/mechanics/triggers/rooms.rb +49 -0
  144. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +20 -9
  145. data/lib/enjine/mechanics/triggers/zone_changes.rb +24 -9
  146. data/lib/enjine/mechanics/types/battle.rb +130 -0
  147. data/lib/enjine/mechanics/values.rb +84 -30
  148. data/lib/enjine/replacements.rb +21 -2
  149. data/lib/enjine/rules_monitor.rb +56 -71
  150. data/lib/enjine/snapshot/deep_copy.rb +23 -0
  151. data/lib/enjine/snapshot/player_checks.rb +10 -2
  152. data/lib/enjine/snapshot.rb +2 -1
  153. data/lib/enjine/state.rb +2 -2
  154. data/lib/enjine/verify.rb +10 -3
  155. data/lib/enjine/version.rb +1 -1
  156. data/lib/enjine/view.rb +50 -14
  157. data/lib/enjine.rb +1 -1
  158. metadata +34 -1
@@ -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"]
@@ -40,6 +89,7 @@ module Enjine
40
89
  obj.deathtouched = true if has[:deathtouch] # CR 702.2b
41
90
  end
42
91
  remove_counters!(obj, "loyalty", amount) if defn.planeswalker? # CR 120.3c
92
+ remove_counters!(obj, "defense", amount) if defn.type?(:battle) # CR 120.3h, 310.6
43
93
  end
44
94
  lifelink!(source, amount) if lifelink && has[:lifelink]
45
95
  amount
@@ -54,12 +104,14 @@ module Enjine
54
104
  end
55
105
 
56
106
  # CR 120.6, 120.4a: damage that would be lethal to the creature `id` from `source`, counting damage already
57
- # marked on it (1 if the source has deathtouch, CR 702.2c); a planeswalker's is its loyalty (CR 120.10).
107
+ # marked on it (1 if the source has deathtouch, CR 702.2c); a planeswalker's is its loyalty, a battle's its defense
108
+ # (CR 120.10).
58
109
  # Nil for a player or an object that is neither.
59
110
  def lethal_damage(source, id)
60
111
  obj = state.objects[id]
61
112
  return nil unless obj && state.battlefield.include?(id)
62
113
  return loyalty(obj) if !chars(obj).creature? && chars(obj).planeswalker?
114
+ return obj.counters.fetch("defense", 0) if !chars(obj).creature? && chars(obj).type?(:battle) # CR 310.4c
63
115
  return nil unless chars(obj).creature?
64
116
 
65
117
  lethal = [toughness(obj) - obj.damage, 0].max
@@ -80,6 +132,16 @@ module Enjine
80
132
  @damage_batch = nil
81
133
  end
82
134
 
135
+ # The events of the block are one event batch for "one or more" triggers (CR 603.2c; Engine::Triggering#event_batch),
136
+ # unless an outer block already named one.
137
+ def in_batch(name)
138
+ outer = @event_batch
139
+ @event_batch ||= name
140
+ yield
141
+ ensure
142
+ @event_batch = outer
143
+ end
144
+
83
145
  # Whether a damage source has `keyword` (deathtouch, lifelink, wither): a card (a permanent or a spell) as it
84
146
  # is now; a source no longer in the zone it's expected to be in, as it last existed (CR 702.2e, 702.15c,
85
147
  # 702.80b).
@@ -155,6 +217,28 @@ module Enjine
155
217
  emit Events::PlayerCountersChanged.new(player: pl.name, counter: kind, from: before, to: before + amount)
156
218
  end
157
219
 
220
+ # Removes up to `amount` counters of `kind` from a player (CR 122.1, 122.8). Returns how many came off.
221
+ def remove_player_counters!(index, kind, amount)
222
+ pl = player(index)
223
+ before = player_counters(index).fetch(kind, 0)
224
+ after = [before - amount, 0].max
225
+ return 0 if after == before
226
+
227
+ if kind == "poison" then pl.poison = after
228
+ elsif after.zero? then pl.counters.delete(kind)
229
+ else pl.counters[kind] = after
230
+ end
231
+ emit Events::PlayerCountersChanged.new(player: pl.name, counter: kind, from: before, to: after)
232
+ before - after
233
+ end
234
+
235
+ # CR 122.1: every counter of `kind` (of every kind, if nil) on a player.
236
+ def remove_all_player_counters!(index, kind = nil)
237
+ (kind ? [kind] : player_counters(index).keys.sort).each do
238
+ remove_player_counters!(index, it, player_counters(index).fetch(it, 0))
239
+ end
240
+ end
241
+
158
242
  def remove_counters!(object, kind, amount)
159
243
  before = object.counters.fetch(kind, 0)
160
244
  after = [before - amount, 0].max
@@ -21,7 +21,33 @@ module Enjine
21
21
  abilities = if id.is_a?(GameObject) || state.objects.key?(id) then chars(id).abilities
22
22
  else token_to_create(id).printed_characteristics.abilities
23
23
  end
24
- abilities.map(&:ability).select { it.kind == :entering_choice }
24
+ abilities.map(&:ability).select { it.kind == :entering_choice } + granted_entering_choices(id)
25
+ end
26
+
27
+ # CR 614.12: "as this enters" choices of keywords that static abilities on the battlefield would grant the
28
+ # permanent once it's there ("Other Spiders you control have riot"), judged as it would exist there, under
29
+ # its controller (or its owner's, for a card that has none). A token about to be created isn't judged yet.
30
+ def granted_entering_choices(id)
31
+ obj = id.is_a?(GameObject) ? id : state.objects[id]
32
+ return [] if obj.nil? || obj.zone == :battlefield
33
+
34
+ granting = board_abilities(:static).select { |_, ability| ability.keywords.any? { Entering.entering_keyword?(it) } }
35
+ return [] if granting.empty?
36
+
37
+ stand_in = obj.dup.tap { it.controller ||= it.owner }
38
+ current = chars(obj)
39
+ granting.flat_map do |source, ability|
40
+ next [] unless ability.active?(self, source) && ability.affects?(stand_in, source, facts(obj, current))
41
+
42
+ ability.keywords.flat_map { CardDefinition.keyword_instances(it) }.map(&:ability).select { it.kind == :entering_choice }
43
+ end
44
+ end
45
+
46
+ # Whether a keyword brings an "as this enters" choice (riot).
47
+ def self.entering_keyword?(keyword)
48
+ (@entering_keywords ||= {}).fetch(keyword) do
49
+ @entering_keywords[keyword] = CardDefinition.keyword_instances(keyword).any? { it.ability.kind == :entering_choice }
50
+ end
25
51
  end
26
52
 
27
53
  def entering_choice(id) = entering_choices(id).first
@@ -51,11 +77,18 @@ module Enjine
51
77
  ask!(nil)
52
78
  end
53
79
 
54
- def ask_enter_choice!(id, controller)
80
+ def ask_enter_choice!(id, controller, given = nil)
81
+ before_entering_choice!(id, controller, given)
55
82
  ask!("kind" => "enter_choice", "player" => controller, "object" => id)
56
83
  :wait
57
84
  end
58
85
 
86
+ # What happens just before a choice is asked ("look at an opponent's hand, then choose", CR 701.20e).
87
+ def before_entering_choice!(id, controller, given)
88
+ choice = entering_choices(id)[Entering.answers(given).size]
89
+ choice.before_choice(self, controller) if choice.respond_to?(:before_choice)
90
+ end
91
+
59
92
  def enters_from_answer(id, frame) = entering_statuses(id, Entering.answers(frame["enter"]))
60
93
 
61
94
  # What a permanent enters with given its "as this enters" answers, combined (memories merged, counters
@@ -101,6 +134,7 @@ module Enjine
101
134
  return nil unless id
102
135
 
103
136
  token = state.objects.key?(id) ? {} : { "card" => token_to_create(id).id }
137
+ before_entering_choice!(id, controller, answers[id])
104
138
  ask!({ "kind" => "enter_choice", "player" => controller, "object" => id, "effect" => true }.merge(token))
105
139
  :wait
106
140
  end
@@ -6,14 +6,23 @@ module Enjine
6
6
  FACE_DOWN_ID = "face_down"
7
7
 
8
8
  # Cards exiled face down (CR 406.3, 406.3a-b). Such a card has no characteristics (Engine#chars) and
9
- # only the players in its memory "may_look" see which card it is (View, Events::ZoneChanged). The effect
9
+ # only the players in its memory "may_look" see which card it is (View, Events::ZoneChanged); a hidden-away
10
+ # card (memory "looker_source", CR 702.75a), the player who controls that permanent now. The effect
10
11
  # that exiled it may let a player play it; the card is turned face up just before it's played, so
11
12
  # whether it can be played is judged face up, and only for a player who may look at it.
12
13
  module FaceDown
13
14
  def face_down?(obj) = obj.zone == :exile && obj.memory["face_down"] == true
14
15
 
15
- # Whether `index` may look at the face-down card (always true for a face-up card).
16
- def may_look?(obj, index) = !face_down?(obj) || obj.memory.fetch("may_look", []).include?(index)
16
+ # Whether `index` may look at the face-down card (always true for a face-up card). A hidden-away card's
17
+ # looker follows its permanent's controller while that permanent is on the battlefield (CR 702.75a).
18
+ def may_look?(obj, index)
19
+ return true unless face_down?(obj)
20
+
21
+ source = state.objects[obj.memory["looker_source"]]
22
+ return source.controller == index if source&.zone == :battlefield
23
+
24
+ obj.memory.fetch("may_look", []).include?(index)
25
+ end
17
26
 
18
27
  # Evaluates the block with the face-down card `id` seen face up (CR 406.3a: "turned face up just
19
28
  # before the player announces that they are playing the card"). Nothing in the block changes state.
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Face-down spells and permanents (CR 708): manifested (CR 701.40), cloaked (CR 701.58), and cast face down with
6
+ # morph (CR 702.37) or disguise (CR 702.168). The object's `card` names its face-down characteristics
7
+ # (CardDefinition::FaceDownCards: a nameless 2/2 creature, with ward {2} for cloak and disguise) and they are its
8
+ # copiable values (CR 708.2), so every rule reads them with no special case; the card it really is waits in
9
+ # its memory:
10
+ #
11
+ # memory["face_down_card"] the card's own id (Engine::Copies#own_card reads it)
12
+ # memory["face_down_as"] "manifest" | "cloak" | "morph" | "disguise": what made it face down
13
+ # memory["turned_face_up"] the turn it was turned face up (it's the same object, CR 708.8)
14
+ #
15
+ # Its id doesn't name the card (Engine::FACE_DOWN_ID, like a card exiled face down). Only its controller may
16
+ # look at it (CR 708.5, View and Events::ZoneChanged); it is revealed as it leaves the battlefield or the stack
17
+ # for anywhere but the battlefield, and at the end of the game (CR 708.9).
18
+ module FaceDownPermanents
19
+ AS = { "manifest" => CardDefinition::FaceDownCards::PLAIN, "cloak" => CardDefinition::FaceDownCards::WARD,
20
+ "morph" => CardDefinition::FaceDownCards::PLAIN, "disguise" => CardDefinition::FaceDownCards::WARD }.freeze
21
+
22
+ def face_down_object?(obj) = obj.memory.key?("face_down_card")
23
+
24
+ # CR 708.5: you may look at a face-down spell or permanent you control.
25
+ def sees_face_down?(obj, index) = !face_down_object?(obj) || obj.controller == index
26
+
27
+ # CR 701.40a, 701.58a, 702.37c, 702.168b: it becomes a face-down 2/2 (with ward {2} for cloak and disguise).
28
+ def turn_face_down!(obj, kind)
29
+ obj.memory["face_down_card"] = obj.card
30
+ obj.memory["face_down_as"] = kind
31
+ obj.card = AS.fetch(kind)
32
+ end
33
+
34
+ # The ways `obj` (a face-down permanent) can be turned face up now and their costs (CR 701.40b-d, 701.58b-d,
35
+ # 702.37e, 702.168d): "mana_cost" for a manifested or cloaked creature card with a mana cost, and its own
36
+ # "morph" / "disguise" cost (whatever made it face down).
37
+ def face_up_costs(obj)
38
+ return {} unless face_down_object?(obj) && obj.zone == :battlefield
39
+
40
+ real = catalog.fetch(obj.memory["face_down_card"])
41
+ costs = {}
42
+ costs["mana_cost"] = real.mana_cost if %w[manifest cloak].include?(obj.memory["face_down_as"]) && real.creature? && real.mana_cost
43
+ real.ability_instances.each do |inst|
44
+ ability = inst.ability
45
+ costs[ability.keyword] ||= ability.face_up_cost if ability.respond_to?(:face_up_cost) && ability.face_up_cost
46
+ end
47
+ costs
48
+ end
49
+
50
+ # CR 116.2b: any time they have priority, a player may turn a face-down permanent they control face up.
51
+ def face_up_options(index)
52
+ state.battlefield.flat_map do |id|
53
+ obj = object(id)
54
+ next [] unless obj.controller == index && face_down_object?(obj)
55
+
56
+ face_up_costs(obj).filter_map { |via, cost| { type: "turn_face_up", object: id, via: via } if affordable?(index, cost, nil) }
57
+ end
58
+ end
59
+
60
+ # CR 708.8: its copiable values become its card's; effects that applied to it still apply, and abilities about
61
+ # entering the battlefield don't trigger. An instant or sorcery card is revealed and stays face down
62
+ # (CR 701.40g, 701.58g).
63
+ def turn_face_up!(obj, index = obj.controller)
64
+ return false unless face_down_object?(obj) && obj.zone == :battlefield
65
+
66
+ real = obj.memory["face_down_card"]
67
+ defn = catalog.fetch(real)
68
+ if defn.type?(:instant) || defn.type?(:sorcery)
69
+ emit Events::CardRevealed.new(player: name(index), object: obj.id, card: real)
70
+ return false
71
+ end
72
+ obj.card = obj.memory.delete("face_down_card")
73
+ obj.memory.delete("face_down_as")
74
+ obj.memory["turned_face_up"] = state.turn
75
+ emit Events::TurnedFaceUp.new(player: name(index), object: obj.id, card: real)
76
+ true
77
+ end
78
+
79
+ # CR 701.40a, 701.58a, 701.40f: the top card of `index`'s library is put onto the battlefield face down under
80
+ # their control. Returns the new permanent, or nil.
81
+ def manifest!(index, kind = "manifest", id = player(index).library.first)
82
+ return nil unless id
83
+
84
+ fresh = move!(id, :battlefield, reason: kind, controller: index, face_down_as: kind)
85
+ fresh&.zone == :battlefield ? fresh : nil
86
+ end
87
+
88
+ # CR 708.9: what was face down is revealed to all as it leaves the battlefield (or the stack) for a zone
89
+ # where it isn't public.
90
+ def reveal_face_down_left!(old, fresh)
91
+ return unless face_down_object?(old) && %i[hand library].include?(fresh.zone)
92
+
93
+ emit Events::CardRevealed.new(player: name(old.owner), object: fresh.id, card: fresh.card)
94
+ end
95
+
96
+ # CR 708.9: at the end of the game every face-down permanent and spell is revealed to all.
97
+ def reveal_face_down_at_end!
98
+ (state.battlefield + state.stack).each do |id|
99
+ obj = state.objects[id]
100
+ next unless obj && face_down_object?(obj)
101
+
102
+ emit Events::CardRevealed.new(player: name(obj.owner), object: id, card: obj.memory["face_down_card"])
103
+ end
104
+ end
105
+ end
106
+ include FaceDownPermanents
107
+ end
108
+ end
@@ -13,7 +13,7 @@ module Enjine
13
13
  # memory["melded"] on a melded permanent (its object is one card of the pair, back face up): the
14
14
  # other card's id (CR 713.1a)
15
15
  module Faces
16
- ALTERNATIVE_SPELLS = %w[modal adventure omen].freeze
16
+ ALTERNATIVE_SPELLS = %w[modal adventure omen room].freeze
17
17
 
18
18
  # ---- reading -----------------------------------------------------------------------------
19
19
 
@@ -31,6 +31,7 @@ module Enjine
31
31
  def card_after_move(old, to)
32
32
  own = own_card(old)
33
33
  return own if old.memory["copy"] || (old.zone == :stack && to == :battlefield)
34
+ return room_locked_face(own) if to == :battlefield && catalog.fetch(own).layout == "room" # CR 709.5d (Engine::Rooms)
34
35
 
35
36
  catalog.fetch(own).card.id
36
37
  end
@@ -63,7 +64,7 @@ module Enjine
63
64
  # face is an instant or sorcery (CR 701.27e). It stays the same object (CR 701.27c, 712.15).
64
65
  def transform!(obj)
65
66
  own = catalog.fetch(own_card(obj))
66
- return false unless obj.zone == :battlefield && own.double_faced?
67
+ return false unless obj.zone == :battlefield && own.double_faced? && !face_down_object?(obj)
67
68
 
68
69
  into = own.other_face
69
70
  return false if into.type?(:instant) || into.type?(:sorcery)
@@ -103,8 +104,20 @@ module Enjine
103
104
 
104
105
  state.exile.delete(second.id)
105
106
  state.objects.delete(second.id)
106
- move!(first.id, :battlefield, controller: controller, reason: "meld",
107
- enters: { "face" => 1, "memory" => { "melded" => second.card } })
107
+ melded = move!(first.id, :battlefield, controller: controller, reason: "meld",
108
+ enters: { "face" => 1, "memory" => { "melded" => second.card } })
109
+ # The second card leaves exile too; it's part of the melded permanent, not an object of its own.
110
+ emit Events::ZoneChanged.new(card: second.card, old_id: second.id, new_id: nil, owner: name(second.owner),
111
+ from: "exile", to: "battlefield", reason: "meld")
112
+ melded
113
+ end
114
+
115
+ # CR 713.5c, 202.3c: a melded permanent's mana value is the sum of its front faces' mana values. Nil for any
116
+ # other object (a copy of a melded permanent has the back face's copiable values, so its mana value is 0).
117
+ def melded_mana_value(obj)
118
+ return nil unless obj.zone == :battlefield && obj.memory["melded"] && !obj.memory["own_card"]
119
+
120
+ [obj.card, obj.memory["melded"]].sum { catalog.fetch(it).card.mana_cost&.mana_value.to_i }
108
121
  end
109
122
 
110
123
  # CR 713.8, 713.8c: a melded permanent that leaves the battlefield puts its two cards into the new zone;
@@ -121,11 +134,13 @@ module Enjine
121
134
  # ---- casting another face (CR 712.8b, 716.3, 721.3) ----------------------------------------------
122
135
 
123
136
  # The faces other than the front a card can be cast as: a modal card's nonland faces, an Adventure, an
124
- # Omen. A preparation card's spell is cast only as a copy (CR 723.3).
137
+ # Omen, a Room's doors. A preparation card's spell is cast only as a copy (CR 723.3).
125
138
  def alternative_faces(obj)
126
139
  defn = catalog.fetch(obj.card)
127
140
  return [] if obj.memory["copy"] || defn.face_index.positive? || !ALTERNATIVE_SPELLS.include?(defn.layout)
128
141
 
142
+ return Rooms::DOOR_FACE.values if defn.layout == "room" # CR 709.3: either door, never both (Engine::Rooms)
143
+
129
144
  (1...defn.faces.size).reject { defn.face(it).land? }
130
145
  end
131
146
 
@@ -17,7 +17,10 @@ module Enjine
17
17
  effects = catalog.fetch(entry["card"]).ability(entry["ref"]).effects
18
18
  memory = { "triggering" => seen, "source_card" => entry["card"] }
19
19
  ctx = Mechanics::EffectContext.new(entry["controller"], entry["source"], entry["source"], [], [], [], memory)
20
- effects.each { it.run(self, ctx, {}) } # effects that need no choice (CR 615.5)
20
+ # Effects that need no choice (CR 615.5); with nothing prevented (CR 615.12) no "when damage is prevented
21
+ # this way" triggers.
22
+ effects = effects.grep_v(Mechanics::Effects::ReflexiveTrigger) if entry["unprevented"]
23
+ with_damage_orders(nil) { effects.each { it.run(self, ctx, {}) } }
21
24
  end
22
25
  end
23
26
  end
@@ -12,6 +12,7 @@ module Enjine
12
12
  # lets restricted mana count where it may be spent (CR 106.6).
13
13
  def affordable?(index, cost, excluded_source, purpose = nil)
14
14
  return true if cost.nil? || cost.mana_value.zero?
15
+ return false if @options_memo && cost.equivalents.all? { it.mana_value > mana_unit_bound(index) }
15
16
 
16
17
  covers?(cost, mana_units(index, excluded_source, purpose))
17
18
  end
@@ -54,8 +55,10 @@ module Enjine
54
55
 
55
56
  ability = chars(id).ability(ref)
56
57
  next if ability.mana_cost || (ability.spend_only && !ability.spend_only.allows?(self, purpose))
58
+ next if (granter = tapped_granter(ref, ability)) && excluded.include?(granter)
57
59
 
58
- by_source[id].concat(ability.outcomes(self, object(id)))
60
+ # Abilities that tap the permanent granting them (CR 602.2b) make mana once among them all.
61
+ by_source[granter ? "granter:#{granter}" : id].concat(ability.outcomes(self, object(id)))
59
62
  end
60
63
  units = by_source.values.flat_map { |options| Array.new(options.map(&:size).max) { options.flatten.uniq } }
61
64
  as_any_type(units, purpose)
@@ -102,7 +105,19 @@ module Enjine
102
105
  # CR 602.5b: "Activate only once each turn" counts on the source, as for other activated abilities.
103
106
  def mana_ability_usable?(obj, inst)
104
107
  per_turn = inst.ability.per_turn
105
- (per_turn.nil? || activations_this_turn(obj, inst.ref) < per_turn) && inst.ability.activatable?(self, obj)
108
+ (per_turn.nil? || activations_this_turn(obj, inst.ref) < per_turn) &&
109
+ inst.ability.activatable?(self, obj, mana_ability_costs(inst.ref, inst.ability))
110
+ end
111
+
112
+ # A mana ability's costs, those naming the permanent that granted it bound to it ("tap the granter", CR 602.2b,
113
+ # 607.1a; Engine::Casting#granter_costs).
114
+ def mana_ability_costs(ref, ability) = granter_costs(ability.costs, AbilityLayers.granted_parts(ref)&.last)
115
+
116
+ # The permanent a granted mana ability taps besides its source ({"tap": "granter"}), or nil.
117
+ def tapped_granter(ref, ability)
118
+ return nil unless ability.costs.any?(Mechanics::Costs::TapGranter)
119
+
120
+ mana_ability_costs(ref, ability).find { it.is_a?(Mechanics::Costs::TapGranter) }&.granter
106
121
  end
107
122
 
108
123
  # Activation options for mana abilities: one per source, or one per mana it could add when the
@@ -126,7 +141,7 @@ module Enjine
126
141
  from = mana_provenance(id) # before a cost sacrifices it (a Treasure)
127
142
  record_activation!("source" => id, "ability" => ability_ref) if ability.per_turn
128
143
  pay_from_pool!(index, ability.mana_cost, id) if ability.mana_cost
129
- ability.costs.each { |cost| cost.pay!(self, obj) }
144
+ mana_ability_costs(ability_ref, ability).each { |cost| cost.pay!(self, obj) }
130
145
  produced = chosen || ability.outcomes(self, obj).first # CR 605.3b: a fixed amount is counted as it resolves
131
146
  add_mana!(index, produced, id, restriction: ability.spend_only&.data, from: from)
132
147
  end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Shortcuts used while one decision's legal options are computed (Engine#options). Nothing changes state
6
+ # meanwhile, so facts can be found once and kept in `@options_memo` (dropped when the options are done; never
7
+ # carried to another decision), and some candidates can be ruled out before the full check. Each shortcut gives
8
+ # exactly the answer of the full check; script/determinism_digest.rb compares whole games option by option.
9
+ module OptionsMemo
10
+ EMPTY_LIST = [].freeze
11
+
12
+ # The memo table `key` of the decision whose options are being computed; outside that, a fresh table that is
13
+ # thrown away (so the same code answers, only without keeping anything).
14
+ def options_memo(key, identity: false)
15
+ @options_memo&.[](key) || begin
16
+ table = identity ? {}.compare_by_identity : {}
17
+ @options_memo[key] = table if @options_memo
18
+ table
19
+ end
20
+ end
21
+
22
+ # On the battlefield (Engine::Characteristics#chars): the layer pass's result, or the copiable values of an
23
+ # object no effect modifies. While legal options are computed it is kept for the decision under the object's id
24
+ # (ids are never reused, CR 400.7), but never mid-pass (`@layering`), when it is still partial.
25
+ def board_chars(object)
26
+ return board_characteristics.fetch(object.id) { copy_base(object) } if @options_memo.nil? || @layering
27
+
28
+ @options_memo[object.id] ||= board_characteristics.fetch(object.id) { copy_base(object) }
29
+ end
30
+
31
+ # Permanents `index` controls whose static abilities let them play cards from other zones
32
+ # (Engine::Permissions#scan_permission_sources): asked for the cast and the land options and by each card.
33
+ def permission_sources(index)
34
+ options_memo(:permission_sources)[index] ||= scan_permission_sources(index)
35
+ end
36
+
37
+ # The play methods of a candidate (Engine::Permissions#play_methods): the cast and the land options both ask.
38
+ def candidate_play_methods(index, ref, obj, sources)
39
+ (options_memo(:play_methods)[index] ||= {})[ref] ||= play_methods(index, obj, sources)
40
+ end
41
+
42
+ # Whether Engine::Permissions#candidate_methods can skip the candidate `obj` of `index` (`plain`: no permanent
43
+ # lets them play cards from other zones and no card was granted an ability or an alternative cost; `land`:
44
+ # only lands are asked for):
45
+ # - an exiled card `index` doesn't own can only be played by a permission effect of theirs naming it
46
+ # (Engine::Permissions#granted_methods; every other method needs them to own the card, CR 108.3);
47
+ # - while `plain`, a card in a graveyard or library only by an ability of its own (#unplayable_elsewhere?);
48
+ # - for the land options, a card that isn't a land (seen face up, CR 406.3a).
49
+ def unplayable_candidate?(index, obj, plain, land)
50
+ return true if obj.zone == :exile && obj.owner != index && !permission_named_ids(index).include?(obj.id)
51
+
52
+ (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
53
+ end
54
+
55
+ # The ids of the objects permission effects of `index` name (Engine::Permissions#granted_methods), once per
56
+ # decision.
57
+ def permission_named_ids(index)
58
+ options_memo(:permission_named)[index] ||=
59
+ state.effects.flat_map { it["kind"] == "permission" && it["controller"] == index ? it["affected"] : [] }
60
+ end
61
+
62
+ # The abilities of `chars` (Characteristics) of one kind, in order. Indexed once per Characteristics object
63
+ # while legal options are computed (it is immutable, and the options ask each card about its kicker,
64
+ # additional costs and so on several times).
65
+ def abilities_of_kind(chars, kind)
66
+ by_kind = options_memo(:abilities_by_kind, identity: true)
67
+ (by_kind[chars] ||= chars.abilities.map(&:ability).group_by(&:kind).each_value(&:freeze)).fetch(kind, EMPTY_LIST)
68
+ end
69
+
70
+ # While no effect grants cards abilities (Engine::Casting#own_abilities_only?), a card that isn't a copy has
71
+ # only abilities its card's faces have, printed or nested (Engine::Characteristics#off_board_chars: a
72
+ # characteristic-defining power and toughness or max speed add no other), so the facts of
73
+ # Engine::Casting#card_off_board answer for its characteristics.
74
+ def printed_faces_only?(obj, own_abilities_only)
75
+ own_abilities_only && !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects")
76
+ end
77
+
78
+ # ---- the mana pre-check (CR 601.2f-h) ----------------------------------------------------
79
+
80
+ # An upper bound on how many units ManaSources#mana_units could ever list for `index`, whatever the purpose
81
+ # or excluded source. ManaSources#covers? needs at least a cost's mana value in units (each unit pays one
82
+ # symbol, CR 601.2h), so ManaSources#affordable? rejects a cost above the bound without building the units for
83
+ # each card, and the answer is the same. It counts:
84
+ # - every mana in the pool, restricted or not (#pool_units counts no more);
85
+ # - for each mana ability of #all_mana_sources, its largest outcome, ignoring "spend only" restrictions and
86
+ # mana costs (#source_units counts one source's largest outcome at most, CR 605);
87
+ # - twice each untapped permanent `index` controls that isn't a mana source: once for convoke or improvise
88
+ # (CR 702.51a, 702.126a; #convoke_units counts only those) and once for waterbend (CR 701.67a;
89
+ # #waterbend_units counts only those).
90
+ def mana_unit_bound(index)
91
+ options_memo(:mana_unit_bound)[index] ||= begin
92
+ pl = player(index)
93
+ sources = all_mana_sources(index)
94
+ ids = sources.map(&:first)
95
+ helpers = state.battlefield.count { |id| (obj = object(id)).controller == index && !obj.tapped && !ids.include?(id) }
96
+ pl.mana_pool.sum { |_, n| [n, 0].max } + pl.restricted_mana.size + (2 * helpers) +
97
+ sources.sum { |id, ref| chars(id).ability(ref).outcomes(self, object(id)).map(&:size).max.to_i }
98
+ end
99
+ end
100
+
101
+ # No effect gives a card off the battlefield an ability (CR 113.6b): each has only its own (and its copiable
102
+ # values'), so the quick nos below hold.
103
+ def own_abilities_only? = state.effects.none? { it["kind"] == "card_ability" }
104
+
105
+ # A card that isn't a copy, none of whose faces has an activated ability functioning from the zone it's in
106
+ # (CardDefinition#activation_zones, CR 113.6): nothing of it can be activated there.
107
+ def no_activations_here?(obj)
108
+ !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
109
+ !card_off_board(obj.card)[:activation_zones].include?(obj.zone)
110
+ end
111
+
112
+ # What a card's faces can do off the battlefield (CardDefinition#plays_itself?, #activation_zones,
113
+ # #special_actions?) and the fewest colored and hybrid mana symbols in any face's mana cost (0 if a face has
114
+ # none; Engine::OptionsMemo#mana_out_of_reach?), once per card: printed facts that never change.
115
+ def card_off_board(card)
116
+ (@card_off_board ||= {}.compare_by_identity)[card] ||= catalog.fetch(card).faces.then do |faces|
117
+ { plays_itself: faces.any?(&:plays_itself?), activation_zones: faces.flat_map(&:activation_zones).uniq,
118
+ special_actions: faces.any?(&:special_actions?),
119
+ colored_floor: faces.map { |face| (cost = face.mana_cost) ? cost.colored.values.sum + cost.hybrid.size : 0 }.min }
120
+ end
121
+ end
122
+
123
+ # A quick no for Engine::Casting#castable?: mana can't pay the card's colored and hybrid symbols. Casting from
124
+ # the hand pays the spell's own mana cost, or the kicked cost with more on top (an alternative cost is a
125
+ # method, Engine::Permissions), and cost changes add or remove only generic mana (CR 601.2f; X is 0 until
126
+ # announced, CR 107.3g). So the total cost's mana value is at least that many symbols (each hybrid one at
127
+ # least 1, CR 202.3f), and ManaSources#affordable? would find fewer units than that (#mana_unit_bound). The
128
+ # spell's mana cost is that of one of its card's faces: the characteristics of a card that is a copy (memory
129
+ # "copy_except", "copy_effects") may say otherwise, so it gets the full look.
130
+ def mana_out_of_reach?(index, obj)
131
+ return false unless @options_memo
132
+ return false if obj.memory.key?("copy_except") || obj.memory.key?("copy_effects")
133
+
134
+ card_off_board(obj.card)[:colored_floor] > mana_unit_bound(index)
135
+ end
136
+ end
137
+
138
+ include OptionsMemo
139
+ end
140
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Designations of a permanent that last until it leaves the battlefield and aren't copiable values: "solved"
6
+ # (a Case, CR 720.3b) and "harnessed" (CR 701.64b). Kept in the permanent's memory, so a new object (CR 400.7)
7
+ # has neither. Abilities that work only while it has one: Mechanics::Abilities::DesignatedAbility; conditions
8
+ # {"solved": true} / {"harnessed": true}.
9
+ module PermanentDesignations
10
+ NAMES = %w[solved harnessed].freeze
11
+
12
+ def designated?(obj, designation) = obj.zone == :battlefield && obj.memory[designation] == true
13
+
14
+ # CR 720.3a, 701.64a: "if it isn't [designated], it becomes [designated]". Only a permanent can
15
+ # (CR 701.64b). Returns whether it changed.
16
+ def designate!(obj, designation)
17
+ return false unless obj.zone == :battlefield && !designated?(obj, designation)
18
+
19
+ obj.memory[designation] = true
20
+ emit Events::PermanentDesignated.new(object: obj.id, designation: designation)
21
+ true
22
+ end
23
+
24
+ # The designations a permanent has, for views.
25
+ def permanent_designations(obj) = NAMES.select { designated?(obj, it) }
26
+ end
27
+ include PermanentDesignations
28
+ end
29
+ end