@pkmn/engine 0.1.0-dev.21e728d9 → 0.1.0-dev.26a79a0e

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 (83) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +51 -23
  3. package/build/pkg/addon/browser.d.ts +3 -0
  4. package/build/pkg/addon/browser.js +47 -0
  5. package/build/pkg/addon/browser.js.map +1 -0
  6. package/build/pkg/addon/node.d.ts +3 -0
  7. package/build/pkg/addon/node.js +110 -0
  8. package/build/pkg/addon/node.js.map +1 -0
  9. package/build/pkg/addon/wasm.d.ts +2 -0
  10. package/build/pkg/addon/wasm.js +53 -0
  11. package/build/pkg/addon/wasm.js.map +1 -0
  12. package/build/pkg/addon.d.ts +25 -3
  13. package/build/pkg/addon.js +39 -71
  14. package/build/pkg/addon.js.map +1 -1
  15. package/build/pkg/data/layout.json +15 -2
  16. package/build/pkg/data/protocol.json +23 -9
  17. package/build/pkg/data.d.ts +27 -5
  18. package/build/pkg/data.js.map +1 -1
  19. package/build/pkg/gen1.d.ts +15 -18
  20. package/build/pkg/gen1.js +28 -19
  21. package/build/pkg/gen1.js.map +1 -1
  22. package/build/pkg/index.d.ts +42 -91
  23. package/build/pkg/index.js +23 -70
  24. package/build/pkg/index.js.map +1 -1
  25. package/build/pkg/protocol.d.ts +20 -1
  26. package/build/pkg/protocol.js +109 -107
  27. package/build/pkg/protocol.js.map +1 -1
  28. package/build/tools/debug.js +53 -78
  29. package/build/tools/debug.js.map +1 -1
  30. package/build/tools/display/debug.jsx +152 -0
  31. package/build/tools/display/debug.jsx.map +1 -0
  32. package/build/tools/display/index.js +152 -0
  33. package/build/tools/display/index.js.map +1 -0
  34. package/build/tools/display/ui.jsx +359 -0
  35. package/build/tools/display/ui.jsx.map +1 -0
  36. package/build/tools/display/util.js +33 -0
  37. package/build/tools/display/util.js.map +1 -0
  38. package/build.zig +330 -93
  39. package/package.json +59 -132
  40. package/src/bin/install-pkmn-engine +31 -20
  41. package/src/bin/pkmn-debug +1 -1
  42. package/src/lib/bindings/c.zig +255 -0
  43. package/src/lib/{binding → bindings}/node.zig +8 -21
  44. package/src/lib/bindings/wasm.zig +59 -0
  45. package/src/lib/common/array.zig +77 -0
  46. package/src/lib/common/data.zig +4 -4
  47. package/src/lib/common/debug.zig +39 -8
  48. package/src/lib/common/js.zig +4 -2
  49. package/src/lib/common/optional.zig +14 -10
  50. package/src/lib/common/options.zig +6 -0
  51. package/src/lib/common/protocol.zig +390 -412
  52. package/src/lib/common/rational.zig +137 -34
  53. package/src/lib/common/rng.zig +7 -9
  54. package/src/lib/common/util.zig +60 -1
  55. package/src/lib/gen1/calc.zig +706 -163
  56. package/src/lib/gen1/chance.zig +405 -280
  57. package/src/lib/gen1/data/moves.zig +2 -4
  58. package/src/lib/gen1/data/species.zig +2 -4
  59. package/src/lib/gen1/data/types.zig +1 -2
  60. package/src/lib/gen1/data.zig +24 -27
  61. package/src/lib/gen1/helpers.zig +92 -548
  62. package/src/lib/gen1/mechanics.zig +575 -461
  63. package/src/lib/gen2/calc.zig +37 -27
  64. package/src/lib/gen2/chance.zig +84 -496
  65. package/src/lib/gen2/data/items.zig +1 -3
  66. package/src/lib/gen2/data/moves.zig +2 -4
  67. package/src/lib/gen2/data/species.zig +1 -3
  68. package/src/lib/gen2/data/types.zig +1 -2
  69. package/src/lib/gen2/data.zig +19 -22
  70. package/src/lib/gen2/generated.zig +22 -29
  71. package/src/lib/gen2/helpers.zig +46 -25
  72. package/src/lib/gen2/mechanics.zig +487 -413
  73. package/src/lib/node.zig +18 -0
  74. package/src/lib/pkmn.zig +37 -15
  75. package/src/lib/wasm.zig +17 -0
  76. package/src/tools/display/dom.ts +93 -0
  77. package/src/tools/display/ui.css +354 -0
  78. package/build/test/display.js +0 -400
  79. package/build/test/display.js.map +0 -1
  80. package/src/lib/binding/wasm.zig +0 -12
  81. package/src/lib/gen1/README.md +0 -894
  82. package/src/lib/gen2/README.md +0 -329
  83. package/src/test/display/pkmn.html.tmpl +0 -368
@@ -1,42 +1,43 @@
1
- const std = @import("std");
2
-
3
- const pkmn = @import("../pkmn.zig");
1
+ const DEBUG = @import("../common/debug.zig").print;
4
2
 
3
+ const chance = @import("chance.zig");
5
4
  const common = @import("../common/data.zig");
6
- const DEBUG = @import("../common/debug.zig").print;
5
+ const data = @import("data.zig");
6
+ const helpers = @import("helpers.zig");
7
7
  const optional = @import("../common/optional.zig");
8
+ const pkmn = @import("../pkmn.zig");
8
9
  const protocol = @import("../common/protocol.zig");
9
10
  const rational = @import("../common/rational.zig");
11
+ const std = @import("std");
10
12
  const util = @import("../common/util.zig");
11
13
 
12
- const chance = @import("chance.zig");
13
- const data = @import("data.zig");
14
- const helpers = @import("helpers.zig");
15
-
14
+ const Action = chance.Action;
15
+ const Actions = chance.Actions;
16
16
  const assert = std.debug.assert;
17
-
17
+ const BigRational = rational.BigRational;
18
+ const Chance = chance.Chance;
19
+ const Choice = common.Choice;
20
+ const Confusion = chance.Confusion;
21
+ const Duration = chance.Duration;
22
+ const Durations = chance.Durations;
23
+ const enabled = pkmn.options.calc;
18
24
  const expect = std.testing.expect;
19
25
  const expectEqual = std.testing.expectEqual;
20
-
21
- const enabled = pkmn.options.calc;
22
-
26
+ const expectEqualSlices = std.testing.expectEqualSlices;
27
+ const isPointerTo = util.isPointerTo;
28
+ const Observation = chance.Observation;
29
+ const Optional = optional.Optional;
23
30
  const Player = common.Player;
31
+ const PointerType = util.PointerType;
32
+ const Rational = rational.Rational;
24
33
  const Result = common.Result;
25
- const Choice = common.Choice;
26
-
27
- const Optional = optional.Optional;
34
+ const Sleeps = chance.Sleeps;
28
35
 
29
- const Rational = rational.Rational;
36
+ const tty = true; // DEBUG
37
+ const summary = false; // DEBUG
30
38
 
31
- const PointerType = util.PointerType;
32
-
33
- const Actions = chance.Actions;
34
- const Action = chance.Action;
35
- const Chance = chance.Chance;
36
- const Durations = chance.Durations;
37
- const Duration = chance.Duration;
38
-
39
- const Rolls = helpers.Rolls;
39
+ const Int = if (@hasField(std.builtin.Type, "int")) .int else .Int;
40
+ const Enum = if (@hasField(std.builtin.Type, "enum")) .@"enum" else .Enum;
40
41
 
41
42
  /// Information relevant to damage calculation that occured during a Generation I battle `update`.
42
43
  pub const Summaries = extern struct {
@@ -51,7 +52,7 @@ pub const Summaries = extern struct {
51
52
 
52
53
  /// Returns the `Summary` for the given `player`.
53
54
  pub fn get(self: anytype, player: Player) PointerType(@TypeOf(self), Summary) {
54
- assert(@typeInfo(@TypeOf(self)).Pointer.child == Summaries);
55
+ assert(isPointerTo(self, Summaries));
55
56
  return if (player == .P1) &self.p1 else &self.p2;
56
57
  }
57
58
  };
@@ -69,8 +70,10 @@ pub const Summary = extern struct {
69
70
  /// The final computed damage that gets applied to the Pokémon. May exceed the target's HP
70
71
  // (to determine the *actual* damage done compare the target's stored HP before and after).
71
72
  final: u16 = 0,
72
- /// Whether higher damage will saturate / result in the same outcome (e.g. additional damage
73
- /// gets ignored due to it already breaking a Substitute or causing the target to faint).
73
+ /// Whether higher direct damage will saturate / result in the same outcome (e.g. additional
74
+ /// direct damage gets ignored due to it already breaking a Substitute or causing the target
75
+ /// to faint). Note that this field does not get set in scenarios where the target would
76
+ /// only be guaranteed to faint due to some sort of subsequent recoil or residual damage.
74
77
  capped: bool = false,
75
78
 
76
79
  // NOTE: 15 bits padding
@@ -85,25 +88,11 @@ pub const Summary = extern struct {
85
88
  }
86
89
  };
87
90
 
88
- /// TODO
89
- pub const Overrides = extern struct {
90
- /// TODO
91
- actions: Actions = .{},
92
- /// TODO
93
- durations: Durations = .{},
94
-
95
- _: u32 = 0,
96
-
97
- comptime {
98
- assert(@sizeOf(Overrides) == 24);
99
- }
100
- };
101
-
102
91
  /// Allows for forcing the value of specific RNG events during a Generation I battle `update` via
103
92
  /// `overrides` and tracks `summaries` of information relevant to damage calculation.
104
93
  pub const Calc = struct {
105
94
  /// Overrides the normal behavior of the RNG during an `update` to force specific outcomes.
106
- overrides: Overrides = .{},
95
+ overrides: Actions = .{},
107
96
  /// Information relevant to damage calculation.
108
97
  summaries: Summaries = .{},
109
98
 
@@ -114,26 +103,20 @@ pub const Calc = struct {
114
103
  ) ?std.meta.FieldType(Action, field) {
115
104
  if (!enabled) return null;
116
105
 
117
- const overrides =
118
- if (player == .P1) self.overrides.actions.p1 else self.overrides.actions.p2;
119
- const val = @field(overrides, @tagName(field));
106
+ const val = @field(self.overrides.get(player), @tagName(field));
120
107
  return if (switch (@typeInfo(@TypeOf(val))) {
121
- .Enum => val != .None,
122
- .Int => val != 0,
108
+ Enum => val != .None,
109
+ Int => val != 0,
123
110
  else => unreachable,
124
111
  }) val else null;
125
112
  }
126
113
 
127
- pub fn modify(self: Calc, player: Player, comptime field: Duration.Field) ?bool {
128
- if (!enabled) return null;
129
-
130
- const durations = self.overrides.durations;
131
- const set = @field(if (player == .P1) durations.p1 else durations.p2, @tagName(field));
132
- if (set == 0) return null;
114
+ pub fn confusion(self: *Calc, player: Player) void {
115
+ if (!enabled) return;
133
116
 
134
- const actions = self.overrides.actions;
135
- const overrides = if (player == .P1) actions.p1.durations else actions.p2.durations;
136
- return @field(overrides, @tagName(field)) != 0;
117
+ if (self.overrides.get(player).confusion == .started) {
118
+ self.overrides.get(player).confusion = .None;
119
+ }
137
120
  }
138
121
 
139
122
  pub fn base(self: *Calc, player: Player, val: u16) void {
@@ -169,9 +152,8 @@ const Null = struct {
169
152
  return null;
170
153
  }
171
154
 
172
- pub fn modify(self: Null, player: Player, comptime field: Duration.Field) ?bool {
173
- _ = .{ self, player, field };
174
- return null;
155
+ pub fn confusion(self: Null, player: Player) void {
156
+ _ = .{ self, player };
175
157
  }
176
158
 
177
159
  pub fn base(self: Null, player: Player, val: u16) void {
@@ -195,12 +177,14 @@ pub const Stats = struct {
195
177
  };
196
178
 
197
179
  pub const Options = struct {
198
- actions: Actions = .{},
180
+ durations: Durations,
199
181
  seed: ?u64 = null,
200
182
  cap: bool = false,
201
183
  metronome: bool = false,
202
184
  };
203
185
 
186
+ pub const MAX_FRONTIER = 81;
187
+
204
188
  pub fn transitions(
205
189
  battle: anytype,
206
190
  c1: Choice,
@@ -211,31 +195,32 @@ pub fn transitions(
211
195
  ) !?Stats {
212
196
  var stats: Stats = .{};
213
197
 
214
- var actions = options.actions;
215
- var cap = options.cap;
198
+ const cap = options.cap;
216
199
 
217
200
  var seen = std.AutoHashMap(Actions, void).init(allocator);
218
201
  defer seen.deinit();
219
202
  var frontier = std.ArrayList(Actions).init(allocator);
220
203
  defer frontier.deinit();
221
204
 
205
+ const d = options.durations;
206
+
222
207
  var opts = pkmn.battle.options(
223
208
  protocol.NULL,
224
- Chance(Rational(u128)){ .probability = .{}, .actions = actions },
225
- Calc{ .overrides = .{ .actions = actions, .durations = .{
226
- .p1 = actions.p1.durations,
227
- .p2 = actions.p2.durations,
228
- } } },
209
+ Chance(Rational(u128)){ .probability = .{}, .durations = d },
210
+ Calc{},
229
211
  );
230
212
 
231
213
  var b = battle;
232
214
  _ = try b.update(c1, c2, &opts);
233
215
  stats.updates += 1;
234
216
 
235
- var p1 = b.side(.P1);
236
- var p2 = b.side(.P2);
217
+ const p1 = b.side(.P1);
218
+ const p2 = b.side(.P2);
237
219
 
238
- var p: Rational(u128) = .{ .p = 0, .q = 1 };
220
+ var p = try BigRational.init(allocator);
221
+ defer p.deinit();
222
+ try p.val.p.set(0);
223
+ try p.val.q.set(1);
239
224
  try frontier.append(opts.chance.actions);
240
225
 
241
226
  // zig fmt: off
@@ -247,85 +232,111 @@ pub fn transitions(
247
232
  var i: usize = 0;
248
233
  assert(frontier.items.len == 1);
249
234
  while (i < frontier.items.len) : (i += 1) {
250
- var template = frontier.items[i];
251
- opts.calc.overrides.durations = .{
252
- .p1 = template.p1.durations,
253
- .p2 = template.p2.durations,
235
+ const f = frontier.items[i];
236
+ const saved = stats.saved;
237
+
238
+ var r = try BigRational.init(allocator);
239
+ defer r.deinit();
240
+ try r.val.p.set(0);
241
+ try r.val.q.set(1);
242
+
243
+ try debug(writer, f, .{
244
+ .shape = true,
245
+ .color = i,
246
+ .bold = true,
247
+ .background = true,
248
+ .indent = false,
249
+ });
250
+
251
+ var a: Actions = .{
252
+ .p1 = .{ .metronome = p1_move, .pp = f.p1.pp, .duration = f.p1.duration },
253
+ .p2 = .{ .metronome = p2_move, .pp = f.p2.pp, .duration = f.p2.duration },
254
254
  };
255
255
 
256
- try debug(writer, template, true, .{ .color = i, .bold = true, .background = true });
257
-
258
- var a: Actions = .{ .p1 = .{ .metronome = p1_move }, .p2 = .{ .metronome = p2_move } };
259
-
260
- for (Rolls.speedTie(template.p1)) |tie| { a.p1.speed_tie = tie; a.p2.speed_tie = tie;
261
- for (Rolls.sleep(template.p1, actions.p1)) |p1_slp| { a.p1.durations.sleep = p1_slp;
262
- for (Rolls.sleep(template.p2, actions.p2)) |p2_slp| { a.p2.durations.sleep = p2_slp;
263
- for (Rolls.disable(template.p1, actions.p1, p1_slp)) |p1_disable| { a.p1.durations.disable = p1_disable;
264
- for (Rolls.disable(template.p2, actions.p2, p2_slp)) |p2_disable| { a.p2.durations.disable = p2_disable;
265
- for (Rolls.confusion(template.p1, actions.p1, p1_slp)) |p1_cfz| { a.p1.durations.confusion = p1_cfz;
266
- for (Rolls.confusion(template.p2, actions.p2, p1_slp)) |p2_cfz| { a.p2.durations.confusion = p2_cfz;
267
- for (Rolls.confused(template.p1, p1_cfz)) |p1_cfzd| { a.p1.confused = p1_cfzd;
268
- for (Rolls.confused(template.p2, p2_cfz)) |p2_cfzd| { a.p2.confused = p2_cfzd;
269
- for (Rolls.paralyzed(template.p1, p1_cfzd)) |p1_par| { a.p1.paralyzed = p1_par;
270
- for (Rolls.paralyzed(template.p2, p2_cfzd)) |p2_par| { a.p2.paralyzed = p2_par;
271
- for (Rolls.attacking(template.p1, actions.p1, p1_par)) |p1_atk| { a.p1.durations.attacking = p1_atk;
272
- for (Rolls.attacking(template.p2, actions.p2, p2_par)) |p2_atk| { a.p2.durations.attacking = p2_atk;
273
- for (Rolls.binding(template.p1, actions.p1, p1_par)) |p1_bind| { a.p1.durations.binding = p1_bind;
274
- for (Rolls.binding(template.p2, actions.p2, p2_par)) |p2_bind| { a.p2.durations.binding = p2_bind;
275
- for (Rolls.duration(template.p1, p1_par)) |p1_dur| { a.p1.duration = p1_dur;
276
- for (Rolls.duration(template.p2, p2_par)) |p2_dur| { a.p2.duration = p2_dur;
277
- for (Rolls.hit(template.p1, p1_par)) |p1_hit| { a.p1.hit = p1_hit;
278
- for (Rolls.hit(template.p2, p2_par)) |p2_hit| { a.p2.hit = p2_hit;
279
- for (Rolls.psywave(template.p1, p1, p1_hit)) |p1_psywave| { a.p1.psywave = p1_psywave;
280
- for (Rolls.psywave(template.p2, p2, p2_hit)) |p2_psywave| { a.p2.psywave = p2_psywave;
281
- for (Rolls.moveSlot(template.p1, p1_hit)) |p1_slot| { a.p1.move_slot = p1_slot;
282
- for (Rolls.moveSlot(template.p2, p2_hit)) |p2_slot| { a.p2.move_slot = p2_slot;
283
- for (Rolls.multiHit(template.p1, p1_hit)) |p1_multi| { a.p1.multi_hit = p1_multi;
284
- for (Rolls.multiHit(template.p2, p1_hit)) |p2_multi| { a.p2.multi_hit = p2_multi;
285
- for (Rolls.secondaryChance(template.p1, p1_hit)) |p1_sec| { a.p1.secondary_chance = p1_sec;
286
- for (Rolls.secondaryChance(template.p2, p2_hit)) |p2_sec| { a.p2.secondary_chance = p2_sec;
287
- for (Rolls.criticalHit(template.p1, p1_hit)) |p1_crit| { a.p1.critical_hit = p1_crit;
288
- for (Rolls.criticalHit(template.p2, p2_hit)) |p2_crit| { a.p2.critical_hit = p2_crit;
289
-
290
- var p1_dmg = Rolls.damage(template.p1, p1_hit);
256
+ for (Rolls.speedTie(f.p1)) |tie| { a.p1.speed_tie = tie; a.p2.speed_tie = tie;
257
+ for (Rolls.sleep(f.p1, d.p1)) |p1_slp| { a.p1.sleep = p1_slp;
258
+ for (Rolls.sleep(f.p2, d.p2)) |p2_slp| { a.p2.sleep = p2_slp;
259
+ for (Rolls.disable(f.p1, d.p1, p1_slp)) |p1_dis| { a.p1.disable = p1_dis;
260
+ for (Rolls.disable(f.p2, d.p2, p2_slp)) |p2_dis| { a.p2.disable = p2_dis;
261
+ for (Rolls.attacking(f.p1, d.p1, p1_slp)) |p1_atk| { a.p1.attacking = p1_atk;
262
+ for (Rolls.attacking(f.p2, d.p2, p2_slp)) |p2_atk| { a.p2.attacking = p2_atk;
263
+ for (Rolls.confusion(f.p1, d.p1, tie, p1_atk, p1_slp)) |p1_cfz| { a.p1.confusion = p1_cfz;
264
+ for (Rolls.confusion(f.p2, d.p2, tie, p2_atk, p2_slp)) |p2_cfz| { a.p2.confusion = p2_cfz;
265
+ for (Rolls.confused(f.p1, p1_cfz)) |p1_cfzd| { a.p1.confused = p1_cfzd;
266
+ for (Rolls.confused(f.p2, p2_cfz)) |p2_cfzd| { a.p2.confused = p2_cfzd;
267
+ for (Rolls.paralyzed(f.p1, p1_cfzd)) |p1_par| { a.p1.paralyzed = p1_par;
268
+ for (Rolls.paralyzed(f.p2, p2_cfzd)) |p2_par| { a.p2.paralyzed = p2_par;
269
+ for (Rolls.binding(f.p1, d.p1, p1_par)) |p1_bind| { a.p1.binding = p1_bind;
270
+ for (Rolls.binding(f.p2, d.p2, p2_par)) |p2_bind| { a.p2.binding = p2_bind;
271
+ for (Rolls.hit(f.p1, p1_par)) |p1_hit| { a.p1.hit = p1_hit;
272
+ for (Rolls.hit(f.p2, p2_par)) |p2_hit| { a.p2.hit = p2_hit;
273
+ for (Rolls.psywave(f.p1, p1, p1_hit)) |p1_psywave| { a.p1.psywave = p1_psywave;
274
+ for (Rolls.psywave(f.p2, p2, p2_hit)) |p2_psywave| { a.p2.psywave = p2_psywave;
275
+ for (Rolls.moveSlot(f.p1, p1_hit)) |p1_slot| { a.p1.move_slot = p1_slot;
276
+ for (Rolls.moveSlot(f.p2, p2_hit)) |p2_slot| { a.p2.move_slot = p2_slot;
277
+ for (Rolls.multiHit(f.p1, p1_hit)) |p1_multi| { a.p1.multi_hit = p1_multi;
278
+ for (Rolls.multiHit(f.p2, p2_hit)) |p2_multi| { a.p2.multi_hit = p2_multi;
279
+ for (Rolls.secondaryChance(f.p1, p1_hit)) |p1_sec| { a.p1.secondary_chance = p1_sec;
280
+ for (Rolls.secondaryChance(f.p2, p2_hit)) |p2_sec| { a.p2.secondary_chance = p2_sec;
281
+ for (Rolls.criticalHit(f.p1, p1_hit)) |p1_crit| { a.p1.critical_hit = p1_crit;
282
+ for (Rolls.criticalHit(f.p2, p2_hit)) |p2_crit| { a.p2.critical_hit = p2_crit;
283
+
284
+ var p1_dmg = Rolls.damage(f.p1, p1_hit);
291
285
  while (p1_dmg.min < p1_dmg.max) : (p1_dmg.min += 1) {
292
286
  a.p1.damage = @intCast(p1_dmg.min);
293
- var p1_min: u8 = 0;
294
287
 
295
- var p2_dmg = Rolls.damage(template.p2, p2_hit);
288
+ var p2_dmg = Rolls.damage(f.p2, p2_hit);
289
+
290
+ const p1_min: u9 = p1_dmg.min;
291
+ const p2_min: u9 = p2_dmg.min;
292
+
296
293
  while (p2_dmg.min < p2_dmg.max) : (p2_dmg.min += 1) {
297
294
  a.p2.damage = @intCast(p2_dmg.min);
298
295
 
299
- opts.calc.overrides.actions = a;
300
- opts.chance = .{ .probability = .{}, .actions = actions };
296
+ opts.calc.overrides = a;
297
+ opts.calc.summaries = .{};
298
+ opts.chance = .{ .probability = .{}, .durations = d };
301
299
  const q = &opts.chance.probability;
302
300
 
303
301
  b = battle;
304
302
  _ = try b.update(c1, c2, &opts);
305
- stats.updates += 1;
306
-
307
- const p1_max: u8 = @intCast(p1_dmg.min);
308
- const p2_max: u8 = @intCast(p2_dmg.min);
309
- _ = cap;
310
303
 
311
- // var p1_max = if (p1_min != 0) p1_min else
312
- // try Rolls.coalesce(.P1, @intCast(u8, p1_dmg.min), &opts.calc.summaries, cap);
313
- // var p2_max =
314
- // try Rolls.coalesce(.P2, @intCast(u8, p2_dmg.min), &opts.calc.summaries, cap);
304
+ stats.updates += 1;
315
305
 
316
- if (opts.chance.actions.matches(template)) {
317
- if (!opts.chance.actions.eql(a)) {
318
- try debug(writer, opts.chance.actions, false, .{ .color = i, .dim = true });
306
+ const summaries = &opts.calc.summaries;
307
+ const p1_max: u9 = if (p2_dmg.min != p2_min)
308
+ p1_dmg.min
309
+ else
310
+ Rolls.coalesce(.P1, @as(u8, @intCast(p1_dmg.min)), summaries, cap);
311
+ const p2_max: u9 =
312
+ Rolls.coalesce(.P2, @as(u8, @intCast(p2_dmg.min)), summaries, cap);
313
+
314
+ if (opts.chance.actions.matches(f)) {
315
+ if (!opts.chance.actions.relax().eql(a)) {
316
+ if (!summary) {
317
+ try debug(writer, opts.chance.actions, .{
318
+ .p1_max = p1_max,
319
+ .p2_max = p2_max,
320
+ .color = i,
321
+ .dim = true,
322
+ });
323
+ }
319
324
 
320
- p1_min = p1_max;
325
+ p1_dmg.min = p1_max;
321
326
  p2_dmg.min = p2_max;
322
327
  continue;
323
328
  }
324
329
 
325
- try debug(writer, opts.chance.actions, false, .{ .color = i });
330
+ if (!summary) {
331
+ try debug(writer, opts.chance.actions, .{
332
+ .p1_max = p1_max,
333
+ .p2_max = p2_max,
334
+ .color = i,
335
+ });
336
+ }
326
337
 
327
- for (p1_dmg.min..@as(u9, p1_max) + 1) |p1d| {
328
- for (p2_dmg.min..@as(u9, p2_max) + 1) |p2d| {
338
+ for (p1_min..p1_max + 1) |p1d| {
339
+ for (p2_dmg.min..p2_max + 1) |p2d| {
329
340
  var acts = opts.chance.actions;
330
341
  acts.p1.damage = @intCast(p1d);
331
342
  acts.p2.damage = @intCast(p2d);
@@ -335,38 +346,61 @@ pub fn transitions(
335
346
  }
336
347
  }
337
348
  }
338
-
339
- if (p1_max != p1_dmg.min) try q.update(p1_max - p1_dmg.min + 1, 1);
349
+ if (p1_max != p1_min) try q.update(p1_max - p1_min + 1, 1);
340
350
  if (p2_max != p2_dmg.min) try q.update(p2_max - p2_dmg.min + 1, 1);
351
+
352
+ q.reduce();
341
353
  try p.add(q);
354
+ try r.add(q);
355
+
342
356
  stats.saved += 1;
343
357
 
344
- if (p.q < p.p) {
358
+ if (p.val.q.order(p.val.p) == .lt) {
345
359
  err("improper fraction {}", .{p}, options.seed);
346
360
  return error.TestUnexpectedResult;
347
361
  }
348
362
  } else {
349
- try debug(writer, opts.chance.actions, false, .{ .dim = true });
350
-
351
- if (!matches(opts.chance.actions, i, frontier.items)) {
363
+ if (!opts.chance.actions.matchesAny(frontier.items, i)) {
352
364
  try frontier.append(opts.chance.actions);
353
365
 
354
- try debug(writer, opts.chance.actions, true, .{
366
+ try debug(writer, opts.chance.actions, .{
367
+ .p1_max = p1_max,
368
+ .p2_max = p2_max,
369
+ .dim = true,
370
+ .newline = false,
371
+ });
372
+ try writer.writeAll(" → ");
373
+ try debug(writer, opts.chance.actions, .{
374
+ .shape = true,
355
375
  .color = frontier.items.len - 1,
356
376
  .dim = true,
357
- .background = true
377
+ .background = true,
378
+ .indent = false,
379
+ });
380
+ } else if (!summary) {
381
+ try debug(writer, opts.chance.actions, .{
382
+ .p1_max = p1_max,
383
+ .p2_max = p2_max,
384
+ .dim = true,
358
385
  });
359
386
  }
360
387
  }
361
388
 
362
- p1_min = p1_max;
389
+ p1_dmg.min = p1_max;
363
390
  p2_dmg.min = p2_max;
364
391
  }
365
392
 
366
- assert(p1_min > 0 or p1_dmg.min == 0);
367
- p1_dmg.min = p1_min;
393
+ }}}}}}}}}}}}}}}}}}}}}}}}}}}}
394
+
395
+ assert(stats.saved > saved);
396
+ const old = @hasDecl(std.fmt, "formatFloatDecimal");
397
+ if (!old and @TypeOf(writer) != @TypeOf(std.io.null_writer)) {
398
+ try writer.print(
399
+ " {} ({d:.2}%)\n = ──────────\n {} ({d:.2}%)\n\n",
400
+ .{r.val, percent(r.val), p.val, percent(p.val)},
401
+ );
402
+ }
368
403
 
369
- }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
370
404
  }
371
405
 
372
406
  assert(frontier.items.len == i);
@@ -378,8 +412,7 @@ pub fn transitions(
378
412
 
379
413
  stats.seen = seen.count();
380
414
 
381
- p.reduce();
382
- if (p.p != 1 or p.q != 1) {
415
+ if (try p.val.p.to(u128) != 1 or try p.val.q.to(u128) != 1) {
383
416
  err("expected 1, found {}", .{p}, options.seed);
384
417
  return error.TestExpectedEqual;
385
418
  }
@@ -387,13 +420,117 @@ pub fn transitions(
387
420
  return stats;
388
421
  }
389
422
 
390
- fn matches(actions: Actions, i: usize, frontier: []Actions) bool {
391
- for (frontier, 0..) |f, j| {
392
- // TODO: is skipping this redundant check worth it?
393
- if (i == j) continue;
394
- if (f.matches(actions)) return true;
423
+ fn percent(r: anytype) f128 {
424
+ return 100 * @as(f128, @floatFromInt(r.p.to(u128) catch unreachable)) /
425
+ @as(f128, @floatFromInt(r.q.to(u128) catch unreachable));
426
+ }
427
+
428
+ pub fn update(
429
+ battle: anytype,
430
+ c1: Choice,
431
+ c2: Choice,
432
+ options: anytype,
433
+ allocator: std.mem.Allocator,
434
+ writer: anytype,
435
+ transition: bool,
436
+ ) !Result {
437
+ const durations = options.chance.durations;
438
+ options.chance.reset();
439
+
440
+ if (!pkmn.options.chance or !pkmn.options.calc) return battle.update(c1, c2, options);
441
+
442
+ const original = battle.*;
443
+
444
+ // Perfom the actual update
445
+ const result = battle.update(c1, c2, options);
446
+ var overrides = options.chance.actions;
447
+ const updated = options.chance.durations;
448
+
449
+ if (@TypeOf(battle.rng) == data.PRNG) {
450
+ // Ensure we can encode the diffs in less than MAX_DIFFS bytes.
451
+ var buf: [helpers.MAX_DIFFS]u8 = undefined;
452
+ var stream: protocol.ByteStream = .{ .buffer = &buf };
453
+ const n = try helpers.diff(&original, battle, stream.writer());
454
+
455
+ // Applying the diff to the battle should take us back to the original copy
456
+ // of the battle (ignoring the RNG).
457
+ var patched = battle.*;
458
+ patched.rng = original.rng;
459
+ helpers.patch(&patched, buf[0..n]);
460
+ try expectEqual(original, patched);
461
+ }
462
+
463
+ if (transition) {
464
+ // Ensure we can generate all transitions from the same original state
465
+ // (we must change the battle's RNG from a FixedRNG to a PRNG because
466
+ // the transitions function relies on RNG for discovery of states)
467
+ if (try transitions(unfix(original), c1, c2, allocator, writer, .{
468
+ .durations = durations,
469
+ .cap = true,
470
+ })) |stats| try expect(stats.frontier <= MAX_FRONTIER);
395
471
  }
396
- return false;
472
+
473
+ // Demonstrate that we can produce the same state by forcing the RNG to behave the
474
+ // same as we observed.
475
+ var override = pkmn.battle.options(
476
+ protocol.NULL,
477
+ Chance(Rational(u128)){ .probability = .{}, .durations = durations },
478
+ Calc{ .overrides = overrides },
479
+ );
480
+ var copy = original;
481
+ var overridden = copy.update(c1, c2, &override);
482
+ try expectEqual(result, overridden);
483
+ try expectEqualActions(overrides, override.chance.actions);
484
+ try expectEqual(updated, override.chance.durations);
485
+
486
+ // The actual battle excluding its RNG field should match a copy updated with
487
+ // overridden RNG (the copy RNG may have advanced because of no-ops)
488
+ copy.rng = battle.rng;
489
+ try expectEqual(battle.*, copy);
490
+
491
+ // Demonstrate that even with the duration rolls changed, the duration
492
+ // fields on their own are sufficient to achieve the same outcomes
493
+ // NB: The actual battle bytes will differ because the durations won't match
494
+ overrides.p1.duration = if (overrides.p1.duration > 0) 2 else 0;
495
+ overrides.p2.duration = if (overrides.p2.duration > 0) 2 else 0;
496
+
497
+ override = pkmn.battle.options(
498
+ protocol.NULL,
499
+ Chance(Rational(u128)){ .probability = .{}, .durations = durations },
500
+ Calc{ .overrides = overrides },
501
+ );
502
+ copy = original;
503
+ overridden = copy.update(c1, c2, &override);
504
+ try expectEqual(result, overridden);
505
+ try expectEqualActions(overrides, override.chance.actions);
506
+ try expectEqual(updated, override.chance.durations);
507
+
508
+ return result;
509
+ }
510
+
511
+ fn expectEqualActions(expected: Actions, actual: Actions) !void {
512
+ return expectEqual(expected, actual) catch |e| switch (e) {
513
+ error.TestExpectedEqual => {
514
+ std.debug.print("expected {}, found {}\n", .{ expected, actual });
515
+ return e;
516
+ },
517
+ else => return e,
518
+ };
519
+ }
520
+
521
+ fn unfix(actual: anytype) data.Battle(data.PRNG) {
522
+ return .{
523
+ .sides = actual.sides,
524
+ .turn = actual.turn,
525
+ .last_damage = actual.last_damage,
526
+ .last_moves = actual.last_moves,
527
+ .rng = .{ .src = .{
528
+ .seed = if (pkmn.options.showdown)
529
+ 0x12345678
530
+ else
531
+ .{ 123, 234, 56, 78, 9, 101, 112, 131, 4 },
532
+ } },
533
+ };
397
534
  }
398
535
 
399
536
  fn err(comptime fmt: []const u8, v: anytype, seed: ?u64) void {
@@ -404,23 +541,429 @@ fn err(comptime fmt: []const u8, v: anytype, seed: ?u64) void {
404
541
  }
405
542
 
406
543
  const Style = struct {
544
+ shape: bool = false,
545
+ p1_max: u9 = 0,
546
+ p2_max: u9 = 0,
407
547
  color: ?usize = null,
408
548
  bold: bool = false,
409
549
  background: bool = false,
410
550
  dim: bool = false,
551
+ newline: bool = true,
552
+ indent: bool = true,
553
+ };
554
+
555
+ fn debug(writer: anytype, actions: Actions, style: Style) !void {
556
+ if (style.indent) try writer.writeAll(" ");
557
+ if (tty) {
558
+ const mod: usize = if (style.dim) 2 else 1;
559
+ const background: usize = if (style.background) 4 else 3;
560
+ const color: usize = if (style.color) |c| (c % 6) + 1 else 7;
561
+
562
+ if (style.dim or style.bold) try writer.print("\x1b[{d}m", .{mod});
563
+ try writer.print("\x1b[{d}{d}m", .{ background, color });
564
+ const p1 = if (style.p1_max != 0 and style.p1_max != actions.p1.damage) style.p1_max else 0;
565
+ const p2 = if (style.p2_max != 0 and style.p2_max != actions.p2.damage) style.p2_max else 0;
566
+ if (p1 != 0 or p2 != 0) {
567
+ assert(!style.shape);
568
+ try format(writer, actions, p1, p2);
569
+ } else {
570
+ try actions.fmt(writer, style.shape);
571
+ }
572
+ try writer.writeAll("\x1b[0m");
573
+ } else {
574
+ if (style.dim) try writer.writeAll(" ");
575
+ try actions.fmt(writer, style.shape);
576
+ }
577
+ if (style.newline) try writer.writeByte('\n');
578
+ }
579
+
580
+ fn format(writer: anytype, actions: Actions, p1: u9, p2: u9) !void {
581
+ var input: [1024]u8 = undefined;
582
+ var output: [1024]u8 = undefined;
583
+
584
+ var stream = std.io.fixedBufferStream(&input);
585
+ try actions.fmt(&stream.writer(), false);
586
+ var len = stream.getWritten().len;
587
+ @memcpy(output[0..len], input[0..len]);
588
+
589
+ var find: [16]u8 = undefined;
590
+ var repl: [22]u8 = undefined;
591
+ if (p1 != 0 and actions.p1.damage != 0) {
592
+ const n = try std.fmt.bufPrint(&find, "P1 = (damage:{d}", .{actions.p1.damage});
593
+ const r = try std.fmt.bufPrint(&repl, "P1 = (damage:{d}…{d}", .{ actions.p1.damage, p1 });
594
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
595
+ @memcpy(input[0 .. len + 6], output[0 .. len + 6]);
596
+ len += 6;
597
+ }
598
+ if (p2 != 0 and actions.p2.damage != 0) {
599
+ const n = try std.fmt.bufPrint(&find, "P2 = (damage:{d}", .{actions.p2.damage});
600
+ const r = try std.fmt.bufPrint(&repl, "P2 = (damage:{d}…{d}", .{ actions.p2.damage, p2 });
601
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
602
+ len += 6;
603
+ }
604
+
605
+ try writer.writeAll(output[0..len]);
606
+ }
607
+
608
+ /// Helper functions that efficiently return valid ranges for various RNG events based on the
609
+ /// state of an `Action` and other events to be used to construct a "transitions" function.
610
+ pub const Rolls = struct {
611
+ const PLAYER_NONE = [_]Optional(Player){.None};
612
+ const PLAYERS = [_]Optional(Player){ .P1, .P2 };
613
+
614
+ /// Returns a slice with the correct range of values for speed ties given the `action` state.
615
+ pub fn speedTie(action: Action) []const Optional(Player) {
616
+ return if (action.speed_tie == .None) &PLAYER_NONE else &PLAYERS;
617
+ }
618
+
619
+ const OBS_NONE = [_]Optional(Observation){.None};
620
+ const OBS_STARTED = [_]Optional(Observation){.started};
621
+ const OBS_CONTINUING = [_]Optional(Observation){.continuing};
622
+ const OBS_ENDED = [_]Optional(Observation){.ended};
623
+ const OBS_ALL = [_]Optional(Observation){ .started, .continuing, .ended };
624
+ const OBS = [_]Optional(Observation){ .continuing, .ended };
625
+
626
+ /// Returns a slice with a range of values for sleep given the `action` state and observed
627
+ /// `durations`.
628
+ pub fn sleep(action: Action, duration: Duration) []const Optional(Observation) {
629
+ if (action.sleep == .None) return &OBS_NONE;
630
+ return if (Sleeps.get(duration.sleeps, 0) == 0 and action.speed_tie != .None)
631
+ &OBS_ALL
632
+ else switch (action.sleep) {
633
+ .started => &OBS_STARTED,
634
+ else => if (Sleeps.get(duration.sleeps, 0) >= 7) &OBS_ENDED else &OBS,
635
+ };
636
+ }
637
+
638
+ /// Returns a slice with a range of values for disable given the `action`, observed `durations`,
639
+ /// and the state of the `parent` (observation of the player's Pokémon sleep status).
640
+ pub fn disable(
641
+ action: Action,
642
+ duration: Duration,
643
+ parent: Optional(Observation),
644
+ ) []const Optional(Observation) {
645
+ if (action.disable == .None) return &OBS_NONE;
646
+ return if (duration.disable == 0 and action.speed_tie != .None)
647
+ &OBS_ALL
648
+ else switch (action.disable) {
649
+ .started => &OBS_STARTED,
650
+ else => if (duration.disable >= 8)
651
+ &OBS_ENDED
652
+ else if (parent != .None and parent != .started)
653
+ &OBS_CONTINUING
654
+ else
655
+ &OBS,
656
+ };
657
+ }
658
+
659
+ /// FIXME
660
+ pub fn attacking(
661
+ action: Action,
662
+ duration: Duration,
663
+ parent: Optional(Observation),
664
+ ) []const Optional(Observation) {
665
+ return switch (action.attacking) {
666
+ .None => &OBS_NONE,
667
+ .started => &OBS_STARTED,
668
+ else => if (duration.attacking >= 3)
669
+ &OBS_ENDED
670
+ else if ((parent == .continuing and parent == .ended) or duration.attacking < 2)
671
+ &OBS_CONTINUING
672
+ else
673
+ &OBS,
674
+ };
675
+ }
676
+
677
+ const CFZ_NONE = [_]Optional(Confusion){.None};
678
+ const CFZ_STARTED = [_]Optional(Confusion){.started};
679
+ const CFZ_OVERWRITTEN = [_]Optional(Confusion){ .started, .overwritten };
680
+ const CFZ_CONTINUING = [_]Optional(Confusion){.continuing};
681
+ const CFZ_ENDED = [_]Optional(Confusion){.ended};
682
+ const CFZ = [_]Optional(Confusion){ .continuing, .ended };
683
+ const CFZ_TIE = [_]Optional(Confusion){ .started, .continuing, .ended };
684
+
685
+ /// FIXME
686
+ pub fn confusion(
687
+ action: Action,
688
+ duration: Duration,
689
+ tie: Optional(Player),
690
+ sibling: Optional(Observation),
691
+ parent: Optional(Observation),
692
+ ) []const Optional(Confusion) {
693
+ return switch (action.confusion) {
694
+ .None => &CFZ_NONE,
695
+ .started => if (pkmn.options.overwrite and sibling == .ended and duration.confusion < 5)
696
+ &CFZ_OVERWRITTEN
697
+ else
698
+ &CFZ_STARTED,
699
+ else => if (duration.confusion >= 5)
700
+ &CFZ_ENDED
701
+ else if ((parent == .continuing and parent == .ended) or duration.confusion < 2)
702
+ &CFZ_CONTINUING
703
+ else if (tie != .None)
704
+ &CFZ_TIE
705
+ else
706
+ &CFZ,
707
+ };
708
+ }
709
+
710
+ /// Returns a slice with a range of values for binding given the `action`, observed `durations`,
711
+ /// and the state of the `parent` (whether the player's Pokémon was fully paralyzed).
712
+ pub fn binding(
713
+ action: Action,
714
+ duration: Duration,
715
+ parent: Optional(bool),
716
+ ) []const Optional(Observation) {
717
+ if (parent == .true) return &OBS_NONE;
718
+ return switch (action.binding) {
719
+ .None => &OBS_NONE,
720
+ .started => &OBS_STARTED,
721
+ else => if (duration.binding >= 4) &OBS_ENDED else &OBS,
722
+ };
723
+ }
724
+
725
+ const BOOL_NONE = [_]Optional(bool){.None};
726
+ const BOOLS = [_]Optional(bool){ .false, .true };
727
+
728
+ /// Returns a slice with the correct range of values for hits given the `action` state
729
+ /// and the state of the `parent` (whether the player's Pokémon was fully paralyzed).
730
+ pub fn hit(action: Action, parent: Optional(bool)) []const Optional(bool) {
731
+ if (parent == .true) return &BOOL_NONE;
732
+ return if (action.hit == .None) &BOOL_NONE else &BOOLS;
733
+ }
734
+
735
+ /// Returns a slice with the correct range of values for critical hits given the `action` state
736
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
737
+ pub fn criticalHit(action: Action, parent: Optional(bool)) []const Optional(bool) {
738
+ if (pkmn.options.showdown and parent == .false) return &BOOL_NONE;
739
+ return if (action.critical_hit == .None) &BOOL_NONE else &BOOLS;
740
+ }
741
+
742
+ /// Returns a slice with the correct range of values for secondary chances hits given the
743
+ /// `action` state and the state of the `parent` (whether the player's Pokémon's move hit).
744
+ pub fn secondaryChance(action: Action, parent: Optional(bool)) []const Optional(bool) {
745
+ if (parent == .false) return &BOOL_NONE;
746
+ return if (@field(action, "secondary_chance") == .None) &BOOL_NONE else &BOOLS;
747
+ }
748
+
749
+ /// The min and max bounds on iteration over damage rolls.
750
+ pub const Range = struct { min: u9, max: u9 };
751
+
752
+ /// Returns the range bounding damage rolls given the `action` state and the state of
753
+ /// the `parent` (whether the player's Pokémon's move hit).
754
+ pub fn damage(action: Action, parent: Optional(bool)) Range {
755
+ return if (parent == .false or action.damage == 0)
756
+ .{ .min = 0, .max = 1 }
757
+ else
758
+ .{ .min = 217, .max = 256 };
759
+ }
760
+
761
+ /// Returns the max damage roll which will produce the same damage as `roll`
762
+ /// given the base damage in `summaries`.
763
+ pub fn coalesce(player: Player, roll: u8, summaries: *Summaries, cap: bool) u8 {
764
+ if (roll == 0) return roll;
765
+
766
+ const dmg = summaries.get(player.foe()).damage;
767
+ if (dmg.base == 0 or (cap and dmg.capped)) return 255;
768
+
769
+ // Closed form solution for max damage roll provided by Orion Taylor (taylorott)
770
+ return @min(255, roll + ((254 - ((@as(u32, dmg.base) * roll) % 255)) / dmg.base));
771
+ }
772
+
773
+ /// Returns a slice with the correct range of values for confused given the `action` state and
774
+ /// the state of the `parent` (observation of the player's Pokémon confusion status).
775
+ pub fn confused(action: Action, parent: Optional(Confusion)) []const Optional(bool) {
776
+ const done = parent == .None or parent == .ended;
777
+ return if (done or action.confused == .None) &BOOL_NONE else &BOOLS;
778
+ }
779
+
780
+ /// Returns a slice with the correct range of values for paralysis given the `action` state
781
+ /// and the state of the `parent` (whether the player's Pokémon was confused).
782
+ pub fn paralyzed(action: Action, parent: Optional(bool)) []const Optional(bool) {
783
+ if (parent == .true) return &BOOL_NONE;
784
+ return if (action.paralyzed == .None) &BOOL_NONE else &BOOLS;
785
+ }
786
+
787
+ const SLOT_NONE = [_]u4{0};
788
+ const SLOT = [_]u4{ 1, 2, 3, 4 };
789
+
790
+ /// Returns a slice with a range of values for move slots given the `action` state
791
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
792
+ ///
793
+ /// These slots may or **may not be valid** as slots may be unset / have 0 PP.
794
+ pub fn moveSlot(action: Action, parent: Optional(bool)) []const u4 {
795
+ if (parent == .false) return &SLOT_NONE;
796
+ return if (action.move_slot == 0) &SLOT_NONE else &SLOT;
797
+ }
798
+
799
+ const MULTI_NONE = [_]u4{0};
800
+ const MULTI = [_]u4{ 2, 3, 4, 5 };
801
+
802
+ /// Returns a slice with the correct range of values for multi hit given the `action` state
803
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
804
+ pub fn multiHit(action: Action, parent: Optional(bool)) []const u4 {
805
+ if (parent == .false) return &MULTI_NONE;
806
+ return if (action.multi_hit == 0) &MULTI_NONE else &MULTI;
807
+ }
808
+
809
+ const PSYWAVE_NONE = [_]u8{0};
810
+ const PSYWAVE = init: {
811
+ var rolls: [150]u8 = undefined;
812
+ for (0..150) |i| rolls[i] = i + 1;
813
+ break :init rolls;
814
+ };
815
+
816
+ /// Returns a slice with the correct range of values for psywave given the `action` state,
817
+ /// the `side`, and the state of the `parent` (whether the player's Pokémon's move hit).
818
+ pub fn psywave(
819
+ action: Action,
820
+ side: *data.Side,
821
+ parent: Optional(bool),
822
+ ) []const u8 {
823
+ if (parent == .false) return &PSYWAVE_NONE;
824
+ return if (action.psywave == 0)
825
+ &PSYWAVE_NONE
826
+ else
827
+ PSYWAVE[0 .. @as(u16, side.stored().level) * 3 / 2];
828
+ }
829
+
830
+ const MOVE_NONE = [_]data.Move{.None};
831
+
832
+ /// Returns a slice with the correct range of values for metronome given the `action` state.
833
+ pub fn metronome(action: Action) []const data.Move {
834
+ return if (action.metronome == .None) &MOVE_NONE else &data.Move.METRONOME;
835
+ }
411
836
  };
412
837
 
413
- fn debug(writer: anytype, actions: Actions, shape: bool, style: Style) !void {
414
- _ = .{ writer, actions, shape, style };
415
- // const mod: usize = if (style.dim) 2 else 1;
416
- // const background: usize = if (style.background) 4 else 3;
417
- // const color: usize = if (style.color) |c| (c % 6) + 1 else 7;
418
- // if (style.dim or style.bold) try writer.print("\x1b[{d}m", .{mod});
419
- // try writer.print("\x1b[{d}{d}m", .{ background, color });
420
- // try actions.fmt(writer, shape);
421
- // try writer.writeAll("\x1b[0m\n");
422
- // DEBUG
423
- // if (style.dim) try writer.writeAll(" ");
424
- // try actions.fmt(writer, shape);
425
- // try writer.writeByte('\n');
838
+ test "Rolls.speedTie" {
839
+ const actions: Actions = .{ .p1 = .{ .speed_tie = .P2 } };
840
+ try expectEqualSlices(Optional(Player), &.{ .P1, .P2 }, Rolls.speedTie(actions.p1));
841
+ try expectEqualSlices(Optional(Player), &.{.None}, Rolls.speedTie(actions.p2));
842
+ }
843
+
844
+ test "Rolls.sleep" {
845
+ return error.SkipZigTest; // TODO
846
+ }
847
+
848
+ test "Rolls.disable" {
849
+ return error.SkipZigTest; // TODO
850
+ }
851
+
852
+ test "Rolls.confusion" {
853
+ return error.SkipZigTest; // TODO
854
+ }
855
+
856
+ test "Rolls.atacking" {
857
+ return error.SkipZigTest; // TODO
858
+ }
859
+
860
+ test "Rolls.binding" {
861
+ return error.SkipZigTest; // TODO
862
+ }
863
+
864
+ test "Rolls.damage" {
865
+ const actions: Actions = .{ .p2 = .{ .damage = 221 } };
866
+ try expectEqual(Rolls.Range{ .min = 0, .max = 1 }, Rolls.damage(actions.p1, .None));
867
+ try expectEqual(Rolls.Range{ .min = 217, .max = 256 }, Rolls.damage(actions.p2, .None));
868
+ try expectEqual(Rolls.Range{ .min = 0, .max = 1 }, Rolls.damage(actions.p2, .false));
869
+ }
870
+
871
+ test "Rolls.coalesce" {
872
+ var summaries = Summaries{ .p1 = .{ .damage = .{ .base = 74, .final = 69, .capped = true } } };
873
+ try expectEqual(@as(u8, 0), Rolls.coalesce(.P2, 0, &summaries, false));
874
+ try expectEqual(@as(u8, 241), Rolls.coalesce(.P2, 238, &summaries, false));
875
+ try expectEqual(@as(u8, 255), Rolls.coalesce(.P2, 238, &summaries, true));
876
+ summaries.p1.damage.final = 74;
877
+ try expectEqual(@as(u8, 217), Rolls.coalesce(.P2, 217, &summaries, false));
878
+ try expectEqual(@as(u8, 255), Rolls.coalesce(.P2, 217, &summaries, true));
879
+ }
880
+
881
+ test "Rolls.hit" {
882
+ const actions: Actions = .{ .p2 = .{ .hit = .true } };
883
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.hit(actions.p1, .None));
884
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.hit(actions.p2, .None));
885
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.hit(actions.p2, .true));
886
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.hit(actions.p2, .false));
887
+ }
888
+
889
+ test "Rolls.secondaryChance" {
890
+ const actions: Actions = .{ .p1 = .{ .secondary_chance = .true } };
891
+ try expectEqualSlices(
892
+ Optional(bool),
893
+ &.{ .false, .true },
894
+ Rolls.secondaryChance(actions.p1, .None),
895
+ );
896
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.secondaryChance(actions.p1, .false));
897
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.secondaryChance(actions.p2, .None));
898
+ }
899
+
900
+ test "Rolls.criticalHit" {
901
+ const actions: Actions = .{ .p1 = .{ .critical_hit = .true } };
902
+ try expectEqualSlices(
903
+ Optional(bool),
904
+ &.{ .false, .true },
905
+ Rolls.criticalHit(actions.p1, .None),
906
+ );
907
+ try expectEqualSlices(
908
+ Optional(bool),
909
+ if (pkmn.options.showdown) &.{.None} else &.{ .false, .true },
910
+ Rolls.criticalHit(actions.p1, .false),
911
+ );
912
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.criticalHit(actions.p2, .None));
913
+ }
914
+
915
+ test "Rolls.confused" {
916
+ const actions: Actions = .{ .p2 = .{ .confused = .true } };
917
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.confused(actions.p1, .None));
918
+ try expectEqualSlices(
919
+ Optional(bool),
920
+ &.{ .false, .true },
921
+ Rolls.confused(actions.p2, .continuing),
922
+ );
923
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.confused(actions.p2, .ended));
924
+ }
925
+
926
+ test "Rolls.paralyzed" {
927
+ const actions: Actions = .{ .p2 = .{ .paralyzed = .true } };
928
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.paralyzed(actions.p1, .None));
929
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.paralyzed(actions.p2, .None));
930
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.paralyzed(actions.p2, .false));
931
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.paralyzed(actions.p2, .true));
932
+ }
933
+
934
+ test "Rolls.moveSlot" {
935
+ const actions: Actions = .{ .p2 = .{ .move_slot = 3 } };
936
+ try expectEqualSlices(u4, &.{0}, Rolls.moveSlot(actions.p1, .None));
937
+ try expectEqualSlices(u4, &.{ 1, 2, 3, 4 }, Rolls.moveSlot(actions.p2, .None));
938
+ try expectEqualSlices(u4, &.{0}, Rolls.moveSlot(actions.p2, .false));
939
+ }
940
+
941
+ test "Rolls.multiHit" {
942
+ const actions: Actions = .{ .p2 = .{ .multi_hit = 3 } };
943
+ try expectEqualSlices(u4, &.{0}, Rolls.multiHit(actions.p1, .None));
944
+ try expectEqualSlices(u4, &.{ 2, 3, 4, 5 }, Rolls.multiHit(actions.p2, .None));
945
+ try expectEqualSlices(u4, &.{0}, Rolls.multiHit(actions.p2, .false));
946
+ }
947
+
948
+ test "Rolls.metronome" {
949
+ const actions: Actions = .{ .p2 = .{ .metronome = .Surf } };
950
+ try expectEqualSlices(data.Move, &.{.None}, Rolls.metronome(actions.p1));
951
+ try expectEqual(@as(data.Move, @enumFromInt(24)), Rolls.metronome(actions.p2)[23]);
952
+ }
953
+
954
+ test "Rolls.psywave" {
955
+ const actions: Actions = .{ .p2 = .{ .psywave = 79 } };
956
+ var side = helpers.Side.init(&[_]helpers.Pokemon{.{
957
+ .species = .Bulbasaur,
958
+ .level = 100,
959
+ .moves = &[_]data.Move{.Tackle},
960
+ }});
961
+
962
+ try expectEqualSlices(u8, &.{0}, Rolls.psywave(actions.p1, &side, .None));
963
+ var rolls = Rolls.psywave(actions.p2, &side, .None);
964
+ try expectEqual(@as(u8, 150), rolls[rolls.len - 1]);
965
+ side.stored().level = 81;
966
+ rolls = Rolls.psywave(actions.p2, &side, .None);
967
+ try expectEqual(@as(u8, 121), rolls[rolls.len - 1]);
968
+ try expectEqualSlices(u8, &.{0}, Rolls.psywave(actions.p2, &side, .false));
426
969
  }