enjine 0.2.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +66 -1
  3. data/README.md +2 -1
  4. data/SUPPORTED.md +4 -4
  5. data/docs/ARCHITECTURE.md +2 -0
  6. data/docs/DESIGN.md +12 -5
  7. data/docs/MECHANICS_COVERAGE.md +32 -4
  8. data/docs/guides/api.md +51 -0
  9. data/docs/guides/card-data-format.md +58 -1
  10. data/docs/guides/deck-builder.md +18 -0
  11. data/docs/plans/commander.md +63 -0
  12. data/docs/plans/dsl-gaps.md +76 -0
  13. data/docs/reference/decisions.md +5 -1
  14. data/docs/reference/effects.md +12 -9
  15. data/docs/reference/triggers.md +3 -1
  16. data/lib/enjine/actions/cast.rb +12 -4
  17. data/lib/enjine/card_definition.rb +39 -3
  18. data/lib/enjine/cli/text.rb +23 -1
  19. data/lib/enjine/cli.rb +2 -1
  20. data/lib/enjine/color_identity.rb +38 -0
  21. data/lib/enjine/decisions/commander_zone.rb +36 -0
  22. data/lib/enjine/deck.rb +73 -14
  23. data/lib/enjine/deck_builder.rb +62 -18
  24. data/lib/enjine/engine/casting/alt_casting.rb +9 -0
  25. data/lib/enjine/engine/casting/casting.rb +19 -0
  26. data/lib/enjine/engine/casting/permissions.rb +19 -14
  27. data/lib/enjine/engine/characteristics.rb +29 -12
  28. data/lib/enjine/engine/commander.rb +125 -0
  29. data/lib/enjine/engine/copies.rb +16 -9
  30. data/lib/enjine/engine/damage.rb +3 -1
  31. data/lib/enjine/engine/durations.rb +47 -0
  32. data/lib/enjine/engine/emblems.rb +1 -1
  33. data/lib/enjine/engine/faces.rb +2 -0
  34. data/lib/enjine/engine/pregame.rb +1 -0
  35. data/lib/enjine/engine/priority.rb +1 -0
  36. data/lib/enjine/engine/rules.rb +3 -2
  37. data/lib/enjine/engine/state_based_actions.rb +9 -0
  38. data/lib/enjine/engine/triggers.rb +16 -9
  39. data/lib/enjine/engine/zones.rb +19 -2
  40. data/lib/enjine/events.rb +4 -1
  41. data/lib/enjine/format.rb +53 -0
  42. data/lib/enjine/fuzz.rb +17 -0
  43. data/lib/enjine/game.rb +4 -3
  44. data/lib/enjine/mechanics/abilities/double_counters.rb +1 -1
  45. data/lib/enjine/mechanics/abilities/play_permissions.rb +3 -2
  46. data/lib/enjine/mechanics/abilities/replacement_effects.rb +2 -1
  47. data/lib/enjine/mechanics/abilities/static.rb +7 -0
  48. data/lib/enjine/mechanics/card_spec.rb +54 -12
  49. data/lib/enjine/mechanics/effects/become.rb +35 -13
  50. data/lib/enjine/mechanics/effects/copy.rb +7 -4
  51. data/lib/enjine/mechanics/effects/gain_control.rb +6 -3
  52. data/lib/enjine/mechanics/effects/return_to_battlefield.rb +25 -6
  53. data/lib/enjine/mechanics/filters/base.rb +19 -2
  54. data/lib/enjine/mechanics/filters/stack.rb +1 -1
  55. data/lib/enjine/mechanics/triggers/base.rb +14 -3
  56. data/lib/enjine/mechanics/triggers/casting.rb +1 -1
  57. data/lib/enjine/mechanics/triggers/tap_and_counters.rb +21 -5
  58. data/lib/enjine/mechanics/triggers/zone_changes.rb +1 -1
  59. data/lib/enjine/mechanics/values.rb +10 -7
  60. data/lib/enjine/mechanics.rb +5 -0
  61. data/lib/enjine/player.rb +2 -1
  62. data/lib/enjine/rules_monitor.rb +29 -3
  63. data/lib/enjine/setup.rb +10 -4
  64. data/lib/enjine/snapshot/player_checks.rb +47 -0
  65. data/lib/enjine/snapshot.rb +4 -1
  66. data/lib/enjine/state.rb +33 -14
  67. data/lib/enjine/steps.rb +10 -1
  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 +7 -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)
@@ -24,6 +24,14 @@ module Enjine
24
24
  # The cards in a hand with an alternative cost (only those can be cast from it with a method).
25
25
  def alt_cost_hand(player) = player.hand.select { |id| chars(id).abilities.any? { it.ability.kind == :alternative_cost } }
26
26
 
27
+ # A card in a graveyard or library, not a copy, with no face that has an ability to play itself
28
+ # (CardDefinition#plays_itself?) has no play method (Engine::Permissions#play_methods): a quick no for most candidates.
29
+ # Exiled cards (permissions, plot, warp, foretell) and a commander always get the full look.
30
+ def unplayable_elsewhere?(obj)
31
+ %i[graveyard library].include?(obj.zone) && !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
32
+ !card_off_board(obj.card)[:plays_itself]
33
+ end
34
+
27
35
  # The alternative-cost methods of `obj` (a card `index` owns) that function now. A face-down card its owner
28
36
  # may look at is seen face up (a foretold card, CR 702.143a, 406.3a).
29
37
  def alt_methods(index, obj)
@@ -143,6 +151,7 @@ module Enjine
143
151
  # trigger (CR 702.185a); the creatures that convoked it (CR 702.51c).
144
152
  def record_cast_how!(obj, ctx)
145
153
  obj.memory["cast_from"] = ctx.dig("origin", "zone") || "hand"
154
+ record_commander_cast!(ctx["player"], ctx["method"]) # CR 903.8 (Engine::Commander)
146
155
  obj.memory["convoked"] = ctx["convoked"].dup if ctx["convoked"]
147
156
  return unless ctx.dig("method", "alt") # mayhem without a cost: no keyword cost was paid
148
157
 
@@ -28,6 +28,25 @@ module Enjine
28
28
  kicked_castable?(index, obj) # CR 702.33g: only the kicked spell has legal targets
29
29
  end
30
30
 
31
+ # No effect gives a card off the battlefield an ability (CR 113.6b): each has only its own (and its copiable
32
+ # values'), so the quick nos below hold.
33
+ def own_abilities_only? = state.effects.none? { it["kind"] == "card_ability" }
34
+
35
+ # A card that isn't a copy, none of whose faces has an activated ability functioning from the zone it's in
36
+ # (CardDefinition#activation_zones, CR 113.6): nothing of it can be activated there.
37
+ def no_activations_here?(obj)
38
+ !obj.memory.key?("copy_except") && !obj.memory.key?("copy_effects") &&
39
+ !card_off_board(obj.card)[:activation_zones].include?(obj.zone)
40
+ end
41
+
42
+ # What a card's faces can do off the battlefield (CardDefinition#plays_itself?, #activation_zones), once per
43
+ # card: printed facts that never change.
44
+ def card_off_board(card)
45
+ (@card_off_board ||= {})[card] ||= catalog.fetch(card).faces.then do |faces|
46
+ { plays_itself: faces.any?(&:plays_itself?), activation_zones: faces.flat_map(&:activation_zones).uniq }
47
+ end
48
+ end
49
+
31
50
  def activatable?(index, id, ability_ref)
32
51
  obj = object(id)
33
52
  ability = chars(obj).ability(ability_ref)
@@ -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
 
@@ -50,25 +50,30 @@ module Enjine
50
50
 
51
51
  # Priority options: `{type: "cast", object: id, via: method}` for every castable card and method.
52
52
  def permission_cast_options(index)
53
- sources = permission_sources(index)
54
- permission_candidates(index, sources).flat_map do |ref|
55
- obj = candidate_object(index, ref)
56
- play_methods(index, obj, sources).filter_map do |method|
57
- { type: "cast", object: ref, via: method["via"] } if castable_via?(index, obj, method)
58
- end
53
+ candidate_methods(index) do |ref, obj, method|
54
+ { type: "cast", object: ref, via: method["via"] } if castable_via?(index, obj, method)
59
55
  end
60
56
  end
61
57
 
62
- # Priority options: lands `index` may play from outside their hand (CR 305.1, 305.2).
58
+ # Priority options: lands `index` may play from outside their hand (CR 305.1, 305.2). A face-down card is
59
+ # played face up (CR 406.3a).
63
60
  def permission_land_options(index)
61
+ candidate_methods(index, land: true) do |ref, _obj, method|
62
+ { type: "play_land", object: ref, via: method["via"] } if method["play"] == "play"
63
+ end
64
+ end
65
+
66
+ # The options the block makes of each [candidate ref, object, play method]. While no permanent lets `index`
67
+ # play cards from other zones and no card was granted an ability, a card in a graveyard or library can only
68
+ # be played by an ability of its own (#unplayable_elsewhere?).
69
+ def candidate_methods(index, land: false, &)
64
70
  sources = permission_sources(index)
71
+ plain = sources.empty? && own_abilities_only?
65
72
  permission_candidates(index, sources).flat_map do |ref|
66
73
  obj = candidate_object(index, ref)
67
- next [] unless face_up(obj.id) { chars(obj).land? } # a face-down card is played face up (CR 406.3a)
74
+ next [] if (plain && unplayable_elsewhere?(obj)) || (land && !face_up(obj.id) { chars(obj).land? })
68
75
 
69
- play_methods(index, obj, sources).filter_map do |method|
70
- { type: "play_land", object: ref, via: method["via"] } if method["play"] == "play"
71
- end
76
+ play_methods(index, obj, sources).filter_map { yield ref, obj, it }
72
77
  end
73
78
  end
74
79
 
@@ -143,7 +148,7 @@ module Enjine
143
148
  def play_methods(index, id, sources = permission_sources(index))
144
149
  obj = id.is_a?(GameObject) ? id : candidate_object(index, id)
145
150
  granted_methods(index, obj) + own_methods(index, obj) + static_methods(index, obj, sources) +
146
- beam_methods(index, obj, sources) + alt_methods(index, obj)
151
+ beam_methods(index, obj, sources) + alt_methods(index, obj) + command_methods(index, obj)
147
152
  end
148
153
 
149
154
  # The method named `via`, or an error (the option was offered from this list).
@@ -292,7 +297,7 @@ module Enjine
292
297
 
293
298
  state.effects << { "kind" => "permission", "timestamp" => next_timestamp!, "controller" => index,
294
299
  "affected" => ids, "duration" => duration, "turn" => state.turn, "play" => play,
295
- **riders.transform_keys(&:to_s).slice(*RIDERS) }
300
+ **end_step_timing(index, duration), **riders.transform_keys(&:to_s).slice(*RIDERS) }
296
301
  emit Events::EffectStarted.new(kind: "permission", affected: ids, details: { "duration" => duration, "play" => play })
297
302
  end
298
303
 
@@ -24,12 +24,13 @@ module Enjine
24
24
 
25
25
  # layer 1 (CR 613.2a-c): its copiable values
26
26
  return board_characteristics.fetch(object.id) { copy_base(object) } if object.zone == :battlefield
27
- return @options_memo[object.id] ||= off_board_chars(object) if @options_memo && object.zone == :hand
27
+ return @options_memo[object.id] ||= off_board_chars(object) if @options_memo # the state holds still meanwhile
28
28
 
29
29
  off_board_chars(object)
30
30
  end
31
31
 
32
- # Off the battlefield. The options of one decision ask about each card in hand often (Engine#options).
32
+ # Off the battlefield. The options of one decision ask about each card in hand, graveyard and exile often
33
+ # (Engine#options).
33
34
  def off_board_chars(object)
34
35
  defn = definition(object)
35
36
  base = copy_base(object)
@@ -152,7 +153,8 @@ module Enjine
152
153
  base = with_added_types(base, ability.card_types) unless ability.card_types.empty?
153
154
  subtypes |= ability.added_subtypes(source)
154
155
  end
155
- effects.each { types = it["types"].map(&:to_sym) if it["kind"] == "creature_types" && it["affected"].include?(obj.id) }
156
+ setting = effects.select { it["kind"] == "creature_types" && it["affected"].include?(obj.id) }.last
157
+ types = Mechanics::Effects::Become.creature_types_of(setting) if setting
156
158
  base = base.with(subtypes: ((base.subtypes & Characteristics::NON_CREATURE_SUBTYPES) | types).freeze) if types
157
159
  base = with_gained_subtypes(base, subtypes - base.subtypes) unless (subtypes - base.subtypes).empty?
158
160
  base.creature? || base.power.nil? ? base : base.with(power: nil, toughness: nil)
@@ -178,12 +180,16 @@ module Enjine
178
180
  # "Is a black Skeleton creature" (CR 205.1a): the card types are exactly these, and subtypes correlated with
179
181
  # a card type it no longer has are lost (creature types without creature, an Equipment without artifact).
180
182
  def with_set_types(base, set)
181
- kept = base.subtypes.select do |sub|
183
+ base = base.with(types: set, subtypes: subtypes_of_types(base.subtypes, set))
184
+ base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
185
+ end
186
+
187
+ # The subtypes still correlated with one of the card types `set` (CR 205.1a).
188
+ def subtypes_of_types(subtypes, set)
189
+ subtypes.select do |sub|
182
190
  correlated = CORRELATED_SUBTYPES.find { |_, list| list.include?(sub) }&.first || :creature
183
191
  set.include?(correlated)
184
- end
185
- base = base.with(types: set, subtypes: kept.freeze)
186
- base.creature? && base.power.nil? ? base.with(power: 0, toughness: 0) : base
192
+ end.freeze
187
193
  end
188
194
 
189
195
  def printed_noncreature_pt?(obj) = definition(obj).then { !it.creature? && !it.power.nil? }
@@ -284,6 +290,8 @@ module Enjine
284
290
  urzas]
285
291
  }.freeze
286
292
  NON_CREATURE_SUBTYPES = CORRELATED_SUBTYPES.values.flatten.freeze
293
+ # Resolved effects that change card types in layer 4, applied in timestamp order (CR 613.7a).
294
+ TYPE_EFFECTS = %w[add_types set_types].freeze
287
295
 
288
296
  # ---- layers 4 and 7b from the object's own state ------------------------------------
289
297
 
@@ -314,7 +322,7 @@ module Enjine
314
322
  symbols += active_max_speed(obj, obj.controller) + active_class_levels(obj)
315
323
  assimilated = !effects.empty? && effects.any? { it["kind"] == "assimilate" && it["affected"].include?(obj.id) }
316
324
  added = effects.empty? ? [] : added_subtypes(obj, effects)
317
- becomes = effects.empty? ? [] : effects.select { it["kind"] == "add_types" && it["affected"].include?(obj.id) }
325
+ becomes = effects.empty? ? [] : effects.select { TYPE_EFFECTS.include?(it["kind"]) && it["affected"].include?(obj.id) }
318
326
  return printed if symbols.empty? && !assimilated && added.empty? && becomes.empty?
319
327
 
320
328
  attrs = printed.to_h
@@ -326,15 +334,24 @@ module Enjine
326
334
  end
327
335
 
328
336
  # "Becomes an artifact creature", "becomes a legendary Spider Hero in addition to its other types" (CR 205.1b):
329
- # card types, supertypes and subtypes are added, none lost. Power/toughness: see Characteristics#with_added_types.
337
+ # card types, supertypes and subtypes are added, none lost. "It's an enchantment. (It's not a creature.)"
338
+ # (CR 205.1a): the card types are set, losing the subtypes of the others. In timestamp order (CR 613.7a).
339
+ # Power/toughness: see Characteristics#with_added_types.
330
340
  def added_type_layers(attrs, effect)
341
+ if effect["kind"] == "set_types"
342
+ attrs[:types] = effect["types"].map(&:to_sym)
343
+ attrs[:subtypes] = subtypes_of_types(attrs[:subtypes], attrs[:types])
344
+ return become_creature_pt(attrs)
345
+ end
331
346
  attrs[:types] = attrs[:types] | effect["types"].map(&:to_sym)
332
347
  attrs[:supertypes] = attrs[:supertypes] | effect["supertypes"].map(&:to_sym)
333
348
  attrs[:subtypes] = attrs[:subtypes] | effect["subtypes"].map(&:to_sym)
334
- return unless attrs[:types].include?(:creature) && attrs[:power].nil?
349
+ become_creature_pt(attrs)
350
+ end
335
351
 
336
- attrs[:power] = 0
337
- attrs[:toughness] = 0
352
+ # A permanent that becomes a creature without power and toughness is 0/0 (CR 301.7b).
353
+ def become_creature_pt(attrs)
354
+ attrs.merge!(power: 0, toughness: 0) if attrs[:types].include?(:creature) && attrs[:power].nil?
338
355
  end
339
356
 
340
357
  def station_symbol_layers(attrs, inst, defn)
@@ -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