enjine 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +146 -1
  3. data/README.md +12 -3
  4. data/SUPPORTED.md +44 -17
  5. data/docs/ARCHITECTURE.md +7 -2
  6. data/docs/MECHANICS_COVERAGE.md +10 -8
  7. data/docs/guides/api.md +2 -1
  8. data/docs/guides/card-data-format.md +40 -8
  9. data/docs/reference/abilities.md +254 -13
  10. data/docs/reference/costs.md +36 -0
  11. data/docs/reference/decisions.md +3 -1
  12. data/docs/reference/effects.md +93 -10
  13. data/docs/reference/filters.md +11 -1
  14. data/docs/reference/keywords.md +42 -0
  15. data/docs/reference/subtypes.md +18 -0
  16. data/docs/reference/triggers.md +69 -8
  17. data/docs/reference/types.md +20 -0
  18. data/lib/enjine/actions/special_action.rb +4 -0
  19. data/lib/enjine/actions/turn_face_up.rb +25 -0
  20. data/lib/enjine/actions/unlock.rb +23 -0
  21. data/lib/enjine/card_definition.rb +50 -12
  22. data/lib/enjine/card_face_down.rb +31 -0
  23. data/lib/enjine/card_faces.rb +4 -2
  24. data/lib/enjine/card_rooms.rb +86 -0
  25. data/lib/enjine/catalog.rb +9 -3
  26. data/lib/enjine/cli/text.rb +1 -0
  27. data/lib/enjine/color_identity.rb +34 -1
  28. data/lib/enjine/decisions/casting.rb +6 -3
  29. data/lib/enjine/engine/ability_layers.rb +8 -0
  30. data/lib/enjine/engine/casting/alt_casting.rb +12 -4
  31. data/lib/enjine/engine/casting/cast_choices.rb +8 -1
  32. data/lib/enjine/engine/casting/casting.rb +18 -22
  33. data/lib/enjine/engine/casting/costs.rb +8 -1
  34. data/lib/enjine/engine/casting/payment.rb +47 -9
  35. data/lib/enjine/engine/casting/permissions.rb +6 -3
  36. data/lib/enjine/engine/characteristics.rb +8 -9
  37. data/lib/enjine/engine/combat.rb +19 -7
  38. data/lib/enjine/engine/copies.rb +2 -1
  39. data/lib/enjine/engine/crimes.rb +46 -0
  40. data/lib/enjine/engine/damage.rb +36 -1
  41. data/lib/enjine/engine/face_down_permanents.rb +108 -0
  42. data/lib/enjine/engine/faces.rb +6 -3
  43. data/lib/enjine/engine/mana_sources.rb +18 -3
  44. data/lib/enjine/engine/options_memo.rb +140 -0
  45. data/lib/enjine/engine/permanent_designations.rb +29 -0
  46. data/lib/enjine/engine/resolution.rb +25 -5
  47. data/lib/enjine/engine/rooms.rb +86 -0
  48. data/lib/enjine/engine/rules.rb +2 -1
  49. data/lib/enjine/engine/state_based_actions.rb +25 -4
  50. data/lib/enjine/engine/triggers.rb +20 -5
  51. data/lib/enjine/engine/turn_history.rb +28 -5
  52. data/lib/enjine/engine/zones.rb +32 -6
  53. data/lib/enjine/engine.rb +5 -1
  54. data/lib/enjine/events.rb +9 -0
  55. data/lib/enjine/frames.rb +3 -0
  56. data/lib/enjine/fuzz.rb +3 -0
  57. data/lib/enjine/game.rb +3 -1
  58. data/lib/enjine/mechanics/abilities/cost_changes.rb +32 -10
  59. data/lib/enjine/mechanics/abilities/damage_replacements.rb +1 -1
  60. data/lib/enjine/mechanics/abilities/designated.rb +57 -0
  61. data/lib/enjine/mechanics/abilities/life_replacements.rb +74 -0
  62. data/lib/enjine/mechanics/abilities/mana_ability.rb +10 -4
  63. data/lib/enjine/mechanics/abilities/player_rules.rb +1 -1
  64. data/lib/enjine/mechanics/abilities/stack_abilities.rb +12 -7
  65. data/lib/enjine/mechanics/abilities/static.rb +18 -5
  66. data/lib/enjine/mechanics/card_spec.rb +12 -3
  67. data/lib/enjine/mechanics/costs/base.rb +3 -2
  68. data/lib/enjine/mechanics/costs/behold.rb +10 -3
  69. data/lib/enjine/mechanics/costs/choose_creature_type.rb +3 -3
  70. data/lib/enjine/mechanics/costs/collect_evidence.rb +60 -0
  71. data/lib/enjine/mechanics/costs/exile_permanent.rb +41 -0
  72. data/lib/enjine/mechanics/effects/base.rb +26 -5
  73. data/lib/enjine/mechanics/effects/choose_cards.rb +44 -14
  74. data/lib/enjine/mechanics/effects/copy.rb +2 -2
  75. data/lib/enjine/mechanics/effects/counters.rb +12 -6
  76. data/lib/enjine/mechanics/effects/delayed_triggers.rb +13 -6
  77. data/lib/enjine/mechanics/effects/may.rb +4 -2
  78. data/lib/enjine/mechanics/effects/pay.rb +20 -6
  79. data/lib/enjine/mechanics/filters/any_target.rb +6 -3
  80. data/lib/enjine/mechanics/filters/base.rb +14 -5
  81. data/lib/enjine/mechanics/filters/permanents.rb +7 -0
  82. data/lib/enjine/mechanics/keywords/alternative_costs.rb +70 -16
  83. data/lib/enjine/mechanics/keywords/cards_have.rb +4 -2
  84. data/lib/enjine/mechanics/keywords/craft.rb +132 -0
  85. data/lib/enjine/mechanics/keywords/cycling.rb +46 -7
  86. data/lib/enjine/mechanics/keywords/extort.rb +2 -0
  87. data/lib/enjine/mechanics/keywords/face_down.rb +165 -0
  88. data/lib/enjine/mechanics/keywords/impending.rb +75 -0
  89. data/lib/enjine/mechanics/keywords/increment.rb +2 -0
  90. data/lib/enjine/mechanics/keywords/infinity.rb +46 -0
  91. data/lib/enjine/mechanics/keywords/miracle.rb +142 -0
  92. data/lib/enjine/mechanics/keywords/ninjutsu.rb +101 -0
  93. data/lib/enjine/mechanics/keywords/offspring.rb +48 -0
  94. data/lib/enjine/mechanics/keywords/persist_and_undying.rb +42 -0
  95. data/lib/enjine/mechanics/keywords/split_second.rb +29 -0
  96. data/lib/enjine/mechanics/keywords/storm_and_cascade.rb +5 -0
  97. data/lib/enjine/mechanics/keywords/void.rb +34 -0
  98. data/lib/enjine/mechanics/linked.rb +2 -2
  99. data/lib/enjine/mechanics/mana_spent.rb +1 -1
  100. data/lib/enjine/mechanics/selector.rb +30 -9
  101. data/lib/enjine/mechanics/subtypes/case.rb +68 -0
  102. data/lib/enjine/mechanics/triggers/base.rb +13 -4
  103. data/lib/enjine/mechanics/triggers/crime.rb +28 -0
  104. data/lib/enjine/mechanics/triggers/damage.rb +33 -18
  105. data/lib/enjine/mechanics/triggers/draw_and_discard.rb +19 -6
  106. data/lib/enjine/mechanics/triggers/rooms.rb +49 -0
  107. data/lib/enjine/mechanics/triggers/zone_changes.rb +24 -9
  108. data/lib/enjine/mechanics/types/battle.rb +130 -0
  109. data/lib/enjine/mechanics/values.rb +74 -27
  110. data/lib/enjine/replacements.rb +18 -0
  111. data/lib/enjine/rules_monitor.rb +49 -75
  112. data/lib/enjine/snapshot/deep_copy.rb +23 -0
  113. data/lib/enjine/snapshot/player_checks.rb +10 -2
  114. data/lib/enjine/snapshot.rb +2 -1
  115. data/lib/enjine/state.rb +2 -2
  116. data/lib/enjine/verify.rb +10 -3
  117. data/lib/enjine/version.rb +1 -1
  118. data/lib/enjine/view.rb +49 -13
  119. data/lib/enjine.rb +1 -1
  120. metadata +29 -1
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "card_faces"
4
+ require_relative "card_rooms"
5
+ require_relative "card_face_down"
4
6
 
5
7
  module Enjine
6
8
  # Immutable, validated blueprint of a card, built from a data block.
@@ -11,7 +13,7 @@ module Enjine
11
13
  # Enjine.registry. Anything unknown is reported (with its path) in a single
12
14
  # InvalidCardDefinition error.
13
15
  class CardDefinition
14
- KEYS = %w[name mana_cost colors types supertypes subtypes keywords power toughness loyalty abilities rules_text deck_limit
16
+ KEYS = %w[name mana_cost colors types supertypes subtypes keywords power toughness loyalty defense abilities rules_text deck_limit
15
17
  color_identity].freeze
16
18
  # Optional catalogue data beside the rules data, never read by the rules: rarity, and the set code and
17
19
  # collector number printed on the card ({"set" => "trk", "number" => "12"}).
@@ -19,7 +21,7 @@ module Enjine
19
21
  SUBTYPE_FORMAT = /\A[a-z][a-z0-9_]*\z/
20
22
  include Faces
21
23
 
22
- attr_reader :id, :name, :mana_cost, :types, :supertypes, :subtypes, :keywords, :power, :toughness, :loyalty,
24
+ attr_reader :id, :name, :mana_cost, :types, :supertypes, :subtypes, :keywords, :power, :toughness, :loyalty, :defense,
23
25
  :abilities, :rules_text, :type_modules, :source, :colors, :power_amount, :toughness_amount, :rarity, :printing
24
26
 
25
27
  # Canonical id derived from a card name: "Jace, the Mind Sculptor" -> "jace_the_mind_sculptor".
@@ -65,26 +67,30 @@ module Enjine
65
67
  @source = deep_freeze(@source.merge("rarity" => @rarity, "printing" => @printing).compact) if @rarity || @printing
66
68
  @printed_characteristics = Characteristics.printed(self) if errors.empty?
67
69
  @color_identity = ColorIdentity.of(self) if face.nil? && errors.empty? # a face has its card's (see #color_identity)
70
+ precompute_texts if errors.empty?
68
71
  freeze
69
72
  end
70
73
 
71
74
  def read_card(card, errors, token_id, face = nil)
72
75
  (card.keys - KEYS).each { |k| errors << "#{k}: unknown field (allowed: #{(KEYS + PRINT_KEYS).join(", ")})" }
73
- @name = read_name(card, errors)
76
+ blank = (face && Rooms.locked_face?(face, card)) || FaceDownCards.id?(token_id) # no name (CR 709.5, 708.2)
77
+ @name = blank ? "" : read_name(card, errors)
74
78
  @id = face ? "#{face[0].id}#{FACE_SEPARATOR}#{face[1]}" : token_id || self.class.slug(@name)
75
79
  @front, @face_index = face
76
- @token = !token_id.nil?
80
+ @token = !token_id.nil? && !FaceDownCards.id?(token_id)
77
81
  @types, @type_modules = read_names(card, "types", :type, errors, required: true)
78
82
  @supertypes, = read_names(card, "supertypes", :supertype, errors)
79
83
  @subtypes = read_subtypes(card, errors)
80
84
  @mana_cost = card.key?("mana_cost") ? Mana.parse_cost(card["mana_cost"], errors) : nil
81
85
  @keywords, keyword_modules = read_names(card, "keywords", :keyword, errors)
86
+ @keyword_instances = read_keyword_instances(card, keyword_modules)
82
87
  @colors = read_colors(card, errors)
83
88
  @deck_limit = read_deck_limit(card, errors)
84
89
  @declared_color_identity = read_color_identity(card, errors)
85
90
  @power, @power_amount = read_pt(card, "power", errors)
86
91
  @toughness, @toughness_amount = read_pt(card, "toughness", errors)
87
92
  @loyalty = read_stat(card, "loyalty", errors)
93
+ @defense = read_stat(card, "defense", errors) # CR 310.4
88
94
  @rules_text = card["rules_text"]
89
95
  errors << "rules_text: must be a string" unless @rules_text.nil? || @rules_text.is_a?(String)
90
96
  @abilities = read_abilities(card, errors)
@@ -168,6 +174,8 @@ module Enjine
168
174
  # This face has an ability of its own to be played from outside its owner's hand: "you may cast this card
169
175
  # from your graveyard" (CR 113.6e), beam me up (CR 702.196a) or an alternative cost (Engine::Permissions).
170
176
  def plays_itself? = @plays_itself
177
+ # This face has an ability that is a special action from the hand (foretell, suspend, plot: Actions::SpecialAction).
178
+ def special_actions? = @special_actions
171
179
  # The zones this face's activated abilities function from (CR 113.6): [:battlefield], or [:hand] for cycling.
172
180
  attr_reader :activation_zones
173
181
 
@@ -195,11 +203,11 @@ module Enjine
195
203
 
196
204
  def mana_abilities = @ability_instances.map(&:ability).select(&:mana_ability?)
197
205
 
198
- def type_line
199
- left = (@supertypes + @types).map { |t| t.to_s.capitalize }.join(" ")
200
- right = @subtypes.map { |t| t.to_s.split("_").map(&:capitalize).join(" ") }.join(" ")
201
- right.empty? ? left : "#{left} — #{right}"
202
- end
206
+ # The type line, e.g. "Legendary Creature — Elf Druid" (frozen; views show it for every object).
207
+ def type_line = @type_line || build_type_line
208
+
209
+ # The mana cost as symbols ("{2}{G}"), or nil without one (frozen; views show it for every object).
210
+ def mana_cost_text = @mana_cost_text || @mana_cost&.to_s
203
211
 
204
212
  # Canonical data form; CardDefinition.from_h(defn.to_h) == defn.
205
213
  def to_h = @source
@@ -215,11 +223,24 @@ module Enjine
215
223
 
216
224
  private
217
225
 
226
+ def build_type_line
227
+ left = (@supertypes + @types).map { |t| t.to_s.capitalize }.join(" ")
228
+ right = @subtypes.map { |t| t.to_s.split("_").map(&:capitalize).join(" ") }.join(" ")
229
+ right.empty? ? left : "#{left} — #{right}"
230
+ end
231
+
232
+ # Texts a view asks of the definition each time it shows an object: built once, as the definition is immutable.
233
+ def precompute_texts
234
+ @type_line = build_type_line.freeze
235
+ @mana_cost_text = @mana_cost&.to_s&.freeze
236
+ end
237
+
218
238
  # What lets this face be used off the battlefield, from all its abilities (keyword abilities and nested ones too).
219
239
  def precompute_off_board
220
240
  own = @ability_instances.map(&:ability) + @nested_instances.map(&:ability)
221
241
  @plays_itself = own.any? { CardDefinition.self_play?(it) }
222
242
  @activation_zones = own.filter_map { it.zone if %i[activated loyalty].include?(it.kind) }.uniq.freeze
243
+ @special_actions = own.any? { it.respond_to?(:special!) }
223
244
  end
224
245
 
225
246
  def precompute_predicates
@@ -258,6 +279,7 @@ module Enjine
258
279
  errors << "power/toughness: only creatures and Vehicles have power and toughness"
259
280
  end
260
281
  errors << "loyalty: only planeswalkers have loyalty" if !planeswalker? && @loyalty
282
+ errors << "defense: only battles have defense" if !type?(:battle) && @defense # CR 310.4
261
283
  @abilities.each_with_index do |ability, i|
262
284
  allowed = ability.allowed_types
263
285
  next if allowed.nil? || allowed.any? { type?(it) }
@@ -425,8 +447,23 @@ module Enjine
425
447
  end
426
448
  end
427
449
 
428
- # Keyword abilities that stand for an ability ("Station" is an activated ability, CR 702.184a).
429
- def keyword_abilities = @keywords.flat_map { CardDefinition.keyword_instances(it) }
450
+ # Keyword abilities that stand for an ability ("Station" is an activated ability, CR 702.184a). A keyword whose
451
+ # instances each trigger separately (cascade, CR 702.85c) brings its abilities once per instance listed.
452
+ def keyword_abilities
453
+ @keywords.flat_map { |kw| CardDefinition.keyword_instances(kw) * @keyword_instances.fetch(kw, 1) }
454
+ end
455
+
456
+ # How many times each keyword is listed, for the keywords where several instances aren't redundant
457
+ # (`multiple_instances?`: "each instance triggers separately", CR 702.40b, 702.85c, 702.101b, 702.191b). Any
458
+ # other keyword listed twice is one instance (redundant, as in CR 702.2f).
459
+ def read_keyword_instances(card, modules)
460
+ list = card.fetch("keywords", [])
461
+ return {}.freeze unless list.is_a?(Array)
462
+
463
+ repeatable = modules.select { it.respond_to?(:multiple_instances?) && it.multiple_instances? }.map { it.primitive_name.to_sym }
464
+ counts = list.map { it.to_s.downcase.tr(" -", "__").to_sym }.tally
465
+ counts.select { |kw, n| n > 1 && repeatable.include?(kw) }.freeze
466
+ end
430
467
 
431
468
  # Abilities nested in another ability (a station symbol's, CR 722.2), referenced as
432
469
  # "<parent ref>:<j>". They're part of the object's characteristics only while the parent applies.
@@ -445,9 +482,10 @@ module Enjine
445
482
  out["types"] = @types.map(&:to_s)
446
483
  out["supertypes"] = @supertypes.map(&:to_s) unless @supertypes.empty?
447
484
  out["subtypes"] = @subtypes.map(&:to_s) unless @subtypes.empty?
448
- out["keywords"] = @keywords.map(&:to_s) unless @keywords.empty?
485
+ out["keywords"] = @keywords.flat_map { [it.to_s] * @keyword_instances.fetch(it, 1) } unless @keywords.empty?
449
486
  %w[power toughness].each { |key| out[key] = normalized_stat(card, key) unless instance_variable_get("@#{key}").nil? }
450
487
  out["loyalty"] = @loyalty unless @loyalty.nil?
488
+ out["defense"] = @defense unless @defense.nil?
451
489
  out["abilities"] = Snapshot.deep_stringify(card["abilities"]) if card["abilities"].is_a?(Array) && !card["abilities"].empty?
452
490
  out["rules_text"] = @rules_text if @rules_text
453
491
  deep_freeze(out.merge!(deck_building_h))
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class CardDefinition
5
+ # The characteristics a face-down spell or permanent has (CR 708.2): a 2/2 creature with no text, no name, no
6
+ # subtypes and no mana cost (manifest, CR 701.40a; morph, CR 702.37a; CR 708.2a), or the same with ward {2}
7
+ # (cloak, CR 701.58a; disguise, CR 702.168a). They aren't cards of any catalog: every catalog knows them
8
+ # (Catalog#fetch), and a face-down object's `card` names one while the card it really is waits in its memory
9
+ # (Engine::FaceDownPermanents).
10
+ module FaceDownCards
11
+ PLAIN = "face_down_2_2"
12
+ WARD = "face_down_ward"
13
+ DATA = {
14
+ PLAIN => { "name" => "", "types" => ["creature"], "power" => 2, "toughness" => 2 },
15
+ WARD => { "name" => "", "types" => ["creature"], "power" => 2, "toughness" => 2,
16
+ "abilities" => [{ "ward" => { "cost" => [{ "mana" => "{2}" }] } }] }
17
+ }.freeze
18
+
19
+ module_function
20
+
21
+ def id?(id) = DATA.key?(id)
22
+
23
+ # The definition with that id, or nil.
24
+ def fetch(id)
25
+ return nil unless id?(id)
26
+
27
+ (@definitions ||= {})[id] ||= CardDefinition.new(DATA.fetch(id).dup, [], token_id: id)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -24,7 +24,7 @@ module Enjine
24
24
  # CardDefinition with the id "<card id>/<index>"; a game object whose `card` names a face has that
25
25
  # face up (see Engine::Faces).
26
26
  module Faces
27
- LAYOUTS = %w[transform modal adventure omen prepare meld].freeze
27
+ LAYOUTS = %w[transform modal adventure omen prepare meld room].freeze
28
28
  DOUBLE_FACED = %w[transform modal].freeze
29
29
  # Layouts whose faces[1] is a spell the card can be (CR 716.2, 721.2, 723.2).
30
30
  SPELL_FACE = { "adventure" => "adventure", "omen" => "omen", "prepare" => nil }.freeze
@@ -68,7 +68,7 @@ module Enjine
68
68
  def other_face = faces[1 - face_index]
69
69
 
70
70
  # "Alfa // Bravo" for a card with faces.
71
- def full_name = faces.map(&:name).join(" // ")
71
+ def full_name = (layout == "room" ? faces[1..2] : faces).map(&:name).join(" // ")
72
72
 
73
73
  private
74
74
 
@@ -86,6 +86,8 @@ module Enjine
86
86
  list << {} while list.size < 2
87
87
  end
88
88
  front, back = list.map { it.transform_keys(&:to_s) }
89
+ return read_room(card, front, back, errors, token_id) if @layout == "room" # CardDefinition::Rooms
90
+
89
91
  read_card(front, prefixed(errors, "faces[0]"), token_id)
90
92
  @faces = [self, CardDefinition.new(back, prefixed(errors, "faces[1]"), face: [self, 1])].freeze
91
93
  validate_faces(card, errors)
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class CardDefinition
5
+ # Room cards: split cards with a shared type line (CR 709.5), written as
6
+ #
7
+ # {"name": "Left // Right", "layout": "room", "faces": [{...left door...}, {...right door...}]}
8
+ #
9
+ # where each door is a card block with its own name, mana cost and abilities and the same types, supertypes
10
+ # and subtypes (the shared type line, CR 709.5a). The card's own definition (faces[0]) has both halves
11
+ # combined: every zone but the stack sees that (CR 709.4, 709.4b: the mana costs combined). The other faces
12
+ # stand for the permanent's unlocked designations (CR 709.5, 709.5c): faces[1] only the left door unlocked
13
+ # (only its name, mana cost and text), faces[2] only the right door, faces[3] both doors locked (no name, mana
14
+ # cost or text, only the type line). With both doors unlocked a Room permanent is the combined card. A door
15
+ # cast as a spell has only that door (CR 709.3b), so the spell is faces[1] or faces[2] (Engine::Rooms).
16
+ #
17
+ # "When you unlock this door" (trigger `unlocks_door`) written on a door without `door` is about that door:
18
+ # it is tagged "left" or "right" as the card is read.
19
+ module Rooms
20
+ DOORS = %w[left right].freeze
21
+ LOCKED_FACE = 3
22
+
23
+ module_function
24
+
25
+ # The fully locked face (CR 709.5: neither unlocked designation): no name.
26
+ def locked_face?(face, card) = face[1] == LOCKED_FACE && face[0].layout == "room" && card["name"] == ""
27
+
28
+ # "When you unlock this door": the door's own unlock triggers name it.
29
+ def tag_doors(value, door)
30
+ case value
31
+ when Hash
32
+ value.to_h do |key, inner|
33
+ if key.to_s == "unlocks_door" && inner.is_a?(Hash) && !inner.key?("door")
34
+ [key, inner.merge("door" => door)]
35
+ else
36
+ [key, tag_doors(inner, door)]
37
+ end
38
+ end
39
+ when Array then value.map { tag_doors(it, door) }
40
+ else value
41
+ end
42
+ end
43
+
44
+ # The two halves combined (CR 709.4, 709.4b-c): both names, the mana costs added up, every ability.
45
+ def combined(left, right)
46
+ card = left.slice("types", "supertypes", "subtypes")
47
+ card["name"] = "#{left["name"]} // #{right["name"]}"
48
+ cost = [left, right].filter_map { it["mana_cost"] if it["mana_cost"].is_a?(String) }.join
49
+ card["mana_cost"] = cost unless cost.empty?
50
+ %w[keywords abilities colors].each do |key|
51
+ list = [left, right].flat_map { it[key].is_a?(Array) ? it[key] : [] }
52
+ card[key] = key == "abilities" ? list : list.uniq unless list.empty?
53
+ end
54
+ card
55
+ end
56
+
57
+ def locked(left) = left.slice("types", "supertypes", "subtypes").merge("name" => "")
58
+ end
59
+
60
+ private
61
+
62
+ def read_room(card, left, right, errors, token_id)
63
+ left, right = [left, right].zip(Rooms::DOORS).map { |door, side| Rooms.tag_doors(door, side) }
64
+ scratch = []
65
+ read_card(Rooms.combined(left, right), scratch, token_id)
66
+ door_errors = %w[faces[0] faces[1]].map { prefixed(errors, it) }
67
+ doors = [left, right].each_with_index.map { |door, i| CardDefinition.new(door, door_errors[i], face: [self, i + 1]) }
68
+ locked = CardDefinition.new(Rooms.locked(left), scratch, face: [self, Rooms::LOCKED_FACE])
69
+ @faces = [self, *doors, locked].freeze
70
+ validate_room(card, doors, errors)
71
+ scratch.each { errors << "faces: #{it}" } if errors.empty? # what only the combination gets wrong
72
+ @source = deep_freeze({ "name" => full_name, "layout" => "room", "faces" => doors.map(&:to_h) })
73
+ end
74
+
75
+ # CR 709.5, 709.5a: one shared type line, on a permanent card.
76
+ def validate_room(card, doors, errors)
77
+ name = card["name"]
78
+ errors << "name: must be #{full_name.inspect} (the doors' names joined by \" // \")" unless name.nil? || name == full_name
79
+ left, right = doors
80
+ unless %i[types supertypes subtypes].all? { left.public_send(it) == right.public_send(it) }
81
+ errors << "faces[1].types: a Room's doors share one type line (types, supertypes, subtypes, CR 709.5a)"
82
+ end
83
+ errors << "faces[0].types: a Room is a permanent card (CR 709.5)" unless left.permanent?
84
+ end
85
+ end
86
+ end
@@ -36,12 +36,18 @@ module Enjine
36
36
  # Accepts an id ("lightning_bolt") or a display name ("Lightning Bolt"). Ids hit an exact
37
37
  # lookup; only names pay for slugging (Unicode normalization), so the engine's hot path stays cheap.
38
38
  def fetch(ref)
39
- @definitions[ref] || @faces[ref] ||
39
+ @definitions[ref] || @faces[ref] || CardDefinition::FaceDownCards.fetch(ref) ||
40
40
  @definitions.fetch(CardDefinition.slug(ref)) { raise KeyError, "unknown card #{ref.inspect}" }
41
41
  end
42
42
 
43
- def [](ref) = @definitions[ref] || @faces[ref] || @definitions[CardDefinition.slug(ref)]
44
- def include?(ref) = @definitions.key?(ref) || @faces.key?(ref) || @definitions.key?(CardDefinition.slug(ref))
43
+ # Face-down characteristics (CardDefinition::FaceDownCards) are known to every catalog without being listed in it.
44
+ def [](ref) = @definitions[ref] || @faces[ref] || CardDefinition::FaceDownCards.fetch(ref) || @definitions[CardDefinition.slug(ref)]
45
+
46
+ def include?(ref)
47
+ @definitions.key?(ref) || @faces.key?(ref) || CardDefinition::FaceDownCards.id?(ref) ||
48
+ @definitions.key?(CardDefinition.slug(ref))
49
+ end
50
+
45
51
  def ids = @definitions.keys
46
52
  def size = @definitions.size
47
53
  def each(&) = @definitions.each_value(&)
@@ -287,6 +287,7 @@ module Enjine
287
287
  when "sba_lethal_damage" then "#{what} dies (lethal damage)"
288
288
  when "sba_toughness" then "#{what} dies (0 toughness)"
289
289
  when "sba_loyalty" then "#{what} is put into the graveyard (0 loyalty)"
290
+ when "sba_defense" then "#{what} is put into the graveyard (0 defense)"
290
291
  when "countered" then "#{what} is countered"
291
292
  when "commander" then "#{ev["owner"]} puts #{what} into the command zone"
292
293
  when "mulligan_bottom" then "#{ev["owner"]} puts #{what} on the bottom of their library (mulligan)"
@@ -9,6 +9,9 @@ module Enjine
9
9
  module ColorIdentity
10
10
  SKIPPED_KEYS = %w[name rules_text rarity printing color_identity].freeze
11
11
  BASIC_LAND_COLORS = { plains: :W, island: :U, swamp: :B, mountain: :R, forest: :G }.freeze
12
+ # A mana ability ({"mana": {...}}) or an add_mana effect: what it adds is written in its own keys.
13
+ MANA_KEYS = %w[mana add_mana].freeze
14
+ COLOR_WORDS = { "white" => :W, "blue" => :U, "black" => :B, "red" => :R, "green" => :G }.freeze
12
15
 
13
16
  module_function
14
17
 
@@ -28,11 +31,41 @@ module Enjine
28
31
  # The colors named by every mana symbol in the card's data, hybrid and monocolored hybrid symbols included.
29
32
  def symbols(node)
30
33
  case node
31
- when Hash then node.flat_map { |key, value| SKIPPED_KEYS.include?(key) ? [] : symbols(value) }
34
+ when Hash then node.flat_map { |key, value| entry_symbols(key, value) }
32
35
  when Array then node.flat_map { symbols(it) }
33
36
  when String then node.scan(Mana::SYMBOL).flatten.flat_map { it.scan(/[WUBRG]/).map(&:to_sym) }
34
37
  else []
35
38
  end
36
39
  end
40
+
41
+ def entry_symbols(key, value)
42
+ return [] if SKIPPED_KEYS.include?(key)
43
+ return mana_symbols(value) if MANA_KEYS.include?(key) && value.is_a?(Hash)
44
+
45
+ symbols(value)
46
+ end
47
+
48
+ # Mana a card adds counts by the symbols its text would print (CR 903.4): `produce`, and the colors of a choice
49
+ # among some ("Add {B} or {G}": `"color": "any_one", "colors": ["B", "G"]`). Mana "of the chosen color" prints
50
+ # no symbol, so it adds nothing: neither `"color": "chosen"` nor one fixed color gated on the color chosen for
51
+ # the permanent (a Thriving land's {"produce": "{W}", "only_if": {"chosen": "white"}}).
52
+ def mana_symbols(ability)
53
+ rest = symbols(ability.except("produce", "colors"))
54
+ return rest if chosen_color?(ability)
55
+
56
+ choice = %w[any_one any].include?(ability["color"]) ? Array(ability["colors"]).map { it.to_s.to_sym } : []
57
+ rest + symbols(ability["produce"]) + (choice & Mana::COLORS)
58
+ end
59
+
60
+ # Whether the mana is the color chosen for the permanent: only_if {"chosen": <color word>} naming every color
61
+ # it produces.
62
+ def chosen_color?(ability)
63
+ condition = ability["only_if"]
64
+ color = condition.is_a?(Hash) && COLOR_WORDS[condition["chosen"]]
65
+ return false unless color
66
+
67
+ produced = symbols(ability["produce"])
68
+ !produced.empty? && produced.all?(color)
69
+ end
37
70
  end
38
71
  end
@@ -5,8 +5,9 @@ module Enjine
5
5
  CANCEL = { type: "cancel" }.freeze
6
6
 
7
7
  # CR 734.1: a cast or activation can be rewound ("cancel") until something irreversible has been
8
- # paid (Engine::Payment#cancellable?); a triggered ability being put on the stack never can.
9
- def self.with_cancel(engine, options) = engine.cancellable? ? options + [CANCEL] : options
8
+ # paid (Engine::Payment#cancellable?), and also after that when no other choice is left (Engine::Payment#stuck?:
9
+ # a decision never has no option); a triggered ability being put on the stack never can.
10
+ def self.with_cancel(engine, options) = engine.cancellable? || engine.stuck?(options) ? options + [CANCEL] : options
10
11
 
11
12
  # CR 601.2b / 603.3c: choose a mode of a modal spell or ability, one per decision.
12
13
  class ChooseMode < Base
@@ -162,7 +163,9 @@ module Enjine
162
163
  'pool_sources[i] names), `{type: "activate_mana", object: id, ability: ref}` ' \
163
164
  '(plus `mana: "{G}{G}"` when the mana is chosen) taps a source, `{type: "cancel"}` ' \
164
165
  "rewinds (or declines a payment asked for while resolving). Cancel isn't offered once a mana ability " \
165
- "with a cost other than {T} (a Treasure) has been activated. `{type: \"convoke\", object: id}` taps a " \
166
+ "with a cost other than {T} (a Treasure) has been activated, unless the cost can no longer be paid: then " \
167
+ "it is the only option, and rewinds keeping the mana abilities' mana in the pool (CR 734.1). " \
168
+ "`{type: \"convoke\", object: id}` taps a " \
166
169
  "creature to pay for {1} or one mana of its color (a spell with convoke); `{type: \"improvise\", object: id}` " \
167
170
  "taps an artifact to pay for {1} (a spell with improvise); `{type: \"waterbend\", object: id}` taps " \
168
171
  "an artifact or creature to pay {1} of a waterbend cost. `remaining` shows what is left to pay."
@@ -5,6 +5,14 @@ module Enjine
5
5
  # Layers 5 and 6 of the layer pass (Engine::Characteristics#apply_layers): colors, and abilities gained
6
6
  # and lost in timestamp order (CR 613.1e-f, 613.7).
7
7
  module AbilityLayers
8
+ # What a static ability matches a permanent on in the layer pass: characteristics, counters and token-ness,
9
+ # plus combat and tapped status (not characteristics, so reading them never depends on the pass, CR 506.4,
10
+ # 613.8).
11
+ def facts(obj, current)
12
+ status = { "attacking" => attackers.key?(obj.id), "blocking" => state.blockers.key?(obj.id), "tapped" => obj.tapped }
13
+ Mechanics::Filters::Facts.new(chars: current, counters: obj.counters, token: token?(obj), status: status)
14
+ end
15
+
8
16
  # Layer 5 (CR 613.1e): effects that set colors, in timestamp order. Layer 6 (CR 613.1f): keyword counters
9
17
  # (CR 122.1b), keywords and abilities from static abilities and resolved effects, and "loses all
10
18
  # abilities", applied in timestamp order (CR 613.7): a removal takes away what the object had then, and
@@ -27,7 +27,14 @@ module Enjine
27
27
  hand = player(index).hand
28
28
  return hand if granted_alt_zones(index).include?(:hand)
29
29
 
30
- hand.select { |id| chars(id).abilities.any? { it.ability.kind == :alternative_cost } }
30
+ own = own_abilities_only?
31
+ hand.select do |id|
32
+ obj = object(id)
33
+ # no face with an alternative cost (CardDefinition#plays_itself?): a quick no (Casting#printed_faces_only?)
34
+ next false if printed_faces_only?(obj, own) && !card_off_board(obj.card)[:plays_itself]
35
+
36
+ chars(obj).abilities.any? { it.ability.kind == :alternative_cost }
37
+ end
31
38
  end
32
39
 
33
40
  # A card in a graveyard or library, not a copy, with no face that has an ability to play itself
@@ -45,7 +52,7 @@ module Enjine
45
52
 
46
53
  own = face_up(obj.id) { chars(obj).abilities }.filter_map do |inst|
47
54
  ability = inst.ability
48
- ability.method_for(inst.ref) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
55
+ ability.method_for(inst.ref, engine: self, obj: obj) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
49
56
  end
50
57
  own + granted_alt_methods(index, obj) + warped_methods(index, obj) + plotted_methods(obj)
51
58
  end
@@ -68,7 +75,7 @@ module Enjine
68
75
  next unless perm.controller == index && grant.functions?(self, obj, index)
69
76
 
70
77
  inst = chars(perm).abilities.find { it.ability.equal?(grant) }
71
- grant.granted.method_for("#{GRANTED}#{perm.id}:#{inst.ref}")
78
+ grant.granted.method_for("#{GRANTED}#{perm.id}:#{inst.ref}", engine: self, obj: obj)
72
79
  end
73
80
  end
74
81
 
@@ -77,7 +84,8 @@ module Enjine
77
84
 
78
85
  # The alternative cost ability a method's ref names: the card's own, or one a permanent grants.
79
86
  def alt_cost_ability(obj, ref)
80
- return chars(obj).ability(ref) unless ref.start_with?(GRANTED)
87
+ # a spell cast face down has its card's alternative cost (morph, disguise), not its face-down abilities (CR 708.4)
88
+ return (face_down_object?(obj) ? catalog.fetch(own_card(obj)) : chars(obj)).ability(ref) unless ref.start_with?(GRANTED)
81
89
 
82
90
  perm, inst = ref.delete_prefix(GRANTED).split(":", 2)
83
91
  state.objects[perm] && chars(perm).ability(inst)&.granted
@@ -8,7 +8,7 @@ module Enjine
8
8
  module CastChoices
9
9
  # ---- additional costs of spells (CR 601.2b, 601.2f, 702.33) ----------------------------
10
10
 
11
- def spell_cost_abilities(obj, kind) = chars(obj).abilities.map(&:ability).select { it.kind == kind }
11
+ def spell_cost_abilities(obj, kind) = abilities_of_kind(chars(obj), kind)
12
12
 
13
13
  # CR 601.2f / 118.3: the spell's mandatory non-mana additional costs can be paid.
14
14
  def additional_costs_payable?(obj) = spell_cost_abilities(obj, :additional_cost).all? { it.payable?(self, obj) }
@@ -221,6 +221,13 @@ module Enjine
221
221
  # The object a cost is paid for: the ability's source, or the spell itself.
222
222
  def cost_payer(ctx) = object(ctx["kind"] == "ability" ? ctx["source"] : ctx["object"])
223
223
 
224
+ # The spell or ability whose costs are being paid now: the one being cast or activated, else the one resolving
225
+ # (a cost paid while it resolves, CR 118.12). It remembers what its costs chose (a creature type, cards exiled).
226
+ def cost_holder
227
+ id = casting&.[]("object") || state.frames.rfind { it["type"] == "resolve" }&.[]("object")
228
+ id && state.objects[id]
229
+ end
230
+
224
231
  def cost_entries(ctx, index) = (ctx["paid"] || []).select { it["cost"] == index }
225
232
 
226
233
  def cost_choice_candidates
@@ -14,6 +14,8 @@ module Enjine
14
14
  obj = object(id)
15
15
  defn = definition(obj)
16
16
  return false unless defn.castable?
17
+ return false if defn.layout == "room" && defn.face_index.zero? # CR 709.3: a Room is cast as one of its doors
18
+ return false if mana_out_of_reach?(index, obj)
17
19
  return false unless defn.instant_speed? || sorcery_timing?(index) || flash_by_cost?(obj)
18
20
  return false if cast_forbidden?(index, obj) # CR 101.2 (Engine::Rules)
19
21
  return false unless additional_costs_payable?(obj) # CR 601.2f: e.g. "sacrifice a creature"
@@ -29,25 +31,6 @@ module Enjine
29
31
  kicked_castable?(index, obj) # CR 702.33g: only the kicked spell has legal targets
30
32
  end
31
33
 
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
-
51
34
  def activatable?(index, id, ability_ref)
52
35
  obj = object(id)
53
36
  ability = chars(obj).ability(ability_ref)
@@ -55,6 +38,7 @@ module Enjine
55
38
  return false unless obj.zone == ability.zone # CR 113.6: e.g. cycling only from the hand (702.29a)
56
39
  return false if ability.sorcery_speed? && !sorcery_timing?(index)
57
40
  return false if activation_forbidden?(index, obj) # CR 602.5, 101.2 (Engine::Rules)
41
+ return false if Mechanics::Keywords::SplitSecond.active?(self) # CR 702.61b
58
42
  return false unless activation_allowed?(index, obj, ability_ref, ability) # CR 602.5b
59
43
 
60
44
  if (ability.kind == :loyalty) && (obj.loyalty_turn == state.turn || (loyalty(obj) + ability.loyalty_cost).negative?)
@@ -141,11 +125,11 @@ module Enjine
141
125
  origin["memory"] = card.memory.slice("face_down", "may_look") if face_down?(card) # turned face up (CR 406.3a)
142
126
  origin["memory"] = card.memory.slice("prepared_for") if card.memory["prepared_for"] # a prepare spell (CR 723.3c)
143
127
  flash_cost = !via && !face && flash_cost_needed?(index, card) # CR 601.3c: the optional cost must be paid
144
- obj = move!(card_id, :stack, controller: index, reason: "cast")
128
+ obj = move!(card_id, :stack, controller: index, reason: "cast", face_down_as: method&.dig("alt", "face_down")) # CR 708.4
145
129
  turn_spell_face!(obj, face) # CR 712.8b, 716.3b, 721.3b
146
130
  extra = method ? { "method" => method } : {}
147
131
  extra["flash_by_cost"] = true if flash_cost
148
- extra["no_priority"] = true if %w[free resolving].include?(via) # cast while resolving (CR 608.2g)
132
+ extra["no_priority"] = true if %w[free resolving].include?(via) || method&.[]("resolving") # cast while resolving (CR 608.2g)
149
133
  start_casting!(index, obj.id, "spell", origin: origin, extra: extra)
150
134
  end
151
135
 
@@ -233,13 +217,25 @@ module Enjine
233
217
  spec = casting_targets[target_slot(ctx)] # Engine::TargetCounts: a counted slot's list may be open
234
218
  taken = spec.respond_to?(:distinct_from) ? spec.distinct_from.flat_map { Array(ctx["targets"][it]) } : []
235
219
  taken += open_target_group(ctx)
236
- candidates = spec.candidates_for(self, ctx["player"], ctx["source"]).reject do
220
+ candidates = spec.candidates_for(self, ctx["player"], ctx["source"], ctx: x_target_context(ctx)).reject do
237
221
  it == ctx["object"] || taken.include?(it) || !targetable?(it, ctx["player"], ctx["source"],
238
222
  targeter: ctx["source"] || ctx["object"])
239
223
  end
240
224
  sharing_type(candidates, spec, ctx)
241
225
  end
242
226
 
227
+ # CR 601.2b-c: X is announced before targets are chosen, so "target ... with mana value X" reads the X of the
228
+ # spell or ability being cast (a triggered ability's: the cycling ability's X, CR 702.29c). Without an X the
229
+ # filter's own default context applies.
230
+ def x_target_context(ctx) = x_context(ctx["player"], ctx["source"], state.objects[ctx["object"]])
231
+
232
+ # The same as its targets are checked on resolution (CR 608.2b, Engine::Resolution#legal_targets).
233
+ def x_context(controller, source, obj)
234
+ return nil if obj&.x.nil?
235
+
236
+ Mechanics::EffectContext.new(controller, source, obj.id, [], [])
237
+ end
238
+
243
239
  # "Target permanents that share a card type" (`shares_type_with`, CR 205.2a): only candidates sharing one
244
240
  # with the earlier target.
245
241
  def sharing_type(candidates, spec, ctx)
@@ -35,8 +35,15 @@ module Enjine
35
35
  end
36
36
  end
37
37
 
38
- # [[permanent, CostModifier], ...] on the battlefield.
38
+ # [[permanent, CostModifier], ...] on the battlefield; once per decision while legal options are computed
39
+ # (Engine#options: the board holds still meanwhile).
39
40
  def cost_modifiers
41
+ return @options_memo[:cost_modifiers] ||= scan_cost_modifiers if @options_memo
42
+
43
+ scan_cost_modifiers
44
+ end
45
+
46
+ def scan_cost_modifiers
40
47
  state.battlefield.flat_map do |id|
41
48
  obj = object(id)
42
49
  chars(obj).abilities.filter_map { [obj, it.ability] if it.ability.kind == :cost_modifier }