@pkmn/engine 0.1.0-dev.89cc1c98 → 0.1.0-dev.8b192003

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 (42) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +44 -19
  3. package/build/pkg/addon.js +6 -7
  4. package/build/pkg/addon.js.map +1 -1
  5. package/build/pkg/data.d.ts +4 -4
  6. package/build/pkg/data.js.map +1 -1
  7. package/build/pkg/gen1.js.map +1 -1
  8. package/build/pkg/index.d.ts +2 -1
  9. package/build/pkg/index.js.map +1 -1
  10. package/build/pkg/protocol.js +5 -5
  11. package/build/pkg/protocol.js.map +1 -1
  12. package/build/test/display.js +2 -2
  13. package/build/test/display.js.map +1 -1
  14. package/build/tools/debug.js +5 -4
  15. package/build/tools/debug.js.map +1 -1
  16. package/build.zig +100 -102
  17. package/package.json +31 -23
  18. package/src/bin/install-pkmn-engine +26 -18
  19. package/src/lib/common/data.zig +4 -4
  20. package/src/lib/common/debug.zig +2 -2
  21. package/src/lib/common/optional.zig +1 -1
  22. package/src/lib/common/options.zig +2 -0
  23. package/src/lib/common/protocol.zig +393 -396
  24. package/src/lib/common/rational.zig +109 -15
  25. package/src/lib/common/rng.zig +20 -11
  26. package/src/lib/gen1/calc.zig +478 -92
  27. package/src/lib/gen1/chance.zig +195 -428
  28. package/src/lib/gen1/data/species.zig +1 -1
  29. package/src/lib/gen1/data.zig +21 -21
  30. package/src/lib/gen1/helpers.zig +88 -534
  31. package/src/lib/gen1/mechanics.zig +377 -360
  32. package/src/lib/gen2/chance.zig +25 -457
  33. package/src/lib/gen2/data.zig +13 -11
  34. package/src/lib/gen2/generated.zig +27 -78
  35. package/src/lib/gen2/helpers.zig +37 -7
  36. package/src/lib/gen2/mechanics.zig +1022 -456
  37. package/src/lib/{binding/node.zig → node.zig} +9 -12
  38. package/src/lib/pkmn.zig +27 -12
  39. package/src/lib/{binding/wasm.zig → wasm.zig} +2 -1
  40. package/src/test/display/pkmn.html.tmpl +5 -5
  41. package/src/lib/gen1/README.md +0 -894
  42. package/src/lib/gen2/README.md +0 -330
@@ -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
 
@@ -34,9 +35,9 @@ const Actions = chance.Actions;
34
35
  const Action = chance.Action;
35
36
  const Chance = chance.Chance;
36
37
  const Durations = chance.Durations;
37
- const Duration = chance.Duration;
38
38
 
39
- const Rolls = helpers.Rolls;
39
+ const tty = true; // DEBUG
40
+ const summary = false; // DEBUG
40
41
 
41
42
  /// Information relevant to damage calculation that occured during a Generation I battle `update`.
42
43
  pub const Summaries = extern struct {
@@ -69,8 +70,10 @@ pub const Summary = extern struct {
69
70
  /// The final computed damage that gets applied to the Pokémon. May exceed the target's HP
70
71
  // (to determine the *actual* damage done compare the target's stored HP before and after).
71
72
  final: u16 = 0,
72
- /// Whether higher damage will saturate / result in the same outcome (e.g. additional damage
73
- /// gets ignored due to it already breaking a Substitute or causing the target to faint).
73
+ /// Whether higher direct damage will saturate / result in the same outcome (e.g. additional
74
+ /// direct damage gets ignored due to it already breaking a Substitute or causing the target
75
+ /// to faint). Note that this field does not get set in scenarios where the target would
76
+ /// only be guaranteed to faint due to some sort of subsequent recoil or residual damage.
74
77
  capped: bool = false,
75
78
 
76
79
  // NOTE: 15 bits padding
@@ -89,13 +92,9 @@ pub const Summary = extern struct {
89
92
  pub const Overrides = extern struct {
90
93
  /// TODO
91
94
  actions: Actions = .{},
92
- /// TODO
93
- durations: Durations = .{},
94
-
95
- _: u32 = 0,
96
95
 
97
96
  comptime {
98
- assert(@sizeOf(Overrides) == 24);
97
+ assert(@sizeOf(Overrides) == 16);
99
98
  }
100
99
  };
101
100
 
@@ -124,18 +123,6 @@ pub const Calc = struct {
124
123
  }) val else null;
125
124
  }
126
125
 
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;
133
-
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;
137
- }
138
-
139
126
  pub fn base(self: *Calc, player: Player, val: u16) void {
140
127
  if (!enabled) return;
141
128
 
@@ -169,11 +156,6 @@ const Null = struct {
169
156
  return null;
170
157
  }
171
158
 
172
- pub fn modify(self: Null, player: Player, comptime field: Duration.Field) ?bool {
173
- _ = .{ self, player, field };
174
- return null;
175
- }
176
-
177
159
  pub fn base(self: Null, player: Player, val: u16) void {
178
160
  _ = .{ self, player, val };
179
161
  }
@@ -195,12 +177,14 @@ pub const Stats = struct {
195
177
  };
196
178
 
197
179
  pub const Options = struct {
198
- actions: Actions = .{},
180
+ durations: Durations,
199
181
  seed: ?u64 = null,
200
182
  cap: bool = false,
201
183
  metronome: bool = false,
202
184
  };
203
185
 
186
+ pub const MAX_FRONTIER = 19;
187
+
204
188
  pub fn transitions(
205
189
  battle: anytype,
206
190
  c1: Choice,
@@ -211,8 +195,7 @@ pub fn transitions(
211
195
  ) !?Stats {
212
196
  var stats: Stats = .{};
213
197
 
214
- var actions = options.actions;
215
- var cap = options.cap;
198
+ const cap = options.cap;
216
199
 
217
200
  var seen = std.AutoHashMap(Actions, void).init(allocator);
218
201
  defer seen.deinit();
@@ -221,19 +204,20 @@ pub fn transitions(
221
204
 
222
205
  var opts = pkmn.battle.options(
223
206
  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
- } } },
207
+ Chance(Rational(u128)){ .probability = .{} },
208
+ Calc{},
229
209
  );
230
210
 
231
211
  var b = battle;
232
212
  _ = try b.update(c1, c2, &opts);
213
+
214
+ var d = options.durations;
215
+ try d.update(&battle, &opts.chance.probability, opts.chance.actions);
216
+
233
217
  stats.updates += 1;
234
218
 
235
- var p1 = b.side(.P1);
236
- var p2 = b.side(.P2);
219
+ const p1 = b.side(.P1);
220
+ const p2 = b.side(.P2);
237
221
 
238
222
  var p: Rational(u128) = .{ .p = 0, .q = 1 };
239
223
  try frontier.append(opts.chance.actions);
@@ -247,31 +231,23 @@ pub fn transitions(
247
231
  var i: usize = 0;
248
232
  assert(frontier.items.len == 1);
249
233
  while (i < frontier.items.len) : (i += 1) {
250
- var template = frontier.items[i];
251
- opts.calc.overrides.durations = .{
252
- .p1 = template.p1.durations,
253
- .p2 = template.p2.durations,
254
- };
234
+ const template = frontier.items[i];
255
235
 
256
- try debug(writer, template, true, .{ .color = i, .bold = true, .background = true });
236
+ try debug(writer, template, .{
237
+ .shape = true,
238
+ .color = i,
239
+ .bold = true,
240
+ .background = true,
241
+ .indent = false,
242
+ });
257
243
 
258
244
  var a: Actions = .{ .p1 = .{ .metronome = p1_move }, .p2 = .{ .metronome = p2_move } };
259
245
 
260
246
  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;
247
+ for (Rolls.confused(template.p1)) |p1_cfzd| { a.p1.confused = p1_cfzd;
248
+ for (Rolls.confused(template.p2)) |p2_cfzd| { a.p2.confused = p2_cfzd;
269
249
  for (Rolls.paralyzed(template.p1, p1_cfzd)) |p1_par| { a.p1.paralyzed = p1_par;
270
250
  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
251
  for (Rolls.duration(template.p1, p1_par)) |p1_dur| { a.p1.duration = p1_dur;
276
252
  for (Rolls.duration(template.p2, p2_par)) |p2_dur| { a.p2.duration = p2_dur;
277
253
  for (Rolls.hit(template.p1, p1_par)) |p1_hit| { a.p1.hit = p1_hit;
@@ -281,7 +257,7 @@ pub fn transitions(
281
257
  for (Rolls.moveSlot(template.p1, p1_hit)) |p1_slot| { a.p1.move_slot = p1_slot;
282
258
  for (Rolls.moveSlot(template.p2, p2_hit)) |p2_slot| { a.p2.move_slot = p2_slot;
283
259
  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;
260
+ for (Rolls.multiHit(template.p2, p2_hit)) |p2_multi| { a.p2.multi_hit = p2_multi;
285
261
  for (Rolls.secondaryChance(template.p1, p1_hit)) |p1_sec| { a.p1.secondary_chance = p1_sec;
286
262
  for (Rolls.secondaryChance(template.p2, p2_hit)) |p2_sec| { a.p2.secondary_chance = p2_sec;
287
263
  for (Rolls.criticalHit(template.p1, p1_hit)) |p1_crit| { a.p1.critical_hit = p1_crit;
@@ -290,42 +266,62 @@ pub fn transitions(
290
266
  var p1_dmg = Rolls.damage(template.p1, p1_hit);
291
267
  while (p1_dmg.min < p1_dmg.max) : (p1_dmg.min += 1) {
292
268
  a.p1.damage = @intCast(p1_dmg.min);
293
- var p1_min: u8 = 0;
294
269
 
295
270
  var p2_dmg = Rolls.damage(template.p2, p2_hit);
271
+
272
+ const p1_min: u9 = p1_dmg.min;
273
+ const p2_min: u9 = p2_dmg.min;
274
+
296
275
  while (p2_dmg.min < p2_dmg.max) : (p2_dmg.min += 1) {
297
276
  a.p2.damage = @intCast(p2_dmg.min);
298
277
 
299
278
  opts.calc.overrides.actions = a;
300
- opts.chance = .{ .probability = .{}, .actions = actions };
279
+ opts.calc.summaries = .{};
280
+ opts.chance = .{ .probability = .{} };
301
281
  const q = &opts.chance.probability;
302
282
 
303
283
  b = battle;
304
284
  _ = try b.update(c1, c2, &opts);
305
- stats.updates += 1;
306
285
 
307
- const p1_max: u8 = @intCast(p1_dmg.min);
308
- const p2_max: u8 = @intCast(p2_dmg.min);
309
- _ = cap;
286
+ d = options.durations;
287
+ try d.update(&b, &q, opts.chance.actions);
288
+
289
+ stats.updates += 1;
310
290
 
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);
291
+ const summaries = &opts.calc.summaries;
292
+ const p1_max: u9 = if (p2_dmg.min != p2_min)
293
+ p1_dmg.min
294
+ else
295
+ try Rolls.coalesce(.P1, @as(u8, @intCast(p1_dmg.min)), summaries, cap);
296
+ const p2_max: u9 =
297
+ try Rolls.coalesce(.P2, @as(u8, @intCast(p2_dmg.min)), summaries, cap);
315
298
 
316
299
  if (opts.chance.actions.matches(template)) {
317
300
  if (!opts.chance.actions.eql(a)) {
318
- try debug(writer, opts.chance.actions, false, .{ .color = i, .dim = true });
301
+ if (!summary) {
302
+ try debug(writer, opts.chance.actions, .{
303
+ .p1_max = p1_max,
304
+ .p2_max = p2_max,
305
+ .color = i,
306
+ .dim = true,
307
+ });
308
+ }
319
309
 
320
- p1_min = p1_max;
310
+ p1_dmg.min = p1_max;
321
311
  p2_dmg.min = p2_max;
322
312
  continue;
323
313
  }
324
314
 
325
- try debug(writer, opts.chance.actions, false, .{ .color = i });
315
+ if (!summary) {
316
+ try debug(writer, opts.chance.actions, .{
317
+ .p1_max = p1_max,
318
+ .p2_max = p2_max,
319
+ .color = i,
320
+ });
321
+ }
326
322
 
327
- for (p1_dmg.min..@as(u9, p1_max) + 1) |p1d| {
328
- for (p2_dmg.min..@as(u9, p2_max) + 1) |p2d| {
323
+ for (p1_min..p1_max + 1) |p1d| {
324
+ for (p2_dmg.min..p2_max + 1) |p2d| {
329
325
  var acts = opts.chance.actions;
330
326
  acts.p1.damage = @intCast(p1d);
331
327
  acts.p2.damage = @intCast(p2d);
@@ -336,7 +332,7 @@ pub fn transitions(
336
332
  }
337
333
  }
338
334
 
339
- if (p1_max != p1_dmg.min) try q.update(p1_max - p1_dmg.min + 1, 1);
335
+ if (p1_max != p1_min) try q.update(p1_max - p1_min + 1, 1);
340
336
  if (p2_max != p2_dmg.min) try q.update(p2_max - p2_dmg.min + 1, 1);
341
337
  try p.add(q);
342
338
  stats.saved += 1;
@@ -346,27 +342,46 @@ pub fn transitions(
346
342
  return error.TestUnexpectedResult;
347
343
  }
348
344
  } else {
349
- try debug(writer, opts.chance.actions, false, .{ .dim = true });
350
-
351
345
  if (!matches(opts.chance.actions, i, frontier.items)) {
352
346
  try frontier.append(opts.chance.actions);
353
347
 
354
- try debug(writer, opts.chance.actions, true, .{
348
+ try debug(writer, opts.chance.actions, .{
349
+ .p1_max = p1_max,
350
+ .p2_max = p2_max,
351
+ .dim = true,
352
+ .newline = false,
353
+ });
354
+ try writer.writeAll(" → ");
355
+ try debug(writer, opts.chance.actions, .{
356
+ .shape = true,
355
357
  .color = frontier.items.len - 1,
356
358
  .dim = true,
357
- .background = true
359
+ .background = true,
360
+ .indent = false,
361
+ });
362
+ } else if (!summary) {
363
+ try debug(writer, opts.chance.actions, .{
364
+ .p1_max = p1_max,
365
+ .p2_max = p2_max,
366
+ .dim = true,
358
367
  });
359
368
  }
360
369
  }
361
370
 
362
- p1_min = p1_max;
371
+ p1_dmg.min = p1_max;
363
372
  p2_dmg.min = p2_max;
364
373
  }
365
374
 
366
- assert(p1_min > 0 or p1_dmg.min == 0);
367
- p1_dmg.min = p1_min;
375
+ }}}}}}}}}}}}}}}}}}}}
376
+
377
+ if (@TypeOf(writer) != @TypeOf(std.io.null_writer)) {
378
+ p.reduce();
379
+ try writer.print(
380
+ " = {s} ({d:.2}%)\n\n",
381
+ .{p, 100 * @as(f128, @floatFromInt(p.p)) / @as(f128, @floatFromInt(p.q))},
382
+ );
383
+ }
368
384
 
369
- }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
370
385
  }
371
386
 
372
387
  assert(frontier.items.len == i);
@@ -387,6 +402,88 @@ pub fn transitions(
387
402
  return stats;
388
403
  }
389
404
 
405
+ pub fn update(
406
+ battle: anytype,
407
+ durations: *Durations,
408
+ c1: Choice,
409
+ c2: Choice,
410
+ options: anytype,
411
+ allocator: std.mem.Allocator,
412
+ writer: anytype,
413
+ transition: bool,
414
+ ) !Result {
415
+ options.chance.reset();
416
+
417
+ if (!pkmn.options.chance or !pkmn.options.calc or @TypeOf(battle.rng) != data.PRNG) {
418
+ return battle.update(c1, c2, options);
419
+ }
420
+
421
+ var copy = battle.*;
422
+ const saved = durations.*;
423
+ const actions = options.chance.actions;
424
+
425
+ // Perfom the actual update
426
+ const result = battle.update(c1, c2, options);
427
+ try durations.update(&battle, actions, &options.chance.probability);
428
+
429
+ // Ensure we can encode the diffs in less than MAX_DIFFS bytes.
430
+ var buf: [helpers.MAX_DIFFS]u8 = undefined;
431
+ var stream: protocol.ByteStream = .{ .buffer = &buf };
432
+ const n = try helpers.diff(&copy, battle, stream.writer());
433
+
434
+ // Applying the diff to the battle should take us back to the original copy
435
+ // of the battle (ignoring the RNG).
436
+ var patched = battle.*;
437
+ patched.rng = copy.rng;
438
+ helpers.patch(&patched, buf[0..n]);
439
+ try expectEqual(copy, patched);
440
+
441
+ if (!pkmn.options.chance or !pkmn.options.calc) return result;
442
+
443
+ if (transition) {
444
+ // Ensure we can generate all transitions from the same original state
445
+ // (we must change the battle's RNG from a FixedRNG to a PRNG because
446
+ // the transitions function relies on RNG for discovery of states)
447
+ if (try transitions(unfix(copy), c1, c2, allocator, writer, .{
448
+ .durations = saved,
449
+ .cap = true,
450
+ })) |stats| try expect(stats.frontier <= MAX_FRONTIER);
451
+ }
452
+
453
+ // Demonstrate that we can produce the same state by forcing the RNG to behave the
454
+ // same as we observed.
455
+ var override = pkmn.battle.options(
456
+ protocol.NULL,
457
+ Chance(Rational(u128)){ .probability = .{} },
458
+ Calc{ .overrides = .{ .actions = actions } },
459
+ );
460
+ const overridden = copy.update(c1, c2, &override);
461
+ try expectEqual(result, overridden);
462
+ try expectEqual(override.chance.actions, actions);
463
+
464
+ // The actual battle excluding its RNG field should match a copy updated with
465
+ // overridden RNG (the copy RNG may have advanced because of no-ops)
466
+ copy.rng = battle.rng;
467
+ try expectEqual(copy, battle.*);
468
+
469
+ return result;
470
+ }
471
+
472
+ fn unfix(actual: anytype) data.Battle(data.PRNG) {
473
+ return .{
474
+ .sides = actual.sides,
475
+ .turn = actual.turn,
476
+ .last_damage = actual.last_damage,
477
+ .last_moves = actual.last_moves,
478
+ .rng = .{ .src = .{
479
+ .seed = if (pkmn.options.showdown)
480
+ 0x12345678
481
+ else
482
+ .{ 123, 234, 56, 78, 9, 101, 112, 131, 4 },
483
+ } },
484
+ };
485
+ }
486
+
390
487
  fn matches(actions: Actions, i: usize, frontier: []Actions) bool {
391
488
  for (frontier, 0..) |f, j| {
392
489
  // TODO: is skipping this redundant check worth it?
@@ -404,23 +501,312 @@ fn err(comptime fmt: []const u8, v: anytype, seed: ?u64) void {
404
501
  }
405
502
 
406
503
  const Style = struct {
504
+ shape: bool = false,
505
+ p1_max: u9 = 0,
506
+ p2_max: u9 = 0,
407
507
  color: ?usize = null,
408
508
  bold: bool = false,
409
509
  background: bool = false,
410
510
  dim: bool = false,
511
+ newline: bool = true,
512
+ indent: bool = true,
513
+ };
514
+
515
+ fn debug(writer: anytype, actions: Actions, style: Style) !void {
516
+ if (style.indent) try writer.writeAll(" ");
517
+ if (tty) {
518
+ const mod: usize = if (style.dim) 2 else 1;
519
+ const background: usize = if (style.background) 4 else 3;
520
+ const color: usize = if (style.color) |c| (c % 6) + 1 else 7;
521
+
522
+ if (style.dim or style.bold) try writer.print("\x1b[{d}m", .{mod});
523
+ try writer.print("\x1b[{d}{d}m", .{ background, color });
524
+ const p1 = if (style.p1_max != 0 and style.p1_max != actions.p1.damage) style.p1_max else 0;
525
+ const p2 = if (style.p2_max != 0 and style.p2_max != actions.p2.damage) style.p2_max else 0;
526
+ if (p1 != 0 or p2 != 0) {
527
+ assert(!style.shape);
528
+ try format(writer, actions, p1, p2);
529
+ } else {
530
+ try actions.fmt(writer, style.shape);
531
+ }
532
+ try writer.writeAll("\x1b[0m");
533
+ } else {
534
+ if (style.dim) try writer.writeAll(" ");
535
+ try actions.fmt(writer, style.shape);
536
+ }
537
+ if (style.newline) try writer.writeByte('\n');
538
+ }
539
+
540
+ fn format(writer: anytype, actions: Actions, p1: u9, p2: u9) !void {
541
+ var input: [1024]u8 = undefined;
542
+ var output: [1024]u8 = undefined;
543
+
544
+ var stream = std.io.fixedBufferStream(&input);
545
+ try actions.fmt(&stream.writer(), false);
546
+ var len = stream.getWritten().len;
547
+ @memcpy(output[0..len], input[0..len]);
548
+
549
+ var find: [16]u8 = undefined;
550
+ var repl: [22]u8 = undefined;
551
+ if (p1 != 0 and actions.p1.damage != 0) {
552
+ const n = try std.fmt.bufPrint(&find, "P1 = (damage:{d}", .{actions.p1.damage});
553
+ const r = try std.fmt.bufPrint(&repl, "P1 = (damage:{d}…{d}", .{ actions.p1.damage, p1 });
554
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
555
+ @memcpy(input[0 .. len + 6], output[0 .. len + 6]);
556
+ len += 6;
557
+ }
558
+ if (p2 != 0 and actions.p2.damage != 0) {
559
+ const n = try std.fmt.bufPrint(&find, "P2 = (damage:{d}", .{actions.p2.damage});
560
+ const r = try std.fmt.bufPrint(&repl, "P2 = (damage:{d}…{d}", .{ actions.p2.damage, p2 });
561
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
562
+ len += 6;
563
+ }
564
+
565
+ try writer.writeAll(output[0..len]);
566
+ }
567
+
568
+ const NONE = @intFromEnum(Optional(bool).None);
569
+
570
+ /// Helper functions that efficiently return valid ranges for various RNG events based on the
571
+ /// state of an `Action` and other events to be used to construct a "transitions" function.
572
+ pub const Rolls = struct {
573
+ const PLAYER_NONE = [_]Optional(Player){.None};
574
+ const PLAYERS = [_]Optional(Player){ .P1, .P2 };
575
+
576
+ /// Returns a slice with the correct range of values for speed ties given the `action` state.
577
+ pub fn speedTie(action: Action) []const Optional(Player) {
578
+ return if (action.speed_tie == .None) &PLAYER_NONE else &PLAYERS;
579
+ }
580
+
581
+ const BOOL_NONE = [_]Optional(bool){.None};
582
+ const BOOLS = [_]Optional(bool){ .false, .true };
583
+
584
+ /// Returns a slice with the correct range of values for hits given the `action` state
585
+ /// and the state of the `parent` (whether the player's Pokémon was fully paralyzed).
586
+ pub fn hit(action: Action, parent: Optional(bool)) []const Optional(bool) {
587
+ if (parent == .true) return &BOOL_NONE;
588
+ return if (action.hit == .None) &BOOL_NONE else &BOOLS;
589
+ }
590
+
591
+ /// Returns a slice with the correct range of values for critical hits given the `action` state
592
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
593
+ pub fn criticalHit(action: Action, parent: Optional(bool)) []const Optional(bool) {
594
+ if (parent == .false) return &BOOL_NONE;
595
+ return if (action.critical_hit == .None) &BOOL_NONE else &BOOLS;
596
+ }
597
+
598
+ /// Returns a slice with the correct range of values for secondary chances hits given the
599
+ /// `action` state and the state of the `parent` (whether the player's Pokémon's move hit).
600
+ pub fn secondaryChance(action: Action, parent: Optional(bool)) []const Optional(bool) {
601
+ if (parent == .false) return &BOOL_NONE;
602
+ return if (@field(action, "secondary_chance") == .None) &BOOL_NONE else &BOOLS;
603
+ }
604
+
605
+ /// The min and max bounds on iteration over damage rolls.
606
+ pub const Range = struct { min: u9, max: u9 };
607
+
608
+ /// Returns the range bounding damage rolls given the `action` state and the state of
609
+ /// the `parent` (whether the player's Pokémon's move hit).
610
+ pub fn damage(action: Action, parent: Optional(bool)) Range {
611
+ return if (parent == .false or action.damage == 0)
612
+ .{ .min = 0, .max = 1 }
613
+ else
614
+ .{ .min = 217, .max = 256 };
615
+ }
616
+
617
+ /// Returns the max damage roll which will produce the same damage as `roll`
618
+ /// given the base damage in `summaries`.
619
+ pub fn coalesce(player: Player, roll: u8, summaries: *Summaries, cap: bool) !u8 {
620
+ if (roll == 0) return roll;
621
+
622
+ const dmg = summaries.get(player.foe()).damage;
623
+ if (dmg.base == 0 or (cap and dmg.capped)) return 255;
624
+
625
+ // Closed form solution for max damage roll provided by Orion Taylor (taylorott)
626
+ return @min(255, roll + ((254 - ((@as(u32, dmg.base) * roll) % 255)) / dmg.base));
627
+ }
628
+
629
+ /// Returns a slice with the correct range of values for confused.
630
+ pub fn confused(action: Action) []const Optional(bool) {
631
+ return if (action.confused == .None) &BOOL_NONE else &BOOLS;
632
+ }
633
+
634
+ /// Returns a slice with the correct range of values for paralysis given the `action` state
635
+ /// and the state of the `parent` (whether the player's Pokémon was confused).
636
+ pub fn paralyzed(action: Action, parent: Optional(bool)) []const Optional(bool) {
637
+ if (parent == .true) return &BOOL_NONE;
638
+ return if (action.paralyzed == .None) &BOOL_NONE else &BOOLS;
639
+ }
640
+
641
+ const DURATION_NONE = [_]u2{0};
642
+ // NB: DURATION must be at least 2 because that is the maximum of the minimums for all rolls
643
+ const DURATION = [_]u2{2};
644
+
645
+ /// Returns a slice with a range of values for duration given the `action` state
646
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
647
+ pub fn duration(action: Action, parent: Optional(bool)) []const u2 {
648
+ if (parent == .false) return &DURATION_NONE;
649
+ return if (action.duration == 0) &DURATION_NONE else &DURATION;
650
+ }
651
+
652
+ const SLOT_NONE = [_]u4{0};
653
+ const SLOT = [_]u4{ 1, 2, 3, 4 };
654
+
655
+ /// Returns a slice with a range of values for move slots given the `action` state
656
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
657
+ ///
658
+ /// These slots may or **may not be valid** as slots may be unset / have 0 PP.
659
+ pub fn moveSlot(action: Action, parent: Optional(bool)) []const u4 {
660
+ if (parent == .false) return &SLOT_NONE;
661
+ return if (action.move_slot == 0) &SLOT_NONE else &SLOT;
662
+ }
663
+
664
+ const MULTI_NONE = [_]u4{0};
665
+ const MULTI = [_]u4{ 2, 3, 4, 5 };
666
+
667
+ /// Returns a slice with the correct range of values for multi hit given the `action` state
668
+ /// and the state of the `parent` (whether the player's Pokémon's move hit).
669
+ pub fn multiHit(action: Action, parent: Optional(bool)) []const u4 {
670
+ if (parent == .false) return &MULTI_NONE;
671
+ return if (action.multi_hit == 0) &MULTI_NONE else &MULTI;
672
+ }
673
+
674
+ const PSYWAVE_NONE = [_]u8{0};
675
+ const PSYWAVE = init: {
676
+ var rolls: [150]u8 = undefined;
677
+ for (0..150) |i| rolls[i] = i + 1;
678
+ break :init rolls;
679
+ };
680
+
681
+ /// Returns a slice with the correct range of values for psywave given the `action` state,
682
+ /// the `side`, and the state of the `parent` (whether the player's Pokémon's move hit).
683
+ pub fn psywave(
684
+ action: Action,
685
+ side: *data.Side,
686
+ parent: Optional(bool),
687
+ ) []const u8 {
688
+ if (parent == .false) return &PSYWAVE_NONE;
689
+ return if (action.psywave == 0)
690
+ &PSYWAVE_NONE
691
+ else
692
+ PSYWAVE[0 .. @as(u16, side.stored().level) * 3 / 2];
693
+ }
694
+
695
+ const MOVE_NONE = [_]data.Move{.None};
696
+
697
+ /// Returns a slice with the correct range of values for metronome given the `action` state.
698
+ pub fn metronome(action: Action) []const data.Move {
699
+ return if (action.metronome == .None) &MOVE_NONE else &data.Move.METRONOME;
700
+ }
411
701
  };
412
702
 
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');
703
+ test "Rolls.speedTie" {
704
+ const actions: Actions = .{ .p1 = .{ .speed_tie = .P2 } };
705
+ try expectEqualSlices(Optional(Player), &.{ .P1, .P2 }, Rolls.speedTie(actions.p1));
706
+ try expectEqualSlices(Optional(Player), &.{.None}, Rolls.speedTie(actions.p2));
707
+ }
708
+
709
+ test "Rolls.damage" {
710
+ const actions: Actions = .{ .p2 = .{ .damage = 221 } };
711
+ try expectEqual(Rolls.Range{ .min = 0, .max = 1 }, Rolls.damage(actions.p1, .None));
712
+ try expectEqual(Rolls.Range{ .min = 217, .max = 256 }, Rolls.damage(actions.p2, .None));
713
+ try expectEqual(Rolls.Range{ .min = 0, .max = 1 }, Rolls.damage(actions.p2, .false));
714
+ }
715
+
716
+ test "Rolls.coalesce" {
717
+ var summaries = Summaries{ .p1 = .{ .damage = .{ .base = 74, .final = 69, .capped = true } } };
718
+ try expectEqual(0, try Rolls.coalesce(.P2, 0, &summaries, false));
719
+ try expectEqual(241, try Rolls.coalesce(.P2, 238, &summaries, false));
720
+ try expectEqual(255, try Rolls.coalesce(.P2, 238, &summaries, true));
721
+ summaries.p1.damage.final = 74;
722
+ try expectEqual(217, try Rolls.coalesce(.P2, 217, &summaries, false));
723
+ try expectEqual(255, try Rolls.coalesce(.P2, 217, &summaries, true));
724
+ }
725
+
726
+ test "Rolls.hit" {
727
+ const actions: Actions = .{ .p2 = .{ .hit = .true } };
728
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.hit(actions.p1, .None));
729
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.hit(actions.p2, .None));
730
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.hit(actions.p2, .true));
731
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.hit(actions.p2, .false));
732
+ }
733
+
734
+ test "Rolls.secondaryChance" {
735
+ const actions: Actions = .{ .p1 = .{ .secondary_chance = .true } };
736
+ try expectEqualSlices(
737
+ Optional(bool),
738
+ &.{ .false, .true },
739
+ Rolls.secondaryChance(actions.p1, .None),
740
+ );
741
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.secondaryChance(actions.p1, .false));
742
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.secondaryChance(actions.p2, .None));
743
+ }
744
+
745
+ test "Rolls.criticalHit" {
746
+ const actions: Actions = .{ .p1 = .{ .critical_hit = .true } };
747
+ try expectEqualSlices(
748
+ Optional(bool),
749
+ &.{ .false, .true },
750
+ Rolls.criticalHit(actions.p1, .None),
751
+ );
752
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.criticalHit(actions.p1, .false));
753
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.criticalHit(actions.p2, .None));
754
+ }
755
+
756
+ test "Rolls.confused" {
757
+ const actions: Actions = .{ .p2 = .{ .confused = .true } };
758
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.confused(actions.p1));
759
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.confused(actions.p2));
760
+ }
761
+
762
+ test "Rolls.paralyzed" {
763
+ const actions: Actions = .{ .p2 = .{ .paralyzed = .true } };
764
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.paralyzed(actions.p1, .None));
765
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.paralyzed(actions.p2, .None));
766
+ try expectEqualSlices(Optional(bool), &.{ .false, .true }, Rolls.paralyzed(actions.p2, .false));
767
+ try expectEqualSlices(Optional(bool), &.{.None}, Rolls.paralyzed(actions.p2, .true));
768
+ }
769
+
770
+ test "Rolls.duration" {
771
+ const actions: Actions = .{ .p2 = .{ .duration = 3 } };
772
+ try expectEqualSlices(u2, &.{0}, Rolls.duration(actions.p1, .None));
773
+ try expectEqualSlices(u2, &.{2}, Rolls.duration(actions.p2, .None));
774
+ try expectEqualSlices(u2, &.{0}, Rolls.duration(actions.p2, .false));
775
+ }
776
+
777
+ test "Rolls.moveSlot" {
778
+ const actions: Actions = .{ .p2 = .{ .move_slot = 3 } };
779
+ try expectEqualSlices(u4, &.{0}, Rolls.moveSlot(actions.p1, .None));
780
+ try expectEqualSlices(u4, &.{ 1, 2, 3, 4 }, Rolls.moveSlot(actions.p2, .None));
781
+ try expectEqualSlices(u4, &.{0}, Rolls.moveSlot(actions.p2, .false));
782
+ }
783
+
784
+ test "Rolls.multiHit" {
785
+ const actions: Actions = .{ .p2 = .{ .multi_hit = 3 } };
786
+ try expectEqualSlices(u4, &.{0}, Rolls.multiHit(actions.p1, .None));
787
+ try expectEqualSlices(u4, &.{ 2, 3, 4, 5 }, Rolls.multiHit(actions.p2, .None));
788
+ try expectEqualSlices(u4, &.{0}, Rolls.multiHit(actions.p2, .false));
789
+ }
790
+
791
+ test "Rolls.metronome" {
792
+ const actions: Actions = .{ .p2 = .{ .metronome = .Surf } };
793
+ try expectEqualSlices(data.Move, &.{.None}, Rolls.metronome(actions.p1));
794
+ try expectEqual(@as(data.Move, @enumFromInt(24)), Rolls.metronome(actions.p2)[23]);
795
+ }
796
+
797
+ test "Rolls.psywave" {
798
+ const actions: Actions = .{ .p2 = .{ .psywave = 79 } };
799
+ var side = helpers.Side.init(&[_]helpers.Pokemon{.{
800
+ .species = .Bulbasaur,
801
+ .level = 100,
802
+ .moves = &[_]data.Move{.Tackle},
803
+ }});
804
+
805
+ try expectEqualSlices(u8, &.{0}, Rolls.psywave(actions.p1, &side, .None));
806
+ var rolls = Rolls.psywave(actions.p2, &side, .None);
807
+ try expectEqual(150, rolls[rolls.len - 1]);
808
+ side.stored().level = 81;
809
+ rolls = Rolls.psywave(actions.p2, &side, .None);
810
+ try expectEqual(121, rolls[rolls.len - 1]);
811
+ try expectEqualSlices(u8, &.{0}, Rolls.psywave(actions.p2, &side, .false));
426
812
  }