enjine 0.3.0 → 0.4.1

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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -1
  3. data/SUPPORTED.md +4 -4
  4. data/docs/guides/card-data-format.md +37 -0
  5. data/docs/plans/dsl-gaps.md +76 -0
  6. data/docs/reference/effects.md +12 -9
  7. data/docs/reference/triggers.md +3 -1
  8. data/lib/enjine/actions/cast.rb +10 -3
  9. data/lib/enjine/card_definition.rb +15 -0
  10. data/lib/enjine/engine/casting/alt_casting.rb +8 -0
  11. data/lib/enjine/engine/casting/casting.rb +19 -0
  12. data/lib/enjine/engine/casting/permissions.rb +17 -12
  13. data/lib/enjine/engine/characteristics.rb +29 -12
  14. data/lib/enjine/engine/copies.rb +16 -9
  15. data/lib/enjine/engine/damage.rb +2 -1
  16. data/lib/enjine/engine/durations.rb +47 -0
  17. data/lib/enjine/engine/faces.rb +2 -0
  18. data/lib/enjine/engine/rules.rb +2 -1
  19. data/lib/enjine/engine/state_based_actions.rb +8 -0
  20. data/lib/enjine/engine/triggers.rb +15 -8
  21. data/lib/enjine/engine/zones.rb +18 -2
  22. data/lib/enjine/events.rb +4 -1
  23. data/lib/enjine/mechanics/abilities/double_counters.rb +1 -1
  24. data/lib/enjine/mechanics/abilities/play_permissions.rb +3 -2
  25. data/lib/enjine/mechanics/abilities/replacement_effects.rb +2 -1
  26. data/lib/enjine/mechanics/abilities/static.rb +7 -0
  27. data/lib/enjine/mechanics/card_spec.rb +54 -12
  28. data/lib/enjine/mechanics/effects/become.rb +35 -13
  29. data/lib/enjine/mechanics/effects/copy.rb +7 -4
  30. data/lib/enjine/mechanics/effects/gain_control.rb +6 -3
  31. data/lib/enjine/mechanics/effects/return_to_battlefield.rb +25 -6
  32. data/lib/enjine/mechanics/filters/base.rb +19 -2
  33. data/lib/enjine/mechanics/filters/stack.rb +1 -1
  34. data/lib/enjine/mechanics/triggers/base.rb +14 -3
  35. data/lib/enjine/mechanics/triggers/casting.rb +1 -1
  36. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +21 -5
  37. data/lib/enjine/mechanics/triggers/zone_changes.rb +1 -1
  38. data/lib/enjine/mechanics/values.rb +10 -7
  39. data/lib/enjine/mechanics.rb +5 -0
  40. data/lib/enjine/rules_monitor.rb +4 -2
  41. data/lib/enjine/steps.rb +10 -1
  42. data/lib/enjine/version.rb +1 -1
  43. metadata +2 -1
@@ -24,12 +24,13 @@ module Enjine
24
24
 
25
25
  # layer 1 (CR 613.2a-c): its copiable values
26
26
  return board_characteristics.fetch(object.id) { copy_base(object) } if object.zone == :battlefield
27
- return @options_memo[object.id] ||= off_board_chars(object) if @options_memo && object.zone == :hand
27
+ return @options_memo[object.id] ||= off_board_chars(object) if @options_memo # the state holds still meanwhile
28
28
 
29
29
  off_board_chars(object)
30
30
  end
31
31
 
32
- # Off the battlefield. The options of one decision ask about each card in hand often (Engine#options).
32
+ # Off the battlefield. The options of one decision ask about each card in hand, graveyard and exile often
33
+ # (Engine#options).
33
34
  def off_board_chars(object)
34
35
  defn = definition(object)
35
36
  base = copy_base(object)
@@ -152,7 +153,8 @@ module Enjine
152
153
  base = with_added_types(base, ability.card_types) unless ability.card_types.empty?
153
154
  subtypes |= ability.added_subtypes(source)
154
155
  end
155
- effects.each { types = it["types"].map(&:to_sym) if it["kind"] == "creature_types" && it["affected"].include?(obj.id) }
156
+ setting = effects.select { it["kind"] == "creature_types" && it["affected"].include?(obj.id) }.last
157
+ types = Mechanics::Effects::Become.creature_types_of(setting) if setting
156
158
  base = base.with(subtypes: ((base.subtypes & Characteristics::NON_CREATURE_SUBTYPES) | types).freeze) if types
157
159
  base = with_gained_subtypes(base, subtypes - base.subtypes) unless (subtypes - base.subtypes).empty?
158
160
  base.creature? || base.power.nil? ? base : base.with(power: nil, toughness: nil)
@@ -178,12 +180,16 @@ module Enjine
178
180
  # "Is a black Skeleton creature" (CR 205.1a): the card types are exactly these, and subtypes correlated with
179
181
  # a card type it no longer has are lost (creature types without creature, an Equipment without artifact).
180
182
  def with_set_types(base, set)
181
- kept = base.subtypes.select do |sub|
183
+ base = base.with(types: set, subtypes: subtypes_of_types(base.subtypes, set))
184
+ base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
185
+ end
186
+
187
+ # The subtypes still correlated with one of the card types `set` (CR 205.1a).
188
+ def subtypes_of_types(subtypes, set)
189
+ subtypes.select do |sub|
182
190
  correlated = CORRELATED_SUBTYPES.find { |_, list| list.include?(sub) }&.first || :creature
183
191
  set.include?(correlated)
184
- end
185
- base = base.with(types: set, subtypes: kept.freeze)
186
- base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
192
+ end.freeze
187
193
  end
188
194
 
189
195
  def printed_noncreature_pt?(obj) = definition(obj).then { !it.creature? && !it.power.nil? }
@@ -284,6 +290,8 @@ module Enjine
284
290
  urzas]
285
291
  }.freeze
286
292
  NON_CREATURE_SUBTYPES = CORRELATED_SUBTYPES.values.flatten.freeze
293
+ # Resolved effects that change card types in layer 4, applied in timestamp order (CR 613.7a).
294
+ TYPE_EFFECTS = %w[add_types set_types].freeze
287
295
 
288
296
  # ---- layers 4 and 7b from the object's own state ------------------------------------
289
297
 
@@ -314,7 +322,7 @@ module Enjine
314
322
  symbols += active_max_speed(obj, obj.controller) + active_class_levels(obj)
315
323
  assimilated = !effects.empty? && effects.any? { it["kind"] == "assimilate" && it["affected"].include?(obj.id) }
316
324
  added = effects.empty? ? [] : added_subtypes(obj, effects)
317
- becomes = effects.empty? ? [] : effects.select { it["kind"] == "add_types" && it["affected"].include?(obj.id) }
325
+ becomes = effects.empty? ? [] : effects.select { TYPE_EFFECTS.include?(it["kind"]) && it["affected"].include?(obj.id) }
318
326
  return printed if symbols.empty? && !assimilated && added.empty? && becomes.empty?
319
327
 
320
328
  attrs = printed.to_h
@@ -326,15 +334,24 @@ module Enjine
326
334
  end
327
335
 
328
336
  # "Becomes an artifact creature", "becomes a legendary Spider Hero in addition to its other types" (CR 205.1b):
329
- # card types, supertypes and subtypes are added, none lost. Power/toughness: see Characteristics#with_added_types.
337
+ # card types, supertypes and subtypes are added, none lost. "It's an enchantment. (It's not a creature.)"
338
+ # (CR 205.1a): the card types are set, losing the subtypes of the others. In timestamp order (CR 613.7a).
339
+ # Power/toughness: see Characteristics#with_added_types.
330
340
  def added_type_layers(attrs, effect)
341
+ if effect["kind"] == "set_types"
342
+ attrs[:types] = effect["types"].map(&:to_sym)
343
+ attrs[:subtypes] = subtypes_of_types(attrs[:subtypes], attrs[:types])
344
+ return become_creature_pt(attrs)
345
+ end
331
346
  attrs[:types] = attrs[:types] | effect["types"].map(&:to_sym)
332
347
  attrs[:supertypes] = attrs[:supertypes] | effect["supertypes"].map(&:to_sym)
333
348
  attrs[:subtypes] = attrs[:subtypes] | effect["subtypes"].map(&:to_sym)
334
- return unless attrs[:types].include?(:creature) && attrs[:power].nil?
349
+ become_creature_pt(attrs)
350
+ end
335
351
 
336
- attrs[:power] = 0
337
- attrs[:toughness] = 0
352
+ # A permanent that becomes a creature without power and toughness is 0/0 (CR 301.7b).
353
+ def become_creature_pt(attrs)
354
+ attrs.merge!(power: 0, toughness: 0) if attrs[:types].include?(:creature) && attrs[:power].nil?
338
355
  end
339
356
 
340
357
  def station_symbol_layers(attrs, inst, defn)
@@ -13,7 +13,8 @@ module Enjine
13
13
  # resolve against that card's data)
14
14
  # memory["own_card"] the card the object really is, while a copy effect changed obj.card
15
15
  # memory["copy_effects"] copy effects on a permanent, in timestamp order (CR 613.7): each
16
- # {"card", "except", "duration" ("permanent" | "end_of_turn"), "timestamp"}
16
+ # {"card", "except", "duration" ("permanent" | "end_of_turn" |
17
+ # "until_your_next_turn", with its "controller"), "timestamp"}
17
18
  # memory["copy_except"] the exceptions of an object created as a copy (a token copy, CR 707.9)
18
19
  # memory["token"] true for a token that is a copy of a card (CR 111.1, 608.3f)
19
20
  # memory["copy"] "spell" for a copy of a spell (CR 707.10), "card" for a copy of a card
@@ -79,11 +80,13 @@ module Enjine
79
80
 
80
81
  # CR 707.4, 613.2a: `obj` becomes a copy of [card, except]; no enter or leave triggers. A
81
82
  # "permanent" copy effect lasts as long as the object stays on the battlefield.
82
- def become_copy!(obj, values, duration: "permanent")
83
+ # `controller`: whose next turn ends an "until your next turn" copy effect (CR 611.2a).
84
+ def become_copy!(obj, values, duration: "permanent", controller: nil)
83
85
  card, except = values
84
86
  obj.memory["own_card"] ||= obj.card
85
- (obj.memory["copy_effects"] ||= []) << { "card" => card, "except" => except, "duration" => duration,
86
- "timestamp" => next_timestamp! }
87
+ entry = { "card" => card, "except" => except, "duration" => duration, "timestamp" => next_timestamp! }
88
+ entry["controller"] = controller if duration == "until_your_next_turn"
89
+ (obj.memory["copy_effects"] ||= []) << entry
87
90
  obj.card = card
88
91
  emit Events::EffectStarted.new(kind: "copy", affected: [obj.id], details: { "card" => card })
89
92
  end
@@ -165,15 +168,19 @@ module Enjine
165
168
  end
166
169
  end
167
170
 
168
- # CR 514.2: "until end of turn" copy effects end; the permanent has the copiable values of the
169
- # newest copy effect left, or its own.
170
- def end_copy_effects!
171
+ # CR 514.2: "until end of turn" copy effects end (with `controller`: that player's "until your next turn"
172
+ # ones, as their turn begins, CR 611.2a); the permanent has the copiable values of the newest copy effect
173
+ # left, or its own.
174
+ def end_copy_effects!(controller: nil)
175
+ ending = lambda do |e|
176
+ controller.nil? ? e["duration"] == "end_of_turn" : e["duration"] == "until_your_next_turn" && e["controller"] == controller
177
+ end
171
178
  state.battlefield.each do |id|
172
179
  obj = object(id)
173
180
  effects = obj.memory["copy_effects"] or next
174
- next unless effects.any? { it["duration"] == "end_of_turn" }
181
+ next unless effects.any?(&ending)
175
182
 
176
- effects.reject! { it["duration"] == "end_of_turn" }
183
+ effects.reject!(&ending)
177
184
  obj.card = effects.last&.fetch("card") || obj.memory["own_card"]
178
185
  obj.memory.delete("copy_effects") if effects.empty?
179
186
  obj.memory.delete("own_card") if effects.empty?
@@ -136,7 +136,8 @@ module Enjine
136
136
  # CR 613.7c: keyword counters of this kind get the new counter's timestamp (Engine::Characteristics#ability_layers).
137
137
  # The next timestamp isn't taken: an effect created later gets this number too and sorts after it.
138
138
  (object.memory["counter_timestamps"] ||= {})[kind] = state.next_id if Mechanics::Counters.keyword?(kind)
139
- emit Events::CountersChanged.new(object: object.id, counter: kind, from: before, to: before + amount)
139
+ emit Events::CountersChanged.new(object: object.id, counter: kind, from: before, to: before + amount,
140
+ by: name(data["player"]))
140
141
  end
141
142
 
142
143
  # Counters on a player (CR 122.1): poison (ten or more lose the game, CR 122.1f, 704.5c), experience, rad, ...
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Durations measured in a player's own turns (CR 611.2a): "until the end of your next turn" control effects
6
+ # and "until your next end step" permissions. "Until your next turn" ends as that turn begins
7
+ # (Engine::Rules#end_effects_until_turn_of!).
8
+ module Durations
9
+ # At cleanup of its controller's next turn (CR 514.2), an "until the end of your next turn" control effect
10
+ # ends and control returns (Engine::Rules#revert_control!).
11
+ def end_next_turn_control!
12
+ ending = state.effects.select do |e|
13
+ e["kind"] == "control" && e["duration"] == "end_of_your_next_turn" && e["controller"] == state.active &&
14
+ state.turn > e["turn"]
15
+ end
16
+ return if ending.empty?
17
+
18
+ revert_control!(ending)
19
+ state.effects.reject! { ending.include?(it) }
20
+ emit Events::EffectsEnded.new(count: ending.size)
21
+ end
22
+
23
+ # What an effect lasting "until your next end step" remembers: an effect made during its controller's end
24
+ # step or cleanup (`late`) lasts until the end step of their next turn; otherwise this turn's end step ends
25
+ # it on their own turn.
26
+ def end_step_timing(index, duration)
27
+ return {} unless duration == "until_your_next_end_step"
28
+
29
+ { "late" => state.active == index && %i[end cleanup].include?(state.step) }
30
+ end
31
+
32
+ # CR 513.1: as the active player's end step begins, their "until your next end step" effects end.
33
+ def expire_end_step_effects!
34
+ ending = state.effects.select do |e|
35
+ e["duration"] == "until_your_next_end_step" && e["controller"] == state.active &&
36
+ (state.turn > e["turn"] || !e["late"])
37
+ end
38
+ return if ending.empty?
39
+
40
+ state.effects.reject! { ending.include?(it) }
41
+ emit Events::EffectsEnded.new(count: ending.size)
42
+ end
43
+ end
44
+
45
+ include Durations
46
+ end
47
+ end
@@ -201,6 +201,8 @@ module Enjine
201
201
  def unprepare!(obj)
202
202
  return false unless obj.memory.delete("prepared")
203
203
 
204
+ rescan_tokens! # its prepare spell copy ceases to exist (CR 723.3c)
205
+
204
206
  emit Events::PreparedChanged.new(object: obj.id, prepared: false)
205
207
  true
206
208
  end
@@ -83,6 +83,7 @@ module Enjine
83
83
 
84
84
  # "Until your next turn" effects end as that player's next turn begins (CR 611.2a, 500.1).
85
85
  def end_effects_until_turn_of!(index)
86
+ end_copy_effects!(controller: index) # Engine::Copies
86
87
  ending = state.effects.count { it["duration"] == "until_your_next_turn" && it["controller"] == index }
87
88
  return if ending.zero?
88
89
 
@@ -202,7 +203,7 @@ module Enjine
202
203
  gain_control!(obj, controller, timestamp)
203
204
  state.effects << { "kind" => "control", "timestamp" => timestamp, "controller" => ctx.controller,
204
205
  "affected" => [obj.id], "duration" => duration, "previous" => previous,
205
- "source" => source }.compact
206
+ "source" => source, "turn" => duration == "end_of_your_next_turn" ? state.turn : nil }.compact
206
207
  emit Events::EffectStarted.new(kind: "control", affected: [obj.id], details: { "controller" => controller })
207
208
  end
208
209
 
@@ -93,16 +93,24 @@ module Enjine
93
93
 
94
94
  # CR 704.5d / 111.7: a token in a zone other than the battlefield ceases to exist. Phased-out tokens are
95
95
  # still on the battlefield (CR 702.26d), see Engine::Copies#ceases_to_exist?.
96
+ # Skipped while the zones are as last scanned (Engine::Zones#zones_version), unless a prepared copy lost its
97
+ # permanent since (Engine::Faces#unprepare!).
96
98
  def remove_tokens_outside_battlefield!
99
+ return false if @tokens_scanned == zones_version
100
+
97
101
  gone = state.objects.values.select { ceases_to_exist?(it) } # and copies, CR 707.10a (Engine::Copies)
98
102
  gone.each do |obj|
99
103
  state.zone_list(obj.zone, obj.owner).delete(obj.id)
100
104
  state.objects.delete(obj.id)
101
105
  emit Events::TokenCeased.new(object: obj.id, card: obj.card, zone: obj.zone.to_s)
102
106
  end
107
+ @tokens_scanned = zones_version
103
108
  !gone.empty?
104
109
  end
105
110
 
111
+ # The next state-based action check looks for tokens and copies to remove again.
112
+ def rescan_tokens! = @tokens_scanned = nil
113
+
106
114
  # CR 704.5j: the legend rule needs a choice, so it runs as a frame before priority.
107
115
  def legend_rule_first!(index)
108
116
  return false if state.frames.any? { it["type"] == "legend_rule" }
@@ -15,7 +15,8 @@ module Enjine
15
15
  # types it had then, not its printed ones.
16
16
  def last_known_info(obj)
17
17
  current = chars(obj)
18
- { "controller" => obj.controller, "card" => obj.card, "types" => current.types, "subtypes" => current.subtypes,
18
+ { "controller" => obj.controller, "owner" => obj.owner, "card" => obj.card, "types" => current.types,
19
+ "subtypes" => current.subtypes,
19
20
  "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
20
21
  "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
21
22
  "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
@@ -178,14 +179,20 @@ module Enjine
178
179
 
179
180
  # CR 113.6k: triggered abilities that function from a graveyard, controlled by the card's owner.
180
181
  def watch_graveyards!(event)
181
- state.players.each_with_index do |pl, owner|
182
- pl.graveyard.each do |id|
183
- instances = graveyard_triggers(object(id).card)
184
- next if instances.empty?
182
+ graveyard_trigger_holders.each do |id, owner, instances|
183
+ source = { "id" => id, "card" => object(id).card, "controller" => owner }
184
+ instances.each { queue_trigger(it, event, source) }
185
+ end
186
+ end
185
187
 
186
- source = { "id" => id, "card" => object(id).card, "controller" => owner }
187
- instances.each { queue_trigger(it, event, source) }
188
- end
188
+ # [[id, owner, instances]] of the cards in graveyards with such abilities, in graveyard order; kept while
189
+ # no object appears, moves or ceases to exist (Engine::Zones#zones_version).
190
+ def graveyard_trigger_holders
191
+ return @graveyard_holders if @graveyard_holders_version == zones_version
192
+
193
+ @graveyard_holders_version = zones_version
194
+ @graveyard_holders = state.players.each_with_index.flat_map do |pl, owner|
195
+ pl.graveyard.map { [it, owner, graveyard_triggers(object(it).card)] }.reject { it[2].empty? }
189
196
  end
190
197
  end
191
198
 
@@ -88,6 +88,10 @@ module Enjine
88
88
  data && execute_zone_change!(data)
89
89
  end
90
90
 
91
+ # Changes whenever an object appears or moves (as a new object, CR 400.7, advancing state.next_id) or ceases
92
+ # to exist, and when the whole state is replaced: what is in which zone holds while it stays the same.
93
+ def zones_version = [state.object_id, state.next_id, state.objects.size]
94
+
91
95
  # The zone change `move!` would make, after replacement effects (CR 614), not yet executed; nil if a
92
96
  # replacement cancelled it. Planning several before executing any lets them happen at once (CR 614.12).
93
97
  def plan_move(id, to, reason:, position: :top, controller: nil, enters: nil, face_down: nil)
@@ -123,8 +127,7 @@ module Enjine
123
127
  left_battlefield!(fresh, old) if lki
124
128
  arrive!(fresh, old, data)
125
129
  fresh.memory.merge!("face_down" => true, "may_look" => face_down.uniq.sort) if face_down
126
- list = state.zone_list(to, old.owner)
127
- data["position"] == :bottom ? list.push(fresh.id) : list.unshift(fresh.id)
130
+ place!(fresh, data)
128
131
  record_result!(fresh.id)
129
132
  note_commander_move!(fresh) # CR 903.9
130
133
  event = Events::ZoneChanged.new(card: old.card, old_id: id, new_id: fresh.id, owner: name(old.owner),
@@ -138,6 +141,19 @@ module Enjine
138
141
  fresh
139
142
  end
140
143
 
144
+ # Puts the new object into its zone's list; on the battlefield, as what it enters as (#enter_as!).
145
+ def place!(fresh, data)
146
+ list = state.zone_list(data["to"], fresh.owner)
147
+ data["position"] == :bottom ? list.push(fresh.id) : list.unshift(fresh.id)
148
+ enter_as!(fresh, data["enters"]["as"]) if data["to"] == :battlefield && data["enters"]["as"]
149
+ end
150
+
151
+ # "Return it to the battlefield. It's an enchantment. (It's not a creature.)": what it is from the moment it
152
+ # enters (CR 614.1c, 205.1a), applied before the event, so abilities triggering on it entering see it so.
153
+ def enter_as!(obj, become)
154
+ become.apply(self, Mechanics::EffectContext.new(obj.controller, obj.id, obj.id, [], []))
155
+ end
156
+
141
157
  # A permanent that left the battlefield: the resolving spell or ability links the new object to it (CR 400.7,
142
158
  # 608.2h; Engine::TurnHistory), it leaves combat, and effects lasting while it stays end (CR 611.2b).
143
159
  def left_battlefield!(fresh, old)
data/lib/enjine/events.rb CHANGED
@@ -76,7 +76,10 @@ module Enjine
76
76
  def gain = [to - from, 0].max
77
77
  def loss = [from - to, 0].max
78
78
  end
79
- CountersChanged = define(:counters_changed, :object, :counter, :from, :to)
79
+ # `by`: the player who put the counters on (CR 122.6a), nil for removals; absent in older histories.
80
+ CountersChanged = define(:counters_changed, :object, :counter, :from, :to, :by) do
81
+ def initialize(by: nil, **) = super # rubocop:disable Naming/MethodParameterName -- the event field
82
+ end
80
83
  PlayerCountersChanged = define(:player_counters_changed, :player, :counter, :from, :to) # poison, rad, ... (CR 122.1)
81
84
  EmblemCreated = define(:emblem_created, :player, :object, :card) # CR 114.2
82
85
  # CR 705: a coin flip; `won` is nil for a flip no one wins or loses (CR 705.2).
@@ -28,7 +28,7 @@ module Enjine
28
28
  affects = { "each" => "permanent" }
29
29
  end
30
30
  Mechanics.check_keys(affects, %w[each controller], errors, "#{path}.affects")
31
- filter = Mechanics.build_entry(:filter, affects["each"], errors, "#{path}.affects.each")
31
+ filter = Mechanics.characteristic_filter(affects["each"], errors, "#{path}.affects.each")
32
32
  live = filter ? filter.live_keys : []
33
33
  errors << "#{path}.affects.each: #{live.join(", ")} can't be used here yet" unless live.empty?
34
34
  controller = affects.fetch("controller", "any")
@@ -209,13 +209,14 @@ module Enjine
209
209
  # Riders like these are stored on the permission (`state.effects` entry) and copied into the play
210
210
  # method, so only casts that use this permission (`via: "effect:<timestamp>"`) see them.
211
211
  class PlayPermission < ChoiceEffect
212
- DURATIONS = %w[end_of_turn end_of_your_next_turn while_exiled].freeze
212
+ DURATIONS = %w[end_of_turn end_of_your_next_turn until_your_next_end_step while_exiled].freeze
213
213
  PLAYERS = %w[controller owner].freeze
214
214
 
215
215
  primitive :effect, :play_permission,
216
216
  description: "A player may play (`play: \"play\"`, default) or cast (`\"cast\"`) each referenced " \
217
217
  "exiled card matching `for`/`not_types`, paying its costs and following timing rules, " \
218
- "for `duration`: end_of_turn (default), end_of_your_next_turn or while_exiled. With " \
218
+ "for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step " \
219
+ "or while_exiled. With " \
219
220
  "`choose: \"one_per_owner\"` only one chosen card per owner. `to_player`: who may " \
220
221
  "play it, \"controller\" (default, the effect's controller), \"owner\" (the card's " \
221
222
  "owner) or a player selector (a face-down card: only someone who may look at it). " \
@@ -17,7 +17,8 @@ module Enjine
17
17
  Mechanics.check_keys(data, %w[each controller other], errors, path)
18
18
  controller = data.fetch("controller", "any")
19
19
  errors << "#{path}.controller: must be one of #{CONTROLLERS.join(", ")}" unless CONTROLLERS.include?(controller)
20
- new(Mechanics.build_entry(:filter, data["each"], errors, "#{path}.each"), controller, data["other"] == true)
20
+ new(Mechanics.characteristic_filter(data["each"], errors, "#{path}.each"),
21
+ controller, data["other"] == true)
21
22
  end
22
23
 
23
24
  def initialize(filter, controller, other)
@@ -229,10 +229,17 @@ module Enjine
229
229
  return object.id == source.id if @filter == :self
230
230
  return false if @other && object.id == source.id
231
231
  return false unless @controller == "any" || (@controller == "you") == (object.controller == source.controller)
232
+ return false unless owner_ok?(object, source)
232
233
 
233
234
  @filter.matches_facts?(@filter.uses_chosen? ? facts.with(chosen: source.memory) : facts) # CR 607.2d
234
235
  end
235
236
 
237
+ # "Creatures you control but don't own" (CR 108.3): ownership isn't a characteristic, so it's read here.
238
+ def owner_ok?(object, source)
239
+ owner = @filter.respond_to?(:owner) && @filter.owner
240
+ !owner || (owner == "you") == (object.owner == source.controller)
241
+ end
242
+
236
243
  def to_s
237
244
  bits = []
238
245
  bits << "loses all abilities" if loses_abilities?
@@ -15,14 +15,21 @@ module Enjine
15
15
  # {"colors": ["B"]} a black card: it has any of the listed colors (CR 105.2)
16
16
  # {"color_count": {"equal": 1}} monocolored (1), multicolored (at least 2), colorless (0)
17
17
  # {"any_of": [spec, spec, ...]} at least one spec must match
18
+ # {"keywords": ["flying"]} "a creature card with flying": any listed keyword (CR 702.1)
19
+ # {"not_subtypes": ["avatar"]} "a non-Avatar card"
20
+ # {"power": {"at_most": 1}} also toughness: its power/toughness as the card is (CR 208.1)
21
+ # {"layout": "adventure"} "a card that has an Adventure": the card's layout (CR 716,
22
+ # CardDefinition::Faces)
18
23
  class CardSpec
19
- KEYS = %w[types not_types subtypes supertypes name any_of permanent mana_value colors color_count].freeze
24
+ KEYS = %w[types not_types subtypes supertypes name any_of permanent mana_value colors color_count keywords
25
+ not_subtypes power toughness layout].freeze
20
26
  SUBTYPE = /\A[a-z][a-z0-9_]*\z/
21
27
  # CR 110.4a: the permanent card types (battles have no primitive yet, so none matches that way).
22
28
  PERMANENT_TYPES = %i[artifact battle creature enchantment land planeswalker].freeze
23
29
  BOUNDS = %w[at_least at_most equal].freeze
24
30
 
25
- attr_reader :types, :not_types, :subtypes, :supertypes, :name, :any_of, :permanent, :mana_value, :colors, :color_count
31
+ attr_reader :types, :not_types, :subtypes, :supertypes, :name, :any_of, :permanent, :mana_value, :colors, :color_count,
32
+ :keywords, :not_subtypes, :stats, :layout
26
33
 
27
34
  def self.build(data, errors, path)
28
35
  return ANY if data.nil? || data == "card"
@@ -35,7 +42,18 @@ module Enjine
35
42
  subtypes: subtype_list(data, errors, path), name: name_param(data, errors, path),
36
43
  any_of: alternatives(data, errors, path), not_types: names(data, "not_types", :type, errors, path),
37
44
  permanent: permanent_param(data, errors, path), mana_value: bounds_param(data, "mana_value", errors, path),
38
- colors: colors_param(data, errors, path), color_count: bounds_param(data, "color_count", errors, path))
45
+ colors: colors_param(data, errors, path), color_count: bounds_param(data, "color_count", errors, path),
46
+ keywords: names(data, "keywords", :keyword, errors, path), not_subtypes: subtype_list(data, errors, path, "not_subtypes"),
47
+ stats: %w[power toughness].to_h { [it, bounds_param(data, it, errors, path)] }.reject { |_, b| b.empty? },
48
+ layout: layout_param(data, errors, path))
49
+ end
50
+
51
+ def self.layout_param(data, errors, path)
52
+ value = data["layout"]
53
+ unless value.nil? || CardDefinition::Faces::LAYOUTS.include?(value)
54
+ errors << "#{path}.layout: must be one of #{CardDefinition::Faces::LAYOUTS.join(", ")}"
55
+ end
56
+ value
39
57
  end
40
58
 
41
59
  def self.colors_param(data, errors, path)
@@ -58,12 +76,12 @@ module Enjine
58
76
  end
59
77
  end
60
78
 
61
- def self.subtype_list(data, errors, path)
62
- list(data, "subtypes", errors, path).filter_map do |raw|
79
+ def self.subtype_list(data, errors, path, key = "subtypes")
80
+ list(data, key, errors, path).filter_map do |raw|
63
81
  sub = raw.to_s.downcase.tr(" -", "__")
64
82
  next sub.to_sym if SUBTYPE.match?(sub)
65
83
 
66
- errors << "#{path}.subtypes: invalid subtype #{raw.inspect}"
84
+ errors << "#{path}.#{key}: invalid subtype #{raw.inspect}"
67
85
  nil
68
86
  end
69
87
  end
@@ -109,7 +127,11 @@ module Enjine
109
127
  end
110
128
 
111
129
  def initialize(types: [], subtypes: [], supertypes: [], name: nil, any_of: [], not_types: [], permanent: false,
112
- mana_value: {}, colors: [], color_count: {})
130
+ mana_value: {}, colors: [], color_count: {}, keywords: [], not_subtypes: [], stats: {}, layout: nil)
131
+ @keywords = keywords.freeze
132
+ @not_subtypes = not_subtypes.freeze
133
+ @stats = stats.freeze
134
+ @layout = layout
113
135
  @colors = colors.freeze
114
136
  @color_count = color_count.freeze
115
137
  @types = types.freeze
@@ -126,7 +148,8 @@ module Enjine
126
148
  # True when the spec states no quality: "a card" (CR 701.23d).
127
149
  def any?
128
150
  types.empty? && not_types.empty? && subtypes.empty? && supertypes.empty? && name.nil? && any_of.empty? &&
129
- !permanent && mana_value.empty? && colors.empty? && color_count.empty?
151
+ !permanent && mana_value.empty? && colors.empty? && color_count.empty? && keywords.empty? && not_subtypes.empty? &&
152
+ stats.empty? && layout.nil?
130
153
  end
131
154
 
132
155
  # Whether a card object matches, by its current characteristics (CR 109.3). `ctx` (an EffectContext)
@@ -139,22 +162,41 @@ module Enjine
139
162
  subtypes.all? { chars.subtypes.include?(it) } && supertypes.all? { chars.supertypes.include?(it) } &&
140
163
  (name.nil? || chars.name == name) && (!permanent || chars.types.intersect?(PERMANENT_TYPES)) &&
141
164
  (colors.empty? || colors.intersect?(chars.colors)) && bounded?(mana_value, chars.mana_cost&.mana_value.to_i, engine, ctx) &&
142
- bounded?(color_count, chars.colors.size, engine, ctx) && (any_of.empty? || any_of.any? { it.chars_match?(engine, chars, ctx) })
165
+ bounded?(color_count, chars.colors.size, engine, ctx) && (any_of.empty? || any_of.any? { it.chars_match?(engine, chars, ctx) }) &&
166
+ other_qualities?(engine, chars, ctx)
167
+ end
168
+
169
+ # Keywords (CR 702.1), non-subtypes and power/toughness (CR 208.1; a "*" with no value is 0 off the battlefield,
170
+ # CR 208.2b).
171
+ def other_qualities?(engine, chars, ctx)
172
+ (keywords.empty? || keywords.any? { chars.keyword?(it) }) && not_subtypes.none? { chars.subtypes.include?(it) } &&
173
+ stats.all? { |stat, bounds| bounded?(bounds, chars.public_send(stat).to_i, engine, ctx) } &&
174
+ (layout.nil? || engine.catalog[chars.name]&.layout == layout) # the card a name stands for (CR 201.2)
143
175
  end
144
176
 
145
177
  def to_s
146
178
  return "#{any_of.map { it.to_s.delete_suffix(" card") }.join(" or ")} card" unless any_of.empty?
147
179
  return "card named #{name}" if name
148
180
 
149
- words = not_types.map { "non#{it}" } + colors + supertypes + subtypes.map { it.to_s.capitalize } + types
181
+ words = not_types.map { "non#{it}" } + not_subtypes.map { "non-#{it.to_s.capitalize}" } + colors + supertypes +
182
+ subtypes.map { it.to_s.capitalize } + types
150
183
  words << "permanent" if permanent
151
- text = (words.map { it.to_s.tr("_", " ") } + ["card"]).join(" ")
152
- bounds = { "mana value" => mana_value, "number of colors" => color_count }.reject { |_, b| b.empty? }
184
+ text = (words.map { it.to_s.tr("_", " ") } + ["card"]).join(" ") + quality_words
185
+ bounds = { "mana value" => mana_value, "number of colors" => color_count, "power" => stats["power"] || {},
186
+ "toughness" => stats["toughness"] || {} }.reject { |_, b| b.empty? }
153
187
  return text if bounds.empty?
154
188
 
155
189
  "#{text} with #{bounds.map { |what, b| "#{what} #{b.map { |bound, n| "#{bound.tr("_", " ")} #{n}" }.join(" and ")}" }.join(", ")}"
156
190
  end
157
191
 
192
+ # " with flying", " that has an Adventure".
193
+ def quality_words
194
+ text = keywords.empty? ? "" : " with #{keywords.join(" or ").tr("_", " ")}"
195
+ return text unless layout
196
+
197
+ "#{text} that has #{"aeiou".include?(layout[0]) ? "an" : "a"} #{layout.capitalize}"
198
+ end
199
+
158
200
  private
159
201
 
160
202
  # CR 202.3: a card's mana value (0 without a mana cost, CR 202.3a), or its number of colors (CR 105.2), within