@pkmn/engine 0.1.0-dev.5570b5c5 → 0.1.0-dev.587596a6

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