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
@@ -25,6 +25,31 @@ module Enjine
25
25
  def to_s = "Sacrifice this"
26
26
  end
27
27
 
28
+ # "Exile this permanent" as a cost (CR 406.1, 602.2b): it leaves the battlefield for exile. Unlike a
29
+ # sacrifice, nothing that watches sacrifices sees it.
30
+ class ExileSelf < Primitive
31
+ primitive :cost, :exile_self,
32
+ description: "Exile the permanent the ability belongs to (\"Exile this enchantment: ...\").",
33
+ rules: %w[406.1 602.2b 118.3],
34
+ example: "exile_self"
35
+
36
+ INSTANCE = new.freeze
37
+
38
+ def self.build(params, errors, path, **)
39
+ Mechanics.check_keys(params, [], errors, path)
40
+ INSTANCE
41
+ end
42
+
43
+ def mana? = false
44
+ def uses_source? = true
45
+ def payable?(engine, object) = engine.state.battlefield.include?(object.id)
46
+ def pay!(engine, object) = engine.move!(object.id, :exile, reason: "cost")
47
+ def to_s = "Exile this"
48
+ end
49
+
50
+ # The costs that take the permanent itself off the battlefield (CR 113.6m: not from another zone).
51
+ LEAVING_SELF = [SacrificeSelf, ExileSelf].freeze
52
+
28
53
  # "Sacrifice a creature" / "Sacrifice another creature or artifact" as a cost (CR 701.21a, 601.2h).
29
54
  # The permanent is chosen while casting and sacrificed as the spell or ability becomes cast; what
30
55
  # it was (types, subtypes, power) is kept for "if you sacrificed a Klingon this way" (CR 608.2h).
@@ -33,7 +58,7 @@ module Enjine
33
58
  description: "Sacrifice `count` permanents you control matching `filter` (`other: true`: not the " \
34
59
  "source). Chosen while casting or activating, sacrificed as it becomes cast; the " \
35
60
  "sacrificed permanent's last known types and subtypes are remembered (condition " \
36
- "`sacrificed`).",
61
+ "`sacrificed`), and its power, toughness and mana value (amount `sacrificed`).",
37
62
  rules: %w[701.21a 601.2h 602.2b 118.3 608.2h],
38
63
  params: { "filter" => "filter (default permanent)", "count" => "integer (default 1)",
39
64
  "other" => "true: not the source itself" },
@@ -44,7 +69,8 @@ module Enjine
44
69
  perm = engine.object(entry["object"])
45
70
  facts = engine.chars(perm)
46
71
  entry.merge!("types" => facts.types.map(&:to_s), "subtypes" => facts.subtypes.map(&:to_s),
47
- "power" => engine.power(perm))
72
+ "power" => engine.power(perm), "toughness" => engine.toughness(perm),
73
+ "mana_value" => Amount.mana_value(engine, perm))
48
74
  engine.move!(perm.id, :graveyard, reason: "sacrifice")
49
75
  end
50
76
  end
@@ -12,7 +12,8 @@ module Enjine
12
12
  # on the battlefield. Granted abilities are part of this card's data, referenced "<this effect's ref>:<j>"
13
13
  # (CardDefinition#effect_granted); on the permanent they are "granted:<card>:<ref>:<j>".
14
14
  class Become < Effect
15
- DURATIONS = %w[end_of_turn indefinite while_source_on_battlefield while_you_control_source].freeze
15
+ DURATIONS = %w[end_of_turn until_your_next_turn indefinite while_source_on_battlefield
16
+ while_you_control_source].freeze
16
17
  GRANTABLE = %i[triggered mana activated play_from additional_land_plays hexproof_from protection_from].freeze
17
18
  # Card types an effect can add (CR 205.1b); instants, sorceries and planeswalkers aren't permanents it makes.
18
19
  ADDABLE_TYPES = %w[artifact creature enchantment land].freeze
@@ -21,7 +22,8 @@ module Enjine
21
22
 
22
23
  primitive :effect, :become,
23
24
  description: "Each referenced permanent becomes what the parameters say, for `duration` " \
24
- "(end_of_turn, default; indefinite: as long as it stays on the battlefield; " \
25
+ "(end_of_turn, default; until_your_next_turn: until your next turn begins; indefinite: " \
26
+ "as long as it stays on the battlefield; " \
25
27
  "while_source_on_battlefield: for as long as this effect's source remains on the " \
26
28
  "battlefield; while_you_control_source: for as long as you control it): it has " \
27
29
  "the card `types`, `supertypes` and `subtypes` in addition to its other types (layer 4, " \
@@ -52,6 +54,8 @@ module Enjine
52
54
  attr_reader :ref, :creature_types, :base_power_toughness, :granted_abilities, :duration, :card_types,
53
55
  :supertypes, :subtypes, :colors, :keywords
54
56
 
57
+ UNTIL = { "end_of_turn" => " until end of turn", "until_your_next_turn" => " until your next turn" }.freeze
58
+
55
59
  def self.keys = CHANGES + %w[duration to if]
56
60
 
57
61
  # A list of registered names (card types, supertypes, keywords) as symbols; [] when absent.
@@ -96,7 +100,7 @@ module Enjine
96
100
  def duration_details(engine, ctx)
97
101
  case @duration
98
102
  when "indefinite" then { "duration" => "permanent" }
99
- when "end_of_turn" then { "duration" => "end_of_turn" }
103
+ when "end_of_turn", "until_your_next_turn" then { "duration" => @duration } # CR 611.2a, 500.1
100
104
  else
101
105
  holds = engine.source_duration_holds?(@duration, ctx.source, ctx.controller)
102
106
  holds ? { "duration" => @duration, "source" => ctx.source } : nil
@@ -132,7 +136,7 @@ module Enjine
132
136
  bits << "base #{base_power_toughness.values.join("/")}" if base_power_toughness
133
137
  bits << keywords.join(", ") unless keywords.empty?
134
138
  bits << "\"#{granted_abilities.join("; ")}\"" unless granted_abilities.empty?
135
- "becomes #{bits.join(", ")}#{" until end of turn" if duration == "end_of_turn"} → #{to}"
139
+ "becomes #{bits.join(", ")}#{UNTIL[duration]} → #{to}"
136
140
  end
137
141
 
138
142
  def self.parse_colors(raw, errors, path)
@@ -10,7 +10,7 @@ module Enjine
10
10
  class ChooseCards < ChoiceEffect
11
11
  include NestedList
12
12
 
13
- PUT = %w[hand graveyard exile battlefield library_top library_bottom].freeze
13
+ PUT = %w[hand graveyard exile battlefield library_top library_bottom discard].freeze
14
14
  ZONES = %w[hand graveyard].freeze
15
15
  REVEAL = %w[chosen all].freeze
16
16
  LISTS = %w[then otherwise].freeze
@@ -19,12 +19,12 @@ module Enjine
19
19
  description: "You choose `count` (default 1; \"any\": any number) cards matching `for` from `from`: a " \
20
20
  "selector (e.g. {\"result\": 0}, the cards an earlier effect milled) or a player's zone, " \
21
21
  "{\"hand\": selector} / {\"graveyard\": selector}. `optional`: you may choose fewer. Then " \
22
- "they are put into `put` (`tapped` onto the battlefield, under your control; exiled cards " \
23
- "`link`ed to the source). `look`: you look at the whole zone first; `reveal`: \"chosen\" " \
24
- "reveals what you chose, \"all\" the whole set. `then` runs if a card was chosen, " \
25
- "`otherwise` if none was (\"if you can't\"). `random: true`: the cards are picked at random " \
26
- "(the game's random number generator) instead of chosen.",
27
- rules: %w[701.20a 701.20e 400.7j 608.2c 607.2a 118.12 701.9b],
22
+ "they are put into `put` (`discard`: from a hand, its owner discards them; `tapped` onto the " \
23
+ "battlefield, under your control; exiled cards `link`ed to the source). `look`: you look at the " \
24
+ "whole zone first; `reveal`: \"chosen\" reveals what you chose, \"all\" the whole set. " \
25
+ "`then` runs if a card was chosen, `otherwise` if none was (\"if you can't\"). `random: true`: the " \
26
+ "cards are picked at random (the game's random number generator) instead of chosen.",
27
+ rules: %w[701.20a 701.20e 400.7j 608.2c 607.2a 118.12 701.9a 701.9b],
28
28
  params: { "from" => "selector or {\"hand\"|\"graveyard\": player selector}", "for" => "card spec",
29
29
  "count" => "integer or \"any\"", "optional" => "boolean", "put" => PUT.join(" | "),
30
30
  "tapped" => "boolean", "link" => "boolean", "look" => "boolean", "random" => "boolean",
@@ -47,6 +47,7 @@ module Enjine
47
47
  @optional = Mechanics.flag_param(params, "optional", errors, path)
48
48
  @put = Mechanics.fetch_param(params, :put).to_s
49
49
  errors << "#{path}.put: must be one of #{PUT.join(", ")}" unless PUT.include?(@put)
50
+ errors << "#{path}.put: discard takes cards from a hand" if @put == "discard" && @from_zone != "hand"
50
51
  @flags = %w[tapped link look random].to_h { [it, Mechanics.flag_param(params, it, errors, path)] }
51
52
  errors << "#{path}.count: must be a number to pick at random" if @flags["random"] && @count == "any"
52
53
  @reveal = Mechanics.fetch_param(params, :reveal)
@@ -154,6 +155,7 @@ module Enjine
154
155
 
155
156
  def move(engine, ctx, id)
156
157
  case put
158
+ when "discard" then engine.move!(id, :graveyard, reason: "discard") # CR 701.9a: the owner discards it
157
159
  when "library_top", "library_bottom"
158
160
  engine.move!(id, :library, reason: "put", position: put == "library_top" ? :top : :bottom)
159
161
  else
@@ -104,7 +104,8 @@ module Enjine
104
104
  source = { "id" => ctx.source, "card" => card, "controller" => ctx.controller, "ability" => ref }
105
105
  engine.queue_pending_trigger!(source, nil, { "results" => Snapshot.deep_copy(ctx.results || []),
106
106
  "amounts" => (ctx.amounts || []).dup,
107
- "triggering" => memory["triggering"]&.dup }.compact)
107
+ "triggering" => memory["triggering"]&.dup,
108
+ "departed" => engine.departed_snapshot }.compact)
108
109
  end
109
110
  end
110
111
  end
@@ -6,7 +6,8 @@ module Enjine
6
6
  module Mechanics
7
7
  module Effects
8
8
  # Search your library (CR 701.23), optionally reveal what was found (CR 701.20a), put it
9
- # into your hand or onto the battlefield, then shuffle (CR 701.24).
9
+ # into your hand, onto the battlefield or into your graveyard, then shuffle (CR 701.24); or shuffle
10
+ # and put the found card on top ("then shuffle and put that card on top").
10
11
  #
11
12
  # The searcher picks one card at a time. Copies of the same card in a library are
12
13
  # interchangeable, so each distinct card is offered once. Only the searcher sees the
@@ -17,7 +18,9 @@ module Enjine
17
18
 
18
19
  primitive :effect, :search_library,
19
20
  description: "Search your library for up to `count` cards matching `for`, then put them into your " \
20
- "hand (or onto the battlefield, tapped if `tapped`, with `counters`) and shuffle. With a " \
21
+ "hand (or onto the battlefield, tapped if `tapped`, with `counters`; or into your " \
22
+ "graveyard) and shuffle. `put: library_top`: shuffle, then put the found card (one) on top. " \
23
+ "Computed bounds in `for` are worked out as the effect resolves. With a " \
21
24
  "stated quality you may find fewer (or none); a search for just \"a card\" must find one " \
22
25
  "if it can. `reveal` shows the found cards to every player. `searcher` names another " \
23
26
  "player who searches their own library (e.g. {\"controller_of\": {\"target\": 0}}); " \
@@ -27,7 +30,7 @@ module Enjine
27
30
  params: { "for" => "card spec: \"card\" (default), {\"types\"|\"subtypes\"|\"supertypes\": [...], " \
28
31
  "\"name\": \"...\"} or {\"any_of\": [spec, ...]}",
29
32
  "count" => "integer (default 1), \"any\" (any number), \"x\" or an amount (\"up to that many\")",
30
- "put" => "\"hand\" (default) or \"battlefield\"",
33
+ "put" => "\"hand\" (default), \"battlefield\", \"graveyard\" or \"library_top\" (count 1)",
31
34
  "tapped" => "true: the cards enter tapped (with put: battlefield)",
32
35
  "counters" => "{counter name: n}: the cards enter with these counters (with put: battlefield)",
33
36
  "reveal" => "true: reveal the found cards",
@@ -37,7 +40,7 @@ module Enjine
37
40
  example: { "search_library" => { "for" => { "supertypes" => ["basic"], "types" => ["land"] },
38
41
  "reveal" => true } }
39
42
 
40
- ZONES = %w[hand battlefield].freeze
43
+ ZONES = %w[hand battlefield graveyard library_top].freeze
41
44
 
42
45
  attr_reader :spec, :count, :put, :tapped, :reveal
43
46
 
@@ -54,6 +57,7 @@ module Enjine
54
57
  @may = Mechanics.flag_param(params, :may, errors, path)
55
58
  @different_names = Mechanics.flag_param(params, :different_names, errors, path)
56
59
  errors << "#{path}.tapped: only cards put onto the battlefield can enter tapped" if @tapped && @put != "battlefield"
60
+ errors << "#{path}.count: put library_top takes one card" if @put == "library_top" && @count != 1
57
61
  @counters = parse_counters(Mechanics.fetch_param(params, :counters), errors, path)
58
62
  raw = Mechanics.fetch_param(params, :searcher) || "you"
59
63
  @searcher = Selector.build(raw, errors, "#{path}.searcher", targets_count: @targets_count, results_count: @results_count)
@@ -101,7 +105,7 @@ module Enjine
101
105
  end
102
106
  found = answers(locals).select { it["type"] == "find" }.map { it["object"] }
103
107
  unless stop?(engine, ctx, locals, found)
104
- choices = candidates(engine, index, found)
108
+ choices = candidates(engine, ctx, index, found)
105
109
  return ask(engine, locals, index, "Search your library (#{spec}): find a card", choices) unless choices.empty?
106
110
  end
107
111
  return :wait if entering_choices?(engine, index, locals, found)
@@ -127,10 +131,11 @@ module Enjine
127
131
 
128
132
  # One option per distinct matching card (CR 701.23a); "done" stops looking unless the
129
133
  # search is for just a quantity of cards (CR 701.23b, 701.23d).
130
- def candidates(engine, index, found)
134
+ # Computed bounds ("mana value equal to 1 plus the sacrificed artifact's") are worked out now (CR 608.2h).
135
+ def candidates(engine, ctx, index, found)
131
136
  names = @different_names ? found.map { engine.chars(it).name } : []
132
137
  ids = (engine.player(index).library - found).sort.select do
133
- spec.match?(engine, engine.object(it)) && !names.include?(engine.chars(it).name)
138
+ spec.match?(engine, engine.object(it), ctx) && !names.include?(engine.chars(it).name)
134
139
  end
135
140
  choices = ids.uniq { engine.object(it).card }.map { { "type" => "find", "object" => it } }
136
141
  return choices if choices.empty? || (spec.any? && count != "any")
@@ -139,11 +144,13 @@ module Enjine
139
144
  end
140
145
 
141
146
  def finish!(engine, index, found, locals)
142
- if reveal && put == "hand"
147
+ if reveal && %w[hand library_top].include?(put)
143
148
  found.each do |id|
144
149
  engine.emit Events::CardRevealed.new(player: engine.name(index), object: id, card: engine.object(id).card)
145
150
  end
146
151
  end
152
+ return engine.shuffle_library!(index, then_on_top: found) if put == "library_top" # CR 701.24a
153
+
147
154
  enters = {}
148
155
  enters["tapped"] = true if tapped
149
156
  enters["counters"] = @counters.dup unless @counters.empty?
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enjine
4
+ module Mechanics
5
+ module Abilities
6
+ # "Plot [cost]" (CR 702.170a-b, 116.2k): any time you have priority during your turn, if the stack is empty
7
+ # and it's your main phase, you may pay `cost` and exile this card from your hand (a special action,
8
+ # `{type: "special_action"}`). It becomes a plotted card (Effects::Plot.plot!): its owner may cast it
9
+ # without paying its mana cost during their main phase while the stack is empty, on a later turn
10
+ # (cast option `via: "plotted"`, Engine::AltCasting#plotted_methods).
11
+ class Plot < Primitive
12
+ primitive :ability, :plot,
13
+ description: "Plot `cost`: during your main phase, while the stack is empty, you may pay `cost` and " \
14
+ "exile this card from your hand (special action `{type: \"special_action\"}`). It becomes " \
15
+ "plotted: on a later turn you may cast it from exile without paying its mana cost, " \
16
+ "during your main phase while the stack is empty (cast option `via: \"plotted\"`).",
17
+ rules: %w[702.170a 702.170b 702.170d 116.2k],
18
+ params: { "cost" => "mana cost string" },
19
+ example: { "plot" => { "cost" => "{1}{R}" } }
20
+
21
+ attr_reader :special_cost
22
+
23
+ def self.build(params, errors, path, **)
24
+ Mechanics.check_keys(params, %w[cost], errors, path)
25
+ new(Costs::ManaPayment.build(Mechanics.fetch_param(params, :cost).to_s, errors, "#{path}.cost").mana_cost)
26
+ end
27
+
28
+ def initialize(cost)
29
+ super()
30
+ @special_cost = cost
31
+ freeze
32
+ end
33
+
34
+ def kind = :plot
35
+ def mana_ability? = false
36
+ def allowed_types = nil
37
+ def try_effects = []
38
+ def to_s = "Plot #{special_cost}"
39
+
40
+ # CR 702.170a: during your turn, in your main phase, with an empty stack (as a sorcery, whatever its type).
41
+ def special_allowed?(engine, obj, index) = obj.zone == :hand && engine.sorcery_timing?(index)
42
+
43
+ def special!(engine, obj, _index) = Effects::Plot.plot!(engine, obj.id)
44
+ end
45
+ end
46
+
47
+ module Effects
48
+ # "It becomes plotted" / "plot that card" (CR 702.170c-d): the card is exiled face up (or stays exiled) and
49
+ # becomes a plotted card, remembering the turn. Its owner may cast it without paying its mana cost on a later
50
+ # turn, during their main phase while the stack is empty.
51
+ class Plot < Effect
52
+ primitive :effect, :plot,
53
+ description: "Each referenced card or spell is exiled (if it isn't already) and becomes plotted: its " \
54
+ "owner may cast it from exile without paying its mana cost during their main phase while " \
55
+ "the stack is empty, on any later turn (cast option `via: \"plotted\"`).",
56
+ rules: %w[702.170c 702.170d 406.1],
57
+ params: { "to" => "selector (a spell, a card, or an exiled card such as {\"result\": 0})" },
58
+ example: { "plot" => { "to" => { "target" => 0 } } }
59
+
60
+ def self.keys = %w[to if]
61
+
62
+ def self.plot!(engine, id)
63
+ obj = engine.state.objects[id] or return
64
+ fresh = obj.zone == :exile ? obj : engine.move!(id, :exile, reason: "plot")
65
+ fresh.memory["plotted"] = engine.state.turn if fresh&.zone == :exile
66
+ end
67
+
68
+ def apply(engine, ctx)
69
+ refs(engine, ctx).each do |id|
70
+ obj = engine.state.objects[id]
71
+ Plot.plot!(engine, id) if obj && !obj.ability? && obj.kind == "card"
72
+ end
73
+ end
74
+
75
+ def to_s = "plot → #{to}"
76
+ end
77
+ end
78
+ end
79
+ end
@@ -173,14 +173,16 @@ module Enjine
173
173
  "mana ability. `source`: optional filter on the source's card; `name: \"chosen\"`: only a " \
174
174
  "source with the name chosen as this permanent entered. `exhaust: true`: only an exhaust " \
175
175
  "ability (\"whenever you activate an exhaust ability\", CR 702.177). `boast: true`: only a " \
176
- "boast ability (\"whenever a creature you control boasts\", CR 702.142b).",
177
- rules: %w[602.2 605.1a 603.2 201.4 702.177a 702.142b],
176
+ "boast ability (\"whenever a creature you control boasts\", CR 702.142b). `loyalty: " \
177
+ "true`: only a loyalty ability (CR 606).",
178
+ rules: %w[602.2 605.1a 603.2 201.4 702.177a 702.142b 606.1],
178
179
  params: { "controller" => PLAYERS.join(" | "), "source" => "card filter", "name" => "\"chosen\"",
179
- "exhaust" => "true: only exhaust abilities", "boast" => "true: only boast abilities" },
180
+ "exhaust" => "true: only exhaust abilities", "boast" => "true: only boast abilities",
181
+ "loyalty" => "true: only loyalty abilities" },
180
182
  example: { "activates_ability" => { "controller" => "opponent" } }
181
183
 
182
- def self.keys = %w[controller source name exhaust boast]
183
- KINDS = { "exhaust" => :exhaust?, "boast" => :boast? }.freeze
184
+ def self.keys = %w[controller source name exhaust boast loyalty]
185
+ KINDS = { "exhaust" => :exhaust?, "boast" => :boast?, "loyalty" => :loyalty? }.freeze
184
186
  def event_class = Events::AbilityActivated
185
187
 
186
188
  def setup(params, errors, path)
@@ -202,7 +204,7 @@ module Enjine
202
204
 
203
205
  def to_s
204
206
  what = "#{@kinds.map { "#{it.to_s.delete("?")} " }.join}ability"
205
- "Whenever #{who} activate#{"s" unless @controller == "you"} #{what.start_with?("b") ? "a" : "an"} #{what}#{chosen_words}"
207
+ "Whenever #{who} activate#{"s" unless @controller == "you"} #{what.match?(/\A[aeiou]/) ? "an" : "a"} #{what}#{chosen_words}"
206
208
  end
207
209
 
208
210
  private
@@ -9,10 +9,14 @@ module Enjine
9
9
  # how many the first effect moved or created, e.g. cards drawn)
10
10
  # {"power": selector} / {"toughness": ...} total power / toughness ("Picard's power": {"power": "self"})
11
11
  # {"greatest_power" | "greatest_toughness": selector} the greatest power / toughness among them (0 for none)
12
- # {"hand_size" | "life" | "graveyard_size": player selector}
12
+ # {"hand_size" | "life" | "graveyard_size" | "library_size": player selector}
13
13
  # {"distinct_names": selector} how many different names they have (strange new worlds)
14
14
  # {"mana_value": selector} their total mana value (a spell's X counts on the stack; a spell
15
15
  # countered by the resolving one: as it last existed, CR 608.2h)
16
+ # {"greatest_mana_value": selector} the greatest mana value among them (0 for none, CR 202.3)
17
+ # {"sacrificed": "power" | "toughness" | "mana_value"} of the permanents sacrificed to pay the resolving
18
+ # spell's or ability's cost, as they last existed (CR 601.2h, 608.2h)
19
+ # {"card_types": selector} how many different card types among them (delirium, CR 205.2a)
16
20
  # {"distinct_types": selector} how many different creature types they have (CR 205.3m)
17
21
  # {"distinct_colors": selector} how many colors among them (CR 105.2, 202.2)
18
22
  # {"distinct_land_types": selector} how many basic land types among them (domain, CR 305.6)
@@ -31,14 +35,16 @@ module Enjine
31
35
  # {"mana_spent": {"of": ..., "color" | "colors": ...}} mana spent to cast a spell (CR 601.2h), see mana_spent.rb
32
36
  # {"times": [a, b]} / {"plus": [a, b]} / {"divide": [a, b]} arithmetic on amounts; division rounds down
33
37
  # (CR 107.1a). "-X" is {"times": ["x", -1]}.
34
- # A source that has left the battlefield is used as it last existed (CR 608.2h).
38
+ # A source that has left the battlefield is used as it last existed (CR 608.2h), and so is any object the
39
+ # power, toughness or mana value of which is read after it left the battlefield during the resolving
40
+ # spell or ability (a destroyed target, or {"result": n} of a sacrifice).
35
41
  class Amount
36
42
  SELECTOR_KINDS = %w[count power toughness greatest_power hand_size life graveyard_size distinct_names distinct_types
37
43
  distinct_colors distinct_land_types distinct_planeswalker_types
38
44
  life_gained_this_turn life_lost_this_turn dilemmas_this_turn returned_this_turn
39
45
  cards_drawn_this_turn cards_discarded_this_turn spells_cast_this_game speed
40
46
  noncombat_damage_this_turn noncombat_damage_last_turn turns_taken greatest_toughness
41
- mana_value].freeze
47
+ mana_value greatest_mana_value card_types library_size].freeze
42
48
  ARITHMETIC = %w[times plus divide].freeze
43
49
  BASIC_LAND_TYPES = %i[plains island swamp mountain forest].freeze # CR 305.6
44
50
  # Object history lists: kind -> turn_log key (Engine::TurnHistory).
@@ -46,7 +52,7 @@ module Enjine
46
52
  "sacrificed_this_turn" => "sacrificed", "attackers_this_turn" => "attackers",
47
53
  "exiled_this_turn" => "exiled" }.freeze
48
54
  KINDS = (SELECTOR_KINDS + ARITHMETIC + DEPARTED.keys + %w[counters spells_cast_this_turn lands_played_this_turn this_way
49
- mana_spent]).freeze
55
+ mana_spent sacrificed]).freeze
50
56
  # Player history counters: kind -> turn_log/game_log key.
51
57
  HISTORY = { "life_gained_this_turn" => "life_gained", "life_lost_this_turn" => "life_lost",
52
58
  "dilemmas_this_turn" => "dilemmas", "returned_this_turn" => "returned",
@@ -74,6 +80,7 @@ module Enjine
74
80
  return Departed.build(kind, ref, errors, "#{path}.#{kind}") if DEPARTED.key?(kind)
75
81
  return ThisWay.build(ref, errors, "#{path}.#{kind}", results_count) if kind == "this_way"
76
82
  return ManaSpent.build(ref, errors, "#{path}.#{kind}", **context) if kind == "mana_spent" # mana_spent.rb
83
+ return Sacrificed.build(ref, errors, "#{path}.#{kind}") if kind == "sacrificed"
77
84
 
78
85
  new(kind, Selector.build(ref, errors, "#{path}.#{kind}", **context))
79
86
  end
@@ -96,15 +103,9 @@ module Enjine
96
103
  when "count" then refs.size
97
104
  when "power", "toughness" then refs.empty? ? Amount.last_known(engine, ctx, @selector, @kind) : stats(engine, refs).sum
98
105
  when "greatest_power", "greatest_toughness" then stats(engine, refs).max.to_i
99
- when "mana_value" then refs.sum do
100
- Amount.mana_value(engine, engine.state.objects[it]) || engine.resolving_last_known(it)&.[]("mana_value").to_i
101
- end
102
- when "distinct_names" then live(engine, refs).map { engine.chars(it).name }.uniq.size
103
- when "distinct_types" then live(engine, refs).flat_map { Amount.creature_types(engine.chars(it)) }.uniq.size
104
- when "distinct_colors" then live(engine, refs).flat_map { engine.chars(it).colors }.uniq.size # CR 105.2
105
- when "distinct_land_types" then (live(engine, refs).flat_map { engine.chars(it).subtypes } & BASIC_LAND_TYPES).size
106
- when "distinct_planeswalker_types" # CR 205.3j: a planeswalker's subtypes are planeswalker types
107
- live(engine, refs).flat_map { (c = engine.chars(it)).type?(:planeswalker) ? c.subtypes : [] }.uniq.size
106
+ when "mana_value" then mana_values(engine, refs).sum
107
+ when "greatest_mana_value" then mana_values(engine, refs).max.to_i
108
+ when *DISTINCT then distinct(live(engine, refs).map { engine.chars(it) })
108
109
  else players(engine, refs).sum { player_value(engine, it) }
109
110
  end
110
111
  end
@@ -133,6 +134,17 @@ module Enjine
133
134
  lki ? lki[key].to_i : 0
134
135
  end
135
136
 
137
+ # How an object last existed on the battlefield if it left during the resolving spell or ability: by its
138
+ # old id (a destroyed target), or, for what an earlier effect moved (`moved`: a {"result": n} selector), as
139
+ # the new object it became (CR 400.7). A spell countered by the resolving one, as it last existed on the
140
+ # stack (Engine::TurnHistory#remember_spell!). Nil otherwise: a card in a graveyard looked at for itself is
141
+ # the card there.
142
+ def self.left_battlefield(engine, ref, moved: false)
143
+ return engine.departed_last_known(ref) if moved && engine.departed_last_known(ref)
144
+
145
+ engine.state.objects.key?(ref) ? nil : engine.resolving_last_known(ref)
146
+ end
147
+
136
148
  # How a source that has left the battlefield last existed: remembered by the resolving ability, or,
137
149
  # while its leaves-the-battlefield trigger is being checked (CR 603.4, 603.10a), the engine's.
138
150
  def self.source_lki(engine, ctx)
@@ -141,10 +153,42 @@ module Enjine
141
153
 
142
154
  private
143
155
 
156
+ DISTINCT = %w[card_types distinct_names distinct_types distinct_colors distinct_land_types
157
+ distinct_planeswalker_types].freeze
158
+ private_constant :DISTINCT
159
+
160
+ # How many different card types, names, creature types, colors, basic land types or planeswalker types
161
+ # the objects with these characteristics have between them.
162
+ def distinct(chars)
163
+ case @kind
164
+ when "card_types" then chars.flat_map(&:types).uniq.size # CR 205.2a
165
+ when "distinct_names" then chars.map(&:name).uniq.size
166
+ when "distinct_types" then chars.flat_map { Amount.creature_types(it) }.uniq.size
167
+ when "distinct_colors" then chars.flat_map(&:colors).uniq.size # CR 105.2
168
+ when "distinct_land_types" then (chars.flat_map(&:subtypes) & BASIC_LAND_TYPES).size
169
+ else chars.flat_map { it.type?(:planeswalker) ? it.subtypes : [] }.uniq.size # CR 205.3j
170
+ end
171
+ end
172
+
144
173
  def live(engine, refs) = refs.select { engine.state.objects.key?(it) }
145
174
 
175
+ # Each one's mana value; one that has left as it last existed (CR 608.2h).
176
+ def mana_values(engine, refs)
177
+ refs.map do |ref|
178
+ lki = Amount.left_battlefield(engine, ref, moved: @selector.kind == :result)
179
+ lki ? lki["mana_value"].to_i : Amount.mana_value(engine, engine.state.objects[ref]) || 0
180
+ end
181
+ end
182
+
183
+ # Each one's power or toughness; one that left the battlefield during the resolving spell or ability as it
184
+ # last existed (CR 608.2h), one that's simply gone not at all.
146
185
  def stats(engine, refs)
147
- live(engine, refs).map { engine.public_send(@kind.end_with?("toughness") ? :toughness : :power, engine.object(it)) }
186
+ key = @kind.end_with?("toughness") ? "toughness" : "power"
187
+ refs.filter_map do |ref|
188
+ if (lki = Amount.left_battlefield(engine, ref, moved: @selector.kind == :result)) then lki[key].to_i
189
+ elsif engine.state.objects.key?(ref) then engine.public_send(key, engine.object(ref))
190
+ end
191
+ end
148
192
  end
149
193
 
150
194
  def players(engine, refs) = refs.filter_map { Filters.player_index(engine, it) }
@@ -155,6 +199,7 @@ module Enjine
155
199
  when "life" then engine.player(index).life
156
200
  when "speed" then engine.speed(index) # CR 702.179f: 0 without speed
157
201
  when "graveyard_size" then engine.player(index).graveyard.size
202
+ when "library_size" then engine.player(index).library.size # CR 401.1
158
203
  when "spells_cast_this_game" then engine.game_log(index).fetch("spells", 0)
159
204
  when "turns_taken" then engine.game_log(index).fetch("turns", 0) # this turn included, if it's theirs
160
205
  when *LAST_TURN.keys then engine.last_turn_log(index).fetch(LAST_TURN.fetch(@kind), 0)
@@ -180,6 +225,29 @@ module Enjine
180
225
  def to_s = "that many"
181
226
  end
182
227
 
228
+ # {"sacrificed": "power" | "toughness" | "mana_value"}: "the sacrificed creature's power" — the total of the
229
+ # permanents sacrificed to pay the resolving spell's or ability's cost, as they last existed (CR 601.2h,
230
+ # 608.2h; recorded by Costs::SacrificePermanent). 0 when none was.
231
+ class Sacrificed
232
+ KEYS = %w[power toughness mana_value].freeze
233
+
234
+ def self.build(key, errors, path)
235
+ return new(key) if KEYS.include?(key)
236
+
237
+ errors << "#{path}: must be #{KEYS[0..-2].join(", ")} or #{KEYS.last}"
238
+ Fixed.new(0)
239
+ end
240
+
241
+ def initialize(key)
242
+ @key = key
243
+ freeze
244
+ end
245
+
246
+ def reads_power? = @key != "mana_value"
247
+ def value(engine, ctx) = (engine.state.objects[ctx.object]&.paid || []).sum { it[@key].to_i }
248
+ def to_s = "the sacrificed permanent's #{@key.tr("_", " ")}"
249
+ end
250
+
183
251
  # A fixed number.
184
252
  class Fixed
185
253
  attr_reader :n
data/lib/enjine/player.rb CHANGED
@@ -17,7 +17,8 @@ module Enjine
17
17
  }
18
18
  end
19
19
 
20
- def ready? = @deck.valid?
20
+ # Whether the deck is legal for `format` (Enjine::Format).
21
+ def ready?(format = Format::CONSTRUCTED) = @deck.valid?(format)
21
22
 
22
23
  # True while any game this player is seated in has not ended.
23
24
  def playing? = @games.keys.any? { |game| !game.over? }
@@ -22,6 +22,8 @@ module Enjine
22
22
  @stats = Hash.new(0)
23
23
  @lands_this_turn = Hash.new(0)
24
24
  @loyalty_activations = Hash.new(0)
25
+ @commander_casts = Hash.new(0)
26
+ @cast_from_command = []
25
27
  end
26
28
 
27
29
  def state = @game.state
@@ -109,6 +111,7 @@ module Enjine
109
111
 
110
112
  def zone_changed!(event)
111
113
  land_played!(event) if event.reason == "play_land"
114
+ @cast_from_command << event.new_id if event.reason == "cast" && event.from == "command"
112
115
  return unless event.reason == "resolve" && event.to == "graveyard" && defn(event.card).permanent?
113
116
 
114
117
  finding("608.3", "permanent spell #{event.card} went to the graveyard on resolution")
@@ -144,6 +147,7 @@ module Enjine
144
147
  def spell_cast!(event)
145
148
  card = defn(event.card)
146
149
  @stats["cast:#{event.card}"] += 1
150
+ @commander_casts[event.player] += 1 if @cast_from_command.delete(event.object) # CR 903.8
147
151
  return if card.instant_speed? || event.during_resolution # CR 608.2g: timing doesn't apply
148
152
 
149
153
  caster = event.player
@@ -181,7 +185,7 @@ module Enjine
181
185
  end
182
186
 
183
187
  # Permanents and emblems, whose static abilities function in the command zone (CR 114.4).
184
- def static_holders = state.battlefield + (state.command || [])
188
+ def static_holders = state.battlefield + state.emblem_ids
185
189
 
186
190
  # The static abilities of permanents on the battlefield and emblems that apply to `obj` now, matched on printed types.
187
191
  def applying_statics(obj)
@@ -252,6 +256,26 @@ module Enjine
252
256
  check_damage_life!
253
257
  check_sba! if @game.pending_decision&.kind == "priority"
254
258
  check_hand_size!
259
+ check_commander!
260
+ end
261
+
262
+ # CR 903.8, 903.10a, independently of the engine's counters: the casts from the command zone seen as events
263
+ # are the tax's count, and nobody survives 21 combat damage from one commander.
264
+ def check_commander!
265
+ return unless state.format.commander?
266
+
267
+ state.players.each do |pl|
268
+ casts = @commander_casts[pl.name]
269
+ if pl.commander_casts.to_i != casts
270
+ finding("903.8",
271
+ "#{pl.name} has cast their commander #{casts} times but the tax counts #{pl.commander_casts.to_i}")
272
+ end
273
+ next if pl.lost || state.over?
274
+
275
+ finding("903.10a", "#{pl.name} survived 21 combat damage from one commander") if (pl.commander_damage || {}).values.any? do
276
+ it >= 21
277
+ end
278
+ end
255
279
  end
256
280
 
257
281
  # CR 613.4, recomputed independently: printed (or a 7b setting effect) + counters + active pump effects
data/lib/enjine/setup.rb CHANGED
@@ -8,15 +8,19 @@ module Enjine
8
8
  #
9
9
  # The catalog and decklists are captured at compile time and shared by every game,
10
10
  # so later deck edits never affect an existing Setup.
11
+ #
12
+ # `format:` picks the rules (Enjine::Format): constructed by default; `:duel_commander` plays Commander
13
+ # (CR 903), and each deck then names its commander.
11
14
  class Setup
12
- attr_reader :players, :catalog, :decklists, :outside
15
+ attr_reader :players, :catalog, :decklists, :outside, :format, :commanders
13
16
 
14
- def initialize(*players)
17
+ def initialize(*players, format: Format::CONSTRUCTED)
18
+ @format = Format.fetch(format)
15
19
  players = players.flatten
16
20
  raise ArgumentError, "a game needs exactly 2 players" unless players.size == 2
17
21
  raise ArgumentError, "player names must differ" if players.map(&:name).uniq.size != 2
18
22
 
19
- players.each { |p| raise PlayerNotReady.new(p.deck.errors, name: p.name) unless p.ready? }
23
+ players.each { |p| raise PlayerNotReady.new(p.deck.errors(@format), name: p.name) unless p.ready?(@format) }
20
24
 
21
25
  @players = players.freeze
22
26
  @catalog = Catalog.new
@@ -24,13 +28,15 @@ module Enjine
24
28
  @catalog.freeze
25
29
  @decklists = players.map { |p| p.deck.card_ids.freeze }.freeze
26
30
  @outside = players.map { |p| p.deck.outside_ids.freeze }.freeze # CR 400.11a: the cards they own outside the game
31
+ @commanders = players.map { |p| p.deck.commander }.freeze # CR 903.3: the card each player leads with, or nil
27
32
  freeze
28
33
  end
29
34
 
30
35
  def names = @players.map(&:name)
31
36
 
32
37
  def new_game(seed:)
33
- Game.start(catalog: @catalog, names: names, decklists: @decklists, seed: seed, outside: @outside).tap do |game|
38
+ Game.start(catalog: @catalog, names: names, decklists: @decklists, seed: seed, outside: @outside,
39
+ format: @format, commanders: @commanders).tap do |game|
34
40
  @players.each { |p| p.seat(game) }
35
41
  end
36
42
  end