@pkmn/engine 0.1.0-dev.a0167a9d → 0.1.0-dev.a0447192

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