@pkmn/engine 0.1.0-dev.84cc1a02 → 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 (63) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +135 -71
  3. package/build/pkg/addon.d.ts +7 -0
  4. package/build/pkg/addon.js +111 -0
  5. package/build/pkg/addon.js.map +1 -0
  6. package/build/pkg/data/ids.json +12 -12
  7. package/build/pkg/data/layout.json +27 -5
  8. package/build/pkg/data/protocol.json +69 -12
  9. package/build/pkg/data.d.ts +5 -6
  10. package/build/pkg/data.js +3 -5
  11. package/build/pkg/data.js.map +1 -1
  12. package/build/pkg/gen1.d.ts +5 -4
  13. package/build/pkg/gen1.js +49 -33
  14. package/build/pkg/gen1.js.map +1 -1
  15. package/build/pkg/index.d.ts +17 -13
  16. package/build/pkg/index.js.map +1 -1
  17. package/build/pkg/protocol.d.ts +4 -2
  18. package/build/pkg/protocol.js +65 -44
  19. package/build/pkg/protocol.js.map +1 -1
  20. package/build/test/display.js +400 -0
  21. package/build/test/display.js.map +1 -0
  22. package/build/tools/debug.js +134 -0
  23. package/build/tools/debug.js.map +1 -0
  24. package/build.zig +161 -147
  25. package/package.json +86 -46
  26. package/src/bin/install-pkmn-engine +67 -35
  27. package/src/bin/pkmn-debug +62 -0
  28. package/src/lib/common/battle.zig +17 -0
  29. package/src/lib/common/data.zig +19 -31
  30. package/src/lib/common/debug.zig +23 -13
  31. package/src/lib/common/js.zig +118 -0
  32. package/src/lib/common/optional.zig +67 -0
  33. package/src/lib/common/options.zig +14 -3
  34. package/src/lib/common/protocol.zig +942 -403
  35. package/src/lib/common/rational.zig +447 -0
  36. package/src/lib/common/rng.zig +35 -26
  37. package/src/lib/common/util.zig +12 -0
  38. package/src/lib/gen1/calc.zig +812 -0
  39. package/src/lib/gen1/chance.zig +827 -0
  40. package/src/lib/gen1/data/moves.zig +202 -190
  41. package/src/lib/gen1/data/species.zig +5 -5
  42. package/src/lib/gen1/data/types.zig +10 -10
  43. package/src/lib/gen1/data.zig +108 -94
  44. package/src/lib/gen1/helpers.zig +136 -37
  45. package/src/lib/gen1/mechanics.zig +1188 -835
  46. package/src/lib/gen2/calc.zig +143 -0
  47. package/src/lib/gen2/chance.zig +882 -0
  48. package/src/lib/gen2/data/items.zig +14 -20
  49. package/src/lib/gen2/data/moves.zig +664 -570
  50. package/src/lib/gen2/data/species.zig +2 -2
  51. package/src/lib/gen2/data/types.zig +137 -34
  52. package/src/lib/gen2/data.zig +134 -96
  53. package/src/lib/gen2/generated.zig +806 -0
  54. package/src/lib/gen2/helpers.zig +50 -26
  55. package/src/lib/gen2/mechanics.zig +3564 -12
  56. package/src/lib/node.zig +131 -0
  57. package/src/lib/pkmn.zig +86 -12
  58. package/src/lib/wasm.zig +13 -0
  59. package/src/test/display/pkmn.html.tmpl +368 -0
  60. package/src/lib/binding/node.zig +0 -229
  61. package/src/lib/binding/wasm.zig +0 -10
  62. package/src/lib/gen1/README.md +0 -778
  63. package/src/lib/gen2/README.md +0 -309
@@ -0,0 +1,827 @@
1
+ const std = @import("std");
2
+
3
+ const assert = std.debug.assert;
4
+ const print = std.debug.print;
5
+
6
+ const expect = std.testing.expect;
7
+ const expectEqual = std.testing.expectEqual;
8
+
9
+ const DEBUG = @import("../common/debug.zig").print;
10
+ const options = @import("../common/options.zig");
11
+ const rational = @import("../common/rational.zig");
12
+ const util = @import("../common/util.zig");
13
+
14
+ const Player = @import("../common/data.zig").Player;
15
+ const Optional = @import("../common/optional.zig").Optional;
16
+
17
+ const data = @import("data.zig");
18
+
19
+ const enabled = options.chance;
20
+ const showdown = options.showdown;
21
+
22
+ const Move = data.Move;
23
+ const MoveSlot = data.MoveSlot;
24
+
25
+ /// Actions taken by a hypothetical "chance player" that convey information about which RNG events
26
+ /// were observed during a Generation I battle `update`. This can additionally be provided as input
27
+ /// to the `update` call to override the normal behavior of the RNG in order to force specific
28
+ /// outcomes.
29
+ pub const Actions = extern struct {
30
+ /// Information about the RNG activity for Player 1.
31
+ p1: Action = .{},
32
+ /// Information about the RNG activity for Player 2.
33
+ p2: Action = .{},
34
+
35
+ comptime {
36
+ assert(@sizeOf(Actions) == 16);
37
+ }
38
+
39
+ /// Returns the `Action` for the given `player`.
40
+ pub fn get(self: anytype, player: Player) util.PointerType(@TypeOf(self), Action) {
41
+ assert(@typeInfo(@TypeOf(self)).Pointer.child == Actions);
42
+ return if (player == .P1) &self.p1 else &self.p2;
43
+ }
44
+
45
+ /// Returns true if `a` is equal to `b`.
46
+ pub fn eql(a: Actions, b: Actions) bool {
47
+ return @as(u128, @bitCast(a)) == @as(u128, @bitCast(b));
48
+ }
49
+
50
+ /// Returns true if `a` has the same "shape" as `b`, where `Actions` are defined to have the
51
+ /// same shape if they have the same fields set (though those fields need not necessarily be
52
+ /// set to the same value).
53
+ pub fn matches(a: Actions, b: Actions) bool {
54
+ inline for (@typeInfo(Actions).Struct.fields) |player| {
55
+ inline for (@typeInfo(Action).Struct.fields) |field| {
56
+ const a_val = @field(@field(a, player.name), field.name);
57
+ const b_val = @field(@field(b, player.name), field.name);
58
+
59
+ switch (@typeInfo(@TypeOf(a_val))) {
60
+ .Enum => if ((@intFromEnum(a_val) > 0) != (@intFromEnum(b_val) > 0))
61
+ return false,
62
+ .Int => if ((a_val > 0) != (b_val > 0)) return false,
63
+ else => unreachable,
64
+ }
65
+ }
66
+ }
67
+ return true;
68
+ }
69
+
70
+ pub fn fmt(self: Actions, writer: anytype, shape: bool) !void {
71
+ try writer.writeAll("<P1 = ");
72
+ try self.p1.fmt(writer, shape);
73
+ try writer.writeAll(", P2 = ");
74
+ try self.p2.fmt(writer, shape);
75
+ try writer.writeAll(">");
76
+ }
77
+
78
+ pub fn format(a: Actions, comptime f: []const u8, o: std.fmt.FormatOptions, w: anytype) !void {
79
+ _ = .{ f, o };
80
+ try fmt(a, w, false);
81
+ }
82
+ };
83
+
84
+ test Actions {
85
+ const a: Actions = .{ .p1 = .{ .hit = .true, .critical_hit = .false, .damage = 245 } };
86
+ const b: Actions = .{ .p1 = .{ .hit = .false, .critical_hit = .true, .damage = 246 } };
87
+ const c: Actions = .{ .p1 = .{ .hit = .true } };
88
+
89
+ try expect(a.eql(a));
90
+ try expect(!a.eql(b));
91
+ try expect(!b.eql(a));
92
+ try expect(!a.eql(c));
93
+ try expect(!c.eql(a));
94
+
95
+ try expect(a.matches(a));
96
+ try expect(a.matches(b));
97
+ try expect(b.matches(a));
98
+ try expect(!a.matches(c));
99
+ try expect(!c.matches(a));
100
+ }
101
+
102
+ pub const Observation = enum { started, continuing, ended };
103
+
104
+ /// Information about the RNG that was observed during a Generation I battle `update` for a
105
+ /// single player.
106
+ pub const Action = packed struct(u64) {
107
+ /// If not 0, the roll to be returned Rolls.damage.
108
+ damage: u8 = 0,
109
+
110
+ /// If not None, the value to return for Rolls.hit.
111
+ hit: Optional(bool) = .None,
112
+ /// If not None, the value to be returned by Rolls.criticalHit.
113
+ critical_hit: Optional(bool) = .None,
114
+ /// If not None, the value to be returned for
115
+ /// Rolls.{confusionChance,secondaryChance,poisonChance}.
116
+ secondary_chance: Optional(bool) = .None,
117
+ /// If not None, the Player to be returned by Rolls.speedTie.
118
+ speed_tie: Optional(Player) = .None,
119
+
120
+ /// If not None, the value to return for Rolls.confused.
121
+ confused: Optional(bool) = .None,
122
+ /// If not None, the value to return for Rolls.paralyzed.
123
+ paralyzed: Optional(bool) = .None,
124
+ /// If not 0, the value to be returned by Rolls.distribution in the case of binding moves
125
+ /// or Rolls.{sleepDuration,disableDuration,confusionDuration,attackingDuration} otherwise.
126
+ duration: u4 = 0,
127
+
128
+ // TODO
129
+ sleep: Optional(Observation) = .None,
130
+ confusion: Optional(Observation) = .None,
131
+ disable: Optional(Observation) = .None,
132
+ bide: Optional(Observation) = .None,
133
+ binding: Optional(Observation) = .None,
134
+ thrashing: Optional(Observation) = .None,
135
+
136
+ _: u4 = 0, // TODO
137
+
138
+ /// If not 0, the move slot (1-4) to return in Rolls.moveSlot. If present as an override,
139
+ /// invalid values (eg. due to empty move slots or 0 PP) will be ignored.
140
+ move_slot: u4 = 0,
141
+ /// If not 0, the value (2-5) to return for Rolls.distribution for multi hit.
142
+ multi_hit: u4 = 0,
143
+
144
+ /// If not 0, psywave - 1 should be returned as the damage roll for Rolls.psywave.
145
+ psywave: u8 = 0,
146
+
147
+ /// If not None, the Move to return for Rolls.metronome.
148
+ metronome: Move = .None,
149
+
150
+ pub const Field = std.meta.FieldEnum(Action);
151
+
152
+ pub fn format(a: Action, comptime f: []const u8, o: std.fmt.FormatOptions, w: anytype) !void {
153
+ _ = .{ f, o };
154
+ try fmt(a, w, false);
155
+ }
156
+
157
+ pub fn fmt(self: Action, writer: anytype, shape: bool) !void {
158
+ try writer.writeByte('(');
159
+ var printed = false;
160
+ inline for (@typeInfo(Action).Struct.fields) |field| {
161
+ const val = @field(self, field.name);
162
+ switch (@typeInfo(@TypeOf(val))) {
163
+ .Enum => if (val != .None) {
164
+ if (printed) try writer.writeAll(", ");
165
+ if (shape) {
166
+ try writer.print("{s}:?", .{field.name});
167
+ } else if (@TypeOf(val) == Optional(bool)) {
168
+ try writer.print("{s}{s}", .{
169
+ if (val == .false) "!" else "",
170
+ field.name,
171
+ });
172
+ } else if (@TypeOf(val) == Optional(Observation)) {
173
+ try writer.print("{s}{s}", .{
174
+ switch (val) {
175
+ .started => "+",
176
+ .continuing => "",
177
+ .ended => if (std.mem.eql(u8, field.name, "thrashing"))
178
+ "~"
179
+ else
180
+ "-",
181
+ else => unreachable,
182
+ },
183
+ field.name,
184
+ });
185
+ } else {
186
+ try writer.print("{s}:{s}", .{ field.name, @tagName(val) });
187
+ }
188
+ printed = true;
189
+ },
190
+ .Int => if (val != 0) {
191
+ if (printed) try writer.writeAll(", ");
192
+ if (shape) {
193
+ try writer.print("{s}:?", .{field.name});
194
+ } else {
195
+ try writer.print("{s}:{d}", .{ field.name, val });
196
+ }
197
+ printed = true;
198
+ },
199
+ else => unreachable,
200
+ }
201
+ }
202
+ try writer.writeByte(')');
203
+ }
204
+ };
205
+
206
+ /// TODO
207
+ pub const Durations = struct {
208
+ /// TODO
209
+ p1: Duration = .{},
210
+ /// TODO
211
+ p2: Duration = .{},
212
+
213
+ /// TODO
214
+ pub fn get(self: anytype, player: Player) util.PointerType(@TypeOf(self), Duration) {
215
+ assert(@typeInfo(@TypeOf(self)).Pointer.child == Durations);
216
+ return if (player == .P1) &self.p1 else &self.p2;
217
+ }
218
+
219
+ /// TODO
220
+ pub fn update(self: *Durations, battle: anytype, q: anytype, actions: Actions) !void {
221
+ for (&battle.sides, 0..) |*s, i| {
222
+ const p: Player = @enumFromInt(i);
223
+ const action = actions.get(p);
224
+ var duration = self.get(p);
225
+
226
+ // TODO sleeps
227
+
228
+ duration.confusion =
229
+ if (@intFromEnum(action.confusion) > 1) duration.confusion + 1 else 0;
230
+ duration.disable =
231
+ if (@intFromEnum(action.disable) > 1) duration.disable + 1 else 0;
232
+ duration.bide =
233
+ if (@intFromEnum(action.bide) > 1) duration.bide + 1 else 0;
234
+ duration.binding =
235
+ if (@intFromEnum(action.binding) > 1) duration.binding + 1 else 0;
236
+
237
+ // NOTE: this relies on private information!
238
+ if (action.thrashing == .ended) {
239
+ duration.thrashing =
240
+ if (s.active.volatiles.Thrashing) duration.thrashing + 1 else 0;
241
+ } else {
242
+ duration.thrashing =
243
+ if (@intFromEnum(action.thrashing) > 1) duration.thrashing + 1 else 0;
244
+ }
245
+
246
+ _ = q;
247
+ }
248
+ }
249
+
250
+ pub fn format(
251
+ self: Durations,
252
+ comptime fmt: []const u8,
253
+ opts: std.fmt.FormatOptions,
254
+ writer: anytype,
255
+ ) !void {
256
+ _ = .{ fmt, opts };
257
+ try writer.print("[P1 = {}, P2 = {}]", .{ self.p1, self.p2 });
258
+ }
259
+ };
260
+
261
+ /// TODO
262
+ pub const Duration = struct {
263
+ sleeps: [6]u3 = .{0} ** 6,
264
+ confusion: u3 = 0,
265
+ disable: u4 = 0,
266
+ bide: u3 = 0,
267
+ thrashing: u3 = 0,
268
+ binding: u3 = 0,
269
+
270
+ pub fn format(
271
+ self: Duration,
272
+ comptime fmt: []const u8,
273
+ opts: std.fmt.FormatOptions,
274
+ writer: anytype,
275
+ ) !void {
276
+ _ = .{ fmt, opts };
277
+ try writer.writeByte('(');
278
+ var printed = false;
279
+ inline for (@typeInfo(Duration).Struct.fields) |field| {
280
+ const val = @field(self, field.name);
281
+ switch (@typeInfo(@TypeOf(val))) {
282
+ .Int => if (val != 0) {
283
+ if (printed) try writer.writeAll(", ");
284
+ try writer.print("{s}:{d}", .{ field.name, val });
285
+ printed = true;
286
+ },
287
+ .Array => {
288
+ var total: usize = 0;
289
+ for (val) |v| total += v;
290
+ if (total > 0) {
291
+ if (printed) try writer.writeAll(", ");
292
+ try writer.print("{s}:[", .{field.name});
293
+ for (val, 0..) |v, i| {
294
+ if (i != 0) try writer.writeByte(',');
295
+ try writer.print("{d}", .{v});
296
+ }
297
+ try writer.writeAll("]");
298
+ printed = true;
299
+ }
300
+ },
301
+ else => unreachable,
302
+ }
303
+ }
304
+ try writer.writeByte(')');
305
+ }
306
+ };
307
+
308
+ pub const Commit = enum { hit, miss };
309
+
310
+ const uN = if (options.miss) u8 else u9;
311
+
312
+ /// Tracks chance actions and their associated probability during a Generation I battle update when
313
+ /// `options.chance` is enabled.
314
+ pub fn Chance(comptime Rational: type) type {
315
+ return struct {
316
+ const Self = @This();
317
+
318
+ /// The probability of the actions taken by a hypothetical "chance player" occurring.
319
+ probability: Rational,
320
+ /// The actions taken by a hypothetical "chance player" that convey information about which
321
+ /// RNG events were observed during a battle `update`.
322
+ actions: Actions = .{},
323
+
324
+ // In many cases on both the cartridge and on Pokémon Showdown rolls are made even though
325
+ // later checks render their result irrelevant (missing when the target is actually immune,
326
+ // rolling for damage when the move is later revealed to have missed, etc). We can't reorder
327
+ // the logic to ensure we only ever make rolls when required due to our desire to maintain
328
+ // RNG frame accuracy, so instead we save these "pending" updates to the probability and
329
+ // only commit them once we know they are relevant (a naive solution would be to instead
330
+ // update the probability eagerly and later "undo" the update by multiplying by the inverse
331
+ // but this would be more costly and also error prone in the presence of
332
+ // overflow/normalization).
333
+ //
334
+ // This design deliberately make use of the fact that recursive moves on the cartridge may
335
+ // overwrite critical hit information multiple times as only the last update actually
336
+ // matters for the purposes of the logical results.
337
+ //
338
+ // Finally, because each player's actions are processed sequentially we only need a single
339
+ // shared structure to track this information (though it needs to be cleared appropriately)
340
+ pending: if (showdown) struct {} else struct {
341
+ crit: bool = false,
342
+ crit_probablity: u8 = 0,
343
+ damage_roll: u8 = 0,
344
+ hit: bool = false,
345
+ hit_probablity: uN = 0,
346
+ } = .{},
347
+
348
+ /// Possible error returned by operations tracking chance probability.
349
+ pub const Error = Rational.Error;
350
+
351
+ /// Convenience helper to clear fields which typically should be cleared between updates.
352
+ pub fn reset(self: *Self) void {
353
+ if (!enabled) return;
354
+
355
+ self.probability.reset();
356
+ self.actions = .{};
357
+ self.pending = .{};
358
+ }
359
+
360
+ pub fn commit(self: *Self, player: Player, kind: Commit) Error!void {
361
+ if (!enabled) return;
362
+
363
+ assert(!showdown);
364
+
365
+ var action = self.actions.get(player);
366
+
367
+ // Always commit the hit result if we make it here (commit won't be called at all if the
368
+ // target is immune/behind a sub/etc)
369
+ if (self.pending.hit_probablity != 0) {
370
+ try self.probability.update(self.pending.hit_probablity, 256);
371
+ action.hit = if (self.pending.hit) .true else .false;
372
+ }
373
+
374
+ // If the move actually lands we can commit any past critical hit / damage rolls. Note
375
+ // we can't rely on the presence or absence of a damage roll to determine whether a
376
+ // "critical hit" was spurious or not as moves that do 1 or less damage don't rol for
377
+ // damage but can still crit (instead, whether or not a roll is deemed to be a no-op is
378
+ // passed to the critical hit helper)
379
+ if (kind != .hit) return assert(!self.pending.crit or self.pending.crit_probablity > 0);
380
+
381
+ if (self.pending.crit_probablity != 0) {
382
+ try self.probability.update(self.pending.crit_probablity, 256);
383
+ action.critical_hit = if (self.pending.crit) .true else .false;
384
+ }
385
+
386
+ if (self.pending.damage_roll > 0) {
387
+ try self.probability.update(1, 39);
388
+ action.damage = self.pending.damage_roll;
389
+ }
390
+ }
391
+
392
+ pub fn clearPending(self: *Self) void {
393
+ if (!enabled) return;
394
+
395
+ self.pending = .{};
396
+ }
397
+
398
+ pub fn speedTie(self: *Self, p1: bool) Error!void {
399
+ if (!enabled) return;
400
+
401
+ try self.probability.update(1, 2);
402
+ self.actions.p1.speed_tie = if (p1) .P1 else .P2;
403
+ self.actions.p2.speed_tie = self.actions.p1.speed_tie;
404
+ }
405
+
406
+ pub fn hit(self: *Self, player: Player, ok: bool, accuracy: uN) Error!void {
407
+ if (!enabled) return;
408
+
409
+ const p = if (ok) accuracy else @as(u8, @intCast(256 - @as(u9, accuracy)));
410
+ if (showdown) {
411
+ try self.probability.update(p, 256);
412
+ self.actions.get(player).hit = if (ok) .true else .false;
413
+ } else {
414
+ self.pending.hit = ok;
415
+ self.pending.hit_probablity = p;
416
+ }
417
+ }
418
+
419
+ pub fn criticalHit(self: *Self, player: Player, crit: bool, rate: u8) Error!void {
420
+ if (!enabled) return;
421
+
422
+ const n = if (crit) rate else @as(u8, @intCast(256 - @as(u9, rate)));
423
+ if (showdown) {
424
+ try self.probability.update(n, 256);
425
+ self.actions.get(player).critical_hit = if (crit) .true else .false;
426
+ } else {
427
+ self.pending.crit = crit;
428
+ self.pending.crit_probablity = n;
429
+ }
430
+ }
431
+
432
+ pub fn damage(self: *Self, player: Player, roll: u8) Error!void {
433
+ if (!enabled) return;
434
+
435
+ if (showdown) {
436
+ try self.probability.update(1, 39);
437
+ self.actions.get(player).damage = roll;
438
+ } else {
439
+ self.pending.damage_roll = roll;
440
+ }
441
+ }
442
+
443
+ pub fn secondaryChance(self: *Self, player: Player, proc: bool, rate: u8) Error!void {
444
+ if (!enabled) return;
445
+
446
+ const n = if (proc) rate else @as(u8, @intCast(256 - @as(u9, rate)));
447
+ try self.probability.update(n, 256);
448
+ self.actions.get(player).secondary_chance = if (proc) .true else .false;
449
+ }
450
+
451
+ pub fn confused(self: *Self, player: Player, cfz: bool) Error!void {
452
+ if (!enabled) return;
453
+
454
+ try self.probability.update(1, 2);
455
+ self.actions.get(player).confused = if (cfz) .true else .false;
456
+ }
457
+
458
+ pub fn paralyzed(self: *Self, player: Player, par: bool) Error!void {
459
+ if (!enabled) return;
460
+
461
+ try self.probability.update(@as(u8, if (par) 1 else 3), 4);
462
+ self.actions.get(player).paralyzed = if (par) .true else .false;
463
+ }
464
+
465
+ pub fn moveSlot(
466
+ self: *Self,
467
+ player: Player,
468
+ slot: u4,
469
+ ms: []const MoveSlot,
470
+ n: u4,
471
+ ) Error!void {
472
+ if (!enabled) return;
473
+
474
+ const denominator = if (n != 0) n else denominator: {
475
+ var i: usize = ms.len;
476
+ while (i > 0) {
477
+ i -= 1;
478
+ if (ms[i].id != .None) break :denominator i + 1;
479
+ }
480
+ unreachable;
481
+ };
482
+
483
+ if (denominator != 1) try self.probability.update(1, denominator);
484
+ self.actions.get(player).move_slot = @intCast(slot);
485
+ }
486
+
487
+ pub fn multiHit(self: *Self, player: Player, n: u3) Error!void {
488
+ if (!enabled) return;
489
+
490
+ try self.probability.update(@as(u8, if (n > 3) 1 else 3), 8);
491
+ self.actions.get(player).multi_hit = n;
492
+ }
493
+
494
+ pub fn duration(self: *Self, player: Player, turns: u4) void {
495
+ if (!enabled) return;
496
+
497
+ self.actions.get(player).duration = if (options.key) 1 else turns;
498
+ }
499
+
500
+ pub fn durations(
501
+ self: *Self,
502
+ comptime f: Action.Field,
503
+ player: Player,
504
+ observation: Optional(Observation),
505
+ ) void {
506
+ if (!enabled) return;
507
+
508
+ @field(self.actions.get(player), @tagName(f)) = observation;
509
+ }
510
+
511
+ pub fn psywave(self: *Self, player: Player, power: u8, max: u8) Error!void {
512
+ if (!enabled) return;
513
+
514
+ try self.probability.update(1, max);
515
+ self.actions.get(player).psywave = power + 1;
516
+ }
517
+
518
+ pub fn metronome(self: *Self, player: Player, move: Move) Error!void {
519
+ if (!enabled) return;
520
+
521
+ try self.probability.update(1, Move.METRONOME.len);
522
+ self.actions.get(player).metronome = move;
523
+ }
524
+ };
525
+ }
526
+
527
+ test "Chance.speedTie" {
528
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
529
+
530
+ try chance.speedTie(true);
531
+ try expectProbability(&chance.probability, 1, 2);
532
+ try expectValue(Optional(Player).P1, chance.actions.p1.speed_tie);
533
+ try expectValue(chance.actions.p1.speed_tie, chance.actions.p2.speed_tie);
534
+
535
+ chance.reset();
536
+
537
+ try chance.speedTie(false);
538
+ try expectProbability(&chance.probability, 1, 2);
539
+ try expectValue(Optional(Player).P2, chance.actions.p1.speed_tie);
540
+ try expectValue(chance.actions.p1.speed_tie, chance.actions.p2.speed_tie);
541
+ }
542
+
543
+ test "Chance.hit" {
544
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
545
+
546
+ try chance.hit(.P1, true, 229);
547
+ if (!showdown) {
548
+ try expectProbability(&chance.probability, 1, 1);
549
+ try expectValue(Optional(bool).None, chance.actions.p1.hit);
550
+
551
+ try chance.commit(.P1, .hit);
552
+ }
553
+ try expectValue(Optional(bool).true, chance.actions.p1.hit);
554
+ try expectProbability(&chance.probability, 229, 256);
555
+
556
+ chance.reset();
557
+
558
+ try chance.hit(.P2, false, 255);
559
+ if (!showdown) {
560
+ try expectProbability(&chance.probability, 1, 1);
561
+ try expectValue(Optional(bool).None, chance.actions.p2.hit);
562
+
563
+ try chance.commit(.P2, .miss);
564
+ }
565
+ try expectValue(Optional(bool).false, chance.actions.p2.hit);
566
+ try expectProbability(&chance.probability, 1, 256);
567
+ }
568
+
569
+ test "Chance.criticalHit" {
570
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
571
+
572
+ try chance.criticalHit(.P1, true, 17);
573
+ if (showdown) {
574
+ try expectValue(Optional(bool).true, chance.actions.p1.critical_hit);
575
+ try expectProbability(&chance.probability, 17, 256);
576
+ } else {
577
+ try expectProbability(&chance.probability, 1, 1);
578
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
579
+
580
+ try chance.hit(.P1, true, 128);
581
+
582
+ try expectProbability(&chance.probability, 1, 1);
583
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
584
+
585
+ try chance.damage(.P1, 217);
586
+
587
+ try expectProbability(&chance.probability, 1, 1);
588
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
589
+
590
+ try chance.commit(.P1, .hit);
591
+
592
+ try expectProbability(&chance.probability, 17, 19968); // (1/2) * (17/256) * (1/39)
593
+ try expectValue(Optional(bool).true, chance.actions.p1.critical_hit);
594
+ }
595
+
596
+ chance.reset();
597
+
598
+ try chance.criticalHit(.P2, false, 5);
599
+ if (showdown) {
600
+ try expectProbability(&chance.probability, 251, 256);
601
+ try expectValue(Optional(bool).false, chance.actions.p2.critical_hit);
602
+ } else {
603
+ try expectProbability(&chance.probability, 1, 1);
604
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
605
+
606
+ try chance.hit(.P1, true, 128);
607
+
608
+ try expectProbability(&chance.probability, 1, 1);
609
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
610
+
611
+ try chance.damage(.P1, 217);
612
+ try chance.commit(.P1, .hit);
613
+
614
+ try expectProbability(&chance.probability, 251, 19968); // (1/2) * (251/256) * (1/39)
615
+ try expectValue(Optional(bool).false, chance.actions.p1.critical_hit);
616
+ }
617
+ }
618
+
619
+ test "Chance.damage" {
620
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
621
+
622
+ try chance.damage(.P1, 217);
623
+ if (showdown) {
624
+ try expectValue(217, chance.actions.p1.damage);
625
+ try expectProbability(&chance.probability, 1, 39);
626
+ } else {
627
+ try expectProbability(&chance.probability, 1, 1);
628
+ try expectValue(0, chance.actions.p1.damage);
629
+
630
+ try chance.commit(.P1, .hit);
631
+
632
+ try expectProbability(&chance.probability, 1, 39);
633
+ try expectValue(217, chance.actions.p1.damage);
634
+ }
635
+ }
636
+
637
+ test "Chance.secondaryChance" {
638
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
639
+
640
+ try chance.secondaryChance(.P1, true, 25);
641
+ try expectProbability(&chance.probability, 25, 256);
642
+ try expectValue(Optional(bool).true, chance.actions.p1.secondary_chance);
643
+
644
+ chance.reset();
645
+
646
+ try chance.secondaryChance(.P2, false, 77);
647
+ try expectProbability(&chance.probability, 179, 256);
648
+ try expectValue(Optional(bool).false, chance.actions.p2.secondary_chance);
649
+ }
650
+
651
+ test "Chance.confused" {
652
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
653
+
654
+ try chance.confused(.P1, false);
655
+ try expectProbability(&chance.probability, 1, 2);
656
+ try expectValue(Optional(bool).false, chance.actions.p1.confused);
657
+
658
+ chance.reset();
659
+
660
+ try chance.confused(.P2, true);
661
+ try expectProbability(&chance.probability, 1, 2);
662
+ try expectValue(Optional(bool).true, chance.actions.p2.confused);
663
+ }
664
+
665
+ test "Chance.paralyzed" {
666
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
667
+
668
+ try chance.paralyzed(.P1, false);
669
+ try expectProbability(&chance.probability, 3, 4);
670
+ try expectValue(Optional(bool).false, chance.actions.p1.paralyzed);
671
+
672
+ chance.reset();
673
+
674
+ try chance.paralyzed(.P2, true);
675
+ try expectProbability(&chance.probability, 1, 4);
676
+ try expectValue(Optional(bool).true, chance.actions.p2.paralyzed);
677
+ }
678
+
679
+ test "Chance.moveSlot" {
680
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
681
+ var ms = [_]MoveSlot{ .{ .id = Move.Surf }, .{ .id = Move.Psychic }, .{ .id = Move.Recover } };
682
+
683
+ try chance.moveSlot(.P2, 2, &ms, 2);
684
+ try expectProbability(&chance.probability, 1, 2);
685
+ try expectValue(2, chance.actions.p2.move_slot);
686
+
687
+ chance.reset();
688
+
689
+ try chance.moveSlot(.P1, 1, &ms, 0);
690
+ try expectProbability(&chance.probability, 1, 3);
691
+ try expectValue(1, chance.actions.p1.move_slot);
692
+ }
693
+
694
+ test "Chance.multiHit" {
695
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
696
+
697
+ try chance.multiHit(.P1, 3);
698
+ try expectProbability(&chance.probability, 3, 8);
699
+ try expectValue(3, chance.actions.p1.multi_hit);
700
+
701
+ chance.reset();
702
+
703
+ try chance.multiHit(.P2, 5);
704
+ try expectProbability(&chance.probability, 1, 8);
705
+ try expectValue(5, chance.actions.p2.multi_hit);
706
+ }
707
+
708
+ test "Chance.duration" {
709
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
710
+
711
+ chance.duration(.P1, 2);
712
+ try expectValue(2, chance.actions.p1.duration);
713
+
714
+ chance.reset();
715
+
716
+ chance.duration(.P2, 4);
717
+ try expectValue(4, chance.actions.p2.duration);
718
+ }
719
+
720
+ test "Chance.psywave" {
721
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
722
+
723
+ try chance.psywave(.P2, 100, 150);
724
+ try expectProbability(&chance.probability, 1, 150);
725
+ try expectValue(101, chance.actions.p2.psywave);
726
+ }
727
+
728
+ test "Chance.metronome" {
729
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
730
+
731
+ try chance.metronome(.P1, Move.HornAttack);
732
+ try expectProbability(&chance.probability, 1, 163);
733
+ try expectValue(Move.HornAttack, chance.actions.p1.metronome);
734
+ }
735
+
736
+ pub fn expectProbability(r: anytype, p: u64, q: u64) !void {
737
+ if (!enabled) return;
738
+
739
+ r.reduce();
740
+ if (r.p != p or r.q != q) {
741
+ print("expected {d}/{d}, found {}\n", .{ p, q, r });
742
+ return error.TestExpectedEqual;
743
+ }
744
+ }
745
+
746
+ pub fn expectValue(a: anytype, b: anytype) !void {
747
+ if (!enabled) return;
748
+
749
+ try expectEqual(a, b);
750
+ }
751
+
752
+ /// Null object pattern implementation of Generation I `Chance` which does nothing, though chance
753
+ /// tracking should additionally be turned off entirely via `options.chance`.
754
+ pub const NULL: Null = .{};
755
+
756
+ const Null = struct {
757
+ pub const Error = error{};
758
+
759
+ pub fn commit(self: Null, player: Player, kind: Commit) Error!void {
760
+ _ = .{ self, player, kind };
761
+ }
762
+
763
+ pub fn clearPending(self: Null) void {
764
+ _ = .{self};
765
+ }
766
+
767
+ pub fn switched(self: Null, player: Player, in: u8, out: u8) void {
768
+ _ = .{ self, player, in, out };
769
+ }
770
+
771
+ pub fn speedTie(self: Null, p1: bool) Error!void {
772
+ _ = .{ self, p1 };
773
+ }
774
+
775
+ pub fn hit(self: Null, player: Player, ok: bool, accuracy: uN) Error!void {
776
+ _ = .{ self, player, ok, accuracy };
777
+ }
778
+
779
+ pub fn criticalHit(self: Null, player: Player, crit: bool, rate: u8) Error!void {
780
+ _ = .{ self, player, crit, rate };
781
+ }
782
+
783
+ pub fn damage(self: Null, player: Player, roll: u8) Error!void {
784
+ _ = .{ self, player, roll };
785
+ }
786
+
787
+ pub fn confused(self: Null, player: Player, ok: bool) Error!void {
788
+ _ = .{ self, player, ok };
789
+ }
790
+
791
+ pub fn paralyzed(self: Null, player: Player, ok: bool) Error!void {
792
+ _ = .{ self, player, ok };
793
+ }
794
+
795
+ pub fn secondaryChance(self: Null, player: Player, proc: bool, rate: u8) Error!void {
796
+ _ = .{ self, player, proc, rate };
797
+ }
798
+
799
+ pub fn moveSlot(self: Null, player: Player, slot: u4, ms: []const MoveSlot, n: u4) Error!void {
800
+ _ = .{ self, player, slot, ms, n };
801
+ }
802
+
803
+ pub fn multiHit(self: Null, player: Player, n: u3) Error!void {
804
+ _ = .{ self, player, n };
805
+ }
806
+
807
+ pub fn durations(
808
+ self: Null,
809
+ comptime f: Action.Field,
810
+ player: Player,
811
+ observation: Optional(Observation),
812
+ ) void {
813
+ _ = .{ self, f, player, observation };
814
+ }
815
+
816
+ pub fn duration(self: Null, player: Player, turns: u4) void {
817
+ _ = .{ self, player, turns };
818
+ }
819
+
820
+ pub fn psywave(self: Null, player: Player, power: u8, max: u8) Error!void {
821
+ _ = .{ self, player, power, max };
822
+ }
823
+
824
+ pub fn metronome(self: Null, player: Player, move: Move) Error!void {
825
+ _ = .{ self, player, move };
826
+ }
827
+ };