enjine 0.1.0 → 0.3.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +55 -1
  3. data/README.md +2 -1
  4. data/SUPPORTED.md +12 -9
  5. data/docs/ARCHITECTURE.md +2 -0
  6. data/docs/DESIGN.md +12 -5
  7. data/docs/MECHANICS_COVERAGE.md +33 -5
  8. data/docs/guides/api.md +51 -0
  9. data/docs/guides/card-data-format.md +43 -4
  10. data/docs/guides/deck-builder.md +18 -0
  11. data/docs/plans/commander.md +63 -0
  12. data/docs/plans/dsl-gaps.md +606 -0
  13. data/docs/plans/standard.md +3 -0
  14. data/docs/reference/abilities.md +33 -7
  15. data/docs/reference/costs.md +11 -1
  16. data/docs/reference/decisions.md +6 -2
  17. data/docs/reference/effects.md +30 -9
  18. data/docs/reference/triggers.md +3 -2
  19. data/lib/enjine/actions/cast.rb +2 -1
  20. data/lib/enjine/actions/special_action.rb +4 -2
  21. data/lib/enjine/card_definition.rb +24 -3
  22. data/lib/enjine/cli/text.rb +23 -1
  23. data/lib/enjine/cli.rb +2 -1
  24. data/lib/enjine/color_identity.rb +38 -0
  25. data/lib/enjine/decisions/commander_zone.rb +36 -0
  26. data/lib/enjine/deck.rb +73 -14
  27. data/lib/enjine/deck_builder.rb +62 -18
  28. data/lib/enjine/engine/casting/alt_casting.rb +19 -2
  29. data/lib/enjine/engine/casting/casting.rb +3 -3
  30. data/lib/enjine/engine/casting/costs.rb +5 -1
  31. data/lib/enjine/engine/casting/permissions.rb +3 -3
  32. data/lib/enjine/engine/characteristics.rb +0 -13
  33. data/lib/enjine/engine/commander.rb +125 -0
  34. data/lib/enjine/engine/damage.rb +1 -0
  35. data/lib/enjine/engine/defined_power_toughness.rb +30 -0
  36. data/lib/enjine/engine/emblems.rb +1 -1
  37. data/lib/enjine/engine/mana_sources.rb +8 -1
  38. data/lib/enjine/engine/pregame.rb +1 -0
  39. data/lib/enjine/engine/priority.rb +1 -0
  40. data/lib/enjine/engine/resolution.rb +1 -0
  41. data/lib/enjine/engine/rules.rb +1 -1
  42. data/lib/enjine/engine/state_based_actions.rb +1 -0
  43. data/lib/enjine/engine/triggers.rb +2 -1
  44. data/lib/enjine/engine/turn_history.rb +25 -1
  45. data/lib/enjine/engine/zones.rb +17 -6
  46. data/lib/enjine/format.rb +53 -0
  47. data/lib/enjine/fuzz.rb +17 -0
  48. data/lib/enjine/game.rb +4 -3
  49. data/lib/enjine/mechanics/abilities/additional_triggers.rb +23 -11
  50. data/lib/enjine/mechanics/abilities/cost_changes.rb +20 -7
  51. data/lib/enjine/mechanics/abilities/mana_ability.rb +21 -6
  52. data/lib/enjine/mechanics/abilities/stack_abilities.rb +13 -9
  53. data/lib/enjine/mechanics/abilities/static.rb +13 -7
  54. data/lib/enjine/mechanics/costs/sacrifice.rb +28 -2
  55. data/lib/enjine/mechanics/effects/become.rb +8 -4
  56. data/lib/enjine/mechanics/effects/choose_cards.rb +9 -7
  57. data/lib/enjine/mechanics/effects/delayed_triggers.rb +2 -1
  58. data/lib/enjine/mechanics/effects/search.rb +15 -8
  59. data/lib/enjine/mechanics/keywords/plot.rb +79 -0
  60. data/lib/enjine/mechanics/triggers/casting.rb +8 -6
  61. data/lib/enjine/mechanics/values.rb +82 -14
  62. data/lib/enjine/player.rb +2 -1
  63. data/lib/enjine/rules_monitor.rb +25 -1
  64. data/lib/enjine/setup.rb +10 -4
  65. data/lib/enjine/snapshot/player_checks.rb +47 -0
  66. data/lib/enjine/snapshot.rb +4 -1
  67. data/lib/enjine/state.rb +33 -14
  68. data/lib/enjine/version.rb +1 -1
  69. data/lib/enjine/view.rb +18 -1
  70. data/lib/enjine.rb +2 -0
  71. metadata +9 -1
@@ -9,6 +9,7 @@ module Enjine
9
9
  state.decklists.each_with_index do |list, owner|
10
10
  list.each { |card| state.players[owner].library << create_object(card, owner, :library).id }
11
11
  end
12
+ place_commanders! # CR 903.6
12
13
  emit Events::GameStarted.new(players: names, seed: state.seed)
13
14
  winner = state.rng.rand(state.players.size)
14
15
  emit Events::DieRolled.new(winner: name(winner))
@@ -9,6 +9,7 @@ module Enjine
9
9
  check_state_based_actions!
10
10
  return if state.over?
11
11
  return if legend_rule_first!(index)
12
+ return if commander_choice_first!(index) # CR 903.9
12
13
  return if put_triggers_first!(index)
13
14
 
14
15
  state.priority = index
@@ -67,6 +67,7 @@ module Enjine
67
67
  "object" => obj.id, "targets" => targets, "results" => {} }
68
68
  frame["ctx"]["linked"] = obj.memory["results"] if obj.memory.key?("results") # a delayed trigger's (CR 603.7c)
69
69
  frame["ctx"]["linked_amounts"] = obj.memory["amounts"] if obj.memory.key?("amounts") # a reflexive trigger's
70
+ frame["ctx"].merge!(Snapshot.deep_copy(obj.memory["departed"])) if obj.memory.key?("departed") # and its LKI
70
71
  end
71
72
 
72
73
  # CR 400.7j / 608.2c: objects an effect moves or creates, so later effects can refer to them
@@ -57,7 +57,7 @@ module Enjine
57
57
  @board_abilities_state = state
58
58
  @board_abilities = {}
59
59
  end
60
- @board_abilities[kind] ||= (state.battlefield + (state.command || [])).flat_map do |id|
60
+ @board_abilities[kind] ||= (state.battlefield + state.emblem_ids).flat_map do |id|
61
61
  source = object(id)
62
62
  chars(source).abilities.filter_map { [source, it.ability] if it.ability.kind == kind }
63
63
  end
@@ -18,6 +18,7 @@ module Enjine
18
18
  reason = if loses_for_life?(i) then "life" # CR 704.5a (unless an effect says otherwise)
19
19
  elsif pl.drew_from_empty then "empty_library" # CR 704.5b
20
20
  elsif pl.poison >= 10 then "poison" # CR 704.5c
21
+ elsif loses_to_commander_damage?(i) then "commander_damage" # CR 903.10a
21
22
  end
22
23
  pl.drew_from_empty = false
23
24
  lose!(i, reason) if reason
@@ -17,6 +17,7 @@ module Enjine
17
17
  current = chars(obj)
18
18
  { "controller" => obj.controller, "card" => obj.card, "types" => current.types, "subtypes" => current.subtypes,
19
19
  "power" => current.power, "toughness" => current.toughness, "counters" => obj.counters.dup,
20
+ "mana_value" => Mechanics::Amount.mana_value(self, obj), # CR 202.3
20
21
  "keywords" => current.keywords.map(&:to_s), # deathtouch, lifelink, wither (CR 702.2e, 702.15c, 702.80b)
21
22
  "token" => token?(obj), "except" => copy_exceptions(obj), "abilities" => current.abilities }
22
23
  .merge(obj.memory.slice(Mechanics::Linked::EXILED)) # the cards exiled with it (CR 607.2a)
@@ -127,7 +128,7 @@ module Enjine
127
128
 
128
129
  @trigger_epoch = @epoch
129
130
  @trigger_state = state
130
- @trigger_sources = (state.battlefield + (state.command || [])).filter_map do |id| # emblems too (CR 114.4)
131
+ @trigger_sources = (state.battlefield + state.emblem_ids).filter_map do |id| # emblems too (CR 114.4)
131
132
  instances = chars(id).triggered_abilities.select { it.ability.zone == :battlefield }
132
133
  [id, instances] unless instances.empty?
133
134
  end
@@ -109,7 +109,8 @@ module Enjine
109
109
  # The part of last known information an ability keeps in its memory ("source_lki"): plain data.
110
110
  def last_known_memory(lki)
111
111
  info = { "controller" => lki["controller"], "power" => lki["power"], "toughness" => lki["toughness"],
112
- "counters" => lki["counters"].dup, "card" => lki["card"], "keywords" => lki["keywords"].dup }
112
+ "mana_value" => lki["mana_value"], "counters" => lki["counters"].dup, "card" => lki["card"],
113
+ "keywords" => lki["keywords"].dup }
113
114
  info["except"] = lki["except"] if lki["except"] # what a copy of it copies (CR 707.2, Engine::Copies)
114
115
  info.merge(lki.slice(Mechanics::Linked::EXILED).transform_values(&:dup)) # CR 607.2a (Linked.exiled_with)
115
116
  end
@@ -117,6 +118,29 @@ module Enjine
117
118
  # What the resolving spell or ability remembers about an object that left the battlefield during it.
118
119
  def resolving_last_known(id) = state.frames.rfind { it["type"] == "resolve" && it["ctx"] }&.dig("ctx", "lki", id)
119
120
 
121
+ # A permanent that left the battlefield while a spell or ability resolves becomes a new object (CR 400.7);
122
+ # the resolving one links the new object to the permanent it was, so "the sacrificed creature's power"
123
+ # ({"power": {"result": n}}) is read as the permanent last existed (CR 608.2h).
124
+ def remember_departed!(new_id, old_id)
125
+ resolving = state.frames.rfind { it["type"] == "resolve" && it["ctx"] } or return
126
+ (resolving["ctx"]["departed"] ||= {})[new_id] = old_id
127
+ end
128
+
129
+ # What the resolving spell or ability knows of permanents that left (their last known information and the
130
+ # new objects they became), for a reflexive trigger it creates ("when you do", CR 603.12, 608.2h).
131
+ def departed_snapshot
132
+ ctx = state.frames.rfind { it["type"] == "resolve" && it["ctx"] }&.fetch("ctx") or return nil
133
+ snapshot = ctx.slice("lki", "departed")
134
+ snapshot.empty? ? nil : Snapshot.deep_copy(snapshot)
135
+ end
136
+
137
+ # The last known information of the permanent a new object was, if it left the battlefield during the
138
+ # resolving spell or ability.
139
+ def departed_last_known(new_id)
140
+ ctx = state.frames.rfind { it["type"] == "resolve" && it["ctx"] }&.fetch("ctx") or return nil
141
+ (old_id = ctx.dig("departed", new_id)) && ctx.dig("lki", old_id)
142
+ end
143
+
120
144
  # CR 702.171b: a permanent becomes saddled until the end of the turn; leaving the battlefield ends it (the
121
145
  # card is a new object, CR 400.7), and it isn't copiable (it lives on the object, not its characteristics).
122
146
  def saddle!(id) = object_memory!(id, "saddled")
@@ -120,15 +120,13 @@ module Enjine
120
120
  face_down = to == :exile ? data["face_down"] : nil
121
121
  fresh = create_object(card_after_move(old, to), old.owner, to, hidden: !face_down.nil?) # front face up (Engine::Faces)
122
122
  carry_copy_status!(fresh, old, to) # a token or copy stays one (Engine::Copies)
123
- if old.zone == :battlefield
124
- leave_combat!(id)
125
- end_while_source_effects!(id) # CR 611.2b
126
- end
123
+ left_battlefield!(fresh, old) if lki
127
124
  arrive!(fresh, old, data)
128
125
  fresh.memory.merge!("face_down" => true, "may_look" => face_down.uniq.sort) if face_down
129
126
  list = state.zone_list(to, old.owner)
130
127
  data["position"] == :bottom ? list.push(fresh.id) : list.unshift(fresh.id)
131
128
  record_result!(fresh.id)
129
+ note_commander_move!(fresh) # CR 903.9
132
130
  event = Events::ZoneChanged.new(card: old.card, old_id: id, new_id: fresh.id, owner: name(old.owner),
133
131
  from: old.zone.to_s, to: to.to_s, reason: data["reason"],
134
132
  lookers: face_down&.map { name(it) })
@@ -140,6 +138,14 @@ module Enjine
140
138
  fresh
141
139
  end
142
140
 
141
+ # A permanent that left the battlefield: the resolving spell or ability links the new object to it (CR 400.7,
142
+ # 608.2h; Engine::TurnHistory), it leaves combat, and effects lasting while it stays end (CR 611.2b).
143
+ def left_battlefield!(fresh, old)
144
+ remember_departed!(fresh.id, old.id)
145
+ leave_combat!(old.id)
146
+ end_while_source_effects!(old.id)
147
+ end
148
+
143
149
  # Status of the new object in its new zone (CR 110.2, 614.12 entering status).
144
150
  def arrive!(fresh, old, data)
145
151
  case data["to"]
@@ -225,8 +231,13 @@ module Enjine
225
231
  end
226
232
  end
227
233
 
228
- def shuffle_library!(index)
229
- state.rng.shuffle!(player(index).library)
234
+ # `then_on_top`: cards set aside while the rest is shuffled, then put on top in that order ("then shuffle and
235
+ # put that card on top"; they stay in the library, CR 701.24a).
236
+ def shuffle_library!(index, then_on_top: [])
237
+ library = player(index).library
238
+ library.reject! { then_on_top.include?(it) }
239
+ state.rng.shuffle!(library)
240
+ library.unshift(*then_on_top)
230
241
  emit Events::LibraryShuffled.new(player: name(index))
231
242
  end
232
243
 
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ # The rules a game is set up with: how it starts and what a legal deck is. `CONSTRUCTED` is the default
5
+ # (CR 100.2, 103.4); `DUEL_COMMANDER` is the two-player Commander variant (CR 903).
6
+ #
7
+ # Enjine::Setup.new(alice, bob, format: :duel_commander)
8
+ #
9
+ # A format is plain data: a game keeps only its name (State#format round-trips through snapshots).
10
+ Format = Data.define(:name, :starting_life, :deck_size, :commander) do
11
+ # `deck_size`: the sizes a deck may have, its commander included (CR 903.5a).
12
+ def commander? = commander
13
+
14
+ # The most copies of `definition` a deck may hold, nil for any number. Constructed: its own limit (CR 100.2a).
15
+ # Commander: one of each card named differently, only basic lands exempt (CR 903.5b).
16
+ def copy_limit(definition)
17
+ return definition.deck_limit unless commander?
18
+
19
+ definition.supertype?(:basic) ? nil : 1
20
+ end
21
+
22
+ def to_s = name
23
+ end
24
+
25
+ class Format
26
+ CONSTRUCTED = new(name: "constructed", starting_life: 20, deck_size: 60.., commander: false) # CR 100.2a, 103.4
27
+ DUEL_COMMANDER = new(name: "duel_commander", starting_life: 40, deck_size: 100..100, commander: true) # CR 903.5a, 903.7
28
+ ALL = [CONSTRUCTED, DUEL_COMMANDER].freeze
29
+
30
+ # Whether a card may be a commander: a legendary creature, Vehicle, or Spacecraft with power and toughness
31
+ # (CR 903.3). Cards that say they can be your commander are deferred.
32
+ def self.commander_card?(definition)
33
+ return false unless definition.supertype?(:legendary)
34
+
35
+ definition.type?(:creature) || definition.subtypes.include?(:vehicle) ||
36
+ (definition.subtypes.include?(:spacecraft) && stationed?(definition))
37
+ end
38
+
39
+ # A Spacecraft has power and toughness through a station symbol (CR 722.2b).
40
+ def self.stationed?(definition)
41
+ definition.abilities.any? { it.kind == :station_symbol && it.power }
42
+ end
43
+ private_class_method :stationed?
44
+
45
+ # The format a name (or a Format) stands for.
46
+ def self.fetch(value)
47
+ return value if value.is_a?(Format)
48
+
49
+ ALL.find { it.name == value.to_s } or
50
+ raise ArgumentError, "unknown format #{value.inspect} (use #{ALL.map { ":#{it.name}" }.join(", ")})"
51
+ end
52
+ end
53
+ end
data/lib/enjine/fuzz.rb CHANGED
@@ -39,6 +39,23 @@ module Enjine
39
39
  doc
40
40
  end
41
41
 
42
+ # A random legal Duel Commander deck (CR 903.5) from `cards`: a random legendary commander, then random
43
+ # distinct cards inside its color identity, filled up with basic lands of its colors. The cards need a
44
+ # legendary creature of at least one color and a basic land of each color.
45
+ def random_commander_deck(cards, rng:)
46
+ definitions = cards.map { CardDefinition.from_h(it) }.reject(&:token?)
47
+ leaders = definitions.select { Format.commander_card?(it) && !it.color_identity.empty? }
48
+ commander = leaders[rng.rand(leaders.size)]
49
+ identity = commander.color_identity
50
+ fitting = definitions.reject { it.supertype?(:basic) || it.id == commander.id || !(it.color_identity - identity).empty? }
51
+ chosen = rng.shuffle!(fitting).first(Format::DUEL_COMMANDER.deck_size.min / 2)
52
+ basics = identity.map { |color| definitions.find { it.supertype?(:basic) && ColorIdentity.land_colors(it) == [color] } }
53
+ counts = (Format::DUEL_COMMANDER.deck_size.min - 1 - chosen.size).times.map { basics[rng.rand(basics.size)] }.tally
54
+ { "cards" => (chosen + [commander] + counts.keys).map(&:to_h),
55
+ "main" => chosen.map { { "card" => it.id, "count" => 1 } } + counts.map { |card, n| { "card" => card.id, "count" => n } },
56
+ "commander" => commander.id }
57
+ end
58
+
42
59
  # Picks `number` random cards that still fit the four-copy rule, yielding each one's id.
43
60
  def draw(definitions, counts, rng, number)
44
61
  number.times do
data/lib/enjine/game.rb CHANGED
@@ -20,8 +20,9 @@ module Enjine
20
20
 
21
21
  attr_reader :catalog, :history
22
22
 
23
- def self.start(catalog:, names:, decklists:, seed:, outside: nil)
24
- new(catalog, State.initial(names: names, decklists: decklists, seed: seed, outside: outside)).tap(&:start!)
23
+ def self.start(catalog:, names:, decklists:, seed:, outside: nil, format: Format::CONSTRUCTED, commanders: nil)
24
+ state = State.initial(names: names, decklists: decklists, seed: seed, outside: outside, format: format, commanders: commanders)
25
+ new(catalog, state).tap(&:start!)
25
26
  end
26
27
 
27
28
  # Resumes a game from #export output (a JSON String or the parsed Hash).
@@ -125,7 +126,7 @@ module Enjine
125
126
  # Starts this game over from its opening, with the same or a new seed.
126
127
  def restart(seed: nil)
127
128
  fresh = State.initial(names: names, decklists: state.decklists, seed: seed.nil? ? state.seed : seed,
128
- outside: state.outside_lists)
129
+ outside: state.outside_lists, format: state.format, commanders: state.commanders)
129
130
  @engine.state = fresh
130
131
  @history = []
131
132
  @buffer.clear
@@ -12,24 +12,29 @@ module Enjine
12
12
 
13
13
  primitive :ability, :additional_triggers,
14
14
  description: "While this permanent is on the battlefield, a triggered ability of a permanent its " \
15
- "controller controls that triggers because of `cause` triggers an additional time. " \
16
- "`cause`: you_gain_life (its controller gaining life).",
17
- rules: %w[603.2d 119.9],
18
- params: { "cause" => CAUSES.join(" | ") },
19
- example: { "additional_triggers" => { "cause" => "you_gain_life" } }
15
+ "controller controls triggers an additional time if it triggers because of `cause` " \
16
+ "(you_gain_life: its controller gaining life) and/or its permanent matches `of` (a " \
17
+ "filter: \"triggered abilities of Allies you control\", {\"creature\": {\"other\": " \
18
+ "true, \"subtypes\": \"chosen\"}}). At least one of them.",
19
+ rules: %w[603.2d 119.9 607.2d],
20
+ params: { "cause" => CAUSES.join(" | "), "of" => "filter of the permanent whose ability triggers" },
21
+ example: { "additional_triggers" => { "of" => { "creature" => { "subtypes" => ["ally"] } } } }
20
22
 
21
- attr_reader :cause
23
+ attr_reader :cause, :of
22
24
 
23
25
  def self.build(params, errors, path, **)
24
- Mechanics.check_keys(params, %w[cause], errors, path)
26
+ Mechanics.check_keys(params, %w[cause of], errors, path)
25
27
  cause = Mechanics.fetch_param(params, :cause)
26
- errors << "#{path}.cause: must be one of #{CAUSES.join(", ")}" unless CAUSES.include?(cause)
27
- new(cause)
28
+ errors << "#{path}.cause: must be one of #{CAUSES.join(", ")}" unless cause.nil? || CAUSES.include?(cause)
29
+ raw = Mechanics.fetch_param(params, :of)
30
+ errors << "#{path}: needs cause or of" if cause.nil? && raw.nil?
31
+ new(cause, raw && Mechanics.build_entry(:filter, raw, errors, "#{path}.of"))
28
32
  end
29
33
 
30
- def initialize(cause)
34
+ def initialize(cause, filter = nil)
31
35
  super()
32
36
  @cause = cause
37
+ @of = filter
33
38
  freeze
34
39
  end
35
40
 
@@ -37,11 +42,18 @@ module Enjine
37
42
  def mana_ability? = false
38
43
  def allowed_types = nil
39
44
  def try_effects = []
40
- def to_s = "triggered abilities of your permanents that trigger from you gaining life trigger an additional time"
45
+
46
+ def to_s
47
+ label = of.is_a?(Class) ? of.primitive_name.to_s.tr("_", " ") : of.to_s
48
+ whose = of ? "each #{label} you control" : "your permanents"
49
+ "triggered abilities of #{whose}#{" that trigger from you gaining life" if cause} trigger an additional time"
50
+ end
41
51
 
42
52
  # `holder`: the permanent with this ability; `source`: the triggering ability's source (a permanent).
43
53
  def additional_trigger?(engine, event, holder, source)
44
54
  return false unless source["controller"] == holder.controller
55
+ return false if of && !of.match_for?(engine, source["id"], holder.controller, holder.id)
56
+ return true if cause.nil?
45
57
 
46
58
  event.is_a?(Events::LifeChanged) && event.gain.positive? && engine.names.index(event.player) == holder.controller
47
59
  end
@@ -73,14 +73,17 @@ module Enjine
73
73
  class CostModifier < Primitive
74
74
  TYPES = %w[artifact creature enchantment land planeswalker instant sorcery].freeze
75
75
  CASTERS = %w[you opponent any].freeze
76
+ SPEC_KEYS = %w[subtypes colors].freeze
76
77
 
77
78
  primitive :ability, :cost_modifier,
78
79
  description: "While on the battlefield: spells cast by `caster` (you, opponent or any; default you) " \
79
80
  "whose card types match `spells` ({\"any_of\": [types], \"not\": [types]}, default all " \
80
- "spells) cost `reduce` less or `increase` more generic mana. `from` / `not_from`: only " \
81
+ "spells; `subtypes` and `colors` narrow it: \"Dragon spells\", \"red spells\") cost " \
82
+ "`reduce` less or `increase` more generic mana. `from` / `not_from`: only " \
81
83
  "spells cast from (not from) that zone (hand | graveyard | exile | library | outside).",
82
84
  rules: %w[601.2f 118.7a 604.1 601.2a],
83
- params: { "spells" => "{\"any_of\": [types], \"not\": [types]} (optional)",
85
+ params: { "spells" => "{\"any_of\": [types], \"not\": [types], \"subtypes\": [subtypes], \"colors\": [colors]} " \
86
+ "(optional)",
84
87
  "caster" => "you | opponent | any", "reduce" => "amount", "increase" => "amount",
85
88
  "from" => "zone", "not_from" => "zone" },
86
89
  example: { "cost_modifier" => { "spells" => { "not" => ["creature"] }, "reduce" => 1 } }
@@ -94,7 +97,7 @@ module Enjine
94
97
  errors << "#{path}.spells: must be an object"
95
98
  spells = {}
96
99
  end
97
- Mechanics.check_keys(spells, %w[any_of not], errors, "#{path}.spells")
100
+ Mechanics.check_keys(spells, %w[any_of not] + SPEC_KEYS, errors, "#{path}.spells")
98
101
  lists = %w[any_of not].to_h do |key|
99
102
  list = Array(spells.transform_keys(&:to_s)[key]).map(&:to_s)
100
103
  errors << "#{path}.spells.#{key}: must be card types (#{TYPES.join(", ")})" unless (list - TYPES).empty?
@@ -103,7 +106,13 @@ module Enjine
103
106
  caster = Mechanics.fetch_param(params, :caster) || "you"
104
107
  errors << "#{path}.caster: must be one of #{CASTERS.join(", ")}" unless CASTERS.include?(caster)
105
108
  new(caster, lists["any_of"], lists["not"], *build_amount(params, errors, path),
106
- zones: CastFrom.build(params, errors, path))
109
+ zones: CastFrom.build(params, errors, path), spec: build_spec(spells, errors, path))
110
+ end
111
+
112
+ # "Dragon spells", "red spells": the subtypes and colors in `spells`, matched as a card spec.
113
+ def self.build_spec(spells, errors, path)
114
+ data = spells.transform_keys(&:to_s).slice(*SPEC_KEYS)
115
+ data.empty? ? nil : CardSpec.build(data, errors, "#{path}.spells")
107
116
  end
108
117
 
109
118
  def self.build_amount(params, errors, path)
@@ -115,8 +124,9 @@ module Enjine
115
124
  [Amount.build(params[keys.first], errors, "#{path}.#{keys.first}", targets_count: 0), keys.first == "reduce" ? -1 : 1]
116
125
  end
117
126
 
118
- def initialize(caster, any_of, not_types, amount, sign, zones: CastFrom.new(nil, nil))
127
+ def initialize(caster, any_of, not_types, amount, sign, zones: CastFrom.new(nil, nil), spec: nil)
119
128
  super()
129
+ @spec = spec
120
130
  @caster = caster
121
131
  @any_of = any_of.freeze
122
132
  @not_types = not_types.freeze
@@ -135,15 +145,18 @@ module Enjine
135
145
  def change_for(engine, permanent, spell, caster_index)
136
146
  return 0 unless caster == "any" || (caster == "you") == (caster_index == permanent.controller)
137
147
 
138
- types = engine.chars(spell).types
148
+ chars = engine.chars(spell)
149
+ types = chars.types
139
150
  return 0 if types.intersect?(not_types) || !(any_of.empty? || types.intersect?(any_of))
151
+ return 0 if @spec && !@spec.chars_match?(engine, chars)
140
152
  return 0 unless @zones.match?(engine.cast_origin(spell))
141
153
 
142
154
  sign * amount.value(engine, EffectContext.new(permanent.controller, permanent.id, permanent.id, []))
143
155
  end
144
156
 
145
157
  def to_s
146
- kinds = [not_types.map { "non#{it}" }, any_of.join(" or ")].flatten.reject(&:empty?).join(" ")
158
+ narrow = @spec ? [@spec.colors.map(&:to_s), @spec.subtypes.map { it.to_s.capitalize }] : []
159
+ kinds = [not_types.map { "non#{it}" }, narrow, any_of.join(" or ")].flatten.reject(&:empty?).join(" ")
147
160
  whose = { "you" => "you cast", "opponent" => "your opponents cast", "any" => "" }[caster]
148
161
  "#{[kinds, "spells", whose].reject(&:empty?).join(" ")}#{@zones} cost {#{amount}} " \
149
162
  "#{sign.negative? ? "less" : "more"}"
@@ -76,20 +76,22 @@ module Enjine
76
76
  "`amount` mana (default 1) of one color you choose as you activate it " \
77
77
  "(`\"any_one\"`) or in any combination of colors (`\"any\"`); `colors` limits " \
78
78
  "the choice. `\"chosen\"`: of the color chosen as this entered (choose_color). " \
79
- "`spend_only` restricts how the mana can be spent. `only_if`: \"Activate only if ...\".",
79
+ "`spend_only` restricts how the mana can be spent. `only_if`: \"Activate only if ...\". " \
80
+ "`limit: \"once_each_turn\"`: \"Activate only once each turn.\"",
80
81
  rules: %w[605.1a 605.3a 605.3b 106.1a 106.4 106.6 607.2d 602.5b],
81
82
  params: { "cost" => "list of costs (e.g. [\"tap\"])",
82
83
  "produce" => "mana symbols added, e.g. \"{G}\" or \"{C}{C}\"",
83
84
  "amount" => "amount (default 1; with produce: how many times)",
84
85
  "color" => CHOICES.join(" | "), "colors" => "list of colors to choose from (default all five)",
85
86
  "spend_only" => "{\"spells\": card spec, \"abilities\": card spec, \"from\" | \"not_from\": zone}",
86
- "only_if" => "condition: it can be activated only while it holds (CR 602.5b)" },
87
+ "only_if" => "condition: it can be activated only while it holds (CR 602.5b)",
88
+ "limit" => "\"once_each_turn\" (CR 602.5b)" },
87
89
  example: { "mana" => { "cost" => ["tap"], "produce" => "{C}" } }
88
90
 
89
91
  attr_reader :costs, :produce, :color, :colors, :amount, :spend_only
90
92
 
91
93
  def self.build(params, errors, path, **)
92
- Mechanics.check_keys(params, %w[cost produce amount color colors spend_only only_if], errors, path)
94
+ Mechanics.check_keys(params, %w[cost produce amount color colors spend_only only_if limit], errors, path)
93
95
  costs = build_costs(Mechanics.fetch_param(params, :cost), errors, path)
94
96
  raw = Mechanics.fetch_param(params, :produce)
95
97
  color = Mechanics.fetch_param(params, :color)
@@ -103,7 +105,8 @@ module Enjine
103
105
  raw_if = Mechanics.fetch_param(params, :only_if)
104
106
  only_if = raw_if && Condition.build(raw_if, errors, "#{path}.only_if")
105
107
  new(costs.compact.freeze, produce, color: color, colors: build_colors(params, color, errors, path),
106
- amount: amount, spend_only: spend_only, only_if: only_if)
108
+ amount: amount, spend_only: spend_only, only_if: only_if,
109
+ per_turn: build_limit(params, errors, path))
107
110
  end
108
111
 
109
112
  # CR 605.3a: a mana ability is paid for and resolves at once, so none of its costs can wait for a
@@ -126,6 +129,14 @@ module Enjine
126
129
  (cost.respond_to?(:mana_cost) && cost.mana_cost.hybrid.any? { Mana.mono_hybrid?(it) })
127
130
  end
128
131
 
132
+ LIMITS = { "once_each_turn" => 1 }.freeze
133
+
134
+ def self.build_limit(params, errors, path)
135
+ limit = Mechanics.fetch_param(params, :limit)
136
+ errors << "#{path}.limit: must be one of #{LIMITS.keys.join(", ")}" unless limit.nil? || LIMITS.key?(limit)
137
+ LIMITS[limit]
138
+ end
139
+
129
140
  def self.build_colors(params, color, errors, path)
130
141
  raw = Mechanics.fetch_param(params, :colors)
131
142
  return COLORS if raw.nil?
@@ -137,8 +148,9 @@ module Enjine
137
148
  COLORS
138
149
  end
139
150
 
140
- def initialize(costs, produce, color: nil, colors: COLORS, amount: nil, spend_only: nil, only_if: nil)
151
+ def initialize(costs, produce, color: nil, colors: COLORS, amount: nil, spend_only: nil, only_if: nil, per_turn: nil)
141
152
  super()
153
+ @per_turn = per_turn
142
154
  @costs = costs
143
155
  @produce = produce
144
156
  @color = color
@@ -164,6 +176,9 @@ module Enjine
164
176
  costs.all? { |c| c.payable?(engine, object) } && (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
165
177
  end
166
178
 
179
+ # How many times it may be activated each turn (nil: no limit, CR 602.5b); kept by Engine#record_activation!.
180
+ attr_reader :per_turn
181
+
167
182
  # The sum of its mana costs, or nil.
168
183
  attr_reader :mana_cost
169
184
 
@@ -201,7 +216,7 @@ module Enjine
201
216
  "#{" (#{colors.join("/")})" unless colors == COLORS}"
202
217
  end
203
218
  "#{costs.join(", ")}: #{what}.#{" #{spend_only.to_s.capitalize}." if spend_only}" \
204
- "#{" Activate only if #{@only_if}." if @only_if}"
219
+ "#{" Activate only if #{@only_if}." if @only_if}#{" Activate only once each turn." if per_turn}"
205
220
  end
206
221
  end
207
222
  end
@@ -350,8 +350,8 @@ module Enjine
350
350
 
351
351
  own = costs.filter_map { it.zone if it.respond_to?(:zone) }.first
352
352
  errors << "#{path}.zone: its costs are paid from the #{own}" if own && own.to_s != zone
353
- if costs.any? { it.is_a?(Costs::Tap) || it.is_a?(Costs::SacrificeSelf) }
354
- errors << "#{path}.zone: an ability of a card in the #{zone} can't tap or sacrifice it"
353
+ if costs.any? { it.is_a?(Costs::Tap) || Costs::LEAVING_SELF.include?(it.class) }
354
+ errors << "#{path}.zone: an ability of a card in the #{zone} can't tap, sacrifice or exile it"
355
355
  end
356
356
  zone.to_sym
357
357
  end
@@ -386,9 +386,9 @@ module Enjine
386
386
  def self.check_cost_zones(costs, errors, path)
387
387
  zones = costs.filter_map { it.zone if it.respond_to?(:zone) }.uniq
388
388
  errors << "#{path}.cost: costs can't be paid from both #{zones.join(" and ")}" if zones.size > 1
389
- return if zones.empty? || costs.none? { it.is_a?(Costs::Tap) || it.is_a?(Costs::SacrificeSelf) }
389
+ return if zones.empty? || costs.none? { it.is_a?(Costs::Tap) || Costs::LEAVING_SELF.include?(it.class) }
390
390
 
391
- errors << "#{path}.cost: a cost paid from the #{zones.first} can't be combined with tap or sacrifice"
391
+ errors << "#{path}.cost: a cost paid from the #{zones.first} can't be combined with tap, sacrifice or exile"
392
392
  end
393
393
 
394
394
  attr_reader :cost_reduction
@@ -513,7 +513,8 @@ module Enjine
513
513
  "and is paid on activation. Sorcery speed, and only one loyalty ability per " \
514
514
  "planeswalker per turn.",
515
515
  rules: %w[606.3 606.4 606.5 602.2b],
516
- params: { "cost" => "integer, e.g. 1 for +1 or -2", "targets" => "list of target filters",
516
+ params: { "cost" => "integer, e.g. 1 for +1 or -2; or \"-X\" (X is announced, at most its loyalty)",
517
+ "targets" => "list of target filters",
517
518
  "effects" => "list of effects" },
518
519
  example: { "loyalty" => { "cost" => -3, "targets" => ["creature"],
519
520
  "effects" => [{ "deal_damage" => { "amount" => 3, "to" => { "target" => 0 } } }] } }
@@ -521,8 +522,8 @@ module Enjine
521
522
  def self.build(params, errors, path, **)
522
523
  Mechanics.check_keys(params, %w[cost] + BODY_KEYS, errors, path)
523
524
  cost = Mechanics.fetch_param(params, :cost)
524
- errors << "#{path}.cost: must be an integer loyalty change" unless cost.is_a?(Integer)
525
- new(**parse_body(params, errors, path), loyalty: cost.to_i)
525
+ errors << "#{path}.cost: must be an integer loyalty change or \"-X\"" unless cost.is_a?(Integer) || cost == "-X"
526
+ new(**parse_body(params, errors, path), loyalty: cost == "-X" ? cost : cost.to_i)
526
527
  end
527
528
 
528
529
  def initialize(loyalty:, **)
@@ -531,11 +532,14 @@ module Enjine
531
532
  end
532
533
 
533
534
  def kind = :loyalty
534
- def loyalty_cost = @loyalty
535
+ def loyalty? = true
536
+ # The fixed loyalty change; a "-X" ability's is chosen as it's activated (CR 107.3, 601.2b), so it's 0 here.
537
+ def loyalty_cost = x_loyalty? ? 0 : @loyalty
538
+ def x_loyalty? = @loyalty == "-X"
535
539
  def sorcery_speed? = true
536
540
  def allowed_types = [:planeswalker]
537
541
 
538
- def to_s = "#{"+" if @loyalty.positive?}#{@loyalty}: #{effects_text}"
542
+ def to_s = "#{"+" if !x_loyalty? && @loyalty.positive?}#{@loyalty}: #{effects_text}"
539
543
  end
540
544
  end
541
545
  end
@@ -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 hexproof_from protection_from tapping_power].freeze
45
+ GRANTABLE = %i[triggered mana activated loyalty hexproof_from protection_from tapping_power].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
@@ -272,17 +272,22 @@ module Enjine
272
272
  module Effects
273
273
  # "gains flying until end of turn" (CR 611.2, 613.1f): grant keywords to a locked set.
274
274
  class Grant < Effect
275
+ DURATIONS = %w[end_of_turn until_your_next_turn].freeze
276
+
275
277
  primitive :effect, :grant,
276
- description: "Each referenced permanent (or spell on the stack) gains the `keywords` until end of turn.",
277
- rules: %w[611.2a 611.2c 613.1f 514.2],
278
- params: { "keywords" => "list of keywords", "to" => "selector" },
278
+ description: "Each referenced permanent (or spell on the stack) gains the `keywords` until end of turn " \
279
+ "(`duration: \"until_your_next_turn\"`: until its controller's next turn begins).",
280
+ rules: %w[611.2a 611.2c 613.1f 514.2 500.1],
281
+ params: { "keywords" => "list of keywords", "to" => "selector", "duration" => DURATIONS.join(" | ") },
279
282
  example: { "grant" => { "keywords" => ["flying"], "to" => { "target" => 0 } } }
280
283
 
281
284
  attr_reader :keywords
282
285
 
283
- def self.keys = %w[keywords to if]
286
+ def self.keys = %w[keywords to duration if]
284
287
 
285
288
  def setup(params, errors, path)
289
+ @duration = Mechanics.fetch_param(params, :duration) || "end_of_turn"
290
+ errors << "#{path}.duration: must be one of #{DURATIONS.join(", ")}" unless DURATIONS.include?(@duration)
286
291
  @keywords = Array(Mechanics.fetch_param(params, :keywords)).map { it.to_s.downcase.tr(" -", "__") }
287
292
  errors << "#{path}.keywords: needs at least one keyword" if @keywords.empty?
288
293
  @keywords.each { errors << "#{path}.keywords: unknown keyword #{it.inspect}" unless Enjine.registry.fetch(:keyword, it) }
@@ -291,10 +296,11 @@ module Enjine
291
296
  # A spell on the stack can gain keywords too ("those spells gain wither", Engine::SpellGrants).
292
297
  def apply(engine, ctx)
293
298
  spells = refs(engine, ctx).select { (obj = engine.state.objects[it]) && obj.zone == :stack && !obj.ability? }
294
- engine.add_continuous_effect!("grant", ctx, objects(engine, ctx) + spells, "keywords" => keywords)
299
+ engine.add_continuous_effect!("grant", ctx, objects(engine, ctx) + spells, "keywords" => keywords,
300
+ "duration" => @duration)
295
301
  end
296
302
 
297
- def to_s = "gains #{keywords.join(", ")} until end of turn → #{to}"
303
+ def to_s = "gains #{keywords.join(", ")} until #{@duration.delete_prefix("until_").tr("_", " ")} → #{to}"
298
304
  end
299
305
 
300
306
  # Setting a creature's creature types until end of turn; its other creature types are lost (CR 205.1a, 613.1d).