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
@@ -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
@@ -30,6 +30,20 @@ module Enjine
30
30
  obj.ability? ? stack_ability(obj) : definition(obj).spell_ability
31
31
  end
32
32
 
33
+ # CR 608.2n, 400.7: a spell that leaves the stack as part of its own resolution ("exile this spell") becomes a
34
+ # new object, but its resolution goes on: its resolve frame keeps the spell as it last existed on the stack
35
+ # ("left_stack"), which stands in for it (Engine#object) for the rest of its effects (a choice, a payment, a
36
+ # reflexive trigger) and as it finishes resolving.
37
+ def note_left_stack!(old)
38
+ frame = state.frames.rfind { it["type"] == "resolve" && it["object"] == old.id } or return
39
+ frame["left_stack"] = old.to_h
40
+ end
41
+
42
+ def resolving_stand_in(id)
43
+ frame = state.frames.rfind { it["type"] == "resolve" && it["object"] == id }
44
+ frame&.key?("left_stack") ? Snapshot.build_object(frame["left_stack"]) : nil
45
+ end
46
+
33
47
  def step_resolution!(frame)
34
48
  obj = object(frame["object"])
35
49
  ability = resolving_ability(obj)
@@ -129,12 +143,18 @@ module Enjine
129
143
  end
130
144
 
131
145
  # `base` is the plan position of the first effect of this effect's list: result n is at base + n.
132
- # A delayed trigger's effects see the results of the list that created it instead.
146
+ # A delayed or reflexive trigger's effects see the results (and amounts) of the earlier effects of the list
147
+ # that created it first, then their own (StackAbility.parse_effects numbers them on, CR 603.7c, 603.12).
133
148
  def effect_context(data, offset = 0, count = nil, base = 0)
134
149
  targets = count ? data["targets"][offset, count] || [] : data["targets"]
135
150
  own = data["results"] || {}
136
- results = data["linked"] || Array.new([own.size - base, 0].max) { own[(base + it).to_s] || [] }
137
- amounts = data["linked_amounts"] || Array.new(results.size) { data.fetch("amounts", {})[(base + it).to_s] || 0 }
151
+ results = Array.new([own.size - base, 0].max) { own[(base + it).to_s] || [] }
152
+ amounts = Array.new(results.size) { data.fetch("amounts", {})[(base + it).to_s] || 0 }
153
+ if (linked = data["linked"])
154
+ linked_amounts = Array.new(linked.size) { data["linked_amounts"]&.[](it).to_i }
155
+ results = linked + results
156
+ amounts = linked_amounts + amounts
157
+ end
138
158
  Mechanics::EffectContext.new(data["controller"], data["source"], data["object"], targets, results, amounts)
139
159
  end
140
160
 
@@ -153,8 +173,8 @@ module Enjine
153
173
  # Targets that are still legal; illegal ones become nil and are ignored (CR 608.2b).
154
174
  def legal_targets(obj, specs)
155
175
  legal = lambda { |ref, spec|
156
- spec&.match_for?(self, ref, obj.controller,
157
- obj.source) && targetable?(ref, obj.controller, obj.source, targeter: obj.source || obj.id)
176
+ spec&.match_for?(self, ref, obj.controller, obj.source, ctx: x_context(obj.controller, obj.source, obj)) &&
177
+ targetable?(ref, obj.controller, obj.source, targeter: obj.source || obj.id)
158
178
  }
159
179
  (obj.targets || []).each_with_index.map do |ref, i|
160
180
  ref.is_a?(Array) ? ref.select { legal.call(it, specs[i]) } : (ref if legal.call(ref, specs[i])) # a counted slot's list
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Room permanents (CR 709.5, CardDefinition::Rooms). Which doors are unlocked is the face the permanent has up:
6
+ # its card is the combined card with both doors unlocked, "<id>/1" with only the left one, "<id>/2" with only
7
+ # the right one and "<id>/3" with neither. So its name, mana cost, mana value and abilities are always those of
8
+ # its unlocked doors (CR 709.5) with no special case elsewhere.
9
+ #
10
+ # A door cast as a spell (CR 709.3) is the spell's face; the permanent it becomes has that door unlocked
11
+ # (CR 709.5d) and "when you unlock this door" triggers (CR 709.5h). A Room put onto the battlefield any other way
12
+ # enters with both doors locked (Engine::Faces#card_after_move). Unlocking is a special action (Actions::Unlock,
13
+ # CR 116.2m, 709.5e).
14
+ module Rooms
15
+ FACE_DOORS = { 0 => %w[left right], 1 => %w[left], 2 => %w[right], 3 => [] }.freeze
16
+ DOOR_FACE = { "left" => 1, "right" => 2 }.freeze
17
+
18
+ def room?(obj) = !obj.memory["own_card"] && catalog.fetch(obj.card).layout == "room"
19
+
20
+ # The doors of a Room permanent that are unlocked (CR 709.5c), and those that are locked.
21
+ def unlocked_doors(obj) = room?(obj) && obj.zone == :battlefield ? FACE_DOORS.fetch(catalog.fetch(obj.card).face_index) : []
22
+ def locked_doors(obj) = room?(obj) && obj.zone == :battlefield ? CardDefinition::Rooms::DOORS - unlocked_doors(obj) : []
23
+
24
+ # A door's unlock cost: its mana cost (CR 709.5e).
25
+ def door_cost(obj, door) = catalog.fetch(obj.card).card.face(DOOR_FACE.fetch(door)).mana_cost
26
+
27
+ # The face a Room card has when it enters the battlefield not as a resolving door spell: both doors locked
28
+ # (CR 709.5d).
29
+ def room_locked_face(card) = catalog.fetch(card).card.face(CardDefinition::Rooms::LOCKED_FACE).id
30
+
31
+ # CR 116.2m, 709.5e: in a main phase of their turn with an empty stack, the player may unlock each locked door
32
+ # of each Room they control that they can pay for.
33
+ def unlock_options(index)
34
+ return [] unless sorcery_timing?(index)
35
+
36
+ state.battlefield.flat_map do |id|
37
+ obj = object(id)
38
+ next [] unless obj.controller == index && room?(obj)
39
+
40
+ locked_doors(obj).filter_map do |door|
41
+ cost = door_cost(obj, door)
42
+ { type: "unlock", object: id, door: door } if cost && affordable?(index, cost, nil)
43
+ end
44
+ end
45
+ end
46
+
47
+ # The permanent gets that door's unlocked designation (CR 709.5c, 709.5f); "when you unlock this door" and "when
48
+ # you fully unlock" trigger (CR 709.5h-i). `player`: who unlocked it.
49
+ def unlock_door!(obj, door, player = obj.controller)
50
+ return false unless locked_doors(obj).include?(door)
51
+
52
+ open = unlocked_doors(obj) + [door]
53
+ set_room_doors!(obj, open)
54
+ emit Events::DoorUnlocked.new(player: name(player), object: obj.id, door: door, fully: open.size == 2)
55
+ true
56
+ end
57
+
58
+ # CR 709.5g: the permanent loses that door's unlocked designation.
59
+ def lock_door!(obj, door)
60
+ return false unless unlocked_doors(obj).include?(door)
61
+
62
+ set_room_doors!(obj, unlocked_doors(obj) - [door])
63
+ emit Events::DoorLocked.new(object: obj.id, door: door)
64
+ true
65
+ end
66
+
67
+ # CR 709.5d, 709.5h: the permanent a door spell became has that door unlocked, which triggers abilities.
68
+ def room_entered!(fresh, old)
69
+ return unless old.zone == :stack && fresh.zone == :battlefield && room?(fresh)
70
+
71
+ door = FACE_DOORS.fetch(catalog.fetch(fresh.card).face_index)
72
+ return unless door.size == 1
73
+
74
+ emit Events::DoorUnlocked.new(player: name(fresh.controller), object: fresh.id, door: door.first, fully: false)
75
+ end
76
+
77
+ private
78
+
79
+ def set_room_doors!(obj, open)
80
+ index = FACE_DOORS.key(CardDefinition::Rooms::DOORS & open)
81
+ obj.card = catalog.fetch(obj.card).card.face(index).id
82
+ end
83
+ end
84
+ include Rooms
85
+ end
86
+ end
@@ -31,7 +31,8 @@ module Enjine
31
31
  # CR 101.2: "can't cast" beats any permission to cast. `obj`: the card (or stand-in) to be cast. The card's own
32
32
  # "you can't cast this spell unless ..." too (CR 601.3).
33
33
  def cast_forbidden?(index, obj)
34
- player_rule?(index, "cant_cast", obj) || (obj.zone != :hand && player_rule?(index, "cant_cast_except_from_hand")) ||
34
+ Mechanics::Keywords::SplitSecond.active?(self) || # CR 702.61b
35
+ player_rule?(index, "cant_cast", obj) || (obj.zone != :hand && player_rule?(index, "cant_cast_except_from_hand")) ||
35
36
  chars(obj).abilities.any? { it.ability.kind == :cast_restriction && !it.ability.allows?(self, index, obj) }
36
37
  end
37
38
 
@@ -49,6 +49,7 @@ module Enjine
49
49
  state.result = { "winner" => winner, "reason" => reason }
50
50
  ask!(nil)
51
51
  state.frames.clear
52
+ reveal_face_down_at_end! # CR 708.9 (Engine::FaceDownPermanents)
52
53
  emit Events::GameEnded.new(winner: winner, reason: reason)
53
54
  end
54
55
 
@@ -64,19 +65,39 @@ module Enjine
64
65
  state.battlefield.each do |id|
65
66
  obj = object(id)
66
67
  defn = chars(obj)
67
- reason = if defn.creature? then creature_sba(obj)
68
- elsif defn.planeswalker? && loyalty(obj) <= 0 then "sba_loyalty"
69
- end
68
+ reason = defn.creature? ? creature_sba(obj) : noncreature_sba(obj, defn)
70
69
  reason ||= "sba_aura" if illegal_aura?(obj) # CR 704.5m
71
70
  reason ||= "sacrifice" if saga_complete?(obj) # CR 704.5s: its controller sacrifices it
72
71
  (doomed ||= []) << [id, reason] if reason
73
72
  end
74
73
  return ceased unless doomed
75
74
 
76
- simultaneously { doomed.each { |id, reason| move!(id, :graveyard, reason: reason) } } # CR 704.3, 603.10a
75
+ in_batch("sba:#{state.next_id}") do # CR 704.3, 603.2c, 603.10a: at once, one event batch
76
+ simultaneously { doomed.each { |id, reason| move!(id, :graveyard, reason: reason) } }
77
+ end
77
78
  true
78
79
  end
79
80
 
81
+ # CR 704.5i: a planeswalker with 0 loyalty is put into its owner's graveyard; a battle, see #battle_sba.
82
+ def noncreature_sba(obj, current)
83
+ return "sba_loyalty" if current.planeswalker? && loyalty(obj) <= 0
84
+
85
+ battle_sba(obj) if current.type?(:battle)
86
+ end
87
+
88
+ # CR 704.5v, 310.7: a battle with defense 0 is put into its owner's graveyard, unless it's the source of a
89
+ # triggered ability that has triggered but not yet left the stack (a Siege's defeat trigger, CR 310.12).
90
+ # CR 704.5x: a Siege its protector controls gets a new protector from among its controller's opponents (no
91
+ # choice in a two-player game).
92
+ def battle_sba(obj)
93
+ obj.memory["protector"] = state.opponent(obj.controller) if protector(obj) == obj.controller && chars(obj).subtypes.include?(:siege)
94
+ return nil if obj.counters.fetch("defense", 0).positive?
95
+
96
+ waiting = state.pending_triggers.any? { it["source"] == obj.id } ||
97
+ state.stack.any? { (ability = object(it)).ability? && ability.source == obj.id && ability.memory.key?("trigger_id") }
98
+ waiting ? nil : "sba_defense"
99
+ end
100
+
80
101
  # CR 704.5q, 122.3: N +1/+1 and N -1/-1 counters are removed, N the smaller count.
81
102
  def annihilate_counters!
82
103
  hit = state.battlefield.filter_map do |id|
@@ -41,6 +41,7 @@ module Enjine
41
41
  watch_delayed!(event) unless state.delayed_triggers.empty?
42
42
  watch_speed!(event) # CR 702.179d (Engine::Speed)
43
43
  Mechanics::Keywords::Suspend.watch!(self, event) # CR 702.62a: suspended cards in exile
44
+ Mechanics::Abilities::Miracle.watch!(self, event) # CR 702.94a: the first card drawn this turn
44
45
  end
45
46
 
46
47
  # "For the first time each turn" (trigger counters_placed with first_time_this_turn): every placement of
@@ -206,19 +207,25 @@ module Enjine
206
207
  return if once_each_turn_used!(ability, inst.ref, source)
207
208
 
208
209
  memory = trigger_memory(source)
210
+ memory = memory.merge("source_moved_to" => event.new_id) if source_left?(trigger, event, source)
209
211
  batch = trigger.respond_to?(:batched?) && trigger.batched? ? event_batch : nil
210
212
  times = 1 + additional_triggers(event, source)
211
213
  card, ref, granter = AbilityLayers.granted_parts(inst.ref) # a granted ability lives in the granting card's data (CR 613.1f)
212
214
  queued = source.merge("ability" => ref || inst.ref, "card" => card || source["card"])
213
215
  memory = memory.merge("granter" => granter) if granter # CR 607.1a (Selector "granter")
214
216
  found.first(limited?(ability) ? 1 : found.size).each do |facts|
215
- next if batch && batched_pending!(source, queued["ability"], batch)
217
+ next if batch && batched_pending!(source, queued["ability"], batch, facts)
216
218
 
217
- facts = facts.merge("amount" => 1) if batch # "that many": the occurrences so far (batched_pending!)
218
- times.times { queue_pending_trigger!(queued, event, memory.merge("triggering" => facts), batch: batch) }
219
+ # "that many" / "those": the occurrences and their objects so far (batched_pending!)
220
+ facts = facts.merge("amount" => 1, "objects" => [facts["object"]].compact) if batch
221
+ times.times { queue_pending_trigger!(queued, event, memory.merge("triggering" => Snapshot.deep_copy(facts)), batch: batch) }
219
222
  end
220
223
  end
221
224
 
225
+ # CR 400.7e, 603.10a: a leaves-the-battlefield ability of the permanent that left ("when this dies, return it to
226
+ # its owner's hand") can find the new object it became; Selector "self" looks for it.
227
+ def source_left?(trig, event, src) = trig.leaves_battlefield? && event.is_a?(Events::ZoneChanged) && event.old_id == src["id"]
228
+
222
229
  # A once-each-turn limit: remembered on the source object, so the same card
223
230
  # as a new object (CR 400.7) may trigger again.
224
231
  def limited?(ability) = ability.respond_to?(:limit) && !ability.limit.nil?
@@ -256,18 +263,24 @@ module Enjine
256
263
  # The event batch an event belongs to, for "one or more" triggers (CR 603.2c): everything one effect
257
264
  # of a resolving spell or ability does, or one cast or activation (its costs). Outside those, each
258
265
  # event is its own batch.
266
+ # Events that happen at once outside those (state-based actions, CR 704.3) share the batch `in_batch` names.
259
267
  def event_batch
268
+ return @event_batch if @event_batch
269
+
260
270
  frame = state.frames.last or return "event:#{state.next_id}"
261
271
  "#{frame["type"]}:#{frame["object"]}:#{frame["pc"]}"
262
272
  end
263
273
 
264
274
  # Whether a "one or more" trigger already waits for this batch. If so, this occurrence joins it: its
265
- # "that many" counts the occurrences in the batch (CR 603.2c).
266
- def batched_pending!(source, ref, batch)
275
+ # "that many" counts the occurrences in the batch and its "those" ({"triggering": "objects"}) gains the
276
+ # occurrence's object (CR 603.2c).
277
+ def batched_pending!(source, ref, batch, found = {})
267
278
  waiting = state.pending_triggers.select { it["source"] == source["id"] && it["ability"] == ref && it["batch"] == batch }
268
279
  waiting.each do |trigger|
269
280
  facts = trigger["memory"]["triggering"]
270
281
  facts["amount"] = facts.fetch("amount", 1) + 1
282
+ objects = (facts["objects"] ||= [])
283
+ objects << found["object"] if found["object"] && !objects.include?(found["object"])
271
284
  end
272
285
  !waiting.empty?
273
286
  end
@@ -330,6 +343,8 @@ module Enjine
330
343
  # CR 107.3m: an enters-the-battlefield trigger uses the X its permanent was cast with.
331
344
  def entered_x(trigger)
332
345
  event = trigger["event"]
346
+ # "When you cycle this card, ... with mana value X": the X of the activated ability (CR 702.29c, 107.3).
347
+ return state.objects[event["object"]]&.x if event["type"] == "ability_activated"
333
348
  return nil unless event["type"] == "zone_changed" && event["to"] == "battlefield" &&
334
349
  event["new_id"] == trigger["source"]
335
350
 
@@ -25,6 +25,9 @@ module Enjine
25
25
  # "returned" permanents returned to their hand from the battlefield
26
26
  # "drawn" / "discarded" how many cards they drew (CR 121.2) / discarded (CR 701.9a)
27
27
  # "dilemmas" dilemmas they faced (CR 700.17)
28
+ # "crimes" crimes they committed (CR 700.13)
29
+ # "entered_face_down" / "turned_face_up" permanents that entered face down under their control / that they
30
+ # turned face up (CR 708.3, 708.8)
28
31
  # "noncombat_damage" noncombat damage dealt to them (CR 120.2b)
29
32
  # "coin_flips" coins they flipped (CR 705)
30
33
  # The game log also counts the turns each player has begun ("turns").
@@ -41,6 +44,8 @@ module Enjine
41
44
  zone_change_recorded!(event)
42
45
  discard_recorded!(event) # mayhem (Engine::AltCasting)
43
46
  when Events::DilemmaFaced then bump!(log_of(event.player), "dilemmas", 1)
47
+ when Events::CrimeCommitted then bump!(log_of(event.player), "crimes", 1) # CR 700.13 (Engine::Crimes)
48
+ when Events::TurnedFaceUp then bump!(log_of(event.player), "turned_face_up", 1) # CR 708.8
44
49
  when Events::AttackerDeclared then attack_recorded!(event)
45
50
  when Events::AttacksDeclared # the attacking creatures' total power, per combat (Triggers::PlayerAttacks)
46
51
  (log_of(event.player)["attack_powers"] ||= []) << event.attackers.sum { power(object(it)) }
@@ -117,10 +122,21 @@ module Enjine
117
122
  "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
118
123
  "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
119
124
  "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities,
120
- "attacking" => attackers.key?(obj.id) } # "if it was attacking" (CR 506.4, 608.2h)
125
+ "attacking" => attackers.key?(obj.id), # "if it was attacking" (CR 506.4, 608.2h)
126
+ "memory" => cast_memory(obj) } # how it was cast, for its leaves-the-battlefield triggers (CR 400.7d)
121
127
  .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
122
128
  end
123
129
 
130
+ # What a permanent remembers of the spell it was (CR 400.7d): whether it was cast, kicked, how and from where,
131
+ # and the mana spent on it (CR 601.2h). Plain data; empty for a permanent that wasn't cast.
132
+ CAST_MEMORY = %w[cast kicked cast_from cast_with kicked_with mana_from].freeze
133
+
134
+ def cast_memory(obj)
135
+ memory = Snapshot.deep_copy(obj.memory.slice(*CAST_MEMORY))
136
+ memory["mana_spent"] = obj.mana_spent.dup if obj.mana_spent
137
+ memory
138
+ end
139
+
124
140
  # The part of last known information an ability keeps in its memory ("source_lki"): plain data.
125
141
  def last_known_memory(lki)
126
142
  info = { "controller" => lki["controller"], "power" => lki["power"], "toughness" => lki["toughness"],
@@ -130,6 +146,10 @@ module Enjine
130
146
  info.merge(lki.slice(Mechanics::Linked::EXILED).transform_values(&:dup)) # CR 607.2a (Linked.exiled_with)
131
147
  end
132
148
 
149
+ # What a source that is being looked at while its leaves-the-battlefield trigger is checked remembered of the
150
+ # spell it was (CR 400.7d, 603.4): the ability isn't on the stack yet, and the permanent is gone.
151
+ def departed_cast_memory(id) = last_known(id)&.[]("memory")
152
+
133
153
  # What the resolving spell or ability remembers about an object that left the battlefield during it.
134
154
  def resolving_last_known(id) = state.frames.rfind { it["type"] == "resolve" && it["ctx"] }&.dig("ctx", "lki", id)
135
155
 
@@ -205,6 +225,7 @@ module Enjine
205
225
  def entered_recorded!(event)
206
226
  obj = state.objects[event.new_id] or return
207
227
  (turn_log(obj.controller)["entered"] ||= []) << history_entry(event.card, chars(obj))
228
+ bump!(turn_log(obj.controller), "entered_face_down", 1) if face_down_object?(obj) # CR 708.3
208
229
  end
209
230
 
210
231
  # CR 305.1: the player who plays a land controls it as it enters.
@@ -260,16 +281,18 @@ module Enjine
260
281
 
261
282
  # What a triggered ability remembers of its source: whether it was cast (CR 400.7d) and kicked (CR 702.33d),
262
283
  # how it was cast, the mana spent to cast it (CR 601.2h) and, for a source that just left the battlefield
263
- # ("when this leaves, put its counters on ..."), how it last existed (CR 603.10a, 608.2h).
284
+ # ("when this leaves, put its counters on ..."), how it last existed (CR 603.10a, 608.2h), the way it was cast
285
+ # included ("when this dies, if it was cast from your hand").
264
286
  def trigger_memory(source)
265
287
  obj = state.objects[source["id"]]
266
- source_memory = obj&.memory || {}
288
+ lki = last_known(source["id"])
289
+ source_memory = obj&.memory || lki&.[]("memory") || {}
267
290
  memory = source_memory["cast"] ? { "source_cast" => true } : {}
268
291
  memory["kicked"] = true if source_memory["kicked"] # CR 702.33d: a kicked permanent's "if it was kicked"
269
292
  memory.merge!(source_memory.slice("cast_from", "cast_with", "kicked_with")) # "if its evoke cost was paid" (Engine::AltCasting)
270
- memory["source_mana_spent"] = obj.mana_spent.dup if obj&.mana_spent
293
+ spent = obj ? obj.mana_spent : source_memory["mana_spent"]
294
+ memory["source_mana_spent"] = spent.dup if spent
271
295
  memory["source_mana_from"] = Snapshot.deep_copy(source_memory["mana_from"]) if source_memory["mana_from"]
272
- lki = last_known(source["id"])
273
296
  memory["source_lki"] = last_known_memory(lki) if lki
274
297
  memory
275
298
  end
@@ -82,9 +82,11 @@ module Enjine
82
82
  def propose(kind, data, applied = []) = Replacements.apply(self, Proposal.new(kind, data, applied.dup))
83
83
 
84
84
  # `face_down`: exile it face down (CR 406.3); the list of player indices who may look at it.
85
- def move!(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
85
+ # `face_down_as`: it goes to the battlefield or the stack face down, as "manifest", "cloak", "morph" or
86
+ # "disguise" (Engine::FaceDownPermanents).
87
+ def move!(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil, face_down_as: nil)
86
88
  data = plan_move(id, to, reason: reason, position: position, controller: controller, enters: enters,
87
- face_down: face_down)
89
+ face_down: face_down, face_down_as: face_down_as)
88
90
  data && execute_zone_change!(data)
89
91
  end
90
92
 
@@ -94,9 +96,10 @@ module Enjine
94
96
 
95
97
  # The zone change `move!` would make, after replacement effects (CR 614), not yet executed; nil if a
96
98
  # replacement cancelled it. Planning several before executing any lets them happen at once (CR 614.12).
97
- def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
99
+ def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil, face_down_as: nil)
98
100
  data = { "object" => id, "to" => to, "position" => position, "reason" => reason, "controller" => controller }
99
101
  data["face_down"] = face_down if face_down && to == :exile
102
+ data["face_down_as"] = face_down_as if face_down_as && %i[battlefield stack].include?(to)
100
103
  data["enters"] = { "tapped" => enters&.fetch("tapped", false) == true, "counters" => {} } if to == :battlefield
101
104
  data["enters"]["face"] = enters["face"] if data["enters"] && enters&.key?("face") # seen by its own replacements
102
105
  data = propose("zone_change", data).data
@@ -110,7 +113,10 @@ module Enjine
110
113
  def depart!(old)
111
114
  lki = old.zone == :battlefield ? last_known_info(old) : nil # before it leaves (CR 603.10a)
112
115
  remember_last_known!(old.id, lki) if lki # CR 608.2h (see Engine::TurnHistory)
113
- remember_spell!(old) if old.zone == :stack && !old.ability? # a countered spell's mana spent (Engine::TurnHistory)
116
+ if old.zone == :stack && !old.ability?
117
+ remember_spell!(old) # a countered spell's mana spent (Engine::TurnHistory)
118
+ note_left_stack!(old) # while it resolves (Engine::Resolution)
119
+ end
114
120
  state.zone_list(old.zone, old.owner).delete(old.id)
115
121
  state.objects.delete(old.id)
116
122
  lki
@@ -122,25 +128,45 @@ module Enjine
122
128
  old = object(id)
123
129
  lki = depart!(old)
124
130
  face_down = to == :exile ? data["face_down"] : nil
125
- fresh = create_object(card_after_move(old, to), old.owner, to, hidden: !face_down.nil?) # front face up (Engine::Faces)
131
+ as = face_down_as(old, to, data) # CR 708.3, 708.4 (Engine::FaceDownPermanents)
132
+ fresh = create_object(card_after_move(old, to), old.owner, to, hidden: !face_down.nil? || !as.nil?) # front face up (Engine::Faces)
126
133
  carry_copy_status!(fresh, old, to) # a token or copy stays one (Engine::Copies)
127
134
  left_battlefield!(fresh, old) if lki
128
135
  arrive!(fresh, old, data)
129
136
  fresh.memory.merge!("face_down" => true, "may_look" => face_down.uniq.sort) if face_down
137
+ turn_face_down!(fresh, as) if as
130
138
  place!(fresh, data)
131
139
  record_result!(fresh.id)
132
140
  note_commander_move!(fresh) # CR 903.9
133
141
  event = Events::ZoneChanged.new(card: old.card, old_id: id, new_id: fresh.id, owner: name(old.owner),
134
142
  from: old.zone.to_s, to: to.to_s, reason: data["reason"],
135
- lookers: face_down&.map { name(it) })
143
+ lookers: zone_change_lookers(fresh, face_down, as))
136
144
  lki ? with_last_known(id, lki) { emit event } : emit(event)
145
+ reveal_face_down_left!(old, fresh) # CR 708.9
137
146
  return_exiled_until_leaves!(old) if lki # CR 610.3
138
147
  unmeld!(old, to, data) if old.memory["melded"] # CR 713.8 (Engine::Faces)
139
148
  prepare!(fresh) if to == :battlefield && data["enters"]["prepared"] # "enters prepared" (CR 723.3a)
149
+ room_entered!(fresh, old) if to == :battlefield # CR 709.5d, 709.5h (Engine::Rooms)
140
150
  run_follow_ups!(data, "object" => fresh.id) # "exile it instead. When you do, ..." (Engine::FollowUps)
141
151
  fresh
142
152
  end
143
153
 
154
+ # What a moving object is face down as on arrival: as the move says, or as the face-down spell it was
155
+ # (CR 702.37c, 702.168b: the permanent has the spell's characteristics); nil when it's face up.
156
+ def face_down_as(old, to, data)
157
+ return data["face_down_as"] if data["face_down_as"]
158
+
159
+ old.memory["face_down_as"] if old.zone == :stack && to == :battlefield
160
+ end
161
+
162
+ # Who sees which card moved: the players who may look at a card exiled face down (CR 406.3), the controller of
163
+ # a face-down spell or permanent (CR 708.5); nil when everyone who sees the zones does.
164
+ def zone_change_lookers(fresh, face_down, kind)
165
+ return face_down.map { name(it) } if face_down
166
+
167
+ kind && [name(fresh.controller)]
168
+ end
169
+
144
170
  # Puts the new object into its zone's list; on the battlefield, as what it enters as (#enter_as!).
145
171
  def place!(fresh, data)
146
172
  list = state.zone_list(data["to"], fresh.owner)
data/lib/enjine/engine.rb CHANGED
@@ -24,6 +24,7 @@ module Enjine
24
24
  record_history!(event) # before triggers look at it (see Engine::TurnHistory)
25
25
  @emit.call(event)
26
26
  watch_triggers!(event)
27
+ check_crime!(event) # CR 700.13 (Engine::Crimes)
27
28
  end
28
29
 
29
30
  def name(index) = state.players[index].name
@@ -31,7 +32,10 @@ module Enjine
31
32
  def player(index) = state.players[index]
32
33
  def active_player = state.players[state.active]
33
34
  def definition(object) = catalog.fetch(object.card)
34
- def object(id) = state.objects.fetch(id)
35
+ # A spell that left the stack while resolving stands in for itself until it has resolved (Engine::Resolution).
36
+ def object(id) = state.objects.fetch(id) { resolving_stand_in(id) || raise(KeyError, "key not found: #{id.inspect}") }
37
+ # The object, or that stand-in; nil for an object that no longer exists.
38
+ def find_object(id) = state.objects[id] || resolving_stand_in(id)
35
39
  def ask!(pending) = state.pending = pending
36
40
  def step = Steps.fetch(state.step)
37
41
  def attackers = state.attackers