@pkmn/engine 0.1.0-dev.9a0c07c3 → 0.1.0-dev.a0167a9d

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 (62) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +108 -72
  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 +4 -4
  10. package/build/pkg/data.js.map +1 -1
  11. package/build/pkg/gen1.d.ts +5 -4
  12. package/build/pkg/gen1.js +49 -33
  13. package/build/pkg/gen1.js.map +1 -1
  14. package/build/pkg/index.d.ts +17 -13
  15. package/build/pkg/index.js.map +1 -1
  16. package/build/pkg/protocol.d.ts +4 -2
  17. package/build/pkg/protocol.js +65 -44
  18. package/build/pkg/protocol.js.map +1 -1
  19. package/build/test/display.js +33 -15
  20. package/build/test/display.js.map +1 -1
  21. package/build/tools/debug.js +5 -4
  22. package/build/tools/debug.js.map +1 -1
  23. package/build.zig +155 -138
  24. package/package.json +59 -26
  25. package/src/bin/install-pkmn-engine +36 -23
  26. package/src/bin/pkmn-debug +34 -7
  27. package/src/lib/common/battle.zig +17 -0
  28. package/src/lib/common/data.zig +19 -31
  29. package/src/lib/common/debug.zig +23 -13
  30. package/src/lib/common/js.zig +118 -0
  31. package/src/lib/common/optional.zig +67 -0
  32. package/src/lib/common/options.zig +14 -3
  33. package/src/lib/common/protocol.zig +942 -403
  34. package/src/lib/common/rational.zig +447 -0
  35. package/src/lib/common/rng.zig +35 -26
  36. package/src/lib/common/util.zig +12 -0
  37. package/src/lib/gen1/calc.zig +598 -0
  38. package/src/lib/gen1/chance.zig +1026 -0
  39. package/src/lib/gen1/data/moves.zig +202 -190
  40. package/src/lib/gen1/data/species.zig +5 -5
  41. package/src/lib/gen1/data/types.zig +10 -10
  42. package/src/lib/gen1/data.zig +108 -94
  43. package/src/lib/gen1/helpers.zig +565 -35
  44. package/src/lib/gen1/mechanics.zig +1182 -839
  45. package/src/lib/gen2/calc.zig +143 -0
  46. package/src/lib/gen2/chance.zig +1404 -0
  47. package/src/lib/gen2/data/items.zig +14 -20
  48. package/src/lib/gen2/data/moves.zig +664 -570
  49. package/src/lib/gen2/data/species.zig +2 -2
  50. package/src/lib/gen2/data/types.zig +137 -34
  51. package/src/lib/gen2/data.zig +134 -96
  52. package/src/lib/gen2/generated.zig +806 -0
  53. package/src/lib/gen2/helpers.zig +50 -26
  54. package/src/lib/gen2/mechanics.zig +3591 -12
  55. package/src/lib/node.zig +131 -0
  56. package/src/lib/pkmn.zig +86 -12
  57. package/src/lib/wasm.zig +13 -0
  58. package/src/test/display/pkmn.html.tmpl +5 -5
  59. package/src/lib/binding/node.zig +0 -229
  60. package/src/lib/binding/wasm.zig +0 -10
  61. package/src/lib/gen1/README.md +0 -784
  62. package/src/lib/gen2/README.md +0 -309
@@ -0,0 +1,1026 @@
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
+ /// Information about the RNG that was observed during a Generation I battle `update` for a
103
+ /// single player.
104
+ pub const Action = packed struct(u64) {
105
+ /// If not 0, the roll to be returned Rolls.damage.
106
+ damage: u8 = 0,
107
+
108
+ /// If not None, the value to return for Rolls.hit.
109
+ hit: Optional(bool) = .None,
110
+ /// If not None, the value to be returned by Rolls.criticalHit.
111
+ critical_hit: Optional(bool) = .None,
112
+ /// If not None, the value to be returned for
113
+ /// Rolls.{confusionChance,secondaryChance,poisonChance}.
114
+ secondary_chance: Optional(bool) = .None,
115
+ /// If not None, the Player to be returned by Rolls.speedTie.
116
+ speed_tie: Optional(Player) = .None,
117
+
118
+ /// If not None, the value to return for Rolls.confused.
119
+ confused: Optional(bool) = .None,
120
+ /// If not None, the value to return for Rolls.paralyzed.
121
+ paralyzed: Optional(bool) = .None,
122
+ /// If not 0, the value to be returned by Rolls.distribution in the case of binding moves
123
+ /// or Rolls.{sleepDuration,disableDuration,confusionDuration,attackingDuration} otherwise.
124
+ duration: u4 = 0,
125
+
126
+ _: u16 = 0,
127
+
128
+ /// If not 0, the move slot (1-4) to return in Rolls.moveSlot. If present as an override,
129
+ /// invalid values (eg. due to empty move slots or 0 PP) will be ignored.
130
+ move_slot: u4 = 0,
131
+ /// If not 0, the value (2-5) to return for Rolls.distribution for multi hit.
132
+ multi_hit: u4 = 0,
133
+
134
+ /// If not 0, psywave - 1 should be returned as the damage roll for Rolls.psywave.
135
+ psywave: u8 = 0,
136
+
137
+ /// If not None, the Move to return for Rolls.metronome.
138
+ metronome: Move = .None,
139
+
140
+ pub const Field = std.meta.FieldEnum(Action);
141
+
142
+ pub fn format(a: Action, comptime f: []const u8, o: std.fmt.FormatOptions, w: anytype) !void {
143
+ _ = .{ f, o };
144
+ try fmt(a, w, false);
145
+ }
146
+
147
+ pub fn fmt(self: Action, writer: anytype, shape: bool) !void {
148
+ try writer.writeByte('(');
149
+ var printed = false;
150
+ inline for (@typeInfo(Action).Struct.fields) |field| {
151
+ const val = @field(self, field.name);
152
+ switch (@typeInfo(@TypeOf(val))) {
153
+ .Enum => if (val != .None) {
154
+ if (printed) try writer.writeAll(", ");
155
+ if (shape) {
156
+ try writer.print("{s}:?", .{field.name});
157
+ } else if (@TypeOf(val) == Optional(bool)) {
158
+ try writer.print("{s}{s}", .{
159
+ if (val == .false) "!" else "",
160
+ field.name,
161
+ });
162
+ } else {
163
+ try writer.print("{s}:{s}", .{ field.name, @tagName(val) });
164
+ }
165
+ printed = true;
166
+ },
167
+ .Int => if (val != 0) {
168
+ if (printed) try writer.writeAll(", ");
169
+ if (shape) {
170
+ try writer.print("{s}:?", .{field.name});
171
+ } else {
172
+ try writer.print("{s}:{d}", .{ field.name, val });
173
+ }
174
+ printed = true;
175
+ },
176
+ else => unreachable,
177
+ }
178
+ }
179
+ try writer.writeByte(')');
180
+ }
181
+ };
182
+
183
+ /// TODO
184
+ pub const Durations = extern struct {
185
+ /// Information about the durations for Player 1.
186
+ p1: Duration = .{},
187
+ /// Information about the durations for Player 2.
188
+ p2: Duration = .{},
189
+
190
+ comptime {
191
+ assert(@sizeOf(Durations) == 4);
192
+ }
193
+
194
+ /// Returns the `Duration` for the given `player`.
195
+ pub fn get(self: anytype, player: Player) util.PointerType(@TypeOf(self), Duration) {
196
+ assert(@typeInfo(@TypeOf(self)).Pointer.child == Durations);
197
+ return if (player == .P1) &self.p1 else &self.p2;
198
+ }
199
+ };
200
+
201
+ /// Observed values for various durations that need to be tracked in order to properly
202
+ /// deduplicate transitions with a primary key. TODO
203
+ pub const Duration = packed struct(u16) {
204
+ /// The number of turns a Pokémon has been observed to be sleeping.
205
+ sleep: u3 = 0,
206
+ /// The number of turns a Pokémon has been observed to be confused.
207
+ confusion: u3 = 0,
208
+ /// The number of turns a Pokémon has been observed to be disabled.
209
+ disable: u4 = 0,
210
+ /// The number of turns a Pokémon has been observed to be attacking.
211
+ attacking: u3 = 0,
212
+ /// The number of turns a Pokémon has been observed to be binding their opponent.
213
+ binding: u3 = 0,
214
+
215
+ pub const Field = std.meta.FieldEnum(Duration);
216
+ };
217
+
218
+ pub const Commit = enum { hit, miss, binding };
219
+
220
+ const uN = if (options.miss) u8 else u9;
221
+
222
+ /// Tracks chance actions and their associated probability during a Generation I battle update when
223
+ /// `options.chance` is enabled.
224
+ pub fn Chance(comptime Rational: type) type {
225
+ return struct {
226
+ const Self = @This();
227
+
228
+ /// The probability of the actions taken by a hypothetical "chance player" occurring.
229
+ probability: Rational,
230
+ /// The actions taken by a hypothetical "chance player" that convey information about which
231
+ /// RNG events were observed during a battle `update`.
232
+ actions: Actions = .{},
233
+ /// TODO
234
+ durations: Durations = .{},
235
+
236
+ // Tracks the observed sleep durations for the Pokémon in both player's parties. Unlike
237
+ // other durations which are all tied to volatiles, sleep's counter persists through
238
+ // switching and so we must store it here. The indices of these arrays correspond to the
239
+ // `order` field of a Side. This information could be stored in actions but size is a
240
+ // concern so this is tracked separately as actions only purports to track RNG events
241
+ // observed during a single `update` (not across updates).
242
+ sleeps: [2][6]u3 = .{ .{0} ** 6, .{0} ** 6 },
243
+
244
+ // In many cases on both the cartridge and on Pokémon Showdown rolls are made even though
245
+ // later checks render their result irrelevant (missing when the target is actually immune,
246
+ // rolling for damage when the move is later revealed to have missed, etc). We can't reorder
247
+ // the logic to ensure we only ever make rolls when required due to our desire to maintain
248
+ // RNG frame accuracy, so instead we save these "pending" updates to the probability and
249
+ // only commit them once we know they are relevant (a naive solution would be to instead
250
+ // update the probability eagerly and later "undo" the update by multiplying by the inverse
251
+ // but this would be more costly and also error prone in the presence of
252
+ // overflow/normalization).
253
+ //
254
+ // This design deliberately make use of the fact that recursive moves on the cartridge may
255
+ // overwrite critical hit information multiple times as only the last update actually
256
+ // matters for the purposes of the logical results.
257
+ //
258
+ // Finally, because each player's actions are processed sequentially we only need a single
259
+ // shared structure to track this information (though it needs to be cleared appropriately)
260
+ pending: if (showdown) struct {} else struct {
261
+ crit: bool = false,
262
+ crit_probablity: u8 = 0,
263
+ damage_roll: u8 = 0,
264
+ hit: bool = false,
265
+ hit_probablity: uN = 0,
266
+ binding: u8 = 0,
267
+ } = .{},
268
+
269
+ /// Possible error returned by operations tracking chance probability.
270
+ pub const Error = Rational.Error;
271
+
272
+ /// Convenience helper to clear fields which typically should be cleared between updates.
273
+ pub fn reset(self: *Self) void {
274
+ if (!enabled) return;
275
+
276
+ self.probability.reset();
277
+ self.actions = .{};
278
+ self.pending = .{};
279
+ }
280
+
281
+ pub fn commit(self: *Self, player: Player, kind: Commit) Error!void {
282
+ if (!enabled) return;
283
+
284
+ assert(!showdown);
285
+
286
+ var action = self.actions.get(player);
287
+
288
+ // We need to handle binding specially because we still need to commit it when attacking
289
+ // into a Pokémon that is immune
290
+ if (kind != .miss and self.pending.binding != 0) {
291
+ // assert(action.duration == 0); FIXME
292
+ action.duration = @intCast(self.pending.binding);
293
+
294
+ var durations = self.durations.get(player);
295
+ assert(durations.binding == 0);
296
+ durations.binding = 1;
297
+ }
298
+ if (kind == .binding) return;
299
+
300
+ // Always commit the hit result if we make it here (commit won't be called at all if the
301
+ // target is immune/behind a sub/etc)
302
+ if (self.pending.hit_probablity != 0) {
303
+ try self.probability.update(self.pending.hit_probablity, 256);
304
+ action.hit = if (self.pending.hit) .true else .false;
305
+ }
306
+
307
+ // If the move actually lands we can commit any past critical hit / damage rolls. Note
308
+ // we can't rely on the presence or absence of a damage roll to determine whether a
309
+ // "critical hit" was spurious or not as moves that do 1 or less damage don't rol for
310
+ // damage but can still crit (instead, whether or not a roll is deemed to be a no-op is
311
+ // passed to the critical hit helper)
312
+ if (kind != .hit) return assert(!self.pending.crit or self.pending.crit_probablity > 0);
313
+
314
+ if (self.pending.crit_probablity != 0) {
315
+ try self.probability.update(self.pending.crit_probablity, 256);
316
+ action.critical_hit = if (self.pending.crit) .true else .false;
317
+ }
318
+
319
+ if (self.pending.damage_roll > 0) {
320
+ try self.probability.update(1, 39);
321
+ action.damage = self.pending.damage_roll;
322
+ }
323
+ }
324
+
325
+ pub fn clearPending(self: *Self) void {
326
+ if (!enabled) return;
327
+
328
+ self.pending = .{};
329
+ }
330
+
331
+ pub fn clearDurations(self: *Self, player: Player, haze: ?bool) void {
332
+ if (!enabled) return;
333
+
334
+ var durations = self.durations.get(player);
335
+ if (haze) |status| {
336
+ if (status) durations.sleep = 0;
337
+ durations.confusion = 0;
338
+ durations.disable = 0;
339
+ } else {
340
+ durations.attacking = 0;
341
+ durations.binding = 0;
342
+ }
343
+ }
344
+
345
+ pub fn switched(self: *Self, player: Player, in: u8, out: u8) void {
346
+ if (!enabled) return;
347
+
348
+ assert(in >= 1 and in <= 6);
349
+ assert(out >= 1 and out <= 6);
350
+
351
+ var durations = self.durations.get(player);
352
+
353
+ const slp = durations.sleep;
354
+ durations.* = .{};
355
+
356
+ self.sleeps[@intFromEnum(player)][out - 1] = slp;
357
+ durations.sleep = @intCast(self.sleeps[@intFromEnum(player)][in - 1]);
358
+
359
+ self.durations.get(player.foe()).binding = 0;
360
+ }
361
+
362
+ pub fn speedTie(self: *Self, p1: bool) Error!void {
363
+ if (!enabled) return;
364
+
365
+ try self.probability.update(1, 2);
366
+ self.actions.p1.speed_tie = if (p1) .P1 else .P2;
367
+ self.actions.p2.speed_tie = self.actions.p1.speed_tie;
368
+ }
369
+
370
+ pub fn hit(self: *Self, player: Player, ok: bool, accuracy: uN) Error!void {
371
+ if (!enabled) return;
372
+
373
+ const p = if (ok) accuracy else @as(u8, @intCast(256 - @as(u9, accuracy)));
374
+ if (showdown) {
375
+ try self.probability.update(p, 256);
376
+ self.actions.get(player).hit = if (ok) .true else .false;
377
+ } else {
378
+ self.pending.hit = ok;
379
+ self.pending.hit_probablity = p;
380
+ }
381
+ }
382
+
383
+ pub fn criticalHit(self: *Self, player: Player, crit: bool, rate: u8) Error!void {
384
+ if (!enabled) return;
385
+
386
+ const n = if (crit) rate else @as(u8, @intCast(256 - @as(u9, rate)));
387
+ if (showdown) {
388
+ try self.probability.update(n, 256);
389
+ self.actions.get(player).critical_hit = if (crit) .true else .false;
390
+ } else {
391
+ self.pending.crit = crit;
392
+ self.pending.crit_probablity = n;
393
+ }
394
+ }
395
+
396
+ pub fn damage(self: *Self, player: Player, roll: u8) Error!void {
397
+ if (!enabled) return;
398
+
399
+ if (showdown) {
400
+ try self.probability.update(1, 39);
401
+ self.actions.get(player).damage = roll;
402
+ } else {
403
+ self.pending.damage_roll = roll;
404
+ }
405
+ }
406
+
407
+ pub fn secondaryChance(self: *Self, player: Player, proc: bool, rate: u8) Error!void {
408
+ if (!enabled) return;
409
+
410
+ const n = if (proc) rate else @as(u8, @intCast(256 - @as(u9, rate)));
411
+ try self.probability.update(n, 256);
412
+ self.actions.get(player).secondary_chance = if (proc) .true else .false;
413
+ }
414
+
415
+ pub fn confused(self: *Self, player: Player, cfz: bool) Error!void {
416
+ if (!enabled) return;
417
+
418
+ try self.probability.update(1, 2);
419
+ self.actions.get(player).confused = if (cfz) .true else .false;
420
+ }
421
+
422
+ pub fn paralyzed(self: *Self, player: Player, par: bool) Error!void {
423
+ if (!enabled) return;
424
+
425
+ try self.probability.update(@as(u8, if (par) 1 else 3), 4);
426
+ self.actions.get(player).paralyzed = if (par) .true else .false;
427
+ }
428
+
429
+ pub fn moveSlot(
430
+ self: *Self,
431
+ player: Player,
432
+ slot: u4,
433
+ ms: []const MoveSlot,
434
+ n: u4,
435
+ ) Error!void {
436
+ if (!enabled) return;
437
+
438
+ const denominator = if (n != 0) n else denominator: {
439
+ var i: usize = ms.len;
440
+ while (i > 0) {
441
+ i -= 1;
442
+ if (ms[i].id != .None) break :denominator i + 1;
443
+ }
444
+ unreachable;
445
+ };
446
+
447
+ if (denominator != 1) try self.probability.update(1, denominator);
448
+ self.actions.get(player).move_slot = @intCast(slot);
449
+ }
450
+
451
+ pub fn multiHit(self: *Self, player: Player, n: u3) Error!void {
452
+ if (!enabled) return;
453
+
454
+ try self.probability.update(@as(u8, if (n > 3) 1 else 3), 8);
455
+ self.actions.get(player).multi_hit = n;
456
+ }
457
+
458
+ pub fn duration(
459
+ self: *Self,
460
+ comptime field: Duration.Field,
461
+ player: Player,
462
+ target: Player,
463
+ turns: u4,
464
+ ) void {
465
+ if (!enabled) return;
466
+
467
+ if (!showdown and field == .binding) {
468
+ self.pending.binding = if (options.key) 1 else turns;
469
+ } else {
470
+ var durations = self.durations.get(target);
471
+ assert(@field(durations, @tagName(field)) == 0 or
472
+ (field == .confusion and player == target));
473
+ @field(durations, @tagName(field)) = 1;
474
+
475
+ self.actions.get(player).duration = if (options.key) 1 else turns;
476
+ }
477
+ }
478
+
479
+ pub fn sleep(self: *Self, player: Player, turns: u4) Error!void {
480
+ if (!enabled) return;
481
+
482
+ var durations = self.durations.get(player);
483
+ const n = durations.sleep;
484
+ if (turns == 0) {
485
+ assert(n >= 1 and n <= 7);
486
+ if (n != 7) try self.probability.update(1, 8 - @as(u4, n));
487
+ durations.sleep = 0;
488
+ } else {
489
+ assert(n >= 1 and n < 7);
490
+ try self.probability.update(8 - @as(u4, n) - 1, 8 - @as(u4, n));
491
+ durations.sleep += 1;
492
+ }
493
+ }
494
+
495
+ pub fn confusion(self: *Self, player: Player, turns: u4) Error!void {
496
+ if (!enabled) return;
497
+
498
+ var durations = self.durations.get(player);
499
+ const n = durations.confusion;
500
+ if (turns == 0) {
501
+ assert(n >= 2 and n <= 5);
502
+ if (n != 5) try self.probability.update(1, 6 - @as(u4, n));
503
+ durations.confusion = 0;
504
+ } else {
505
+ assert(n >= 1 and n < 5);
506
+ if (n > 1) try self.probability.update(6 - @as(u4, n) - 1, 6 - @as(u4, n));
507
+ durations.confusion += 1;
508
+ }
509
+ }
510
+
511
+ pub fn disable(self: *Self, player: Player, turns: u4) Error!void {
512
+ if (!enabled) return;
513
+
514
+ var durations = self.durations.get(player);
515
+ const n = durations.disable;
516
+ if (turns == 0) {
517
+ assert(n >= 1 and n <= 8);
518
+ if (n != 8) try self.probability.update(1, 9 - @as(u4, n));
519
+ durations.disable = 0;
520
+ } else {
521
+ assert(n >= 1 and n < 8);
522
+ try self.probability.update(9 - @as(u4, n) - 1, 9 - @as(u4, n));
523
+ durations.disable += 1;
524
+ }
525
+ }
526
+
527
+ pub fn attacking(self: *Self, player: Player, turns: u4) Error!void {
528
+ if (!enabled) return;
529
+
530
+ var durations = self.durations.get(player);
531
+ const n = durations.attacking;
532
+ if (turns == 0) {
533
+ assert(n >= 2 and n <= 3);
534
+ if (n != 3) try self.probability.update(1, 4 - @as(u4, n));
535
+ durations.attacking = 0;
536
+ } else {
537
+ assert(n >= 1 and n < 3);
538
+ if (n > 1) try self.probability.update(4 - @as(u4, n) - 1, 4 - @as(u4, n));
539
+ durations.attacking += 1;
540
+ }
541
+ }
542
+
543
+ pub fn binding(self: *Self, player: Player, turns: u4) Error!void {
544
+ if (!enabled) return;
545
+
546
+ var durations = self.durations.get(player);
547
+ const n = durations.binding;
548
+
549
+ assert(n > 0);
550
+ const p: u4 = if (n < 3) 3 else 1;
551
+ const q: u4 = if (n < 3) 8 - ((n - 1) * p) else 2;
552
+
553
+ if (turns == 0) {
554
+ assert(n >= 1 and n <= 4);
555
+ if (n != 4) try self.probability.update(p, q);
556
+ durations.binding = 0;
557
+ } else {
558
+ assert(n >= 1 and n < 4);
559
+ try self.probability.update(q - p, q);
560
+ durations.binding += 1;
561
+ }
562
+ }
563
+
564
+ pub fn psywave(self: *Self, player: Player, power: u8, max: u8) Error!void {
565
+ if (!enabled) return;
566
+
567
+ try self.probability.update(1, max);
568
+ self.actions.get(player).psywave = power + 1;
569
+ }
570
+
571
+ pub fn metronome(self: *Self, player: Player, move: Move) Error!void {
572
+ if (!enabled) return;
573
+
574
+ try self.probability.update(1, Move.METRONOME.len);
575
+ self.actions.get(player).metronome = move;
576
+ }
577
+ };
578
+ }
579
+
580
+ test "Chance.speedTie" {
581
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
582
+
583
+ try chance.speedTie(true);
584
+ try expectProbability(&chance.probability, 1, 2);
585
+ try expectValue(Optional(Player).P1, chance.actions.p1.speed_tie);
586
+ try expectValue(chance.actions.p1.speed_tie, chance.actions.p2.speed_tie);
587
+
588
+ chance.reset();
589
+
590
+ try chance.speedTie(false);
591
+ try expectProbability(&chance.probability, 1, 2);
592
+ try expectValue(Optional(Player).P2, chance.actions.p1.speed_tie);
593
+ try expectValue(chance.actions.p1.speed_tie, chance.actions.p2.speed_tie);
594
+ }
595
+
596
+ test "Chance.hit" {
597
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
598
+
599
+ try chance.hit(.P1, true, 229);
600
+ if (!showdown) {
601
+ try expectProbability(&chance.probability, 1, 1);
602
+ try expectValue(Optional(bool).None, chance.actions.p1.hit);
603
+
604
+ try chance.commit(.P1, .hit);
605
+ }
606
+ try expectValue(Optional(bool).true, chance.actions.p1.hit);
607
+ try expectProbability(&chance.probability, 229, 256);
608
+
609
+ chance.reset();
610
+
611
+ try chance.hit(.P2, false, 255);
612
+ if (!showdown) {
613
+ try expectProbability(&chance.probability, 1, 1);
614
+ try expectValue(Optional(bool).None, chance.actions.p2.hit);
615
+
616
+ try chance.commit(.P2, .miss);
617
+ }
618
+ try expectValue(Optional(bool).false, chance.actions.p2.hit);
619
+ try expectProbability(&chance.probability, 1, 256);
620
+ }
621
+
622
+ test "Chance.criticalHit" {
623
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
624
+
625
+ try chance.criticalHit(.P1, true, 17);
626
+ if (showdown) {
627
+ try expectValue(Optional(bool).true, chance.actions.p1.critical_hit);
628
+ try expectProbability(&chance.probability, 17, 256);
629
+ } else {
630
+ try expectProbability(&chance.probability, 1, 1);
631
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
632
+
633
+ try chance.hit(.P1, true, 128);
634
+
635
+ try expectProbability(&chance.probability, 1, 1);
636
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
637
+
638
+ try chance.damage(.P1, 217);
639
+
640
+ try expectProbability(&chance.probability, 1, 1);
641
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
642
+
643
+ try chance.commit(.P1, .hit);
644
+
645
+ try expectProbability(&chance.probability, 17, 19968); // (1/2) * (17/256) * (1/39)
646
+ try expectValue(Optional(bool).true, chance.actions.p1.critical_hit);
647
+ }
648
+
649
+ chance.reset();
650
+
651
+ try chance.criticalHit(.P2, false, 5);
652
+ if (showdown) {
653
+ try expectProbability(&chance.probability, 251, 256);
654
+ try expectValue(Optional(bool).false, chance.actions.p2.critical_hit);
655
+ } else {
656
+ try expectProbability(&chance.probability, 1, 1);
657
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
658
+
659
+ try chance.hit(.P1, true, 128);
660
+
661
+ try expectProbability(&chance.probability, 1, 1);
662
+ try expectValue(Optional(bool).None, chance.actions.p1.critical_hit);
663
+
664
+ try chance.damage(.P1, 217);
665
+ try chance.commit(.P1, .hit);
666
+
667
+ try expectProbability(&chance.probability, 251, 19968); // (1/2) * (251/256) * (1/39)
668
+ try expectValue(Optional(bool).false, chance.actions.p1.critical_hit);
669
+ }
670
+ }
671
+
672
+ test "Chance.damage" {
673
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
674
+
675
+ try chance.damage(.P1, 217);
676
+ if (showdown) {
677
+ try expectValue(217, chance.actions.p1.damage);
678
+ try expectProbability(&chance.probability, 1, 39);
679
+ } else {
680
+ try expectProbability(&chance.probability, 1, 1);
681
+ try expectValue(0, chance.actions.p1.damage);
682
+
683
+ try chance.commit(.P1, .hit);
684
+
685
+ try expectProbability(&chance.probability, 1, 39);
686
+ try expectValue(217, chance.actions.p1.damage);
687
+ }
688
+ }
689
+
690
+ test "Chance.secondaryChance" {
691
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
692
+
693
+ try chance.secondaryChance(.P1, true, 25);
694
+ try expectProbability(&chance.probability, 25, 256);
695
+ try expectValue(Optional(bool).true, chance.actions.p1.secondary_chance);
696
+
697
+ chance.reset();
698
+
699
+ try chance.secondaryChance(.P2, false, 77);
700
+ try expectProbability(&chance.probability, 179, 256);
701
+ try expectValue(Optional(bool).false, chance.actions.p2.secondary_chance);
702
+ }
703
+
704
+ test "Chance.confused" {
705
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
706
+
707
+ try chance.confused(.P1, false);
708
+ try expectProbability(&chance.probability, 1, 2);
709
+ try expectValue(Optional(bool).false, chance.actions.p1.confused);
710
+
711
+ chance.reset();
712
+
713
+ try chance.confused(.P2, true);
714
+ try expectProbability(&chance.probability, 1, 2);
715
+ try expectValue(Optional(bool).true, chance.actions.p2.confused);
716
+ }
717
+
718
+ test "Chance.paralyzed" {
719
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
720
+
721
+ try chance.paralyzed(.P1, false);
722
+ try expectProbability(&chance.probability, 3, 4);
723
+ try expectValue(Optional(bool).false, chance.actions.p1.paralyzed);
724
+
725
+ chance.reset();
726
+
727
+ try chance.paralyzed(.P2, true);
728
+ try expectProbability(&chance.probability, 1, 4);
729
+ try expectValue(Optional(bool).true, chance.actions.p2.paralyzed);
730
+ }
731
+
732
+ test "Chance.moveSlot" {
733
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
734
+ var ms = [_]MoveSlot{ .{ .id = Move.Surf }, .{ .id = Move.Psychic }, .{ .id = Move.Recover } };
735
+
736
+ try chance.moveSlot(.P2, 2, &ms, 2);
737
+ try expectProbability(&chance.probability, 1, 2);
738
+ try expectValue(2, chance.actions.p2.move_slot);
739
+
740
+ chance.reset();
741
+
742
+ try chance.moveSlot(.P1, 1, &ms, 0);
743
+ try expectProbability(&chance.probability, 1, 3);
744
+ try expectValue(1, chance.actions.p1.move_slot);
745
+ }
746
+
747
+ test "Chance.multiHit" {
748
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
749
+
750
+ try chance.multiHit(.P1, 3);
751
+ try expectProbability(&chance.probability, 3, 8);
752
+ try expectValue(3, chance.actions.p1.multi_hit);
753
+
754
+ chance.reset();
755
+
756
+ try chance.multiHit(.P2, 5);
757
+ try expectProbability(&chance.probability, 1, 8);
758
+ try expectValue(5, chance.actions.p2.multi_hit);
759
+ }
760
+
761
+ test "Chance.duration" {
762
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
763
+
764
+ chance.duration(.sleep, .P1, .P2, 2);
765
+ try expectValue(2, chance.actions.p1.duration);
766
+ try expectValue(1, chance.durations.p2.sleep);
767
+
768
+ chance.reset();
769
+
770
+ chance.duration(.binding, .P2, .P2, 4);
771
+ if (!showdown) {
772
+ try expectValue(0, chance.actions.p2.duration);
773
+ try expectValue(0, chance.durations.p2.binding);
774
+
775
+ try chance.commit(.P2, .hit);
776
+ }
777
+ try expectValue(4, chance.actions.p2.duration);
778
+ try expectValue(1, chance.durations.p2.binding);
779
+ }
780
+
781
+ test "Chance.sleep" {
782
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
783
+
784
+ for ([_]u8{ 7, 6, 5, 4, 3, 2, 1 }, 1..8) |d, i| {
785
+ chance.durations.p1.sleep = @intCast(i);
786
+ try chance.sleep(.P1, 0);
787
+ try expectProbability(&chance.probability, 1, d);
788
+ try expectValue(0, chance.durations.p1.sleep);
789
+
790
+ chance.reset();
791
+
792
+ if (i < 7) {
793
+ chance.durations.p1.sleep = @intCast(i);
794
+ try chance.sleep(.P1, 1);
795
+ try expectProbability(&chance.probability, d - 1, d);
796
+ try expectValue(@as(u3, @intCast(i)) + 1, chance.durations.p1.sleep);
797
+
798
+ chance.reset();
799
+ }
800
+ }
801
+ }
802
+
803
+ test "Chance.confusion" {
804
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
805
+
806
+ for ([_]u8{ 1, 4, 3, 2, 1 }, 1..6) |d, i| {
807
+ if (i > 1) {
808
+ chance.durations.p2.confusion = @intCast(i);
809
+ try chance.confusion(.P2, 0);
810
+ try expectProbability(&chance.probability, 1, d);
811
+ try expectValue(0, chance.durations.p2.confusion);
812
+
813
+ chance.reset();
814
+ }
815
+
816
+ if (i < 5) {
817
+ chance.durations.p2.confusion = @intCast(i);
818
+ try chance.confusion(.P2, 1);
819
+ try expectProbability(&chance.probability, if (d > 1) d - 1 else d, d);
820
+ try expectValue(@as(u3, @intCast(i)) + 1, chance.durations.p2.confusion);
821
+
822
+ chance.reset();
823
+ }
824
+ }
825
+ }
826
+
827
+ test "Chance.disable" {
828
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
829
+
830
+ for ([_]u8{ 8, 7, 6, 5, 4, 3, 2, 1 }, 1..9) |d, i| {
831
+ chance.durations.p1.disable = @intCast(i);
832
+ try chance.disable(.P1, 0);
833
+ try expectProbability(&chance.probability, 1, d);
834
+ try expectValue(0, chance.durations.p1.disable);
835
+
836
+ chance.reset();
837
+
838
+ if (i < 8) {
839
+ chance.durations.p1.disable = @intCast(i);
840
+ try chance.disable(.P1, 1);
841
+ try expectProbability(&chance.probability, d - 1, d);
842
+ try expectValue(@as(u4, @intCast(i)) + 1, chance.durations.p1.disable);
843
+
844
+ chance.reset();
845
+ }
846
+ }
847
+ }
848
+
849
+ test "Chance.attacking" {
850
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
851
+
852
+ for ([_]u8{ 1, 2, 1 }, 1..4) |d, i| {
853
+ if (i > 1) {
854
+ chance.durations.p2.attacking = @intCast(i);
855
+ try chance.attacking(.P2, 0);
856
+ try expectProbability(&chance.probability, 1, d);
857
+ try expectValue(0, chance.durations.p2.attacking);
858
+
859
+ chance.reset();
860
+ }
861
+
862
+ if (i < 3) {
863
+ chance.durations.p2.attacking = @intCast(i);
864
+ try chance.attacking(.P2, 1);
865
+ try expectProbability(&chance.probability, if (d > 1) d - 1 else d, d);
866
+ try expectValue(@as(u3, @intCast(i)) + 1, chance.durations.p2.attacking);
867
+
868
+ chance.reset();
869
+ }
870
+ }
871
+ }
872
+
873
+ test "Chance.binding" {
874
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
875
+
876
+ const ps = [_]u8{ 3, 3, 1, 1 };
877
+ const qs = [_]u8{ 8, 5, 2, 1 };
878
+
879
+ for (ps, qs, 1..5) |p, q, i| {
880
+ chance.durations.p1.binding = @intCast(i);
881
+ try chance.binding(.P1, 0);
882
+ try expectProbability(&chance.probability, p, q);
883
+ try expectValue(0, chance.durations.p1.binding);
884
+
885
+ chance.reset();
886
+
887
+ if (i < 4) {
888
+ chance.durations.p1.binding = @intCast(i);
889
+ try chance.binding(.P1, 1);
890
+ try expectProbability(&chance.probability, q - p, q);
891
+ try expectValue(@as(u3, @intCast(i)) + 1, chance.durations.p1.binding);
892
+
893
+ chance.reset();
894
+ }
895
+ }
896
+ }
897
+
898
+ test "Chance.psywave" {
899
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
900
+
901
+ try chance.psywave(.P2, 100, 150);
902
+ try expectProbability(&chance.probability, 1, 150);
903
+ try expectValue(101, chance.actions.p2.psywave);
904
+ }
905
+
906
+ test "Chance.metronome" {
907
+ var chance: Chance(rational.Rational(u64)) = .{ .probability = .{} };
908
+
909
+ try chance.metronome(.P1, Move.HornAttack);
910
+ try expectProbability(&chance.probability, 1, 163);
911
+ try expectValue(Move.HornAttack, chance.actions.p1.metronome);
912
+ }
913
+
914
+ pub fn expectProbability(r: anytype, p: u64, q: u64) !void {
915
+ if (!enabled) return;
916
+
917
+ r.reduce();
918
+ if (r.p != p or r.q != q) {
919
+ print("expected {d}/{d}, found {}\n", .{ p, q, r });
920
+ return error.TestExpectedEqual;
921
+ }
922
+ }
923
+
924
+ pub fn expectValue(a: anytype, b: anytype) !void {
925
+ if (!enabled) return;
926
+
927
+ try expectEqual(a, b);
928
+ }
929
+
930
+ /// Null object pattern implementation of Generation I `Chance` which does nothing, though chance
931
+ /// tracking should additionally be turned off entirely via `options.chance`.
932
+ pub const NULL: Null = .{};
933
+
934
+ const Null = struct {
935
+ pub const Error = error{};
936
+
937
+ pub fn commit(self: Null, player: Player, kind: Commit) Error!void {
938
+ _ = .{ self, player, kind };
939
+ }
940
+
941
+ pub fn clearPending(self: Null) void {
942
+ _ = .{self};
943
+ }
944
+
945
+ pub fn clearDurations(self: Null, player: Player, haze: ?bool) void {
946
+ _ = .{ self, player, haze };
947
+ }
948
+
949
+ pub fn switched(self: Null, player: Player, in: u8, out: u8) void {
950
+ _ = .{ self, player, in, out };
951
+ }
952
+
953
+ pub fn speedTie(self: Null, p1: bool) Error!void {
954
+ _ = .{ self, p1 };
955
+ }
956
+
957
+ pub fn hit(self: Null, player: Player, ok: bool, accuracy: uN) Error!void {
958
+ _ = .{ self, player, ok, accuracy };
959
+ }
960
+
961
+ pub fn criticalHit(self: Null, player: Player, crit: bool, rate: u8) Error!void {
962
+ _ = .{ self, player, crit, rate };
963
+ }
964
+
965
+ pub fn damage(self: Null, player: Player, roll: u8) Error!void {
966
+ _ = .{ self, player, roll };
967
+ }
968
+
969
+ pub fn confused(self: Null, player: Player, ok: bool) Error!void {
970
+ _ = .{ self, player, ok };
971
+ }
972
+
973
+ pub fn paralyzed(self: Null, player: Player, ok: bool) Error!void {
974
+ _ = .{ self, player, ok };
975
+ }
976
+
977
+ pub fn secondaryChance(self: Null, player: Player, proc: bool, rate: u8) Error!void {
978
+ _ = .{ self, player, proc, rate };
979
+ }
980
+
981
+ pub fn moveSlot(self: Null, player: Player, slot: u4, ms: []const MoveSlot, n: u4) Error!void {
982
+ _ = .{ self, player, slot, ms, n };
983
+ }
984
+
985
+ pub fn multiHit(self: Null, player: Player, n: u3) Error!void {
986
+ _ = .{ self, player, n };
987
+ }
988
+
989
+ pub fn duration(
990
+ self: Null,
991
+ comptime field: Duration.Field,
992
+ player: Player,
993
+ target: Player,
994
+ turns: u4,
995
+ ) void {
996
+ _ = .{ self, field, player, target, turns };
997
+ }
998
+
999
+ pub fn sleep(self: Null, player: Player, turns: u4) Error!void {
1000
+ _ = .{ self, player, turns };
1001
+ }
1002
+
1003
+ pub fn disable(self: Null, player: Player, turns: u4) Error!void {
1004
+ _ = .{ self, player, turns };
1005
+ }
1006
+
1007
+ pub fn confusion(self: Null, player: Player, turns: u4) Error!void {
1008
+ _ = .{ self, player, turns };
1009
+ }
1010
+
1011
+ pub fn attacking(self: Null, player: Player, turns: u4) Error!void {
1012
+ _ = .{ self, player, turns };
1013
+ }
1014
+
1015
+ pub fn binding(self: Null, player: Player, turns: u4) Error!void {
1016
+ _ = .{ self, player, turns };
1017
+ }
1018
+
1019
+ pub fn psywave(self: Null, player: Player, power: u8, max: u8) Error!void {
1020
+ _ = .{ self, player, power, max };
1021
+ }
1022
+
1023
+ pub fn metronome(self: Null, player: Player, move: Move) Error!void {
1024
+ _ = .{ self, player, move };
1025
+ }
1026
+ };