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