@pkmn/engine 0.1.0-dev.2ad317f2 → 0.1.0-dev.2c426670

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