enjine 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -1
  3. data/SUPPORTED.md +34 -26
  4. data/docs/guides/card-data-format.md +143 -1
  5. data/docs/plans/dsl-gaps.md +99 -0
  6. data/docs/reference/abilities.md +46 -13
  7. data/docs/reference/costs.md +23 -6
  8. data/docs/reference/decisions.md +4 -0
  9. data/docs/reference/effects.md +118 -25
  10. data/docs/reference/filters.md +19 -2
  11. data/docs/reference/keywords.md +16 -2
  12. data/docs/reference/triggers.md +28 -7
  13. data/lib/enjine/actions/cast.rb +10 -3
  14. data/lib/enjine/actions/play_land.rb +3 -1
  15. data/lib/enjine/card_definition.rb +19 -3
  16. data/lib/enjine/cli/text.rb +10 -3
  17. data/lib/enjine/decisions/combat.rb +4 -2
  18. data/lib/enjine/decisions/damage_order.rb +18 -0
  19. data/lib/enjine/engine/ability_layers.rb +6 -1
  20. data/lib/enjine/engine/casting/alt_casting.rb +44 -4
  21. data/lib/enjine/engine/casting/cast_choices.rb +13 -1
  22. data/lib/enjine/engine/casting/casting.rb +43 -7
  23. data/lib/enjine/engine/casting/cost_options.rb +3 -1
  24. data/lib/enjine/engine/casting/permissions.rb +27 -23
  25. data/lib/enjine/engine/casting/target_counts.rb +14 -3
  26. data/lib/enjine/engine/casting/waterbend.rb +22 -2
  27. data/lib/enjine/engine/characteristics.rb +32 -14
  28. data/lib/enjine/engine/combat.rb +26 -7
  29. data/lib/enjine/engine/copies.rb +26 -12
  30. data/lib/enjine/engine/damage.rb +51 -1
  31. data/lib/enjine/engine/durations.rb +47 -0
  32. data/lib/enjine/engine/entering.rb +36 -2
  33. data/lib/enjine/engine/face_down.rb +12 -3
  34. data/lib/enjine/engine/faces.rb +16 -2
  35. data/lib/enjine/engine/follow_ups.rb +4 -1
  36. data/lib/enjine/engine/resolution.rb +46 -1
  37. data/lib/enjine/engine/rules.rb +6 -4
  38. data/lib/enjine/engine/state_based_actions.rb +8 -0
  39. data/lib/enjine/engine/triggers.rb +18 -21
  40. data/lib/enjine/engine/turn_history.rb +16 -1
  41. data/lib/enjine/engine/turn_structure.rb +1 -0
  42. data/lib/enjine/engine/zones.rb +23 -4
  43. data/lib/enjine/events.rb +6 -1
  44. data/lib/enjine/frames.rb +2 -2
  45. data/lib/enjine/mana.rb +3 -0
  46. data/lib/enjine/mechanics/abilities/chosen_values.rb +49 -6
  47. data/lib/enjine/mechanics/abilities/damage_replacements.rb +136 -64
  48. data/lib/enjine/mechanics/abilities/double_counters.rb +1 -1
  49. data/lib/enjine/mechanics/abilities/entering_choices.rb +40 -21
  50. data/lib/enjine/mechanics/abilities/play_permissions.rb +52 -19
  51. data/lib/enjine/mechanics/abilities/player_rules.rb +30 -13
  52. data/lib/enjine/mechanics/abilities/replacement_effects.rb +2 -1
  53. data/lib/enjine/mechanics/abilities/static.rb +8 -1
  54. data/lib/enjine/mechanics/card_spec.rb +99 -14
  55. data/lib/enjine/mechanics/costs/base.rb +67 -9
  56. data/lib/enjine/mechanics/costs/behold.rb +21 -5
  57. data/lib/enjine/mechanics/costs/choose_creature_type.rb +43 -0
  58. data/lib/enjine/mechanics/costs/one_of.rb +3 -0
  59. data/lib/enjine/mechanics/costs/pay_life.rb +27 -8
  60. data/lib/enjine/mechanics/costs/remove_counters.rb +8 -5
  61. data/lib/enjine/mechanics/costs/tap.rb +44 -3
  62. data/lib/enjine/mechanics/effects/base.rb +10 -2
  63. data/lib/enjine/mechanics/effects/become.rb +60 -21
  64. data/lib/enjine/mechanics/effects/copy.rb +63 -23
  65. data/lib/enjine/mechanics/effects/counters.rb +8 -2
  66. data/lib/enjine/mechanics/effects/damage.rb +11 -0
  67. data/lib/enjine/mechanics/effects/earthbend.rb +2 -1
  68. data/lib/enjine/mechanics/effects/fight.rb +11 -0
  69. data/lib/enjine/mechanics/effects/gain_control.rb +6 -3
  70. data/lib/enjine/mechanics/effects/library.rb +76 -18
  71. data/lib/enjine/mechanics/effects/pay.rb +7 -4
  72. data/lib/enjine/mechanics/effects/repeat.rb +92 -0
  73. data/lib/enjine/mechanics/effects/return_to_battlefield.rb +25 -6
  74. data/lib/enjine/mechanics/effects/search.rb +34 -6
  75. data/lib/enjine/mechanics/effects/tokens.rb +42 -10
  76. data/lib/enjine/mechanics/filters/base.rb +40 -13
  77. data/lib/enjine/mechanics/filters/exile.rb +27 -0
  78. data/lib/enjine/mechanics/filters/stack.rb +15 -9
  79. data/lib/enjine/mechanics/keywords/alternative_costs.rb +10 -6
  80. data/lib/enjine/mechanics/keywords/cards_have.rb +65 -0
  81. data/lib/enjine/mechanics/keywords/flags.rb +3 -1
  82. data/lib/enjine/mechanics/keywords/hideaway.rb +6 -5
  83. data/lib/enjine/mechanics/keywords/kicker.rb +24 -6
  84. data/lib/enjine/mechanics/keywords/protection.rb +24 -8
  85. data/lib/enjine/mechanics/keywords/riot.rb +13 -10
  86. data/lib/enjine/mechanics/linked.rb +32 -2
  87. data/lib/enjine/mechanics/selector.rb +32 -9
  88. data/lib/enjine/mechanics/triggers/base.rb +14 -3
  89. data/lib/enjine/mechanics/triggers/casting.rb +16 -10
  90. data/lib/enjine/mechanics/triggers/combat.rb +32 -12
  91. data/lib/enjine/mechanics/triggers/keyword_actions.rb +17 -0
  92. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +38 -11
  93. data/lib/enjine/mechanics/triggers/zone_changes.rb +1 -1
  94. data/lib/enjine/mechanics/values.rb +20 -10
  95. data/lib/enjine/mechanics.rb +5 -0
  96. data/lib/enjine/replacements.rb +3 -2
  97. data/lib/enjine/rules_monitor.rb +17 -4
  98. data/lib/enjine/steps.rb +10 -1
  99. data/lib/enjine/version.rb +1 -1
  100. data/lib/enjine/view.rb +1 -1
  101. metadata +7 -1
@@ -206,31 +206,44 @@ module Enjine
206
206
  # `to_player` "controller" (default), "owner" (each card's owner, CR 108.3) or a player selector
207
207
  # `cost_increase` generic mana added to the total cost of a spell cast with this permission (601.2f)
208
208
  # `any_mana_type` mana of any type may be spent to cast it (CR 609.4b)
209
+ # `during` "your_turn": only during the permission's player's turn
210
+ # `waterbend` "mana_value": cast by waterbending {X} rather than paying its mana cost, X its mana
211
+ # value (an alternative cost, CR 118.9, 701.67a)
209
212
  # Riders like these are stored on the permission (`state.effects` entry) and copied into the play
210
- # method, so only casts that use this permission (`via: "effect:<timestamp>"`) see them.
213
+ # method, so only casts that use this permission (`via: "effect:<timestamp>"`) see them. A
214
+ # `while_you_control_source` permission ends when its source leaves or changes control (CR 611.2b).
211
215
  class PlayPermission < ChoiceEffect
212
- DURATIONS = %w[end_of_turn end_of_your_next_turn while_exiled].freeze
216
+ DURATIONS = %w[end_of_turn end_of_your_next_turn until_your_next_end_step while_exiled
217
+ while_you_control_source].freeze
213
218
  PLAYERS = %w[controller owner].freeze
214
219
 
215
220
  primitive :effect, :play_permission,
216
221
  description: "A player may play (`play: \"play\"`, default) or cast (`\"cast\"`) each referenced " \
217
222
  "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 " \
223
+ "for `duration`: end_of_turn (default), end_of_your_next_turn, until_your_next_end_step, " \
224
+ "while_exiled or while_you_control_source (\"for as long as you control this creature\"). " \
225
+ "With " \
219
226
  "`choose: \"one_per_owner\"` only one chosen card per owner. `to_player`: who may " \
220
227
  "play it, \"controller\" (default, the effect's controller), \"owner\" (the card's " \
221
228
  "owner) or a player selector (a face-down card: only someone who may look at it). " \
222
229
  "`cost_increase`: spells cast this way cost that much generic mana more. " \
223
- "`any_mana_type: true`: mana of any type can be spent to cast those spells.",
224
- rules: %w[611.2a 601.3 305.1 400.7 514.2 601.2f 108.3 406.3b 609.4b],
230
+ "`any_mana_type: true`: mana of any type can be spent to cast those spells. " \
231
+ "`during: \"your_turn\"`: only during your turn. `waterbend: \"mana_value\"`: cast it by " \
232
+ "waterbending {X} rather than paying its mana cost, where X is its mana value.",
233
+ rules: %w[611.2a 611.2b 601.3 305.1 400.7 514.2 601.2f 108.3 406.3b 609.4b 118.9 701.67a],
225
234
  params: { "to" => "selector (usually {\"result\": n})", "duration" => DURATIONS.join(" | "),
226
235
  "play" => "play | cast", "for" => "card spec", "not_types" => "list of card types",
227
236
  "choose" => "one_per_owner", "to_player" => "controller | owner | player selector",
228
237
  "cost_increase" => "integer >= 1", "any_mana_type" => "boolean",
229
238
  "exile_instead" => "true or a card spec: if a spell cast this way (matching it) would be put " \
230
- "into a graveyard, it's exiled instead (CR 614.1a)" },
239
+ "into a graveyard, it's exiled instead (CR 614.1a)",
240
+ "during" => "your_turn", "waterbend" => "mana_value" },
231
241
  example: { "play_permission" => { "to" => { "result" => 0 }, "duration" => "end_of_your_next_turn" } }
232
242
 
233
- def self.keys = %w[to duration play for not_types choose to_player cost_increase any_mana_type exile_instead if]
243
+ def self.keys
244
+ %w[to duration play for not_types choose to_player cost_increase any_mana_type exile_instead during
245
+ waterbend if]
246
+ end
234
247
 
235
248
  def setup(params, errors, path)
236
249
  @duration = Mechanics.fetch_param(params, :duration) || "end_of_turn"
@@ -250,18 +263,23 @@ module Enjine
250
263
  more = @riders["cost_increase"] ? ", costs {#{@riders["cost_increase"]}} more" : ""
251
264
  more += ", mana of any type" if @riders["any_mana_type"]
252
265
  more += ", #{ExileInstead.words(@riders["exile_instead"])}" if @riders["exile_instead"]
266
+ more += ", during your turn" if @riders["during"]
267
+ more += ", by waterbending {X} (X: its mana value)" if @riders["waterbend"]
253
268
  "#{who} may #{@play} #{@filter} (#{@duration.tr("_", " ")}#{more}) → #{to}"
254
269
  end
255
270
 
256
271
  def run(engine, ctx, locals)
257
272
  return :done unless locals["cards"] || condition.nil? || condition.true?(engine, ctx)
273
+ # CR 611.2b: "for as long as you control [this]" that has already ended never starts.
274
+ return :done unless engine.source_duration_holds?(@duration, ctx.source, ctx.controller)
258
275
 
259
276
  cards = (locals["cards"] ||= refs(engine, ctx).select { exiled_match?(engine, it) })
260
277
  picks = @choose ? choose(engine, ctx, locals, cards) : cards
261
278
  return :wait if picks == :wait
262
279
 
280
+ source = ctx.source if Engine::Rules::WHILE_SOURCE.include?(@duration)
263
281
  picks.flat_map { |id| players_for(engine, ctx, id).map { [it, id] } }.group_by(&:first).each do |index, pairs|
264
- engine.grant_play_permission!(index, pairs.map(&:last), duration: @duration, play: @play, **@riders)
282
+ engine.grant_play_permission!(index, pairs.map(&:last), duration: @duration, play: @play, source: source, **@riders)
265
283
  end
266
284
  :done
267
285
  end
@@ -280,7 +298,15 @@ module Enjine
280
298
  errors << "#{path}.cost_increase: must be an integer >= 1" unless ok
281
299
  any_type = Mechanics.flag_param(params, :any_mana_type, errors, path)
282
300
  { "cost_increase" => increase, "any_mana_type" => (true if any_type),
283
- "exile_instead" => ExileInstead.build(params, errors, path) }.compact
301
+ "exile_instead" => ExileInstead.build(params, errors, path),
302
+ "during" => fixed_word(params, :during, "your_turn", errors, path),
303
+ "waterbend" => fixed_word(params, :waterbend, "mana_value", errors, path) }.compact
304
+ end
305
+
306
+ def fixed_word(params, key, word, errors, path)
307
+ value = Mechanics.fetch_param(params, key)
308
+ errors << "#{path}.#{key}: must be \"#{word}\"" unless value.nil? || value == word
309
+ value
284
310
  end
285
311
 
286
312
  # The players who may play `id`: the effect's controller, the card's owner, or the selected players.
@@ -318,23 +344,27 @@ module Enjine
318
344
  # the controller picks a card, casts it right away (a cast frame on top of the resolving one; nobody
319
345
  # gets priority), then the resolution goes on. `count: "any"` repeats until they stop.
320
346
  class CastFree < ChoiceEffect
347
+ FROM = %w[hand graveyard].freeze
348
+
321
349
  primitive :effect, :cast_free,
322
350
  description: "The controller may cast referenced cards without paying their mana costs while this " \
323
351
  "resolves. `to` names the cards ({\"result\": n}), or a player for the cards in their " \
324
- "hand (default: your hand). Only cards matching `for`/`not_types` with mana value up to " \
325
- "`max_mana_value` (optional amount) that could be cast now (legal targets). `count`: 1 " \
326
- "(default) or \"any\" (any number, one at a time). X is 0 (CR 107.3b). `play: true` " \
352
+ "hand (default: your hand), or in the zone `from` (hand | graveyard). Only cards " \
353
+ "matching `for`/`not_types` with mana value up to `max_mana_value` (optional amount) " \
354
+ "that could be cast now (legal targets). `count`: 1 (default), up to N (an integer), or " \
355
+ "\"any\" (any number, one at a time). X is 0 (CR 107.3b). `play: true` " \
327
356
  "(\"you may play\"): a land among them may be played, on your turn with a land play " \
328
357
  "left (`{type: \"play_land\"}`). A face-down card is judged face up.",
329
358
  rules: %w[608.2g 118.9 601.2a 107.3b 118.6a 305.2a 305.3 406.3a],
330
359
  params: { "to" => "selector", "for" => "card spec", "not_types" => "list of card types",
331
- "max_mana_value" => "amount", "count" => "1 or \"any\"", "play" => "boolean",
360
+ "max_mana_value" => "amount", "count" => "integer >= 1 (default 1) or \"any\"",
361
+ "from" => FROM.join(" | "), "play" => "boolean",
332
362
  "exile_instead" => "true or a card spec: if a spell cast this way (matching it) would be put " \
333
363
  "into a graveyard, it's exiled instead (CR 614.1a)",
334
364
  "any_mana_type" => "boolean: mana of any type can be spent to cast it (CR 609.4b)" },
335
365
  example: { "cast_free" => { "to" => { "result" => 0 }, "max_mana_value" => 3, "count" => "any" } }
336
366
 
337
- def self.keys = %w[to for not_types max_mana_value count play exile_instead any_mana_type if]
367
+ def self.keys = %w[to from for not_types max_mana_value count play exile_instead any_mana_type if]
338
368
  def self.default_to = "you"
339
369
 
340
370
  def setup(params, errors, path)
@@ -344,14 +374,17 @@ module Enjine
344
374
  raw = Mechanics.fetch_param(params, :max_mana_value)
345
375
  @max = raw.nil? ? nil : Amount.build(raw, errors, "#{path}.max_mana_value", targets_count: @targets_count)
346
376
  @count = Mechanics.fetch_param(params, :count) || 1
347
- errors << "#{path}.count: must be 1 or \"any\"" unless [1, "any"].include?(@count)
377
+ errors << "#{path}.count: must be an integer >= 1 or \"any\"" unless @count == "any" || (@count.is_a?(Integer) && @count >= 1)
378
+ @from = Mechanics.fetch_param(params, :from) || "hand"
379
+ errors << "#{path}.from: must be one of #{FROM.join(", ")}" unless FROM.include?(@from)
348
380
  @play = Mechanics.flag_param(params, :play, errors, path)
349
381
  end
350
382
 
351
383
  def to_s
352
384
  more = @riders["any_mana_type"] ? ", mana of any type" : ""
353
385
  more += ", #{ExileInstead.words(@riders["exile_instead"])}" if @riders["exile_instead"]
354
- "you may cast #{@count == "any" ? "any number of" : "a"} #{@filter} free#{more} → #{to}"
386
+ how_many = { "any" => "any number of", 1 => "a" }.fetch(@count) { "up to #{@count}" }
387
+ "you may cast #{how_many} #{@filter}#{" from #{@from}" unless @from == "hand"} free#{more} → #{to}"
355
388
  end
356
389
 
357
390
  def run(engine, ctx, locals)
@@ -371,7 +404,7 @@ module Enjine
371
404
  locals["playing"] = answer["object"]
372
405
  return :wait if play_land!(engine, index, locals) == :wait
373
406
  end
374
- return :done if @count == 1 && locals["cast"].to_i >= 1
407
+ return :done if @count != "any" && locals["cast"].to_i >= @count
375
408
 
376
409
  choices = candidates(engine, ctx, locals)
377
410
  return :done if choices.empty?
@@ -432,11 +465,11 @@ module Enjine
432
465
  :done
433
466
  end
434
467
 
435
- # Referenced cards still in the zone they were put in; a player stands for their hand.
468
+ # Referenced cards still in the zone they were put in; a player stands for their hand (or graveyard).
436
469
  def cards(engine, ctx)
437
470
  refs(engine, ctx).flat_map do |ref|
438
471
  index = Filters.player_index(engine, ref)
439
- next engine.player(index).hand if index
472
+ next engine.player(index).public_send(@from).dup if index
440
473
  next [] unless engine.state.objects.key?(ref)
441
474
 
442
475
  %i[stack battlefield].include?(engine.object(ref).zone) ? [] : [ref]
@@ -14,8 +14,10 @@ module Enjine
14
14
  # spells_cant_be_countered spells the player controls (matching `spells`) can't be countered (101.2, 701.6a)
15
15
  # abilities_cant_be_countered activated and triggered abilities the player controls can't be countered (101.2)
16
16
  # cant_gain_life the player can't gain life (119.7)
17
- # cant_activate the player can't activate abilities of sources matching `filter`, except mana
18
- # abilities (602.5)
17
+ # cant_activate the player can't activate abilities of sources matching `filter` (or, with `name:
18
+ # "chosen"`, with the name its source chose, in any zone), except mana abilities (602.5)
19
+ # cant_be_attacked creatures matching `filter` can't attack the player (their planeswalkers still can be)
20
+ # (508.1c)
19
21
  # protection_from_opponents the player has protection from each of their opponents: opponents' spells
20
22
  # and abilities can't target them and damage from opponents' sources is prevented
21
23
  # (702.16b, 702.16e, 702.16k)
@@ -30,11 +32,13 @@ module Enjine
30
32
  "abilities_cant_be_countered" => %w[101.2 701.6a],
31
33
  "cant_gain_life" => %w[119.7], "cant_activate" => %w[101.2 602.5],
32
34
  "damage_cant_be_prevented" => %w[615.12], "combat_damage_cant_be_prevented" => %w[615.12],
33
- "protection_from_opponents" => %w[702.16b 702.16e 702.16k]
35
+ "protection_from_opponents" => %w[702.16b 702.16e 702.16k],
36
+ "cant_be_attacked" => %w[508.1c 506.3]
34
37
  }.freeze
35
- # Rules that take a `filter` of permanents (required for cant_sacrifice) or a card spec of `spells`.
36
- FILTERED = %w[cant_sacrifice cant_activate].freeze
37
- REQUIRED_FILTER = %w[cant_sacrifice].freeze
38
+ # Rules that take a `filter` of permanents (required for cant_sacrifice and cant_be_attacked) or a card
39
+ # spec of `spells`.
40
+ FILTERED = %w[cant_sacrifice cant_activate cant_be_attacked].freeze
41
+ REQUIRED_FILTER = %w[cant_sacrifice cant_be_attacked].freeze
38
42
  SPELLS = %w[cant_cast spells_cant_be_countered].freeze
39
43
 
40
44
  def self.rule(params, errors, path)
@@ -69,34 +73,43 @@ module Enjine
69
73
  "applies to the players in `affects` (you | opponents | each; default you). Rules: " \
70
74
  "#{PlayerRules::RULES.keys.join(", ")}. `cant_sacrifice` takes a `filter` of the " \
71
75
  "permanents that can't be sacrificed, `cant_activate` may take a `filter` of the " \
72
- "sources whose abilities can't be activated (mana abilities still can), and " \
76
+ "sources whose abilities can't be activated (mana abilities still can) or `name: " \
77
+ "\"chosen\"` (sources with the name this permanent chose, in any zone), " \
78
+ "`cant_be_attacked` takes a `filter` of the creatures that can't attack them, and " \
73
79
  "`cant_cast` and `spells_cant_be_countered` may take a card spec of the `spells`. " \
74
80
  "The damage rules apply to all damage whichever players they name.",
75
81
  rules: PlayerRules::RULES.values.flatten.uniq + %w[604.1 604.2 611.3a],
76
82
  params: { "rule" => PlayerRules::RULES.keys.join(" | "), "affects" => AFFECTS.join(" | "),
77
83
  "filter" => "permanent filter (#{PlayerRules::FILTERED.join(", ")})",
78
84
  "spells" => "card spec of the spells (#{PlayerRules::SPELLS.join(", ")})",
85
+ "name" => "\"chosen\" (cant_activate: sources with the chosen name)",
79
86
  "if" => "condition (\"during your turn\": {\"your_turn\": true})" },
80
87
  example: { "player_rule" => { "rule" => "cant_cast", "affects" => "opponents", "if" => { "your_turn" => true } } }
81
88
 
82
89
  attr_reader :rule, :affects, :filter, :spells, :condition
83
90
 
84
91
  def self.build(params, errors, path, **)
85
- Mechanics.check_keys(params, %w[rule affects filter spells if], errors, path)
92
+ Mechanics.check_keys(params, %w[rule affects filter spells name if], errors, path)
86
93
  rule = PlayerRules.rule(params, errors, path)
87
94
  affects = Mechanics.fetch_param(params, :affects) || "you"
88
95
  errors << "#{path}.affects: must be one of #{AFFECTS.join(", ")}" unless AFFECTS.include?(affects)
89
96
  filter, spells = PlayerRules.qualifiers(params, rule, errors, path)
97
+ named = Mechanics.fetch_param(params, :name)
98
+ unless named.nil? || (named == "chosen" && rule == "cant_activate")
99
+ errors << "#{path}.name: must be \"chosen\", and only for cant_activate"
100
+ end
90
101
  raw_if = Mechanics.fetch_param(params, :if)
91
- new(rule, affects, filter, spells: spells, condition: raw_if && Condition.build(raw_if, errors, "#{path}.if"))
102
+ new(rule, affects, filter, spells: spells, chosen_name: !named.nil?,
103
+ condition: raw_if && Condition.build(raw_if, errors, "#{path}.if"))
92
104
  end
93
105
 
94
- def initialize(rule, affects, filter, spells: nil, condition: nil)
106
+ def initialize(rule, affects, filter, spells: nil, chosen_name: false, condition: nil)
95
107
  super()
96
108
  @rule = rule
97
109
  @affects = affects
98
110
  @filter = filter
99
111
  @spells = spells
112
+ @chosen_name = chosen_name
100
113
  @condition = condition
101
114
  freeze
102
115
  end
@@ -116,14 +129,18 @@ module Enjine
116
129
  condition.nil? || condition.true?(engine, EffectContext.new(source.controller, source.id, source.id, [], []))
117
130
  end
118
131
 
119
- # Whether the object asked about (a permanent for `filter`, a card for `spells`) is one the rule is about.
132
+ # Whether the object asked about (a permanent for `filter`, a card for `spells`, a source in any zone with
133
+ # the name its source chose for `name`, CR 201.4) is one the rule is about.
120
134
  def matches?(engine, object, source)
121
- (filter.nil? || filter.match?(engine, object.id, source.controller)) && (spells.nil? || spells.match?(engine, object))
135
+ return false if @chosen_name && engine.chars(object).name != source.memory["chosen_name"]
136
+
137
+ (filter.nil? || filter.match_for?(engine, object.id, source.controller, source.id)) &&
138
+ (spells.nil? || spells.match?(engine, object))
122
139
  end
123
140
 
124
141
  def to_s
125
142
  who = { "you" => "you", "opponents" => "your opponents", "each" => "each player" }.fetch(affects)
126
- about = filter || spells
143
+ about = filter || spells || ("sources with the chosen name" if @chosen_name)
127
144
  "#{who}: #{rule.tr("_", " ")}#{" (#{about.is_a?(Class) ? about.primitive_name : about})" if about}" \
128
145
  "#{" as long as #{condition}" if condition}"
129
146
  end
@@ -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)
@@ -42,7 +42,7 @@ module Enjine
42
42
  example: { "static" => { "affects" => { "each" => "creature", "controller" => "you" },
43
43
  "pump" => { "power" => 1, "toughness" => 1 } } }
44
44
 
45
- GRANTABLE = %i[triggered mana activated loyalty hexproof_from protection_from tapping_power].freeze
45
+ GRANTABLE = %i[triggered mana activated loyalty hexproof_from protection_from tapping_power cant_be_blocked_by].freeze
46
46
  # Data that would make the layer pass depend on its own result (CR 613.8).
47
47
  LIVE = %w[power toughness greatest_power attacking blocking tapped].freeze
48
48
  KEYS = %w[affects if pump keywords creature_types abilities types subtypes loses_abilities colors
@@ -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,25 @@ 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)
23
+ # {"subtypes": "chosen"} of the creature type chosen for the source (CR 607.2d)
24
+ # {"same_name_as": filter} the same name as a permanent the filter matches, e.g. "a
25
+ # legendary permanent you control" (CR 201.2a)
26
+ # The last two read the context (an EffectContext): the source's choices and its controller.
18
27
  class CardSpec
19
- KEYS = %w[types not_types subtypes supertypes name any_of permanent mana_value colors color_count].freeze
28
+ KEYS = %w[types not_types subtypes supertypes name any_of permanent mana_value colors color_count keywords
29
+ not_subtypes power toughness layout same_name_as].freeze
20
30
  SUBTYPE = /\A[a-z][a-z0-9_]*\z/
21
31
  # CR 110.4a: the permanent card types (battles have no primitive yet, so none matches that way).
22
32
  PERMANENT_TYPES = %i[artifact battle creature enchantment land planeswalker].freeze
23
33
  BOUNDS = %w[at_least at_most equal].freeze
24
34
 
25
- attr_reader :types, :not_types, :subtypes, :supertypes, :name, :any_of, :permanent, :mana_value, :colors, :color_count
35
+ attr_reader :types, :not_types, :subtypes, :supertypes, :name, :any_of, :permanent, :mana_value, :colors, :color_count,
36
+ :keywords, :not_subtypes, :stats, :layout, :relations
26
37
 
27
38
  def self.build(data, errors, path)
28
39
  return ANY if data.nil? || data == "card"
@@ -31,11 +42,30 @@ module Enjine
31
42
  data = data.transform_keys(&:to_s)
32
43
  Mechanics.check_keys(data, KEYS, errors, path)
33
44
  errors << "#{path}: needs at least one of #{KEYS.join(", ")}" if data.empty?
45
+ chosen = data["subtypes"] == "chosen"
34
46
  new(types: names(data, "types", :type, errors, path), supertypes: names(data, "supertypes", :supertype, errors, path),
35
- subtypes: subtype_list(data, errors, path), name: name_param(data, errors, path),
47
+ subtypes: chosen ? [] : subtype_list(data, errors, path), name: name_param(data, errors, path),
36
48
  any_of: alternatives(data, errors, path), not_types: names(data, "not_types", :type, errors, path),
37
49
  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))
50
+ colors: colors_param(data, errors, path), color_count: bounds_param(data, "color_count", errors, path),
51
+ keywords: names(data, "keywords", :keyword, errors, path), not_subtypes: subtype_list(data, errors, path, "not_subtypes"),
52
+ stats: %w[power toughness].to_h { [it, bounds_param(data, it, errors, path)] }.reject { |_, b| b.empty? },
53
+ layout: layout_param(data, errors, path), relations: relations_param(data, chosen, errors, path))
54
+ end
55
+
56
+ def self.layout_param(data, errors, path)
57
+ value = data["layout"]
58
+ unless value.nil? || CardDefinition::Faces::LAYOUTS.include?(value)
59
+ errors << "#{path}.layout: must be one of #{CardDefinition::Faces::LAYOUTS.join(", ")}"
60
+ end
61
+ value
62
+ end
63
+
64
+ # What the spec compares with its context: the chosen creature type, permanents to share a name with.
65
+ def self.relations_param(data, chosen, errors, path)
66
+ raw = data["same_name_as"]
67
+ same = raw && Mechanics.build_entry(:filter, raw, errors, "#{path}.same_name_as")
68
+ { "chosen_subtype" => (true if chosen), "same_name_as" => same }.compact
39
69
  end
40
70
 
41
71
  def self.colors_param(data, errors, path)
@@ -58,12 +88,12 @@ module Enjine
58
88
  end
59
89
  end
60
90
 
61
- def self.subtype_list(data, errors, path)
62
- list(data, "subtypes", errors, path).filter_map do |raw|
91
+ def self.subtype_list(data, errors, path, key = "subtypes")
92
+ list(data, key, errors, path).filter_map do |raw|
63
93
  sub = raw.to_s.downcase.tr(" -", "__")
64
94
  next sub.to_sym if SUBTYPE.match?(sub)
65
95
 
66
- errors << "#{path}.subtypes: invalid subtype #{raw.inspect}"
96
+ errors << "#{path}.#{key}: invalid subtype #{raw.inspect}"
67
97
  nil
68
98
  end
69
99
  end
@@ -109,7 +139,13 @@ module Enjine
109
139
  end
110
140
 
111
141
  def initialize(types: [], subtypes: [], supertypes: [], name: nil, any_of: [], not_types: [], permanent: false,
112
- mana_value: {}, colors: [], color_count: {})
142
+ mana_value: {}, colors: [], color_count: {}, keywords: [], not_subtypes: [], stats: {}, layout: nil,
143
+ relations: {})
144
+ @keywords = keywords.freeze
145
+ @not_subtypes = not_subtypes.freeze
146
+ @stats = stats.freeze
147
+ @layout = layout
148
+ @relations = relations.freeze
113
149
  @colors = colors.freeze
114
150
  @color_count = color_count.freeze
115
151
  @types = types.freeze
@@ -123,10 +159,19 @@ module Enjine
123
159
  freeze
124
160
  end
125
161
 
162
+ # The spec without what it reads from its context (the chosen type, a shared name).
163
+ def unrelated
164
+ return self if relations.empty?
165
+
166
+ CardSpec.new(types:, subtypes:, supertypes:, name:, any_of:, not_types:, permanent:, mana_value:, colors:, color_count:,
167
+ keywords:, not_subtypes:, stats:, layout:)
168
+ end
169
+
126
170
  # True when the spec states no quality: "a card" (CR 701.23d).
127
171
  def any?
128
172
  types.empty? && not_types.empty? && subtypes.empty? && supertypes.empty? && name.nil? && any_of.empty? &&
129
- !permanent && mana_value.empty? && colors.empty? && color_count.empty?
173
+ !permanent && mana_value.empty? && colors.empty? && color_count.empty? && keywords.empty? && not_subtypes.empty? &&
174
+ stats.empty? && layout.nil? && relations.empty?
130
175
  end
131
176
 
132
177
  # Whether a card object matches, by its current characteristics (CR 109.3). `ctx` (an EffectContext)
@@ -139,24 +184,64 @@ module Enjine
139
184
  subtypes.all? { chars.subtypes.include?(it) } && supertypes.all? { chars.supertypes.include?(it) } &&
140
185
  (name.nil? || chars.name == name) && (!permanent || chars.types.intersect?(PERMANENT_TYPES)) &&
141
186
  (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) })
187
+ bounded?(color_count, chars.colors.size, engine, ctx) && (any_of.empty? || any_of.any? { it.chars_match?(engine, chars, ctx) }) &&
188
+ other_qualities?(engine, chars, ctx) && (relations.empty? || related?(engine, chars, ctx))
189
+ end
190
+
191
+ # Keywords (CR 702.1), non-subtypes and power/toughness (CR 208.1; a "*" with no value is 0 off the battlefield,
192
+ # CR 208.2b).
193
+ def other_qualities?(engine, chars, ctx)
194
+ (keywords.empty? || keywords.any? { chars.keyword?(it) }) && not_subtypes.none? { chars.subtypes.include?(it) } &&
195
+ stats.all? { |stat, bounds| bounded?(bounds, chars.public_send(stat).to_i, engine, ctx) } &&
196
+ (layout.nil? || engine.catalog[chars.name]&.layout == layout) # the card a name stands for (CR 201.2)
143
197
  end
144
198
 
145
199
  def to_s
146
200
  return "#{any_of.map { it.to_s.delete_suffix(" card") }.join(" or ")} card" unless any_of.empty?
147
201
  return "card named #{name}" if name
148
202
 
149
- words = not_types.map { "non#{it}" } + colors + supertypes + subtypes.map { it.to_s.capitalize } + types
150
- 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? }
203
+ text = (type_words.map { it.to_s.tr("_", " ") } + ["card"]).join(" ") + quality_words
204
+ text += " with the same name as a #{relations["same_name_as"]}" if relations["same_name_as"]
205
+ bounds = { "mana value" => mana_value, "number of colors" => color_count, "power" => stats["power"] || {},
206
+ "toughness" => stats["toughness"] || {} }.reject { |_, b| b.empty? }
153
207
  return text if bounds.empty?
154
208
 
155
209
  "#{text} with #{bounds.map { |what, b| "#{what} #{b.map { |bound, n| "#{bound.tr("_", " ")} #{n}" }.join(" and ")}" }.join(", ")}"
156
210
  end
157
211
 
212
+ # "nonland", "non-Avatar", colors, supertypes, subtypes (or "chosen-type"), types and "permanent".
213
+ def type_words
214
+ chosen = relations["chosen_subtype"] ? ["chosen-type"] : []
215
+ words = not_types.map { "non#{it}" } + not_subtypes.map { "non-#{it.to_s.capitalize}" } + colors + supertypes +
216
+ subtypes.map { it.to_s.capitalize } + chosen + types
217
+ permanent ? words + ["permanent"] : words
218
+ end
219
+
220
+ # " with flying", " that has an Adventure".
221
+ def quality_words
222
+ text = keywords.empty? ? "" : " with #{keywords.join(" or ").tr("_", " ")}"
223
+ return text unless layout
224
+
225
+ "#{text} that has #{"aeiou".include?(layout[0]) ? "an" : "a"} #{layout.capitalize}"
226
+ end
227
+
158
228
  private
159
229
 
230
+ # The chosen creature type (CR 607.2d) and a shared name (CR 201.2a: an object with no name shares none); both
231
+ # need the context.
232
+ def related?(engine, chars, ctx)
233
+ return false unless ctx
234
+
235
+ if relations["chosen_subtype"]
236
+ chosen = Filters.chosen_memory(engine, ctx.source, ctx)["chosen_type"]
237
+ return false unless chosen && chars.subtypes.include?(chosen.to_sym)
238
+ end
239
+ filter = relations["same_name_as"] or return true
240
+ !chars.name.to_s.empty? && engine.state.battlefield.any? do
241
+ filter.match_for?(engine, it, ctx.controller, ctx.source) && engine.chars(it).name == chars.name
242
+ end
243
+ end
244
+
160
245
  # 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
161
246
  # the bounds.
162
247
  def bounded?(bounds, value, engine, ctx)
@@ -73,42 +73,100 @@ module Enjine
73
73
 
74
74
  # `count` cards from one of your zones (`zone`) matching the card spec `card`, never the card the spell
75
75
  # or ability belongs to: "discard a card", "exile two cards from your graveyard" (CR 601.2h, 602.2b).
76
+ #
77
+ # "Exile any number of black cards from your graveyard with fifteen or more black mana symbols among their mana
78
+ # costs" (CR 107.4, 202.1): `count: "any"` with `symbols: {"color": "B", "at_least": 15}`. The player chooses
79
+ # cards one at a time (`choose_cost`) and may stop (`done`) once the chosen cards have enough symbols.
76
80
  class CardsCost < Choosing
77
- def self.keys = %w[count card]
81
+ # Where cards exiled to pay a cost are remembered on the spell or ability (selector "exiled_for_cost").
82
+ EXILED = "exiled_for_cost"
83
+
84
+ def self.keys = %w[count card symbols]
78
85
  def self.zone = raise(NotImplementedError)
79
86
 
80
87
  # `count` "X": as many as the X announced for the spell or ability (CR 601.2b, 107.3a).
81
88
  def self.build(params, errors, path, **)
82
89
  Mechanics.check_keys(params, keys, errors, path)
83
- count = if Mechanics.fetch_param(params, :count) == "X" then "X"
84
- else Mechanics.integer_param(params, :count, errors, path, default: 1, min: 1)
85
- end
90
+ count = Mechanics.fetch_param(params, :count)
91
+ count = Mechanics.integer_param(params, :count, errors, path, default: 1, min: 1) unless %w[X any].include?(count)
86
92
  raw = Mechanics.fetch_param(params, :card)
87
93
  spec = raw && CardSpec.build(raw, errors, "#{path}.card")
88
94
  new(spec, count, false, params, errors, path)
89
95
  end
90
96
 
97
+ def initialize(filter, count, other, params, errors, path)
98
+ @symbols = symbols_param(Mechanics.fetch_param(params, :symbols), errors, path)
99
+ errors << "#{path}.count: \"any\" needs `symbols`" if (count == "any") != !@symbols.nil?
100
+ super
101
+ end
102
+
103
+ def symbols_param(raw, errors, path)
104
+ return nil if raw.nil?
105
+
106
+ ok = raw.is_a?(Hash) && Mana::COLORS.include?(raw["color"].to_s.upcase.to_sym) && raw["at_least"].is_a?(Integer) &&
107
+ raw["at_least"].positive? && raw.keys.sort == %w[at_least color]
108
+ return { "color" => raw["color"].to_s.upcase.to_sym, "at_least" => raw["at_least"] } if ok
109
+
110
+ errors << "#{path}.symbols: must be {\"color\": W|U|B|R|G, \"at_least\": integer >= 1}"
111
+ nil
112
+ end
113
+
114
+ # The card spec sees who pays (CR 201.2a: "the same name as a legendary permanent you control").
91
115
  def candidates(engine, object)
116
+ ctx = EffectContext.new(object.controller, object.id, object.id, [])
92
117
  engine.player(object.controller).public_send(self.class.zone).select do |id|
93
- id != object.id && (filter.nil? || filter.match?(engine, engine.object(id)))
118
+ id != object.id && (filter.nil? || filter.match?(engine, engine.object(id), ctx))
94
119
  end
95
120
  end
96
121
 
97
122
  # "Exile X cards": the engine asks for as many as X (Engine::CastChoices#cost_chosen?); X can be at
98
123
  # most the number of matching cards (Engine::Costs#x_limit).
99
124
  def x? = count == "X"
100
- def choices_needed = x? ? 0 : super
101
- def payable?(engine, object) = x? || super
125
+ def any? = count == "any"
126
+ def choices_needed = x? || any? ? 0 : super
102
127
  def x_limit(engine, object) = candidates(engine, object).size
103
128
 
129
+ def payable?(engine, object)
130
+ return true if x?
131
+ return super unless any?
132
+
133
+ symbols_among(engine, candidates(engine, object)) >= @symbols["at_least"]
134
+ end
135
+
136
+ # An "any number" choice remembers its card's symbols (CR 107.4e: a hybrid symbol is each of its colors).
137
+ def choose!(engine, option)
138
+ entry = super
139
+ any? ? entry.merge("symbols" => symbols_among(engine, [option[:object]])) : entry
140
+ end
141
+
142
+ def finishable?(entries) = any? && entries.sum { it["symbols"].to_i } >= @symbols["at_least"]
143
+
144
+ # Engine::CastChoices#cost_chosen?: "any number" is chosen once enough symbols are and the player is done.
145
+ def chosen?(engine, object, entries, done)
146
+ return entries.size >= choices_needed unless any?
147
+
148
+ finishable?(entries) && (done || choice_options(engine, object, entries).empty?)
149
+ end
150
+
151
+ def symbols_among(engine, ids) = ids.sum { engine.chars(it).mana_cost&.symbols_of(@symbols["color"]).to_i }
152
+
104
153
  # As it becomes cast, the chosen cards still where they were chosen are paid (exiled by default).
105
154
  def pay_chosen!(engine, _object, entries)
106
155
  entries.map { it["object"] }.select { engine.state.objects[it]&.zone == self.class.zone }.each { pay_card!(engine, it) }
107
156
  end
108
157
 
109
- def pay_card!(engine, id) = engine.move!(id, :exile, reason: "cost")
158
+ # An exiled card is remembered by the spell or ability being cast ("copy those exiled cards").
159
+ def pay_card!(engine, id)
160
+ fresh = engine.move!(id, :exile, reason: "cost") or return
161
+ holder = engine.casting && engine.state.objects[engine.casting["object"]]
162
+ (holder.memory[EXILED] ||= []) << fresh.id if holder
163
+ end
110
164
 
111
- def cards_text = "#{count == 1 ? "a" : count} #{filter || "card"}#{"s" unless count == 1}"
165
+ def cards_text
166
+ many = { 1 => "a", "any" => "any number of" }.fetch(count, count)
167
+ text = "#{many} #{filter || "card"}#{"s" unless count == 1}"
168
+ @symbols ? "#{text} with #{@symbols["at_least"]} or more {#{@symbols["color"]}} symbols among their mana costs" : text
169
+ end
112
170
  end
113
171
  end
114
172
  end