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
data/lib/enjine/deck.rb CHANGED
@@ -11,16 +11,24 @@ module Enjine
11
11
  # that is not exempt (basic lands). An invalid deck can still be built and edited;
12
12
  # it is simply not #valid?, so its player is not ready.
13
13
  #
14
+ # A Commander deck (CR 903) names its commander up front, beside the 99 cards of `main`:
15
+ #
16
+ # Deck.from_h({"cards" => [...], "main" => [...], "commander" => "Wort, the Raidmother"})
17
+ #
18
+ # Which rules apply depends on the game's Format: `errors(format)` checks the deck against it, so the
19
+ # same deck can be valid for one format and not another.
20
+ #
14
21
  # Outside the game (CR 400.11, 400.11a): the engine doesn't track a match, so a deck carries the cards
15
22
  # its player owns outside the game as `outside`: a constructed sideboard of at most 15 cards (CR 100.4a).
16
23
  # The four-copy limit applies to the deck and the outside list together, and outside cards don't count
17
24
  # toward the 60. Effects that bring a card into the game from outside it take the card from this list.
18
25
  class Deck
19
- MIN_SIZE = 60
26
+ MIN_SIZE = Format::CONSTRUCTED.deck_size.min
20
27
  MAX_COPIES = 4
21
28
  MAX_OUTSIDE = 15
29
+ NOT_A_COMMANDER = "can't be a commander; it must be a legendary creature, Vehicle or Spacecraft (CR 903.3)"
22
30
 
23
- attr_reader :catalog
31
+ attr_reader :catalog, :commander # commander: a definition id or nil (CR 903.3)
24
32
  attr_writer :guard
25
33
 
26
34
  def self.from_h(hash)
@@ -31,10 +39,13 @@ module Enjine
31
39
  lists = %w[cards main outside].to_h { [it, doc.fetch(it, [])] }
32
40
  lists.each { |key, list| raise InvalidDeck.new(["#{key}: must be a list"]) unless list.is_a?(Array) }
33
41
 
34
- new(cards: lists["cards"], main: lists["main"], outside: lists["outside"])
42
+ commander = doc["commander"]
43
+ raise InvalidDeck.new(["commander: must be a card name"]) unless commander.nil? || commander.is_a?(String)
44
+
45
+ new(cards: lists["cards"], main: lists["main"], outside: lists["outside"], commander: commander)
35
46
  end
36
47
 
37
- def initialize(cards: [], main: [], outside: [])
48
+ def initialize(cards: [], main: [], outside: [], commander: nil)
38
49
  @catalog = Catalog.new
39
50
  cards.each { @catalog.add(it) }
40
51
  @entries = {}
@@ -42,6 +53,7 @@ module Enjine
42
53
  @reference_errors = []
43
54
  main.each_with_index { |entry, i| load_entry(entry, i, @entries, "main") }
44
55
  outside.each_with_index { |entry, i| load_entry(entry, i, @outside, "outside") }
56
+ load_commander(commander)
45
57
  end
46
58
 
47
59
  # Ordered {id => count}.
@@ -57,20 +69,16 @@ module Enjine
57
69
  def outside_size = @outside.values.sum
58
70
  def outside_ids = @outside.flat_map { |id, n| [id] * n }
59
71
 
60
- def errors
72
+ # What is wrong with the deck for `format`, as messages (empty when it is legal).
73
+ def errors(format = Format::CONSTRUCTED)
61
74
  errs = @reference_errors.dup
62
- errs << "deck has #{size} cards; at least #{MIN_SIZE} are required (CR 100.2a)" if size < MIN_SIZE
75
+ errs.concat(size_errors(format))
63
76
  errs << "outside: #{outside_size} cards; at most #{MAX_OUTSIDE} are allowed (CR 100.4a)" if outside_size > MAX_OUTSIDE
64
- @entries.merge(@outside) { |_, a, b| a + b }.each do |id, n|
65
- limit = @catalog.fetch(id).deck_limit # nil: any number (basic lands, "deck_limit": "any")
66
- next if limit.nil? || n <= limit
67
-
68
- errs << "#{@catalog.fetch(id).name}: #{n} copies; at most #{limit} are allowed (CR 100.2a#{", 100.4a" if @outside.key?(id)})"
69
- end
70
- errs
77
+ errs.concat(copy_errors(format))
78
+ errs.concat(commander_errors(format))
71
79
  end
72
80
 
73
- def valid? = errors.empty?
81
+ def valid?(format = Format::CONSTRUCTED) = errors(format).empty?
74
82
 
75
83
  # Adds a card definition this deck can then use.
76
84
  def define(definition)
@@ -116,11 +124,62 @@ module Enjine
116
124
  # Tokens aren't listed: the cards that create them bring them back (two tokens may share a name).
117
125
  doc = { "cards" => @catalog.reject(&:token?).map(&:to_h), "main" => @entries.map { |id, n| { "card" => id, "count" => n } } }
118
126
  doc["outside"] = @outside.map { |id, n| { "card" => id, "count" => n } } unless @outside.empty?
127
+ doc["commander"] = @commander if @commander
119
128
  doc
120
129
  end
121
130
 
122
131
  private
123
132
 
133
+ # Cards in the deck, its commander included (CR 903.5a).
134
+ def total_size = size + (@commander ? 1 : 0)
135
+
136
+ def size_errors(format)
137
+ return [] if format.deck_size.cover?(total_size)
138
+
139
+ if format.commander?
140
+ ["deck has #{total_size} cards; exactly #{format.deck_size.min} are required, its commander included (CR 903.5a)"]
141
+ else
142
+ ["deck has #{size} cards; at least #{format.deck_size.min} are required (CR 100.2a)"]
143
+ end
144
+ end
145
+
146
+ # The copy limit counts the deck and the cards outside the game together (CR 100.4a), and the commander (CR 903.5b).
147
+ def copy_errors(format)
148
+ counts = @entries.merge(@outside) { |_, a, b| a + b }
149
+ counts.merge!(@commander => 1) { |_, a, b| a + b } if @commander
150
+ counts.filter_map do |id, n|
151
+ defn = @catalog.fetch(id)
152
+ limit = format.copy_limit(defn) # nil: any number (basic lands, "deck_limit": "any")
153
+ next if limit.nil? || n <= limit
154
+
155
+ rule = format.commander? ? "CR 903.5b" : "CR 100.2a#{", 100.4a" if @outside.key?(id)}"
156
+ "#{defn.name}: #{n} copies; at most #{limit} are allowed (#{rule})"
157
+ end
158
+ end
159
+
160
+ # A Commander deck has a commander that may lead it, and every card's color identity fits it (CR 903.3, 903.5c).
161
+ def commander_errors(format)
162
+ return @commander ? ["commander: only a Commander deck has one (CR 903.3)"] : [] unless format.commander?
163
+ return ["a Commander deck needs a commander (CR 903.3)"] unless @commander
164
+
165
+ lead = @catalog.fetch(@commander)
166
+ errs = Format.commander_card?(lead) ? [] : ["#{lead.name}: #{NOT_A_COMMANDER}"]
167
+ (@entries.keys + @outside.keys).uniq.each do |id|
168
+ outside = @catalog.fetch(id).color_identity - lead.color_identity
169
+ next if outside.empty?
170
+
171
+ errs << "#{@catalog.fetch(id).name}: color identity #{Mana.symbols(outside)} is not in its commander's (CR 903.5c)"
172
+ end
173
+ errs
174
+ end
175
+
176
+ def load_commander(card)
177
+ return if card.nil?
178
+ return @reference_errors << "commander: #{card.inspect} is not defined in cards" unless @catalog.include?(card)
179
+
180
+ @commander = CardDefinition.slug(card)
181
+ end
182
+
124
183
  def load_entry(entry, index, into, list)
125
184
  card, count = entry.is_a?(Hash) ? entry.transform_keys(&:to_s).values_at("card", "count") : []
126
185
  unless card.is_a?(String) && count.is_a?(Integer) && count.positive?
@@ -18,6 +18,11 @@ module Enjine
18
18
  # never holds more than n copies (and never more than CR 100.2a allows). Basic lands are always
19
19
  # available: the pool's own, else built-in ones.
20
20
  #
21
+ # With `commander:` it builds a Duel Commander deck (CR 903) instead: 99 distinct cards inside that
22
+ # commander's color identity, plus basic lands of its colors:
23
+ #
24
+ # builder.build(commander: "Wort, the Raidmother", seed: 3)
25
+ #
21
26
  # #build returns a deck document ({"name", "description", "cards", "main"}) that
22
27
  # Enjine::Player.new(name:, deck:) accepts. Same pool, arguments and seed, same deck: randomness
23
28
  # comes only from Enjine::Rng, and the pool is sorted by card id, so its order doesn't matter.
@@ -136,8 +141,11 @@ module Enjine
136
141
  # including: pool cards (names or ids) the deck must hold, as many copies as allowed up to 4; they must fit
137
142
  # the colors (a land: produce only deck colors). They define the deck, so a chosen color then
138
143
  # needs no card of its own: it may only bring basics.
139
- def build(seed:, colors: :any, size: BASE_SIZE, profile: {}, including: [])
140
- Draft.new(self, seed: seed, colors: colors, size: size, profile: profile, including: including).deck
144
+ # commander: a pool card (name or id) that may lead a deck (CR 903.3): the deck is a legal Duel Commander
145
+ # deck inside its color identity (CR 903.5), and `colors` and `size` come from it.
146
+ def build(seed:, colors: :any, size: BASE_SIZE, profile: {}, including: [], commander: nil)
147
+ Draft.new(self, seed: seed, colors: colors, size: size, profile: profile, including: including,
148
+ commander: commander).deck
141
149
  end
142
150
 
143
151
  # Copies of a card the pool holds: nil when uncapped, 0 when it isn't in the pool.
@@ -165,22 +173,24 @@ module Enjine
165
173
 
166
174
  # One #build call: the seed-dependent choices for one deck.
167
175
  class Draft
168
- def initialize(builder, seed:, colors:, size:, profile:, including:)
169
- raise ArgumentError, "size must be an Integer of at least #{Deck::MIN_SIZE}" unless size.is_a?(Integer) && size >= Deck::MIN_SIZE
170
-
176
+ def initialize(builder, seed:, colors:, size:, profile:, including:, commander: nil)
171
177
  @builder = builder
172
178
  @pool = builder.cards
173
179
  @rng = Rng.from_seed(seed)
174
180
  @seed = seed
175
- @size = size
176
- @profile = merge_profile(profile)
177
- @colors = resolve_colors(colors)
181
+ @commander = commander && lead_with(commander, colors, size)
182
+ @size = @commander ? Format::DUEL_COMMANDER.deck_size.min - 1 : check_size(size) # the commander is the 100th card
183
+ @profile = merge_profile(@commander ? profile.merge(copies: SINGLETON_COPIES) : profile)
184
+ @colors = @commander ? @commander.color_identity : resolve_colors(colors)
178
185
  @creatures = {}
179
186
  @others = {}
180
187
  @lands = {}
181
188
  include_cards(including)
182
189
  end
183
190
 
191
+ # CR 903.5b: one copy of each card.
192
+ SINGLETON_COPIES = { 4 => 0, 3 => 0, 2 => 0, 1 => 1 }.freeze
193
+
184
194
  def deck
185
195
  check_colors! if @creatures.empty? && @others.empty? && @lands.empty?
186
196
  lands = [scaled(sample(@profile[:lands])), @lands.values.sum].max
@@ -193,6 +203,34 @@ module Enjine
193
203
 
194
204
  # --- inputs -------------------------------------------------------------------------------------
195
205
 
206
+ def check_size(size)
207
+ raise ArgumentError, "size must be an Integer of at least #{Deck::MIN_SIZE}" unless size.is_a?(Integer) && size >= Deck::MIN_SIZE
208
+
209
+ size
210
+ end
211
+
212
+ # The pool card that leads the deck (CR 903.3). Its colors and the deck's size come from the format.
213
+ def lead_with(card, colors, size)
214
+ raise ArgumentError, "a Commander deck's colors and size come from its commander" unless colors == :any && size == BASE_SIZE
215
+
216
+ id = CardDefinition.slug(card)
217
+ raise ArgumentError, "#{card.inspect} is not in the pool" if @builder.count(id)&.zero?
218
+
219
+ @builder.definition(id).tap do |defn|
220
+ raise ArgumentError, "#{defn.name} can't be a commander (CR 903.3)" unless Format.commander_card?(defn)
221
+ if defn.color_identity.empty?
222
+ raise ArgumentError,
223
+ "#{defn.name} is colorless: a colorless commander needs Wastes, which the builder doesn't add"
224
+ end
225
+ end
226
+ end
227
+
228
+ # Whether a card may go in a deck of these colors; a Commander deck needs its color identity inside the
229
+ # commander's (CR 903.5c-d) too.
230
+ def fits?(definition, colors = @colors)
231
+ DeckBuilder.fits?(definition, colors) && (@commander.nil? || (definition.color_identity - @colors).empty?)
232
+ end
233
+
196
234
  def merge_profile(overrides)
197
235
  unknown = overrides.keys.map(&:to_sym) - DEFAULT_PROFILE.keys
198
236
  raise ArgumentError, "unknown profile keys: #{unknown.join(", ")}" unless unknown.empty?
@@ -229,12 +267,12 @@ module Enjine
229
267
  capacity(spells) >= @size - scaled(@profile[:lands][:outliers].max)
230
268
  end
231
269
 
232
- def spells_for(colors) = @pool.select { it.castable? && DeckBuilder.fits?(it, colors) }
270
+ def spells_for(colors) = @pool.select { it.castable? && fits?(it, colors) && it != @commander }
233
271
  def capacity(definitions) = definitions.sum { limit(it) }
234
272
 
235
273
  # Most copies of a card the deck may hold: 4 (CR 100.2a) or any number if exempt, and never
236
274
  # more than the pool holds.
237
- def limit(definition) = [definition.deck_limit || @size, @builder.count(definition.id) || @size].min
275
+ def limit(definition) = [@commander ? 1 : definition.deck_limit || @size, @builder.count(definition.id) || @size].min
238
276
 
239
277
  # Puts each required card in the deck with as many copies as it may hold, up to 4 (basics come anyway).
240
278
  def include_cards(cards)
@@ -243,7 +281,7 @@ module Enjine
243
281
  raise ArgumentError, "#{card.inspect} is not in the pool" if @builder.count(id)&.zero?
244
282
 
245
283
  defn = @builder.definition(id)
246
- fits = defn.land? ? DeckBuilder.produced_colors(defn).all? { @colors.include?(it) } : DeckBuilder.fits?(defn, @colors)
284
+ fits = defn.land? ? lands_fit?(defn) : fits?(defn)
247
285
  raise ArgumentError, "#{defn.name} does not fit a #{@colors.join} deck" unless fits
248
286
  next if DeckBuilder.basic?(defn) # every deck has its basics
249
287
 
@@ -376,8 +414,11 @@ module Enjine
376
414
  end
377
415
 
378
416
  def nonbasic_land?(definition)
379
- definition.land? && !definition.supertype?(:basic) && !definition.mana_abilities.empty? &&
380
- DeckBuilder.produced_colors(definition).all? { @colors.include?(it) }
417
+ definition.land? && !definition.supertype?(:basic) && !definition.mana_abilities.empty? && lands_fit?(definition)
418
+ end
419
+
420
+ def lands_fit?(definition)
421
+ DeckBuilder.produced_colors(definition).all? { @colors.include?(it) } && fits?(definition)
381
422
  end
382
423
 
383
424
  # Weight 4 for lands that produce two or more deck colors (duals), 2 for one color, 1 for colorless-only.
@@ -408,11 +449,14 @@ module Enjine
408
449
  nonbasic = pick_nonbasic_lands(lands)
409
450
  basics = split_basics(lands - nonbasic.values.sum)
410
451
  main = basics.map { |color, n| [basic_land(color), n] } + sorted(nonbasic) + spell_entries
411
- { "name" => "Random #{@colors.join} deck",
412
- "description" => "random deck: colors=#{@colors.join} seed=#{@seed} — #{lands} lands, " \
413
- "#{@creatures.values.sum} creatures, #{@others.values.sum} other spells, #{main.size} distinct cards",
414
- "cards" => main.map { it[0].to_h },
415
- "main" => main.map { |defn, n| { "card" => defn.name, "count" => n } } }
452
+ doc = { "name" => "Random #{@colors.join} deck",
453
+ "description" => "random deck: colors=#{@colors.join} seed=#{@seed} — #{lands} lands, " \
454
+ "#{@creatures.values.sum} creatures, #{@others.values.sum} other spells, #{main.size} distinct cards",
455
+ "cards" => main.map { it[0].to_h },
456
+ "main" => main.map { |defn, n| { "card" => defn.name, "count" => n } } }
457
+ return doc unless @commander
458
+
459
+ doc.merge("cards" => doc["cards"] + [@commander.to_h], "commander" => @commander.name)
416
460
  end
417
461
 
418
462
  def sorted(chosen)
@@ -8,7 +8,8 @@ module Enjine
8
8
  # {"via" => "alt:<ref>", "play" => "cast" | "play", "keyword" => "flashback", "instant" => true (sneak),
9
9
  # "alt" => {"cost" => "{2}{R}", "ref" => ref, "exile" => true, "returns" => "tapped" | "unblocked",
10
10
  # "harmonize" => true}}
11
- # and a warped card in exile has the method {"via" => "warped", "play" => "cast"} (CR 702.185a).
11
+ # and a warped card in exile has the method {"via" => "warped", "play" => "cast"} (CR 702.185a); a plotted one
12
+ # {"via" => "plotted", "play" => "cast", "alt" => {"free" => true}, "sorcery" => true} (CR 702.170d).
12
13
  #
13
14
  # How a spell was cast is remembered on the spell (memory "cast_from": the zone, "cast_with": the keyword)
14
15
  # and on the permanent it becomes (CR 400.7d), and each player's turn log keeps the keywords of the
@@ -32,7 +33,14 @@ module Enjine
32
33
  ability = inst.ability
33
34
  ability.method_for(inst.ref) if ability.kind == :alternative_cost && ability.functions?(self, obj, index)
34
35
  end
35
- own + warped_methods(index, obj)
36
+ own + warped_methods(index, obj) + plotted_methods(obj)
37
+ end
38
+
39
+ # CR 702.170d: a plotted card may be cast without paying its mana cost during its owner's main phase while
40
+ # the stack is empty, on any turn after the one it became plotted in (a sorcery's timing, whatever its type).
41
+ def plotted_methods(obj)
42
+ turn = obj.zone == :exile && obj.memory["plotted"]
43
+ turn && state.turn > turn ? [{ "via" => "plotted", "play" => "cast", "alt" => Permissions::FREE, "sorcery" => true }] : []
36
44
  end
37
45
 
38
46
  # CR 702.185a: "Its owner may cast this card after the current turn has ended for as long as it remains
@@ -42,6 +50,14 @@ module Enjine
42
50
  turn && state.turn > turn ? [{ "via" => "warped", "play" => "cast" }] : []
43
51
  end
44
52
 
53
+ # CR 304.1, 307.1: an instant or flash spell (or a method cast "any time you could cast an instant") at
54
+ # instant timing; anything else, and a plotted card whatever its type (CR 702.170d), at sorcery timing.
55
+ def method_timing?(index, chars, method)
56
+ return true if sorcery_timing?(index)
57
+
58
+ !method["sorcery"] && (chars.type?(:instant) || chars.keyword?(:flash) || method["instant"])
59
+ end
60
+
45
61
  # CR 702.187b: mayhem needs the card to have been discarded this turn (TurnHistory stamps it).
46
62
  def discarded_this_turn?(obj) = !turned_memory(obj, "discarded").nil?
47
63
 
@@ -127,6 +143,7 @@ module Enjine
127
143
  # trigger (CR 702.185a); the creatures that convoked it (CR 702.51c).
128
144
  def record_cast_how!(obj, ctx)
129
145
  obj.memory["cast_from"] = ctx.dig("origin", "zone") || "hand"
146
+ record_commander_cast!(ctx["player"], ctx["method"]) # CR 903.8 (Engine::Commander)
130
147
  obj.memory["convoked"] = ctx["convoked"].dup if ctx["convoked"]
131
148
  return unless ctx.dig("method", "alt") # mayhem without a cost: no keyword cost was paid
132
149
 
@@ -277,18 +277,18 @@ module Enjine
277
277
  end
278
278
 
279
279
  # The non-mana costs (CR 602.2b): its own ({T}, sacrifice it, exile it from the graveyard), then
280
- # the chosen ones (sacrifice another creature, remove counters). A source sacrificed as a cost is
280
+ # the chosen ones (sacrifice another creature, remove counters). A source sacrificed or exiled as a cost is
281
281
  # remembered as it last existed (its counters, CR 608.2h).
282
282
  def pay_ability_costs!(ctx, obj)
283
283
  source = object(ctx["source"])
284
284
  ability = chars(source).ability(ctx["ability"])
285
- obj.memory["source_counters"] = source.counters.dup if ability.costs.any?(Mechanics::Costs::SacrificeSelf)
285
+ obj.memory["source_counters"] = source.counters.dup if ability.costs.any? { Mechanics::Costs::LEAVING_SELF.include?(it.class) }
286
286
  frame_costs(ctx).reject(&:mana?).each { it.pay!(self, source) } # the chosen option of a one_of (CR 601.2b)
287
287
  pay_chosen_costs!(ctx)
288
288
  return unless ability.kind == :loyalty
289
289
 
290
290
  source.loyalty_turn = state.turn
291
- cost = ability.loyalty_cost
291
+ cost = ability.x_loyalty? ? -ctx["x"].to_i : ability.loyalty_cost
292
292
  cost.negative? ? remove_counters!(source, "loyalty", -cost) : add_counters!(source, "loyalty", cost)
293
293
  end
294
294
 
@@ -75,7 +75,7 @@ module Enjine
75
75
  # the mana cost or a cost such as "pay X life" or "exile X cards", X is 0.
76
76
  def ask_x!(ctx)
77
77
  return false unless ctx["x"].nil?
78
- return (ctx["x"] = 0) && false unless base_cost(ctx)&.x_symbols.to_i.positive? || x_costs(ctx).any?
78
+ return (ctx["x"] = 0) && false unless base_cost(ctx)&.x_symbols.to_i.positive? || x_costs(ctx).any? || x_loyalty?(ctx)
79
79
 
80
80
  ask!("kind" => "choose_x", "player" => ctx["player"], "max" => x_limit(ctx))
81
81
  true
@@ -85,6 +85,9 @@ module Enjine
85
85
  # graveyard" (Costs::CardsCost).
86
86
  def x_costs(ctx) = casting_costs(ctx).select { it.respond_to?(:x?) && it.x? }
87
87
 
88
+ # A "-X" loyalty ability being activated (CR 606.4, 107.3).
89
+ def x_loyalty?(ctx) = ctx["kind"] == "ability" && casting_ability.respond_to?(:x_loyalty?) && casting_ability.x_loyalty?
90
+
88
91
  # A {T} ability's own source can't pay for it.
89
92
  def payment_excluded_source(ctx)
90
93
  ctx["type"] == "cast" && ctx["kind"] == "ability" && needs_tap?(casting_ability) ? ctx["source"] : nil
@@ -94,6 +97,7 @@ module Enjine
94
97
  # "pay X life" no more than their life total (CR 119.4), for "exile X cards" no more than there are (CR 118.3).
95
98
  def x_limit(ctx)
96
99
  limits = x_costs(ctx).map { it.x_limit(self, cost_payer(ctx)) }
100
+ limits << loyalty(object(ctx["source"])) if x_loyalty?(ctx) # CR 118.3: no more counters than it has
97
101
  symbols = base_cost(ctx)&.x_symbols.to_i
98
102
  return limits.min if symbols.zero?
99
103
 
@@ -41,7 +41,7 @@ module Enjine
41
41
  # distinct card) while something lets them play those.
42
42
  def permission_candidates(index, sources = permission_sources(index))
43
43
  pl = player(index)
44
- ids = alt_cost_hand(pl) + pl.graveyard + state.exile
44
+ ids = alt_cost_hand(pl) + pl.graveyard + state.exile + commander_candidates(index)
45
45
  ids += [pl.library.first] unless pl.library.empty?
46
46
  return ids unless sources.any? { |_, inst| inst.ability.kind == :play_from && inst.ability.outside? }
47
47
 
@@ -143,7 +143,7 @@ module Enjine
143
143
  def play_methods(index, id, sources = permission_sources(index))
144
144
  obj = id.is_a?(GameObject) ? id : candidate_object(index, id)
145
145
  granted_methods(index, obj) + own_methods(index, obj) + static_methods(index, obj, sources) +
146
- beam_methods(index, obj, sources) + alt_methods(index, obj)
146
+ beam_methods(index, obj, sources) + alt_methods(index, obj) + command_methods(index, obj)
147
147
  end
148
148
 
149
149
  # The method named `via`, or an error (the option was offered from this list).
@@ -162,7 +162,7 @@ module Enjine
162
162
 
163
163
  c = chars(obj)
164
164
  return false if c.land? || (method["alt"].nil? && c.mana_cost.nil?) # CR 305.9
165
- return false unless c.type?(:instant) || c.keyword?(:flash) || method["instant"] || sorcery_timing?(index)
165
+ return false unless method_timing?(index, c, method)
166
166
  return false if cast_forbidden?(index, obj) # CR 101.2
167
167
  return false if returns_creature?(method["alt"]) && return_candidates(index, method["alt"]).empty?
168
168
  return false unless additional_costs_payable?(obj) && alt_parts_payable?(obj, method) # CR 601.2f
@@ -134,12 +134,6 @@ module Enjine
134
134
  granted.empty? ? base : base.with(abilities: (base.abilities + granted).freeze)
135
135
  end
136
136
 
137
- # CR 604.3, 707.9d: a characteristic-defining power/toughness, unless a copy exception sets them.
138
- def defined_pt_copied?(obj)
139
- except = copy_exceptions(obj)
140
- definition(obj).defined_pt? && !(except&.key?("power") || except&.key?("toughness"))
141
- end
142
-
143
137
  # Layers 1-4: the object's own changes and resolved effects that add types (#own_layers),
144
138
  # then static abilities that add card types ("this Vehicle is an artifact creature", CR 205.1b), then effects
145
139
  # that set its creature types (CR 205.1a, 613.1d), statics before resolved effects, each in timestamp order.
@@ -239,13 +233,6 @@ module Enjine
239
233
  sets.max_by(&:first)&.last
240
234
  end
241
235
 
242
- # CR 604.3, 613.4a: power/toughness from a characteristic-defining ability, in every zone.
243
- def defined_power_toughness(obj, base, defn)
244
- ctx = Mechanics::EffectContext.new(obj.controller, obj.id, obj.id, [], [])
245
- base.with(power: defn.power_amount ? defn.power_amount.value(self, ctx) : base.power,
246
- toughness: defn.toughness_amount ? defn.toughness_amount.value(self, ctx) : base.toughness)
247
- end
248
-
249
236
  # [[source object, StaticAbility], ...] for permanents on the battlefield (printed abilities:
250
237
  # an ability granting static abilities would need layer dependencies, CR 613.8).
251
238
  def static_sources
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # The Commander variant (CR 903) for two players: each player's commander starts in the command zone
6
+ # (903.6), may be cast from there for {2} more per earlier cast (903.8), may return to the command zone
7
+ # when it would go elsewhere (903.9), and 21 combat damage from one commander loses the game (903.10a).
8
+ #
9
+ # A commander is a *card*, not an object (CR 903.3): it stays one through zone changes, but a token or a
10
+ # copy of it is not. So nothing marks the object; `commander?` asks whose card it really is.
11
+ #
12
+ # State: `State#commanders` (each player's commander card id), PlayerState#commander_casts (times cast from
13
+ # the command zone) and #commander_damage ({card id => combat damage dealt to them}), and
14
+ # State#commander_returns (see #note_commander_move!).
15
+ module Commander
16
+ TAX = 2 # CR 903.8: {2} more for each previous cast from the command zone
17
+ DAMAGE_LOSS = 21 # CR 903.10a
18
+ # Zones a commander may be sent back from (CR 903.9a graveyard and exile, 903.9b hand and library).
19
+ RETURNABLE_ZONES = %i[graveyard exile hand library].freeze
20
+
21
+ # ---- who is a commander ---------------------------------------------------------------------
22
+
23
+ # The card id of `obj` if it is its owner's commander. A card face counts as its card (a transformed
24
+ # commander is still one); a token, a copy and a card the object copies are not (CR 903.3 examples).
25
+ def commander?(obj)
26
+ return false unless state.format.commander? && obj.kind == "card" && !obj.memory["copy"]
27
+
28
+ own = own_card(obj).split(CardDefinition::FACE_SEPARATOR).first
29
+ own == state.commanders[obj.owner] && !token?(obj)
30
+ end
31
+
32
+ # CR 903.6: each player puts their commander face up into the command zone, before libraries are shuffled.
33
+ def place_commanders!
34
+ state.commanders.each_with_index do |card, owner|
35
+ state.command << create_object(card, owner, :command).id if card
36
+ end
37
+ end
38
+
39
+ # The commander `index` has waiting in the command zone, if it's there.
40
+ def commander_in_command_zone(index)
41
+ state.command.find { state.objects[it]&.owner == index && commander?(object(it)) }
42
+ end
43
+
44
+ # ---- casting (CR 903.8) -----------------------------------------------------------------------
45
+
46
+ def commander_casts(index) = player(index).commander_casts.to_i
47
+
48
+ # The extra generic mana the next cast of `index`'s commander from the command zone costs.
49
+ def commander_tax(index) = TAX * commander_casts(index)
50
+
51
+ # Command-zone cards `index` may try to cast: their commander.
52
+ def commander_candidates(index) = [commander_in_command_zone(index)].compact
53
+
54
+ # The way to cast a commander from the command zone (see Engine::Permissions): its cost includes the tax.
55
+ def command_methods(index, obj)
56
+ return [] unless obj.zone == :command && obj.owner == index && commander?(obj)
57
+
58
+ [{ "via" => "command", "play" => "cast", "cost_increase" => commander_tax(index) }]
59
+ end
60
+
61
+ # As a spell becomes cast from the command zone (CR 601.2i): it counts toward the next tax (CR 903.8).
62
+ def record_commander_cast!(index, method)
63
+ return unless method && method["via"] == "command"
64
+
65
+ player(index).commander_casts = commander_casts(index) + 1
66
+ end
67
+
68
+ # ---- 21 combat damage (CR 903.10a) ----------------------------------------------------------
69
+
70
+ # Combat damage `source` dealt to player `index`: counted against the commander it came from.
71
+ def note_commander_damage!(source, index, amount)
72
+ obj = state.objects[source]
73
+ return unless obj && commander?(obj)
74
+
75
+ total = (player(index).commander_damage ||= {})
76
+ card = state.commanders[obj.owner]
77
+ total[card] = total.fetch(card, 0) + amount
78
+ end
79
+
80
+ def loses_to_commander_damage?(index)
81
+ (player(index).commander_damage || {}).values.any? { it >= DAMAGE_LOSS }
82
+ end
83
+
84
+ # ---- returning to the command zone (CR 903.9) -------------------------------------------------
85
+
86
+ # A commander that moved to a graveyard, exile, hand or library: its owner may send it to the command
87
+ # zone before anyone gets priority (CR 903.9a is a state-based action; 903.9b a replacement effect, which
88
+ # the engine applies right after the move, since a replacement can't ask a player).
89
+ def note_commander_move!(fresh)
90
+ state.commander_returns << fresh.id if RETURNABLE_ZONES.include?(fresh.zone) && commander?(fresh)
91
+ end
92
+
93
+ # Before priority: the next commander waiting to be sent back asks its owner (a frame, like the
94
+ # legend rule). Returns true when it started one.
95
+ def commander_choice_first!(index)
96
+ return false if state.frames.any? { it["type"] == "commander_zone" }
97
+
98
+ state.commander_returns.select! { state.objects.key?(it) } # moved on since
99
+ id = state.commander_returns.first or return false
100
+ state.frames << { "type" => "commander_zone", "then" => index, "object" => id }
101
+ ask!(nil)
102
+ true
103
+ end
104
+
105
+ def step_commander_zone!(frame)
106
+ id = frame["object"]
107
+ unless frame.key?("choice")
108
+ ask!("kind" => "commander_zone", "player" => object(id).owner, "object" => id)
109
+ return :wait
110
+ end
111
+ state.commander_returns.delete(id)
112
+ move!(id, :command, reason: "commander") if frame["choice"] == "command" && state.objects.key?(id)
113
+ give_priority!(frame["then"])
114
+ :done
115
+ end
116
+
117
+ def choose_commander_zone!(to_command_zone)
118
+ state.frames.rfind { it["type"] == "commander_zone" }["choice"] = to_command_zone ? "command" : "stay"
119
+ ask!(nil)
120
+ end
121
+ end
122
+
123
+ include Commander
124
+ end
125
+ end
@@ -27,6 +27,7 @@ module Enjine
27
27
  index = Mechanics::Filters.player_index(self, ref)
28
28
  if index
29
29
  emit Events::DamageDealt.new(source: source, target: ref, amount: amount, combat: combat)
30
+ note_commander_damage!(source, index, amount) if combat # CR 903.10a
30
31
  change_life!(index, -amount) # CR 120.3a
31
32
  else
32
33
  return 0 unless state.battlefield.include?(ref)
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ class Engine
5
+ # Power and toughness defined by a characteristic-defining ability ("*", CR 604.3), used by the layer pass
6
+ # (Engine::Characteristics) on the battlefield and in every other zone.
7
+ module DefinedPowerToughness
8
+ # CR 604.3, 707.9d: a characteristic-defining power/toughness, unless a copy exception sets them.
9
+ def defined_pt_copied?(obj)
10
+ except = copy_exceptions(obj)
11
+ definition(obj).defined_pt? && !(except&.key?("power") || except&.key?("toughness"))
12
+ end
13
+
14
+ # CR 604.3, 613.4a: the defined power/toughness. Its amount may count the object itself ("card types among
15
+ # cards in all graveyards" while it's in one); it can't read power or toughness (CardDefinition#read_pt), so
16
+ # a nested look at the object while it's being computed skips the definition.
17
+ def defined_power_toughness(obj, base, defn)
18
+ return base if (defining = (@defining_pt ||= {})).key?(obj.id)
19
+
20
+ defining[obj.id] = ctx = Mechanics::EffectContext.new(obj.controller, obj.id, obj.id, [], [])
21
+ base.with(power: defn.power_amount ? defn.power_amount.value(self, ctx) : base.power,
22
+ toughness: defn.toughness_amount ? defn.toughness_amount.value(self, ctx) : base.toughness)
23
+ ensure
24
+ @defining_pt.delete(obj.id) if ctx
25
+ end
26
+ end
27
+
28
+ include DefinedPowerToughness
29
+ end
30
+ end
@@ -29,7 +29,7 @@ module Enjine
29
29
  end
30
30
 
31
31
  # The emblems in the command zone, as objects.
32
- def emblems = (state.command || []).map { object(it) }
32
+ def emblems = state.emblem_ids.map { object(it) }
33
33
  end
34
34
 
35
35
  include Emblems
@@ -94,11 +94,17 @@ module Enjine
94
94
  obj = object(id)
95
95
  next unless obj.controller == index && !mana_abilities_forbidden?(obj) # Engine::Rules
96
96
 
97
- chars(obj).mana_abilities.each { |inst| out << [id, inst.ref] if inst.ability.activatable?(self, obj) }
97
+ chars(obj).mana_abilities.each { |inst| out << [id, inst.ref] if mana_ability_usable?(obj, inst) }
98
98
  end
99
99
  out
100
100
  end
101
101
 
102
+ # CR 602.5b: "Activate only once each turn" counts on the source, as for other activated abilities.
103
+ def mana_ability_usable?(obj, inst)
104
+ per_turn = inst.ability.per_turn
105
+ (per_turn.nil? || activations_this_turn(obj, inst.ref) < per_turn) && inst.ability.activatable?(self, obj)
106
+ end
107
+
102
108
  # Activation options for mana abilities: one per source, or one per mana it could add when the
103
109
  # mana is chosen as it's activated (`mana`: e.g. "{G}{G}", CR 605.3b).
104
110
  def mana_activation_options(sources)
@@ -118,6 +124,7 @@ module Enjine
118
124
  ability = chars(obj).ability(ability_ref) or raise ArgumentError, "#{id} has no ability #{ability_ref}"
119
125
  chosen = mana && Mana.parse_produce(mana, [], "mana")
120
126
  from = mana_provenance(id) # before a cost sacrifices it (a Treasure)
127
+ record_activation!("source" => id, "ability" => ability_ref) if ability.per_turn
121
128
  pay_from_pool!(index, ability.mana_cost, id) if ability.mana_cost
122
129
  ability.costs.each { |cost| cost.pay!(self, obj) }
123
130
  produced = chosen || ability.outcomes(self, obj).first # CR 605.3b: a fixed amount is counted as it resolves