@pkmn/engine 0.1.0-dev.15f64810 → 0.1.0-dev.1aa30742

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