@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,598 @@
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
+
21
+ const enabled = pkmn.options.calc;
22
+
23
+ const Player = common.Player;
24
+ const Result = common.Result;
25
+ const Choice = common.Choice;
26
+
27
+ const Optional = optional.Optional;
28
+
29
+ const Rational = rational.Rational;
30
+
31
+ const PointerType = util.PointerType;
32
+
33
+ const Actions = chance.Actions;
34
+ const Action = chance.Action;
35
+ const Chance = chance.Chance;
36
+ const Durations = chance.Durations;
37
+ const Duration = chance.Duration;
38
+
39
+ const Rolls = helpers.Rolls;
40
+
41
+ const tty = true; // DEBUG
42
+ const summary = false; // DEBUG
43
+
44
+ /// Information relevant to damage calculation that occured during a Generation I battle `update`.
45
+ pub const Summaries = extern struct {
46
+ /// Relevant information for Player 1.
47
+ p1: Summary = .{},
48
+ /// Relevant information for Player 2.
49
+ p2: Summary = .{},
50
+
51
+ comptime {
52
+ assert(@sizeOf(Summaries) == 12);
53
+ }
54
+
55
+ /// Returns the `Summary` for the given `player`.
56
+ pub fn get(self: anytype, player: Player) PointerType(@TypeOf(self), Summary) {
57
+ assert(@typeInfo(@TypeOf(self)).Pointer.child == Summaries);
58
+ return if (player == .P1) &self.p1 else &self.p2;
59
+ }
60
+ };
61
+
62
+ /// Information relevant to damage calculation that occured during a Generation I battle `update`
63
+ /// for a single player.
64
+ pub const Summary = extern struct {
65
+ /// The computed raw damage values.
66
+ damage: Damage = .{},
67
+
68
+ /// Intermediate raw damage values computed during a calculation.
69
+ pub const Damage = extern struct {
70
+ /// The base computed damage before the damage roll is applied.
71
+ base: u16 = 0,
72
+ /// The final computed damage that gets applied to the Pokémon. May exceed the target's HP
73
+ // (to determine the *actual* damage done compare the target's stored HP before and after).
74
+ final: u16 = 0,
75
+ /// Whether higher direct damage will saturate / result in the same outcome (e.g. additional
76
+ /// direct damage gets ignored due to it already breaking a Substitute or causing the target
77
+ /// to faint). Note that this field does not get set in scenarios where the target would
78
+ /// only be guaranteed to faint due to some sort of subsequent recoil or residual damage.
79
+ capped: bool = false,
80
+
81
+ // NOTE: 15 bits padding
82
+
83
+ comptime {
84
+ assert(@sizeOf(Damage) == 6);
85
+ }
86
+ };
87
+
88
+ comptime {
89
+ assert(@sizeOf(Summary) == 6);
90
+ }
91
+ };
92
+
93
+ /// TODO
94
+ pub const Overrides = extern struct {
95
+ /// TODO
96
+ actions: Actions = .{},
97
+ /// TODO
98
+ durations: Durations = .{},
99
+
100
+ _: u32 = 0,
101
+
102
+ comptime {
103
+ assert(@sizeOf(Overrides) == 24);
104
+ }
105
+ };
106
+
107
+ /// Allows for forcing the value of specific RNG events during a Generation I battle `update` via
108
+ /// `overrides` and tracks `summaries` of information relevant to damage calculation.
109
+ pub const Calc = struct {
110
+ /// Overrides the normal behavior of the RNG during an `update` to force specific outcomes.
111
+ overrides: Overrides = .{},
112
+ /// Information relevant to damage calculation.
113
+ summaries: Summaries = .{},
114
+
115
+ pub fn overridden(
116
+ self: Calc,
117
+ player: Player,
118
+ comptime field: Action.Field,
119
+ ) ?std.meta.FieldType(Action, field) {
120
+ if (!enabled) return null;
121
+
122
+ const overrides =
123
+ if (player == .P1) self.overrides.actions.p1 else self.overrides.actions.p2;
124
+ const val = @field(overrides, @tagName(field));
125
+ return if (switch (@typeInfo(@TypeOf(val))) {
126
+ .Enum => val != .None,
127
+ .Int => val != 0,
128
+ else => unreachable,
129
+ }) val else null;
130
+ }
131
+
132
+ pub fn modify(self: Calc, player: Player, comptime field: Duration.Field) ?bool {
133
+ if (!enabled) return null;
134
+
135
+ const durations = self.overrides.durations;
136
+ const set = @field(if (player == .P1) durations.p1 else durations.p2, @tagName(field));
137
+ if (set == 0) return null;
138
+
139
+ return null; // TODO
140
+ }
141
+
142
+ pub fn base(self: *Calc, player: Player, val: u16) void {
143
+ if (!enabled) return;
144
+
145
+ self.summaries.get(player).damage.base = val;
146
+ }
147
+
148
+ pub fn final(self: *Calc, player: Player, val: u16) void {
149
+ if (!enabled) return;
150
+
151
+ self.summaries.get(player).damage.final = val;
152
+ }
153
+
154
+ pub fn capped(self: *Calc, player: Player) void {
155
+ if (!enabled) return;
156
+
157
+ self.summaries.get(player).damage.capped = true;
158
+ }
159
+ };
160
+
161
+ /// Null object pattern implementation of Generation I `Calc` which does nothing, though damage
162
+ /// calculator support should additionally be turned off entirely via `options.calc`.
163
+ pub const NULL: Null = .{};
164
+
165
+ const Null = struct {
166
+ pub fn overridden(
167
+ self: Null,
168
+ player: Player,
169
+ comptime field: Action.Field,
170
+ ) ?std.meta.FieldType(Action, field) {
171
+ _ = .{ self, player };
172
+ return null;
173
+ }
174
+
175
+ pub fn modify(self: Null, player: Player, comptime field: Duration.Field) ?bool {
176
+ _ = .{ self, player, field };
177
+ return null;
178
+ }
179
+
180
+ pub fn base(self: Null, player: Player, val: u16) void {
181
+ _ = .{ self, player, val };
182
+ }
183
+
184
+ pub fn final(self: Null, player: Player, val: u16) void {
185
+ _ = .{ self, player, val };
186
+ }
187
+
188
+ pub fn capped(self: Null, player: Player) void {
189
+ _ = .{ self, player };
190
+ }
191
+ };
192
+
193
+ pub const Stats = struct {
194
+ frontier: usize = 0,
195
+ updates: usize = 0,
196
+ seen: usize = 0,
197
+ saved: usize = 0,
198
+ };
199
+
200
+ pub const Options = struct {
201
+ actions: Actions = .{},
202
+ durations: Durations = .{},
203
+ seed: ?u64 = null,
204
+ cap: bool = false,
205
+ metronome: bool = false,
206
+ };
207
+
208
+ pub const MAX_FRONTIER = 19;
209
+
210
+ const Element = struct {
211
+ actions: Actions,
212
+ durations: Durations,
213
+ };
214
+
215
+ pub fn transitions(
216
+ battle: anytype,
217
+ c1: Choice,
218
+ c2: Choice,
219
+ allocator: std.mem.Allocator,
220
+ writer: anytype,
221
+ options: Options,
222
+ ) !?Stats {
223
+ var stats: Stats = .{};
224
+
225
+ const actions = options.actions;
226
+ const durations = options.durations;
227
+ const cap = options.cap;
228
+
229
+ var seen = std.AutoHashMap(Actions, void).init(allocator);
230
+ defer seen.deinit();
231
+ var frontier = std.ArrayList(Element).init(allocator);
232
+ defer frontier.deinit();
233
+
234
+ var opts = pkmn.battle.options(
235
+ protocol.NULL,
236
+ Chance(Rational(u128)){ .probability = .{}, .actions = actions, .durations = durations },
237
+ Calc{ .overrides = .{ .actions = actions, .durations = durations } },
238
+ );
239
+
240
+ var b = battle;
241
+ _ = try b.update(c1, c2, &opts);
242
+ stats.updates += 1;
243
+
244
+ const p1 = b.side(.P1);
245
+ const p2 = b.side(.P2);
246
+
247
+ var p: Rational(u128) = .{ .p = 0, .q = 1 };
248
+ try frontier.append(.{ .actions = opts.chance.actions, .durations = opts.chance.durations });
249
+
250
+ // zig fmt: off
251
+ for (Rolls.metronome(frontier.items[0].actions.p1)) |p1_move| {
252
+ for (Rolls.metronome(frontier.items[0].actions.p2)) |p2_move| {
253
+
254
+ if (!options.metronome and (p1_move != .None or p2_move != .None)) return null;
255
+
256
+ var i: usize = 0;
257
+ assert(frontier.items.len == 1);
258
+ while (i < frontier.items.len) : (i += 1) {
259
+ const template = frontier.items[i];
260
+
261
+ try debug(writer, template.actions, .{
262
+ .shape = true,
263
+ .color = i,
264
+ .bold = true,
265
+ .background = true,
266
+ .indent = false,
267
+ });
268
+
269
+ var a: Actions = .{ .p1 = .{ .metronome = p1_move }, .p2 = .{ .metronome = p2_move } };
270
+ var d: Durations = .{};
271
+
272
+ for (Rolls.speedTie(template.actions.p1)) |tie| { a.p1.speed_tie = tie; a.p2.speed_tie = tie;
273
+ for (Rolls.sleep(template.durations.p1, durations.p1)) |p1_slp| { d.p1.sleep = p1_slp;
274
+ for (Rolls.sleep(template.durations.p2, durations.p2)) |p2_slp| { d.p2.sleep = p2_slp;
275
+ for (Rolls.disable(template.durations.p1, durations.p1, p1_slp)) |p1_disable| { d.p1.disable = p1_disable;
276
+ for (Rolls.disable(template.durations.p2, durations.p2, p2_slp)) |p2_disable| { d.p2.disable = p2_disable;
277
+ for (Rolls.confusion(template.durations.p1, durations.p1, p1_slp)) |p1_cfz| { d.p1.confusion = p1_cfz;
278
+ for (Rolls.confusion(template.durations.p2, durations.p2, p1_slp)) |p2_cfz| { d.p2.confusion = p2_cfz;
279
+ for (Rolls.confused(template.actions.p1, p1_cfz)) |p1_cfzd| { a.p1.confused = p1_cfzd;
280
+ for (Rolls.confused(template.actions.p2, p2_cfz)) |p2_cfzd| { a.p2.confused = p2_cfzd;
281
+ for (Rolls.paralyzed(template.actions.p1, p1_cfzd)) |p1_par| { a.p1.paralyzed = p1_par;
282
+ for (Rolls.paralyzed(template.actions.p2, p2_cfzd)) |p2_par| { a.p2.paralyzed = p2_par;
283
+ for (Rolls.attacking(template.durations.p1, durations.p1, p1_par)) |p1_atk| { d.p1.attacking = p1_atk;
284
+ for (Rolls.attacking(template.durations.p2, durations.p2, p2_par)) |p2_atk| { d.p2.attacking = p2_atk;
285
+ for (Rolls.binding(template.durations.p1, durations.p1, p1_par)) |p1_bind| { d.p1.binding = p1_bind;
286
+ for (Rolls.binding(template.durations.p2, durations.p2, p2_par)) |p2_bind| { d.p2.binding = p2_bind;
287
+ for (Rolls.duration(template.actions.p1, p1_par)) |p1_dur| { a.p1.duration = p1_dur;
288
+ for (Rolls.duration(template.actions.p2, p2_par)) |p2_dur| { a.p2.duration = p2_dur;
289
+ for (Rolls.hit(template.actions.p1, p1_par)) |p1_hit| { a.p1.hit = p1_hit;
290
+ for (Rolls.hit(template.actions.p2, p2_par)) |p2_hit| { a.p2.hit = p2_hit;
291
+ for (Rolls.psywave(template.actions.p1, p1, p1_hit)) |p1_psywave| { a.p1.psywave = p1_psywave;
292
+ for (Rolls.psywave(template.actions.p2, p2, p2_hit)) |p2_psywave| { a.p2.psywave = p2_psywave;
293
+ for (Rolls.moveSlot(template.actions.p1, p1_hit)) |p1_slot| { a.p1.move_slot = p1_slot;
294
+ for (Rolls.moveSlot(template.actions.p2, p2_hit)) |p2_slot| { a.p2.move_slot = p2_slot;
295
+ for (Rolls.multiHit(template.actions.p1, p1_hit)) |p1_multi| { a.p1.multi_hit = p1_multi;
296
+ for (Rolls.multiHit(template.actions.p2, p2_hit)) |p2_multi| { a.p2.multi_hit = p2_multi;
297
+ for (Rolls.secondaryChance(template.actions.p1, p1_hit)) |p1_sec| { a.p1.secondary_chance = p1_sec;
298
+ for (Rolls.secondaryChance(template.actions.p2, p2_hit)) |p2_sec| { a.p2.secondary_chance = p2_sec;
299
+ for (Rolls.criticalHit(template.actions.p1, p1_hit)) |p1_crit| { a.p1.critical_hit = p1_crit;
300
+ for (Rolls.criticalHit(template.actions.p2, p2_hit)) |p2_crit| { a.p2.critical_hit = p2_crit;
301
+
302
+ var p1_dmg = Rolls.damage(template.actions.p1, p1_hit);
303
+ while (p1_dmg.min < p1_dmg.max) : (p1_dmg.min += 1) {
304
+ a.p1.damage = @intCast(p1_dmg.min);
305
+
306
+ var p2_dmg = Rolls.damage(template.actions.p2, p2_hit);
307
+
308
+ const p1_min: u9 = p1_dmg.min;
309
+ const p2_min: u9 = p2_dmg.min;
310
+
311
+ while (p2_dmg.min < p2_dmg.max) : (p2_dmg.min += 1) {
312
+ a.p2.damage = @intCast(p2_dmg.min);
313
+
314
+ opts.calc.overrides.actions = a;
315
+ opts.calc.summaries = .{};
316
+ opts.chance = .{ .probability = .{}, .actions = actions };
317
+ const q = &opts.chance.probability;
318
+
319
+ b = battle;
320
+ _ = try b.update(c1, c2, &opts);
321
+ stats.updates += 1;
322
+
323
+ const summaries = &opts.calc.summaries;
324
+ const p1_max: u9 = if (p2_dmg.min != p2_min)
325
+ p1_dmg.min
326
+ else
327
+ try Rolls.coalesce(.P1, @as(u8, @intCast(p1_dmg.min)), summaries, cap);
328
+ const p2_max: u9 =
329
+ try Rolls.coalesce(.P2, @as(u8, @intCast(p2_dmg.min)), summaries, cap);
330
+
331
+ if (opts.chance.actions.matches(template.actions)) {
332
+ if (!opts.chance.actions.eql(a)) {
333
+ if (!summary) {
334
+ try debug(writer, opts.chance.actions, .{
335
+ .p1_max = p1_max,
336
+ .p2_max = p2_max,
337
+ .color = i,
338
+ .dim = true,
339
+ });
340
+ }
341
+
342
+ p1_dmg.min = p1_max;
343
+ p2_dmg.min = p2_max;
344
+ continue;
345
+ }
346
+
347
+ if (!summary) {
348
+ try debug(writer, opts.chance.actions, .{
349
+ .p1_max = p1_max,
350
+ .p2_max = p2_max,
351
+ .color = i,
352
+ });
353
+ }
354
+
355
+ for (p1_min..p1_max + 1) |p1d| {
356
+ for (p2_dmg.min..p2_max + 1) |p2d| {
357
+ var acts = opts.chance.actions;
358
+ acts.p1.damage = @intCast(p1d);
359
+ acts.p2.damage = @intCast(p2d);
360
+ if ((try seen.getOrPut(acts)).found_existing) {
361
+ err("already seen {}", .{acts}, options.seed);
362
+ return error.TestUnexpectedResult;
363
+ }
364
+ }
365
+ }
366
+
367
+ if (p1_max != p1_min) try q.update(p1_max - p1_min + 1, 1);
368
+ if (p2_max != p2_dmg.min) try q.update(p2_max - p2_dmg.min + 1, 1);
369
+ try p.add(q);
370
+ stats.saved += 1;
371
+
372
+ if (p.q < p.p) {
373
+ err("improper fraction {}", .{p}, options.seed);
374
+ return error.TestUnexpectedResult;
375
+ }
376
+ } else {
377
+ if (!matches(opts.chance.actions, i, frontier.items)) {
378
+ try frontier.append(.{
379
+ .actions = opts.chance.actions,
380
+ .durations = opts.chance.durations,
381
+ });
382
+
383
+ try debug(writer, opts.chance.actions, .{
384
+ .p1_max = p1_max,
385
+ .p2_max = p2_max,
386
+ .dim = true,
387
+ .newline = false,
388
+ });
389
+ try writer.writeAll(" → ");
390
+ try debug(writer, opts.chance.actions, .{
391
+ .shape = true,
392
+ .color = frontier.items.len - 1,
393
+ .dim = true,
394
+ .background = true,
395
+ .indent = false,
396
+ });
397
+ } else if (!summary) {
398
+ try debug(writer, opts.chance.actions, .{
399
+ .p1_max = p1_max,
400
+ .p2_max = p2_max,
401
+ .dim = true,
402
+ });
403
+ }
404
+ }
405
+
406
+ p1_dmg.min = p1_max;
407
+ p2_dmg.min = p2_max;
408
+ }
409
+
410
+ }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
411
+
412
+ if (@TypeOf(writer) != @TypeOf(std.io.null_writer)) {
413
+ p.reduce();
414
+ try writer.print(
415
+ " = {s} ({d:.2}%)\n\n",
416
+ .{p, 100 * @as(f128, @floatFromInt(p.p)) / @as(f128, @floatFromInt(p.q))},
417
+ );
418
+ }
419
+
420
+ }
421
+
422
+ assert(frontier.items.len == i);
423
+ stats.frontier = @max(stats.frontier, i);
424
+ frontier.shrinkRetainingCapacity(1);
425
+
426
+ }}
427
+ // zig fmt: on
428
+
429
+ stats.seen = seen.count();
430
+
431
+ p.reduce();
432
+ if (p.p != 1 or p.q != 1) {
433
+ err("expected 1, found {}", .{p}, options.seed);
434
+ return error.TestExpectedEqual;
435
+ }
436
+
437
+ return stats;
438
+ }
439
+
440
+ pub fn update(
441
+ battle: anytype,
442
+ c1: Choice,
443
+ c2: Choice,
444
+ options: anytype,
445
+ allocator: std.mem.Allocator,
446
+ writer: anytype,
447
+ transition: bool,
448
+ ) !Result {
449
+ options.chance.reset();
450
+
451
+ if (!pkmn.options.chance or !pkmn.options.calc or @TypeOf(battle.rng) != data.PRNG) {
452
+ return battle.update(c1, c2, options);
453
+ }
454
+
455
+ var copy = battle.*;
456
+ const actions = options.chance.actions;
457
+
458
+ // Perfom the actual update
459
+ const result = battle.update(c1, c2, options);
460
+
461
+ // Ensure we can encode the diffs in less than MAX_DIFFS bytes.
462
+ var buf: [helpers.MAX_DIFFS]u8 = undefined;
463
+ var stream: protocol.ByteStream = .{ .buffer = &buf };
464
+ const n = try helpers.diff(&copy, battle, stream.writer());
465
+
466
+ // Applying the diff to the battle should take us back to the original copy
467
+ // of the battle (ignoring the RNG).
468
+ var patched = battle.*;
469
+ patched.rng = copy.rng;
470
+ helpers.patch(&patched, buf[0..n]);
471
+ try expectEqual(copy, patched);
472
+
473
+ if (!pkmn.options.chance or !pkmn.options.calc) return result;
474
+
475
+ if (transition) {
476
+ // Ensure we can generate all transitions from the same original state
477
+ // (we must change the battle's RNG from a FixedRNG to a PRNG because
478
+ // the transitions function relies on RNG for discovery of states)
479
+ if (try transitions(unfix(copy), c1, c2, allocator, writer, .{
480
+ .actions = actions,
481
+ .cap = true,
482
+ })) |stats| try expect(stats.frontier <= MAX_FRONTIER);
483
+ }
484
+
485
+ // Demonstrate that we can produce the same state by forcing the RNG to behave the
486
+ // same as we observed - note that because we do not pass in a durations override
487
+ // mask none of the durations will be extended.
488
+ var override = pkmn.battle.options(
489
+ protocol.NULL,
490
+ chance.NULL,
491
+ Calc{ .overrides = .{ .actions = actions } },
492
+ );
493
+ const overridden = copy.update(c1, c2, &override);
494
+ try expectEqual(result, overridden);
495
+
496
+ // The actual battle excluding its RNG field should match a copy updated with
497
+ // overridden RNG (the copy RNG may have advanced because of no-ops)
498
+ copy.rng = battle.rng;
499
+ try expectEqual(copy, battle.*);
500
+
501
+ return result;
502
+ }
503
+
504
+ fn unfix(actual: anytype) data.Battle(data.PRNG) {
505
+ return .{
506
+ .sides = actual.sides,
507
+ .turn = actual.turn,
508
+ .last_damage = actual.last_damage,
509
+ .last_moves = actual.last_moves,
510
+ .rng = .{ .src = .{
511
+ .seed = if (pkmn.options.showdown)
512
+ 0x12345678
513
+ else
514
+ .{ 123, 234, 56, 78, 9, 101, 112, 131, 4 },
515
+ } },
516
+ };
517
+ }
518
+
519
+ fn matches(actions: Actions, i: usize, frontier: []Element) bool {
520
+ for (frontier, 0..) |f, j| {
521
+ // TODO: is skipping this redundant check worth it?
522
+ if (i == j) continue;
523
+ if (f.actions.matches(actions)) return true;
524
+ }
525
+ return false;
526
+ }
527
+
528
+ fn err(comptime fmt: []const u8, v: anytype, seed: ?u64) void {
529
+ const w = std.io.getStdErr().writer();
530
+ w.print(fmt, v) catch return;
531
+ if (seed) |s| return w.print("{}\n", .{s}) catch return;
532
+ return w.writeByte('\n') catch return;
533
+ }
534
+
535
+ const Style = struct {
536
+ shape: bool = false,
537
+ p1_max: u9 = 0,
538
+ p2_max: u9 = 0,
539
+ color: ?usize = null,
540
+ bold: bool = false,
541
+ background: bool = false,
542
+ dim: bool = false,
543
+ newline: bool = true,
544
+ indent: bool = true,
545
+ };
546
+
547
+ fn debug(writer: anytype, actions: Actions, style: Style) !void {
548
+ if (style.indent) try writer.writeAll(" ");
549
+ if (tty) {
550
+ const mod: usize = if (style.dim) 2 else 1;
551
+ const background: usize = if (style.background) 4 else 3;
552
+ const color: usize = if (style.color) |c| (c % 6) + 1 else 7;
553
+
554
+ if (style.dim or style.bold) try writer.print("\x1b[{d}m", .{mod});
555
+ try writer.print("\x1b[{d}{d}m", .{ background, color });
556
+ const p1 = if (style.p1_max != 0 and style.p1_max != actions.p1.damage) style.p1_max else 0;
557
+ const p2 = if (style.p2_max != 0 and style.p2_max != actions.p2.damage) style.p2_max else 0;
558
+ if (p1 != 0 or p2 != 0) {
559
+ assert(!style.shape);
560
+ try format(writer, actions, p1, p2);
561
+ } else {
562
+ try actions.fmt(writer, style.shape);
563
+ }
564
+ try writer.writeAll("\x1b[0m");
565
+ } else {
566
+ if (style.dim) try writer.writeAll(" ");
567
+ try actions.fmt(writer, style.shape);
568
+ }
569
+ if (style.newline) try writer.writeByte('\n');
570
+ }
571
+
572
+ fn format(writer: anytype, actions: Actions, p1: u9, p2: u9) !void {
573
+ var input: [1024]u8 = undefined;
574
+ var output: [1024]u8 = undefined;
575
+
576
+ var stream = std.io.fixedBufferStream(&input);
577
+ try actions.fmt(&stream.writer(), false);
578
+ var len = stream.getWritten().len;
579
+ @memcpy(output[0..len], input[0..len]);
580
+
581
+ var find: [16]u8 = undefined;
582
+ var repl: [22]u8 = undefined;
583
+ if (p1 != 0 and actions.p1.damage != 0) {
584
+ const n = try std.fmt.bufPrint(&find, "P1 = (damage:{d}", .{actions.p1.damage});
585
+ const r = try std.fmt.bufPrint(&repl, "P1 = (damage:{d}…{d}", .{ actions.p1.damage, p1 });
586
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
587
+ @memcpy(input[0 .. len + 6], output[0 .. len + 6]);
588
+ len += 6;
589
+ }
590
+ if (p2 != 0 and actions.p2.damage != 0) {
591
+ const n = try std.fmt.bufPrint(&find, "P2 = (damage:{d}", .{actions.p2.damage});
592
+ const r = try std.fmt.bufPrint(&repl, "P2 = (damage:{d}…{d}", .{ actions.p2.damage, p2 });
593
+ assert(std.mem.replace(u8, input[0..len], n, r, output[0 .. len + 6]) == 1);
594
+ len += 6;
595
+ }
596
+
597
+ try writer.writeAll(output[0..len]);
598
+ }