enjine 0.6.1 → 0.6.3

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.
@@ -7,6 +7,7 @@ module Enjine
7
7
  def check_state_based_actions!
8
8
  loop do
9
9
  check_player_state_based_actions!
10
+ check_permanent_limit!
10
11
  break if state.over? || !check_permanent_state_based_actions!
11
12
  end
12
13
  end
@@ -45,7 +46,17 @@ module Enjine
45
46
 
46
47
  survivors = state.players.reject(&:lost)
47
48
  winner = survivors.size == 1 ? survivors.first.name : nil
48
- reason = losers.map(&:lost).uniq.join(",")
49
+ end_game!(winner, losers.map(&:lost).uniq.join(","))
50
+ end
51
+
52
+ # The setup's permanent limit (not a rule of the game; off unless set): too large a board is a draw.
53
+ # Checked after players have lost, so a game decided at the same time keeps its winner.
54
+ def check_permanent_limit!
55
+ limit = state.permanent_limit
56
+ end_game!(nil, "permanent_limit") if limit && !state.over? && state.battlefield.size > limit
57
+ end
58
+
59
+ def end_game!(winner, reason)
49
60
  state.result = { "winner" => winner, "reason" => reason }
50
61
  ask!(nil)
51
62
  state.frames.clear
@@ -105,7 +105,7 @@ module Enjine
105
105
  def repeats?(entry) = (entry["turn"] && !entry["once"]) || entry["game"] == true
106
106
 
107
107
  def delayed_memory(entry, facts)
108
- { "results" => entry["results"], "watched" => entry["watched"], "triggering" => facts }.compact
108
+ { "results" => entry["results"], "watched" => entry["watched"], "triggering" => facts, "x" => entry["x"] }.compact
109
109
  end
110
110
 
111
111
  # CR 603.7d-e: its source and controller are those of the spell or ability that created it.
@@ -367,7 +367,7 @@ module Enjine
367
367
  obj.source = trigger["source"]
368
368
  obj.ability = trigger["ability"]
369
369
  obj.memory = Snapshot.deep_copy(trigger.fetch("memory", {})).merge("trigger_id" => trigger["id"])
370
- obj.x = entered_x(trigger)
370
+ obj.x = trigger.dig("memory", "x") || entered_x(trigger) # CR 107.3n: a delayed trigger's X (Effects::DelayedTrigger)
371
371
  state.stack.unshift(obj.id)
372
372
  start_casting!(trigger["controller"], obj.id, "trigger", source: trigger["source"], ability: trigger["ability"])
373
373
  end
data/lib/enjine/game.rb CHANGED
@@ -20,8 +20,10 @@ module Enjine
20
20
 
21
21
  attr_reader :catalog, :history
22
22
 
23
- def self.start(catalog:, names:, decklists:, seed:, outside: nil, format: Format::CONSTRUCTED, commanders: nil)
24
- state = State.initial(names: names, decklists: decklists, seed: seed, outside: outside, format: format, commanders: commanders)
23
+ def self.start(catalog:, names:, decklists:, seed:, outside: nil, format: Format::CONSTRUCTED, commanders: nil,
24
+ permanent_limit: nil)
25
+ state = State.initial(names: names, decklists: decklists, seed: seed, outside: outside, format: format,
26
+ commanders: commanders, permanent_limit: permanent_limit)
25
27
  new(catalog, state).tap(&:start!)
26
28
  end
27
29
 
@@ -126,7 +128,8 @@ module Enjine
126
128
  # Starts this game over from its opening, with the same or a new seed.
127
129
  def restart(seed: nil)
128
130
  fresh = State.initial(names: names, decklists: state.decklists, seed: seed.nil? ? state.seed : seed,
129
- outside: state.outside_lists, format: state.format, commanders: state.commanders)
131
+ outside: state.outside_lists, format: state.format, commanders: state.commanders,
132
+ permanent_limit: state.permanent_limit)
130
133
  @engine.state = fresh
131
134
  @history = []
132
135
  @buffer.clear
data/lib/enjine/mana.rb CHANGED
@@ -65,7 +65,7 @@ module Enjine
65
65
  end
66
66
  end
67
67
 
68
- HYBRID = %r{\A([WUBRG2])/([WUBRG])\z}
68
+ HYBRID = %r{\A([WUBRG2C])/([WUBRG])\z}
69
69
 
70
70
  # A monocolored hybrid symbol such as {2/B} (CR 107.4e); its first component is the generic "2".
71
71
  def self.mono_hybrid?(symbol) = symbol.first.to_s == "2"
@@ -107,9 +107,10 @@ module Enjine
107
107
  Cost.new(generic: generic, colored: colored.freeze, x_symbols: x, hybrid: hybrid.compact.freeze)
108
108
  end
109
109
 
110
- # A hybrid symbol (CR 107.4e), kept in its printed order: two-color such as {R/G} ([:R, :G]) or
111
- # monocolored such as {2/B} ([:"2", :B]: one black mana or two mana of any type). Phyrexian symbols
112
- # aren't supported (they are "unsupported mana symbol"s).
110
+ # A hybrid symbol (CR 107.4, 107.4e), kept in its printed order: two-color such as {R/G} ([:R, :G]),
111
+ # monocolored such as {2/B} ([:"2", :B]: one black mana or two mana of any type) or colorless such as {C/W}
112
+ # ([:C, :W]: one colorless or one white mana; it is white, CR 202.2d, and counts 1 for mana value, CR 202.3f).
113
+ # Phyrexian symbols aren't supported (they are "unsupported mana symbol"s).
113
114
  def self.hybrid_symbol(sym, errors, path)
114
115
  pair = HYBRID.match(sym).captures.map(&:to_sym)
115
116
  return pair.freeze if pair.uniq.size == 2
@@ -17,7 +17,7 @@ module Enjine
17
17
  "`except` modifications) and its enter abilities trigger. `with_counters: true`: it " \
18
18
  "also enters with the counters the copied permanent has. Choosing none: it enters as " \
19
19
  "itself.",
20
- rules: %w[707.5 707.9b 614.1c 614.12],
20
+ rules: %w[707.5 707.9b 205.1a 614.1c 614.12],
21
21
  params: { "of" => "filter (the permanents it may copy)", "except" => Mechanics::CopyExcept::PARAM,
22
22
  "with_counters" => "boolean" },
23
23
  example: { "enter_as_copy" => { "of" => { "permanent" => { "any_of" => %w[artifact creature] } },
@@ -77,21 +77,23 @@ module Enjine
77
77
  "(`\"any_one\"`) or in any combination of colors (`\"any\"`); `colors` limits " \
78
78
  "the choice. `\"chosen\"`: of the color chosen as this entered (choose_color). " \
79
79
  "`spend_only` restricts how the mana can be spent. `only_if`: \"Activate only if ...\". " \
80
- "`limit: \"once_each_turn\"`: \"Activate only once each turn.\"",
81
- rules: %w[605.1a 605.3a 605.3b 106.1a 106.4 106.6 607.2d 602.5b],
80
+ "`limit: \"once_each_turn\"`: \"Activate only once each turn.\" `add_counters`: it also " \
81
+ "puts counters on its own source (\"Add {C}. Put a point counter on this\").",
82
+ rules: %w[605.1a 605.3a 605.3b 106.1a 106.4 106.6 607.2d 602.5b 122.1],
82
83
  params: { "cost" => "list of costs (e.g. [\"tap\"])",
83
84
  "produce" => "mana symbols added, e.g. \"{G}\" or \"{C}{C}\"",
84
85
  "amount" => "amount (default 1; with produce: how many times)",
85
86
  "color" => CHOICES.join(" | "), "colors" => "list of colors to choose from (default all five)",
86
87
  "spend_only" => "{\"spells\": card spec, \"abilities\": card spec, \"from\" | \"not_from\": zone}",
87
88
  "only_if" => "condition: it can be activated only while it holds (CR 602.5b)",
88
- "limit" => "\"once_each_turn\" (CR 602.5b)" },
89
+ "limit" => "\"once_each_turn\" (CR 602.5b)",
90
+ "add_counters" => "{\"counter\": name, \"amount\": integer (default 1)}: put on this permanent" },
89
91
  example: { "mana" => { "cost" => ["tap"], "produce" => "{C}" } }
90
92
 
91
93
  attr_reader :costs, :produce, :color, :colors, :amount, :spend_only
92
94
 
93
95
  def self.build(params, errors, path, **)
94
- Mechanics.check_keys(params, %w[cost produce amount color colors spend_only only_if limit], errors, path)
96
+ Mechanics.check_keys(params, %w[cost produce amount color colors spend_only only_if limit add_counters], errors, path)
95
97
  costs = build_costs(Mechanics.fetch_param(params, :cost), errors, path)
96
98
  raw = Mechanics.fetch_param(params, :produce)
97
99
  color = Mechanics.fetch_param(params, :color)
@@ -106,7 +108,24 @@ module Enjine
106
108
  only_if = raw_if && Condition.build(raw_if, errors, "#{path}.only_if")
107
109
  new(costs.compact.freeze, produce, color: color, colors: build_colors(params, color, errors, path),
108
110
  amount: amount, spend_only: spend_only, only_if: only_if,
109
- per_turn: build_limit(params, errors, path))
111
+ per_turn: build_limit(params, errors, path),
112
+ add_counters: build_add_counters(params, errors, path))
113
+ end
114
+
115
+ # "Put a point counter on this" as part of the effect (CR 605.1a: a mana ability may do more than add mana):
116
+ # [counter, amount] or nil.
117
+ def self.build_add_counters(params, errors, path)
118
+ raw = Mechanics.fetch_param(params, :add_counters)
119
+ return nil if raw.nil?
120
+
121
+ amount = raw.is_a?(Hash) ? raw.fetch("amount", 1) : nil
122
+ if raw.is_a?(Hash) && (raw.keys - %w[counter amount]).empty? && raw["counter"].is_a?(String) &&
123
+ !Counters.error(raw["counter"]) && amount.is_a?(Integer) && amount.positive?
124
+ return [raw["counter"], amount].freeze
125
+ end
126
+
127
+ errors << "#{path}.add_counters: must be {\"counter\": counter name, \"amount\": integer >= 1}"
128
+ nil
110
129
  end
111
130
 
112
131
  # CR 605.3a: a mana ability is paid for and resolves at once, so none of its costs can wait for a
@@ -129,7 +148,10 @@ module Enjine
129
148
  end
130
149
  end
131
150
 
151
+ # "Remove a charge counter from this" needs no choice (Costs::RemoveCounters#at_once?).
132
152
  def self.choosing_cost?(cost)
153
+ return false if cost.respond_to?(:at_once?) && cost.at_once?
154
+
133
155
  cost.respond_to?(:choices_needed) || (cost.respond_to?(:x?) && cost.x?) ||
134
156
  (cost.respond_to?(:mana_cost) && cost.mana_cost.hybrid.any? { Mana.mono_hybrid?(it) })
135
157
  end
@@ -153,8 +175,10 @@ module Enjine
153
175
  COLORS
154
176
  end
155
177
 
156
- def initialize(costs, produce, color: nil, colors: COLORS, amount: nil, spend_only: nil, only_if: nil, per_turn: nil)
178
+ def initialize(costs, produce, color: nil, colors: COLORS, amount: nil, spend_only: nil, only_if: nil, per_turn: nil,
179
+ add_counters: nil)
157
180
  super()
181
+ @add_counters = add_counters
158
182
  @per_turn = per_turn
159
183
  @costs = costs
160
184
  @produce = produce
@@ -182,6 +206,23 @@ module Enjine
182
206
  bound.all? { |c| c.payable?(engine, object) } && (mana_cost.nil? || engine.pool_covers?(object.controller, mana_cost))
183
207
  end
184
208
 
209
+ # [counter, amount] it puts on its source as it resolves, or nil.
210
+ attr_reader :add_counters
211
+
212
+ # One whose costs include more than {T} and mana (a sacrifice, life, a discard, removing counters) or that puts
213
+ # counters on its source can't be undone (CR 734.1 rewinds only tapping and mana).
214
+ def irreversible?
215
+ !add_counters.nil? || costs.any? { !it.is_a?(Costs::Tap) && !it.is_a?(Costs::TapGranter) && !it.mana? }
216
+ end
217
+
218
+ # How many times it could be activated in a row now, for affordability: once, unless every cost is removing
219
+ # counters from it (no {T}, CR 605.3a), then as many times as the counters last.
220
+ def repeats(object, bound = costs)
221
+ return 1 if bound.empty? || !bound.all? { it.respond_to?(:at_once?) && it.at_once? }
222
+
223
+ bound.map { it.times_payable(object) }.min
224
+ end
225
+
185
226
  # How many times it may be activated each turn (nil: no limit, CR 602.5b); kept by Engine#record_activation!.
186
227
  attr_reader :per_turn
187
228
 
@@ -222,6 +263,7 @@ module Enjine
222
263
  "#{" (#{colors.join("/")})" unless colors == COLORS}"
223
264
  end
224
265
  "#{costs.join(", ")}: #{what}.#{" #{spend_only.to_s.capitalize}." if spend_only}" \
266
+ "#{" Put #{add_counters[1]} #{add_counters[0]} counter(s) on this." if add_counters}" \
225
267
  "#{" Activate only if #{@only_if}." if @only_if}#{" Activate only once each turn." if per_turn}"
226
268
  end
227
269
  end
@@ -5,11 +5,20 @@ module Enjine
5
5
  # The exceptions of a copy effect (CR 707.9a-b), e.g. {"legendary": false} ("except it isn't
6
6
  # legendary") or {"keywords": ["menace"]} ("except it has menace"). They become part of the copy's
7
7
  # copiable values, so a copy of the copy has them too (CR 707.2). See Engine::Copies.
8
+ #
9
+ # Types, subtypes and supertypes are added to the copied ones ("in addition to its other types", CR 205.1b).
10
+ # `replace` lists those that instead replace the copied values ("except it's a 4/4 Dragon creature": the
11
+ # creature type and card type are set, CR 707.9b, 205.1a): {"types": ["creature"], "subtypes": ["dragon"],
12
+ # "replace": ["types", "subtypes"]}. Set subtypes replace the creature types; other subtypes stay unless the
13
+ # types are set too.
8
14
  module CopyExcept
9
- KEYS = %w[legendary keywords types subtypes supertypes name power toughness colors].freeze
15
+ KEYS = %w[legendary keywords types subtypes supertypes name power toughness colors replace].freeze
16
+ # The lists `replace` may name (CR 205.1a: an effect that sets a card type, subtype or supertype).
17
+ REPLACEABLE = %w[types subtypes supertypes].freeze
10
18
  LISTS = { "keywords" => :keyword, "types" => :type, "supertypes" => :supertype }.freeze
11
19
  PARAM = "{\"legendary\": false, \"keywords\": [...], \"types\": [...], \"subtypes\": [...], " \
12
- "\"supertypes\": [...], \"name\": ..., \"power\": n, \"toughness\": n, \"colors\": [...]}"
20
+ "\"supertypes\": [...], \"name\": ..., \"power\": n, \"toughness\": n, \"colors\": [...], " \
21
+ "\"replace\": [\"types\" | \"subtypes\" | \"supertypes\"]}"
13
22
 
14
23
  module_function
15
24
 
@@ -26,6 +35,7 @@ module Enjine
26
35
  out["subtypes"] = subtypes(raw["subtypes"], errors, "#{path}.subtypes") if raw.key?("subtypes")
27
36
  values(raw, out, errors, path)
28
37
  out["colors"] = colors(raw["colors"], errors, "#{path}.colors") if raw.key?("colors")
38
+ out["replace"] = replace(raw, errors, "#{path}.replace") if raw.key?("replace")
29
39
  out.freeze
30
40
  end
31
41
 
@@ -41,6 +51,14 @@ module Enjine
41
51
  end
42
52
  end
43
53
 
54
+ # CR 205.1a: the listed values are set, replacing the copied ones; each must be given in the exceptions.
55
+ def replace(raw, errors, path)
56
+ list = raw["replace"]
57
+ ok = list.is_a?(Array) && !list.empty? && list.uniq == list && list.all? { REPLACEABLE.include?(it) && raw.key?(it) }
58
+ errors << "#{path}: must list some of #{REPLACEABLE.join(", ")}, each also given in the exceptions" unless ok
59
+ ok ? list.map(&:to_s).freeze : [].freeze
60
+ end
61
+
44
62
  def names(list, category, errors, path)
45
63
  ok = list.is_a?(Array) && !list.empty? && list.all? { Enjine.registry.fetch(category, it.to_s.downcase.tr(" -", "__")) }
46
64
  errors << "#{path}: must be a non-empty list of #{category}s (#{Enjine.registry.names(category).join(", ")})" unless ok
@@ -65,7 +83,9 @@ module Enjine
65
83
  bits = []
66
84
  bits << "not legendary" if except["legendary"] == false
67
85
  %w[name power toughness].each { bits << "#{it} #{except[it]}" if except.key?(it) }
68
- %w[keywords types subtypes supertypes colors].each { bits << "#{it} #{except[it].join("/")}" if except[it] }
86
+ %w[keywords types subtypes supertypes colors].each do |key|
87
+ bits << "#{"only " if except["replace"]&.include?(key)}#{key} #{except[key].join("/")}" if except[key]
88
+ end
69
89
  " (except #{bits.join(", ")})"
70
90
  end
71
91
  end
@@ -10,8 +10,9 @@ module Enjine
10
10
  description: "Remove `count` counters (of kind `counter`, or any kind) from among permanents you " \
11
11
  "control matching `filter` (default creature), one counter per choice. Removed as " \
12
12
  "it becomes cast. `self: true`: only from this permanent (\"Remove two counters from " \
13
- "Ghost-Spider\").",
14
- rules: %w[602.2b 601.2h 118.3 122.1],
13
+ "Ghost-Spider\"). With `self: true` and a `counter` kind it needs no choice, so a mana " \
14
+ "ability may have it (\"Remove a charge counter from this: Add one mana of any color\").",
15
+ rules: %w[602.2b 601.2h 118.3 122.1 605.3a],
15
16
  params: { "count" => "integer", "filter" => "filter (default creature)", "counter" => "counter name (optional)",
16
17
  "self" => "true: from this permanent only" },
17
18
  example: { "remove_counters" => { "count" => 3 } }
@@ -47,6 +48,15 @@ module Enjine
47
48
  entries.each { engine.remove_counters!(engine.object(it["object"]), it["counter"], 1) }
48
49
  end
49
50
 
51
+ # "Remove a charge counter from this" names both the permanent and the kind, so paying it needs no choice: a
52
+ # mana ability may have it (CR 605.3a), and pays it at once with #pay_at_once!.
53
+ def at_once? = @self && !@counter.nil?
54
+
55
+ def pay_at_once!(engine, object) = engine.remove_counters!(object, @counter, count)
56
+
57
+ # How many times it could be paid now (a mana ability without {T} may be activated again, CR 605.3a).
58
+ def times_payable(object) = object.counters.fetch(@counter, 0) / count
59
+
50
60
  def to_s = "Remove #{count} #{"#{@counter} " if @counter}counters from #{@self ? "this" : "among #{what}s you control"}"
51
61
  end
52
62
  end
@@ -50,6 +50,13 @@ module Enjine
50
50
  # The costs that take the permanent itself off the battlefield (CR 113.6m: not from another zone).
51
51
  LEAVING_SELF = [SacrificeSelf, ExileSelf].freeze
52
52
 
53
+ # Whether paying `cost` takes the source itself off the battlefield: such costs are paid after the others
54
+ # (CR 601.2h: any order), so a cost that needs the permanent (remove counters from it) is paid while it's there.
55
+ def self.leaving_self?(cost) = LEAVING_SELF.include?(cost.class)
56
+
57
+ # `costs` in an order in which all of them can be paid: those that take the source away last (stable).
58
+ def self.payment_order(costs) = costs.each_with_index.sort_by { |cost, i| [leaving_self?(cost) ? 1 : 0, i] }
59
+
53
60
  # "Sacrifice a creature" / "Sacrifice another creature or artifact" as a cost (CR 701.21a, 601.2h).
54
61
  # The permanent is chosen while casting and sacrificed as the spell or ability becomes cast; what
55
62
  # it was (types, subtypes, power) is kept for "if you sacrificed a Klingon this way" (CR 608.2h).
@@ -95,7 +95,7 @@ module Enjine
95
95
  "not counters, status or other effects), with the `except` modifications. The tokens " \
96
96
  "are the effect's result, for later effects such as granting haste or a delayed " \
97
97
  "sacrifice.",
98
- rules: %w[707.2 707.8 707.9a 707.9b 111.1 614.1c],
98
+ rules: %w[707.2 707.8 707.9a 707.9b 205.1a 205.1b 111.1 614.1c],
99
99
  params: { "of" => "selector (what to copy)", "amount" => "amount (default 1)", "tapped" => "boolean",
100
100
  "except" => CopyExcept::PARAM, "to" => "selector (default \"you\")" },
101
101
  example: { "create_token_copy" => { "of" => { "target" => 0 }, "except" => { "legendary" => false } } }
@@ -13,7 +13,7 @@ module Enjine
13
13
  "`effects` may use {\"result\": n} for what earlier effects of the creating list moved or " \
14
14
  "created (n below its position); those objects are affected only if they are still " \
15
15
  "where they were put. Its own effects are numbered on from there.",
16
- rules: %w[603.7a 603.7b 603.7c 603.7d 603.7e],
16
+ rules: %w[603.7a 603.7b 603.7c 603.7d 603.7e 107.3n],
17
17
  params: { "when" => "a trigger condition", "effects" => "list of effects",
18
18
  "watch" => "selector resolved now (e.g. {\"target\": 0}): the objects its trigger subject " \
19
19
  "\"watched\" and its effects' selector \"watched\" mean (\"when that creature dies\")",
@@ -32,6 +32,10 @@ module Enjine
32
32
  # created ability's own effects are numbered right after them (StackAbility.parse_effects).
33
33
  def self.linked(values, count, blank) = Array.new(count) { values&.[](it) || blank }
34
34
 
35
+ # The X announced for the resolving spell or ability that creates a delayed or reflexive trigger (CR 107.3n,
36
+ # 603.12: reflexive triggers follow the delayed-trigger rules), or nil when it had none.
37
+ def self.creating_x(engine, ctx) = engine.find_object(ctx.object)&.x
38
+
35
39
  def setup(params, errors, path)
36
40
  @ref = "delayed:#{path}"
37
41
  raw = Mechanics.fetch_param(params, :when)
@@ -57,6 +61,8 @@ module Enjine
57
61
  entry["watched"] = @watch.resolve(engine, ctx) if @watch
58
62
  entry["turn"] = engine.state.turn if @this_turn
59
63
  entry["once"] = true if @this_turn == "once" # CR 603.7b: the next time only, and only this turn
64
+ x = DelayedTrigger.creating_x(engine, ctx)
65
+ entry["x"] = x if x # CR 107.3n: its X is the X of the spell or ability that created it
60
66
  engine.create_delayed_trigger!(entry)
61
67
  end
62
68
  end
@@ -72,7 +78,7 @@ module Enjine
72
78
  "of the creating list ({\"result\": n} / {\"this_way\": n} with n below its position) and " \
73
79
  "their own, numbered on from there. With `if`, it triggers only when the condition holds " \
74
80
  "(\"when excess damage is dealt this way\").",
75
- rules: %w[603.12 603.12a 603.7d 603.7e 603.3d],
81
+ rules: %w[603.12 603.12a 603.7d 603.7e 603.3d 107.3n],
76
82
  params: { "targets" => "list of target filters", "effects" => "list of effects", "if" => "condition",
77
83
  "divide" => "amount divided among the targets as it's put on the stack (CR 601.2d)" },
78
84
  example: { "reflexive_trigger" => { "targets" => ["any_target"],
@@ -112,6 +118,7 @@ module Enjine
112
118
  engine.queue_pending_trigger!(source, nil, { "results" => results,
113
119
  "amounts" => DelayedTrigger.linked(ctx.amounts, @results_count, 0),
114
120
  "triggering" => memory["triggering"]&.dup,
121
+ "x" => DelayedTrigger.creating_x(engine, ctx),
115
122
  "departed" => engine.departed_snapshot }.compact)
116
123
  end
117
124
  end
@@ -104,7 +104,7 @@ module Enjine
104
104
  engine.begin_payment!(payer_obj.controller, mana, ctx.object, waterbend: bend.positive? ? bend : nil)
105
105
  return :wait
106
106
  end
107
- variant.each_with_index do |cost, i|
107
+ Costs.payment_order(variant).each do |cost, i| # the source leaves last (CR 601.2h)
108
108
  next if cost.mana?
109
109
 
110
110
  if cost.respond_to?(:choices_needed) # a chosen creature type was "paid" as it was chosen
@@ -4,13 +4,35 @@ module Enjine
4
4
  module Mechanics
5
5
  module Effects
6
6
  # Scry N / surveil N (CR 701.22, 701.25): look at the top N, put each on the top or away
7
- # (bottom / graveyard), then order the ones kept on top.
7
+ # (bottom / graveyard), then order the ones kept on top. `to` names who does it ("target player scries 2"):
8
+ # each of them in turn, in APNAP order (CR 101.4), with their own library.
8
9
  class LookAtTop < ChoiceEffect
9
10
  def self.default_to = "you"
10
11
  def self.away = raise(NotImplementedError)
11
12
 
12
13
  def run(engine, ctx, locals)
13
- index = ctx.controller
14
+ return :done unless locals.key?("amount") || condition.nil? || condition.true?(engine, ctx) # CR 608.2c, once
15
+
16
+ players = locals["players"] || who(engine, ctx)
17
+ locals["players"] = players unless players == [ctx.controller] # only "you": nothing to remember
18
+ while (turn = locals.fetch("turn", 0)) < players.size
19
+ return :wait if run_for(engine, ctx, locals, players[turn]) == :wait
20
+ break if players.size == 1
21
+
22
+ locals["turn"] = turn + 1
23
+ locals.delete("seen")
24
+ locals.delete("answers")
25
+ end
26
+ :done
27
+ end
28
+
29
+ # The players it names, in APNAP order (CR 101.4).
30
+ def who(engine, ctx)
31
+ named = players(engine, ctx).uniq
32
+ engine.turn_order_from_active.select { named.include?(it) }
33
+ end
34
+
35
+ def run_for(engine, ctx, locals, index)
14
36
  locals["amount"] ||= amount_for(engine, ctx)
15
37
  seen = (locals["seen"] ||= engine.player(index).library.first(locals["amount"]))
16
38
  decided = answers(locals).reject { it["type"] == "order" }
@@ -43,8 +65,10 @@ module Enjine
43
65
  # Scry N (CR 701.22).
44
66
  class Scry < LookAtTop
45
67
  primitive :effect, :scry, description: "Look at the top `amount` cards of your library; put any number on the " \
46
- "bottom and the rest on top in any order.",
47
- rules: %w[701.22a], params: { "amount" => "integer" }, example: { "scry" => { "amount" => 2 } }
68
+ "bottom and the rest on top in any order. `to`: who scries (default " \
69
+ "\"you\"; e.g. {\"target\": 0} for \"target player scries\"), each in turn.",
70
+ rules: %w[701.22a 101.4], params: { "amount" => "integer", "to" => "selector of players (default you)" },
71
+ example: { "scry" => { "amount" => 2 } }
48
72
  def self.away = "bottom"
49
73
 
50
74
  def place(engine, index, tops, bottoms)
@@ -57,8 +81,10 @@ module Enjine
57
81
  # Surveil N (CR 701.25).
58
82
  class Surveil < LookAtTop
59
83
  primitive :effect, :surveil, description: "Look at the top `amount` cards of your library; put any number into " \
60
- "your graveyard and the rest on top in any order.",
61
- rules: %w[701.25a], params: { "amount" => "integer" },
84
+ "your graveyard and the rest on top in any order. `to`: who " \
85
+ "surveils (default \"you\"), each in turn.",
86
+ rules: %w[701.25a 101.4],
87
+ params: { "amount" => "integer", "to" => "selector of players (default you)" },
62
88
  example: { "surveil" => { "amount" => 2 } }
63
89
  def self.away = "graveyard"
64
90
 
@@ -107,6 +107,8 @@ module Enjine
107
107
  # {"creature": {"saddled": true}} saddled this turn (CR 702.171b)
108
108
  # {"creature": {"entered_this_turn": true}} entered the battlefield this turn
109
109
  # {"spell": {"single_target": true}} a spell with a single target (CR 115.7)
110
+ # {"creature": {"color_count": {"equal": 1}}} monocolored (1), multicolored ({"at_least": 2}), colorless (0)
111
+ # (CR 105.2a-c); fixed integer bounds, matched like a color
110
112
  class Restricted
111
113
  TYPES = %w[artifact battle creature enchantment kindred land planeswalker instant sorcery].freeze
112
114
  BOOLEANS = %w[other attacking blocking tapped token modified transformed prepared saddled entered_this_turn
@@ -115,7 +117,7 @@ module Enjine
115
117
  TYPE_LISTS = %w[not any_of types].freeze
116
118
  NAME_LISTS = %w[subtypes not_subtypes supertypes not_supertypes attached_subtypes].freeze
117
119
  KEYWORD_LISTS = %w[keywords not_keywords].freeze
118
- KEYS = (%w[controller owner counters colors name] + BOOLEANS + RANGES + TYPE_LISTS + NAME_LISTS + KEYWORD_LISTS).freeze
120
+ KEYS = (%w[controller owner counters colors color_count name] + BOOLEANS + RANGES + TYPE_LISTS + NAME_LISTS + KEYWORD_LISTS).freeze
119
121
  # Lists that may be "chosen": the choice remembered under that memory key (CR 607.2d). "name" is only
120
122
  # "chosen" ("with the chosen name", CR 201.4).
121
123
  CHOSEN = { "colors" => "chosen_color", "types" => "chosen_card_type", "not" => "chosen_card_type",
@@ -147,7 +149,7 @@ module Enjine
147
149
  errors << "#{path}.colors: must be a non-empty list of W, U, B, R, G (any of them) or \"chosen\""
148
150
  end
149
151
  errors << "#{path}.name: must be \"chosen\"" unless [nil, "chosen"].include?(params["name"])
150
- new(base, params, ranges)
152
+ new(base, params, ranges, color_count(params, errors, path))
151
153
  end
152
154
 
153
155
  def self.validate_lists(params, errors, path)
@@ -196,12 +198,27 @@ module Enjine
196
198
  range.to_h { |key, n| [key, Amount.build(n, errors, "#{path}.#{key}", targets_count: 0, min: -1_000)] }
197
199
  end
198
200
 
201
+ # "Monocolored" / "multicolored" / "colorless" (CR 105.2a-c): bounds on the number of colors, fixed integers
202
+ # so the layer pass can match them (a characteristic, CR 105.2, not a live value).
203
+ def self.color_count(params, errors, path)
204
+ range = params["color_count"]
205
+ return nil if range.nil?
206
+
207
+ ok = range.is_a?(Hash) && !range.empty? && (range.keys - BOUNDS).empty? &&
208
+ range.values.all? { it.is_a?(Integer) && it.between?(0, 5) }
209
+ return range.transform_keys(&:to_s).freeze if ok
210
+
211
+ errors << "#{path}.color_count: must be {\"at_least\": n}, {\"at_most\": n} and/or {\"equal\": n} (n: 0-5)"
212
+ nil
213
+ end
214
+
199
215
  def self.build_ranges(params, errors, path)
200
216
  RANGES.filter_map { |key| [key, validate_range(params[key], errors, "#{path}.#{key}")] if params.key?(key) }.to_h
201
217
  end
202
218
 
203
- def initialize(base, params, ranges = {})
219
+ def initialize(base, params, ranges = {}, color_count = nil)
204
220
  @base = base
221
+ @color_count = color_count
205
222
  @controller = params["controller"]
206
223
  @other = params["other"] == true
207
224
  @params = params
@@ -263,7 +280,7 @@ module Enjine
263
280
  words.concat(chosen_words)
264
281
  words << (@lists["any_of"].empty? ? base.primitive_name.tr("_", " ") : @lists["any_of"].join(" or "))
265
282
  words.concat(ownership_words)
266
- words.concat(@ranges.map { |key, range| "with #{key.tr("_", " ")} #{range_words(range)}" })
283
+ words.concat(range_list_words)
267
284
  words << "with a #{@lists["attached_subtypes"].join(" or ")} attached" unless @lists["attached_subtypes"].empty?
268
285
  (words + [counter_words, ("with a single target" if @params["single_target"])] + keyword_words).compact.join(" ")
269
286
  end
@@ -285,6 +302,11 @@ module Enjine
285
302
  { "you" => "you own", "opponent" => "an opponent owns" }[@params["owner"]]]
286
303
  end
287
304
 
305
+ def range_list_words
306
+ words = @ranges.map { |key, range| "with #{key.tr("_", " ")} #{range_words(range)}" }
307
+ @color_count ? words << "with number of colors #{range_words(@color_count)}" : words
308
+ end
309
+
288
310
  def range_words(range) = range.map { |k, n| format(RANGE_WORDS.fetch(k), n) }.join(" and ")
289
311
 
290
312
  def chosen_words = @chosen.keys.map { "#{"non-" if it.start_with?("not")}chosen-#{it.delete_prefix("not_")}" }
@@ -343,6 +365,7 @@ module Enjine
343
365
  return false if c.subtypes.intersect?(@lists["not_subtypes"]) || c.supertypes.intersect?(@lists["not_supertypes"])
344
366
  return false unless (@lists["supertypes"] - c.supertypes).empty?
345
367
  return false if @colors && !c.colors.intersect?(@colors) # CR 105.2
368
+ return false if @color_count && !in_range?(c.colors.size, @color_count) # CR 105.2a-c
346
369
  return false unless keywords_ok?(c.keywords)
347
370
  return false if !@params["token"].nil? && facts.token != @params["token"]
348
371
  return false if @params["modified"] == false && Counters.any?(facts.counters)
data/lib/enjine/setup.rb CHANGED
@@ -9,13 +9,22 @@ module Enjine
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
11
  #
12
+ # `permanent_limit:` (off by default; not a rule of the game) ends a game as a draw, with the reason
13
+ # "permanent_limit", once more than that many permanents are on the battlefield: for simulations, where a
14
+ # board that keeps doubling would make every decision slower than the last.
15
+ #
12
16
  # `format:` picks the rules (Enjine::Format): constructed by default; `:duel_commander` plays Commander
13
17
  # (CR 903), and each deck then names its commander.
14
18
  class Setup
15
- attr_reader :players, :catalog, :decklists, :outside, :format, :commanders
19
+ attr_reader :players, :catalog, :decklists, :outside, :format, :commanders, :permanent_limit
16
20
 
17
- def initialize(*players, format: Format::CONSTRUCTED)
21
+ def initialize(*players, format: Format::CONSTRUCTED, permanent_limit: nil)
18
22
  @format = Format.fetch(format)
23
+ unless permanent_limit.nil? || (permanent_limit.is_a?(Integer) && permanent_limit.positive?)
24
+ raise ArgumentError, "permanent_limit must be a positive Integer or nil, got #{permanent_limit.inspect}"
25
+ end
26
+
27
+ @permanent_limit = permanent_limit
19
28
  players = players.flatten
20
29
  raise ArgumentError, "a game needs exactly 2 players" unless players.size == 2
21
30
  raise ArgumentError, "player names must differ" if players.map(&:name).uniq.size != 2
@@ -36,7 +45,7 @@ module Enjine
36
45
 
37
46
  def new_game(seed:)
38
47
  Game.start(catalog: @catalog, names: names, decklists: @decklists, seed: seed, outside: @outside,
39
- format: @format, commanders: @commanders).tap do |game|
48
+ format: @format, commanders: @commanders, permanent_limit: @permanent_limit).tap do |game|
40
49
  @players.each { |p| p.seat(game) }
41
50
  end
42
51
  end
@@ -49,6 +49,12 @@ module Enjine
49
49
  # The format and the commanders (CR 903.3): constructed has none; a Commander game has one per player, and
50
50
  # only a player's own commander card (besides emblems, CR 114.1) is ever in the command zone. Absent in
51
51
  # snapshots of constructed games.
52
+ def validate_permanent_limit(limit, errors)
53
+ return if limit.nil? || (limit.is_a?(Integer) && limit.positive?)
54
+
55
+ errors << "permanent_limit: must be a positive integer (or absent)"
56
+ end
57
+
52
58
  def build_commanders(state, data)
53
59
  state.format = Format.fetch(data.fetch("format", Format::CONSTRUCTED.name))
54
60
  state.commanders = data.fetch("commanders", [nil, nil]).dup.freeze
@@ -31,6 +31,7 @@ module Enjine
31
31
  validate_extra_phases(data, errors)
32
32
  validate_outside(data, catalog, errors)
33
33
  validate_commanders(data, catalog, errors)
34
+ validate_permanent_limit(data["permanent_limit"], errors)
34
35
  errors
35
36
  end
36
37
 
@@ -62,6 +63,7 @@ module Enjine
62
63
  state.extra_phases = deep_copy(data.fetch("extra_phases", State.no_extra_phases))
63
64
  state.outside_lists = data.fetch("outside_lists", [[], []]).map { |l| l.dup.freeze }.freeze
64
65
  build_commanders(state, data)
66
+ state.permanent_limit = data["permanent_limit"] # absent: no limit
65
67
  state.repeat_cleanup = data.fetch("repeat_cleanup", false)
66
68
  state.combat_damage_pass = data["combat_damage_pass"]
67
69
  state.attacks_declared = data.fetch("attacks_declared", 0)