@pkmn/engine 0.1.0-dev.00879b8b

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 (60) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +368 -0
  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 +240 -0
  7. package/build/pkg/data/layout.json +108 -0
  8. package/build/pkg/data/protocol.json +230 -0
  9. package/build/pkg/data.d.ts +91 -0
  10. package/build/pkg/data.js +150 -0
  11. package/build/pkg/data.js.map +1 -0
  12. package/build/pkg/gen1.d.ts +110 -0
  13. package/build/pkg/gen1.js +684 -0
  14. package/build/pkg/gen1.js.map +1 -0
  15. package/build/pkg/index.d.ts +387 -0
  16. package/build/pkg/index.js +122 -0
  17. package/build/pkg/index.js.map +1 -0
  18. package/build/pkg/protocol.d.ts +73 -0
  19. package/build/pkg/protocol.js +473 -0
  20. package/build/pkg/protocol.js.map +1 -0
  21. package/build/test/display.js +400 -0
  22. package/build/test/display.js.map +1 -0
  23. package/build/tools/debug.js +134 -0
  24. package/build/tools/debug.js.map +1 -0
  25. package/build.zig +363 -0
  26. package/package.json +232 -0
  27. package/src/bin/install-pkmn-engine +404 -0
  28. package/src/bin/pkmn-debug +62 -0
  29. package/src/lib/common/battle.zig +17 -0
  30. package/src/lib/common/data.zig +117 -0
  31. package/src/lib/common/debug.zig +74 -0
  32. package/src/lib/common/js.zig +118 -0
  33. package/src/lib/common/optional.zig +67 -0
  34. package/src/lib/common/options.zig +51 -0
  35. package/src/lib/common/protocol.zig +1836 -0
  36. package/src/lib/common/rational.zig +357 -0
  37. package/src/lib/common/rng.zig +243 -0
  38. package/src/lib/common/util.zig +12 -0
  39. package/src/lib/gen1/calc.zig +507 -0
  40. package/src/lib/gen1/chance.zig +1063 -0
  41. package/src/lib/gen1/data/moves.zig +1866 -0
  42. package/src/lib/gen1/data/species.zig +1105 -0
  43. package/src/lib/gen1/data/types.zig +131 -0
  44. package/src/lib/gen1/data.zig +634 -0
  45. package/src/lib/gen1/helpers.zig +866 -0
  46. package/src/lib/gen1/mechanics.zig +3156 -0
  47. package/src/lib/gen2/calc.zig +143 -0
  48. package/src/lib/gen2/chance.zig +1315 -0
  49. package/src/lib/gen2/data/items.zig +230 -0
  50. package/src/lib/gen2/data/moves.zig +2878 -0
  51. package/src/lib/gen2/data/species.zig +1798 -0
  52. package/src/lib/gen2/data/types.zig +226 -0
  53. package/src/lib/gen2/data.zig +463 -0
  54. package/src/lib/gen2/generated.zig +806 -0
  55. package/src/lib/gen2/helpers.zig +249 -0
  56. package/src/lib/gen2/mechanics.zig +3632 -0
  57. package/src/lib/node.zig +131 -0
  58. package/src/lib/pkmn.zig +128 -0
  59. package/src/lib/wasm.zig +13 -0
  60. package/src/test/display/pkmn.html.tmpl +368 -0
@@ -0,0 +1,3156 @@
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 protocol = @import("../common/protocol.zig");
8
+ const rng = @import("../common/rng.zig");
9
+
10
+ const data = @import("data.zig");
11
+
12
+ const assert = std.debug.assert;
13
+
14
+ const expectEqual = std.testing.expectEqual;
15
+
16
+ const showdown = pkmn.options.showdown;
17
+
18
+ const Choice = common.Choice;
19
+ const ID = common.ID;
20
+ const Player = common.Player;
21
+ const Result = common.Result;
22
+
23
+ const Boost = protocol.Boost;
24
+ const Damage = protocol.Damage;
25
+ const Fail = protocol.Fail;
26
+ const Heal = protocol.Heal;
27
+
28
+ const Gen12 = rng.Gen12;
29
+
30
+ const ActivePokemon = data.ActivePokemon;
31
+ const Effectiveness = data.Effectiveness;
32
+ const Move = data.Move;
33
+ const MoveSlot = data.MoveSlot;
34
+ const Pokemon = data.Pokemon;
35
+ const Side = data.Side;
36
+ const Species = data.Species;
37
+ const Stats = data.Stats;
38
+ const Status = data.Status;
39
+ const Type = data.Type;
40
+
41
+ // zig fmt: off
42
+ const BOOSTS = &[_][2]u8{
43
+ .{ 25, 100 }, // -6
44
+ .{ 28, 100 }, // -5
45
+ .{ 33, 100 }, // -4
46
+ .{ 40, 100 }, // -3
47
+ .{ 50, 100 }, // -2
48
+ .{ 66, 100 }, // -1
49
+ .{ 1, 1 }, // 0
50
+ .{ 15, 10 }, // +1
51
+ .{ 2, 1 }, // +2
52
+ .{ 25, 10 }, // +3
53
+ .{ 3, 1 }, // +4
54
+ .{ 35, 10 }, // +5
55
+ .{ 4, 1 }, // +6
56
+ };
57
+ // zig fmt: on
58
+
59
+ const MAX_STAT_VALUE = 999;
60
+
61
+ pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
62
+ assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
63
+ if (battle.turn == 0) return start(battle, options);
64
+
65
+ var s1 = false;
66
+ var s2 = false;
67
+
68
+ if (selectMove(battle, .P1, c1, c2, &s1)) |r| return r;
69
+ if (selectMove(battle, .P2, c2, c1, &s2)) |r| return r;
70
+
71
+ var p1 = battle.side(.P1);
72
+ var p2 = battle.side(.P2);
73
+
74
+ const r1 = showdown and p1.active.volatiles.Binding and c2.type == .Switch;
75
+ const r2 = showdown and p2.active.volatiles.Binding and c1.type == .Switch;
76
+
77
+ if (try turnOrder(battle, c1, c2, options) == .P1) {
78
+ if (try doTurn(battle, .P1, c1, r1, s1, .P2, c2, r2, s2, options)) |r| return r;
79
+ } else {
80
+ if (try doTurn(battle, .P2, c2, r2, s2, .P1, c1, r1, s1, options)) |r| return r;
81
+ }
82
+
83
+ if (p1.active.volatiles.attacks == 0) p1.active.volatiles.Binding = false;
84
+ if (p2.active.volatiles.attacks == 0) p2.active.volatiles.Binding = false;
85
+
86
+ return endTurn(battle, options);
87
+ }
88
+
89
+ fn start(battle: anytype, options: anytype) !Result {
90
+ const p1 = battle.side(.P1);
91
+ const p2 = battle.side(.P2);
92
+
93
+ const p1_slot = findFirstAlive(p1);
94
+ assert(!showdown or p1_slot == 1);
95
+ if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
96
+
97
+ const p2_slot = findFirstAlive(p2);
98
+ assert(!showdown or p2_slot == 1);
99
+ if (p2_slot == 0) return Result.Win;
100
+
101
+ try switchIn(battle, .P1, p1_slot, true, options);
102
+ try switchIn(battle, .P2, p2_slot, true, options);
103
+
104
+ return endTurn(battle, options);
105
+ }
106
+
107
+ fn findFirstAlive(side: *const Side) u8 {
108
+ for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.order[i];
109
+ return 0;
110
+ }
111
+
112
+ fn selectMove(
113
+ battle: anytype,
114
+ player: Player,
115
+ choice: Choice,
116
+ foe_choice: Choice,
117
+ skip_turn: *bool,
118
+ ) ?Result {
119
+ if (choice.type == .Pass) return null;
120
+
121
+ var side = battle.side(player);
122
+ var volatiles = &side.active.volatiles;
123
+ const stored = side.stored();
124
+
125
+ assert(!isForced(side.active) or
126
+ (choice.type == .Move and choice.data == @intFromBool(showdown)));
127
+
128
+ // pre-battle menu
129
+ if (volatiles.Recharging) {
130
+ if (showdown and battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
131
+ return null;
132
+ }
133
+ if (volatiles.Rage) {
134
+ if (showdown) {
135
+ if (battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
136
+ saveMove(battle, player, null);
137
+ }
138
+ return null;
139
+ }
140
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
141
+ if (!showdown) volatiles.Flinch = false;
142
+ if (volatiles.Thrashing or volatiles.Charging) {
143
+ if (showdown) {
144
+ if (battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
145
+ saveMove(battle, player, null);
146
+ }
147
+ return null;
148
+ }
149
+
150
+ // battle menu
151
+ if (choice.type == .Switch) return null;
152
+
153
+ // pre-move select
154
+ if (Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP) or volatiles.Bide) {
155
+ assert(showdown or choice.data == 0);
156
+ if (showdown) {
157
+ if (volatiles.Bide and battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
158
+ saveMove(battle, player, choice);
159
+ }
160
+ return null;
161
+ }
162
+ if (volatiles.Binding) {
163
+ if (showdown) {
164
+ // Pokémon Showdown overwrites Mirror Move with whatever was selected - really this
165
+ // should set side.last_selected_move = last.id to reuse Mirror Move and fail in order
166
+ // to satisfy the conditions of the Desync Clause Mod. However, because Binding is still
167
+ // set the selected move will not actually be used, it will just be reported as having
168
+ // been used (this differs from how Pokémon Showdown works, but its impossible to
169
+ // replicate the incorrect behavior with the correct mechanisms).
170
+ saveMove(battle, player, choice);
171
+ } else {
172
+ assert(choice.data == 0);
173
+ // GLITCH: https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch
174
+ if (foe_choice.type == .Switch) {
175
+ const last = side.active.move(battle.lastMove(player).index);
176
+ if (last.id == .Metronome) side.last_selected_move = last.id;
177
+ if (last.id == .MirrorMove) return Result.Error;
178
+ }
179
+ }
180
+ return null;
181
+ }
182
+
183
+ if (battle.foe(player).active.volatiles.Binding) {
184
+ skip_turn.* = true;
185
+ if (showdown) {
186
+ saveMove(battle, player, choice);
187
+ } else {
188
+ assert(choice.data == 0);
189
+ side.last_selected_move = .SKIP_TURN;
190
+ }
191
+ return null;
192
+ }
193
+
194
+ // move select
195
+ volatiles.state = 0;
196
+ if (choice.data == 0) {
197
+ const struggle = ok: {
198
+ for (side.active.moves, 0..) |move, i| {
199
+ if (move.pp > 0 and volatiles.disable_move != i + 1) break :ok false;
200
+ }
201
+ break :ok true;
202
+ };
203
+ assert(struggle);
204
+ }
205
+ saveMove(battle, player, choice);
206
+
207
+ return null;
208
+ }
209
+
210
+ fn saveMove(battle: anytype, player: Player, choice: ?Choice) void {
211
+ var side = battle.side(player);
212
+
213
+ if (choice) |c| {
214
+ assert(c.type == .Move);
215
+ if (c.data == 0) {
216
+ side.last_selected_move = .Struggle;
217
+ } else {
218
+ assert(showdown or side.active.volatiles.disable_move != c.data);
219
+ const move = side.active.move(c.data);
220
+ // You cannot *select* a move with 0 PP (except on Pokémon Showdown where that is
221
+ // sometimes required...), but a 0 PP move can be used automatically
222
+ assert(showdown or move.pp != 0);
223
+
224
+ side.last_selected_move = move.id;
225
+ battle.lastMove(player).index = @intCast(c.data);
226
+ }
227
+ }
228
+ }
229
+
230
+ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
231
+ var side = battle.side(player);
232
+ var foe = battle.foe(player);
233
+ var active = &side.active;
234
+ const incoming = side.get(slot);
235
+
236
+ assert(incoming.hp != 0);
237
+ assert(slot != 1 or initial);
238
+
239
+ const out = side.order[0];
240
+ side.order[0] = side.order[slot - 1];
241
+ side.order[slot - 1] = out;
242
+
243
+ battle.lastMove(player).index = 1;
244
+
245
+ side.last_used_move = .None;
246
+ foe.last_used_move = .None;
247
+
248
+ active.stats = incoming.stats;
249
+ active.species = incoming.species;
250
+ active.types = incoming.types;
251
+ active.boosts = .{};
252
+ active.volatiles = .{};
253
+ active.moves = incoming.moves;
254
+
255
+ statusModify(incoming.status, &active.stats);
256
+
257
+ foe.active.volatiles.Binding = false;
258
+
259
+ try options.log.switched(.{ battle.active(player), incoming });
260
+ options.chance.switched(player, side.order[0], out);
261
+
262
+ if (showdown and incoming.status == Status.TOX) {
263
+ incoming.status = Status.init(.PSN);
264
+ // Technically, Pokémon Showdown adds these after *both* Pokémon have switched, but we'd
265
+ // rather not clutter up turnOrder just for this (incorrect) log message
266
+ try options.log.status(.{ battle.active(player), incoming.status, .Silent });
267
+ }
268
+ }
269
+
270
+ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
271
+ assert(c1.type != .Pass or c2.type != .Pass);
272
+
273
+ if (c1.type == .Pass) return .P2;
274
+ if (c2.type == .Pass) return .P1;
275
+
276
+ if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
277
+
278
+ // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
279
+ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
280
+ // > your own screen without waiting for the other player's choice (and their choice will appear
281
+ // > to happen first for them too, unless they attacked in which case your switch happens first)
282
+ // A cartridge-compatible implemention must not advance the RNG so we simply default to P1
283
+ const double_switch = c1.type == .Switch and c2.type == .Switch;
284
+ if (!showdown and double_switch) return .P1;
285
+
286
+ const m1 = battle.side(.P1).last_selected_move;
287
+ const m2 = battle.side(.P2).last_selected_move;
288
+ if (!showdown or !double_switch) {
289
+ if ((m1 == .QuickAttack) != (m2 == .QuickAttack)) {
290
+ return if (m1 == .QuickAttack) .P1 else .P2;
291
+ } else if ((m1 == .Counter) != (m2 == .Counter)) {
292
+ return if (m1 == .Counter) .P2 else .P1;
293
+ }
294
+ }
295
+
296
+ const spe1 = battle.side(.P1).active.stats.spe;
297
+ const spe2 = battle.side(.P2).active.stats.spe;
298
+ if (spe1 == spe2) {
299
+ // Pokémon Showdown's beforeTurnCallback shenanigans
300
+ if (showdown and !double_switch and m1 == .Counter and m2 == .Counter) {
301
+ battle.rng.advance(1);
302
+ }
303
+
304
+ const p1 = try Rolls.speedTie(battle, options);
305
+ if (!showdown) return if (p1) .P1 else .P2;
306
+
307
+ // Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
308
+ // meaning that if a side is locked into a thrashing move and wins the speed tie, it
309
+ // actually uses its priority to simply insert its actual changed action into the queue,
310
+ // causing it to then execute *after* the side which should go second...
311
+ const t1 = battle.side(.P1).active.volatiles.Thrashing;
312
+ const t2 = battle.side(.P2).active.volatiles.Thrashing;
313
+ // If *both* sides are thrashing it really should be another speed tie, but we've patched
314
+ // that out and enforce host ordering of events, so P1 just goes first regardless of who
315
+ // won the original coin flip
316
+ if (t1 and t2) return .P1;
317
+ return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
318
+ }
319
+
320
+ return if (spe1 > spe2) .P1 else .P2;
321
+ }
322
+
323
+ fn doTurn(
324
+ battle: anytype,
325
+ player: Player,
326
+ player_choice: Choice,
327
+ player_rewrap: bool,
328
+ player_skip: bool,
329
+ foe_player: Player,
330
+ foe_choice: Choice,
331
+ foe_rewrap: bool,
332
+ foe_skip: bool,
333
+ options: anytype,
334
+ ) !?Result {
335
+ assert(player_choice.type != .Pass);
336
+
337
+ var residual = true;
338
+ var replace = battle.side(player).stored().hp == 0;
339
+ if (try executeMove(
340
+ battle,
341
+ player,
342
+ player_choice,
343
+ player_rewrap,
344
+ player_skip,
345
+ &residual,
346
+ options,
347
+ )) |r| return r;
348
+ if (!replace) {
349
+ if (player_choice.type != .Switch) {
350
+ if (try checkFaint(battle, foe_player, options)) |r| return r;
351
+ }
352
+ if (residual) try handleResidual(battle, player, options);
353
+ if (try checkFaint(battle, player, options)) |r| return r;
354
+ } else if (foe_choice.type == .Pass) return null;
355
+
356
+ options.chance.clearPending();
357
+
358
+ residual = true;
359
+ replace = battle.side(foe_player).stored().hp == 0;
360
+ const calc = pkmn.options.calc and foe_choice.type == .Pass;
361
+ if (if (calc) null else try executeMove(
362
+ battle,
363
+ foe_player,
364
+ foe_choice,
365
+ foe_rewrap,
366
+ foe_skip,
367
+ &residual,
368
+ options,
369
+ )) |r| return r;
370
+ if (!replace) {
371
+ if (!calc and foe_choice.type != .Switch) {
372
+ if (try checkFaint(battle, player, options)) |r| return r;
373
+ }
374
+ if (residual) try handleResidual(battle, foe_player, options);
375
+ if (try checkFaint(battle, foe_player, options)) |r| return r;
376
+ }
377
+
378
+ // Flinch is bugged on Pokémon Showdown because it gets implemented with a duration which causes
379
+ // it to get removed in the non-existent "residual" phase instead of during move selection
380
+ if (showdown) {
381
+ battle.side(.P1).active.volatiles.Flinch = false;
382
+ battle.side(.P2).active.volatiles.Flinch = false;
383
+ }
384
+
385
+ return null;
386
+ }
387
+
388
+ fn executeMove(
389
+ battle: anytype,
390
+ player: Player,
391
+ choice: Choice,
392
+ rewrap: bool,
393
+ skip: bool,
394
+ residual: *bool,
395
+ options: anytype,
396
+ ) !?Result {
397
+ var side = battle.side(player);
398
+
399
+ if (choice.type == .Switch) {
400
+ try switchIn(battle, player, choice.data, false, options);
401
+ return null;
402
+ }
403
+
404
+ // This is the correct place to check for SKIP_TURN and abort early, however since Pokémon
405
+ // Showdown overwrites the SKIP_TURN sentinel with its botched move select we need to add an
406
+ // additional skip boolean to accomplish the same thing in the Binding check of BeforeMove
407
+ if (side.last_selected_move == .SKIP_TURN) {
408
+ assert(!showdown);
409
+ if (battle.foe(player).active.volatiles.Binding) {
410
+ try options.log.cant(.{ battle.active(player), .Bound });
411
+ }
412
+ return null;
413
+ }
414
+
415
+ assert(choice.type == .Move);
416
+ var mslot: u4 = @intCast(choice.data);
417
+ // Sadly, we can't even check `Move.get(side.last_selected_move).effect == .Binding` here
418
+ // because Pokémon Showdown's Mirror Move implementation clobbers side.last_selected_move
419
+ var auto = showdown and side.last_selected_move != .None;
420
+
421
+ // GLITCH: Freeze top move selection desync & PP underflow shenanigans
422
+ if (mslot == 0 and side.last_selected_move != .None and side.last_selected_move != .Struggle) {
423
+ // choice.data == 0 only happens with Struggle on Pokémon Showdown
424
+ assert(!showdown);
425
+ mslot = @intCast(battle.lastMove(player).index);
426
+ const stored = side.stored();
427
+ // GLITCH: Struggle bypass PP underflow via Hyper Beam / Trapping-switch auto selection
428
+ auto = isForced(&side.active) or
429
+ side.active.volatiles.Binding or side.active.volatiles.Bide or
430
+ side.last_selected_move == .HyperBeam or
431
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP);
432
+ // If it wasn't Hyper Beam or the continuation of a move effect then we must have just
433
+ // thawed, in which case we will desync unless the last_selected_move happened to be at
434
+ // index 1 and the current Pokémon has the same move in its first slot.
435
+ if (!auto) {
436
+ // side.active.moves(slot) is safe to check even though the slot in question might not
437
+ // technically be from this Pokémon because it must be exactly 1 to not desync and
438
+ // every Pokémon must have at least one move
439
+ if (mslot != 1 or side.active.move(mslot).id != side.last_selected_move) {
440
+ return Result.Error;
441
+ } else {
442
+ auto = true;
443
+ }
444
+ }
445
+ } else if (showdown and side.active.volatiles.Charging) {
446
+ // Incorrect mslot with Pokémon Showdown choice semantics so we need to recover from index
447
+ assert(mslot == 1);
448
+ mslot = @intCast(battle.lastMove(player).index);
449
+ }
450
+
451
+ var skip_can = false;
452
+ var skip_pp = false;
453
+ switch (try beforeMove(battle, player, skip, residual, options)) {
454
+ .done => return null,
455
+ .skip_can => skip_can = true,
456
+ .skip_pp => skip_pp = true,
457
+ .ok => {},
458
+ .err => return @as(?Result, Result.Error),
459
+ }
460
+
461
+ const can = skip_can or
462
+ try canMove(battle, player, mslot, auto, skip_pp, .None, residual, options);
463
+ if (!can) return null;
464
+
465
+ return doMove(battle, player, mslot, rewrap, auto, residual, options);
466
+ }
467
+
468
+ const BeforeMove = enum { done, skip_can, skip_pp, ok, err };
469
+
470
+ fn beforeMove(
471
+ battle: anytype,
472
+ player: Player,
473
+ skip: bool,
474
+ residual: *bool,
475
+ options: anytype,
476
+ ) !BeforeMove {
477
+ var log = options.log;
478
+ var side = battle.side(player);
479
+ const foe = battle.foe(player);
480
+ var active = &side.active;
481
+ var stored = side.stored();
482
+ const ident = battle.active(player);
483
+ var volatiles = &active.volatiles;
484
+
485
+ if (Status.is(stored.status, .SLP)) {
486
+ const before = stored.status;
487
+ // Even if the EXT bit is set this will still correctly modify the sleep duration
488
+ if (options.calc.modify(player, .sleep)) |extend| {
489
+ if (!extend) stored.status = 0;
490
+ } else {
491
+ stored.status -= 1;
492
+ }
493
+
494
+ const duration = Status.duration(stored.status);
495
+ if (!Status.is(stored.status, .EXT)) {
496
+ try options.chance.sleep(player, duration);
497
+ }
498
+
499
+ if (duration == 0) {
500
+ try log.curestatus(.{ ident, before, .Message });
501
+ stored.status = 0; // clears EXT if present
502
+ } else {
503
+ try log.cant(.{ ident, .Sleep });
504
+ }
505
+ side.last_used_move = .None;
506
+ return .done;
507
+ }
508
+
509
+ if (Status.is(stored.status, .FRZ)) {
510
+ try log.cant(.{ ident, .Freeze });
511
+ side.last_used_move = .None;
512
+ return .done;
513
+ }
514
+
515
+ if (skip or foe.active.volatiles.Binding) {
516
+ try log.cant(.{ ident, .Bound });
517
+ return .done;
518
+ }
519
+
520
+ if (volatiles.Flinch) {
521
+ // Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
522
+ // Pokémon can sometimes flinch multiple times from the same original hit
523
+ if (!showdown) volatiles.Flinch = false;
524
+ try log.cant(.{ ident, .Flinch });
525
+ return .done;
526
+ }
527
+
528
+ if (volatiles.Recharging) {
529
+ volatiles.Recharging = false;
530
+ try log.cant(.{ ident, .Recharge });
531
+ return .done;
532
+ }
533
+
534
+ if (volatiles.disable_duration > 0) {
535
+ if (options.calc.modify(player, .disable)) |extend| {
536
+ if (!extend) volatiles.disable_duration = 0;
537
+ } else {
538
+ volatiles.disable_duration -= 1;
539
+ }
540
+ try options.chance.disable(player, volatiles.disable_duration);
541
+
542
+ if (volatiles.disable_duration == 0) {
543
+ volatiles.disable_move = 0;
544
+ try log.end(.{ ident, .Disable });
545
+ }
546
+ }
547
+ // Pokémon Showdown's disable condition has a single onBeforeMove handler
548
+ if (showdown and try disabled(side, ident, options)) return .done;
549
+
550
+ // This can only happen if a Pokémon started the battle frozen/sleeping and was thawed/woken
551
+ // before the side had a selected a move - we simply need to assume this leads to a desync
552
+ if (side.last_selected_move == .None) {
553
+ assert(!showdown);
554
+ return .err;
555
+ }
556
+
557
+ if (volatiles.Confusion) {
558
+ assert(volatiles.confusion > 0);
559
+
560
+ if (options.calc.modify(player, .confusion)) |extend| {
561
+ if (!extend) volatiles.confusion = 0;
562
+ } else {
563
+ volatiles.confusion -= 1;
564
+ }
565
+ try options.chance.confusion(player, volatiles.confusion);
566
+
567
+ if (volatiles.confusion == 0) {
568
+ volatiles.Confusion = false;
569
+ try log.end(.{ ident, .Confusion });
570
+ } else {
571
+ try log.activate(.{ ident, .Confusion });
572
+
573
+ if (try Rolls.confused(battle, player, options)) {
574
+ assert(!volatiles.MultiHit);
575
+ if (!volatiles.Rage) volatiles.state = 0;
576
+ volatiles.Bide = false;
577
+ volatiles.Thrashing = false;
578
+ volatiles.MultiHit = false;
579
+ volatiles.Flinch = false;
580
+ volatiles.Charging = false;
581
+ volatiles.Binding = false;
582
+ volatiles.Invulnerable = false;
583
+ options.chance.clearDurations(player, null);
584
+ {
585
+ // This feels (and is) disgusting but the cartridge literally just overwrites
586
+ // the opponent's defense with the user's defense and resets it after. As a
587
+ // result of this the *opponent's* Reflect impacts confusion self-hit damage
588
+ const def = foe.active.stats.def;
589
+ foe.active.stats.def = active.stats.def;
590
+ defer foe.active.stats.def = def;
591
+ if (!calcDamage(battle, player, player.foe(), null, false)) return .err;
592
+ }
593
+ // Pokémon Showdown incorrectly changes the "target" of the confusion self-hit based
594
+ // on the targeting behavior of the confused Pokémon's selected move which results
595
+ // in the wrong behavior with respect to the Substitute + Confusion glitch
596
+ const target = if (showdown and Move.get(side.last_selected_move).target == .Self)
597
+ player
598
+ else
599
+ player.foe();
600
+
601
+ const uncapped = battle.last_damage;
602
+ // Skipping adjustDamage / randomizeDamage / checkHit
603
+ _ = try applyDamage(battle, player, target, .Confusion, options);
604
+ // Pokémon Showdown thinks that confusion damage is uncapped ¯\_(ツ)_/¯
605
+ if (showdown) battle.last_damage = uncapped;
606
+
607
+ return .done;
608
+ }
609
+ }
610
+ }
611
+
612
+ if (!showdown and try disabled(side, ident, options)) return .done;
613
+
614
+ if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
615
+ if (!volatiles.Rage) volatiles.state = 0;
616
+ volatiles.Bide = false;
617
+ volatiles.Thrashing = false;
618
+ volatiles.Charging = false;
619
+ volatiles.Binding = false;
620
+ options.chance.clearDurations(player, null);
621
+ // GLITCH: Invulnerable is not cleared, resulting in permanent Fly/Dig invulnerability
622
+ try log.cant(.{ ident, .Paralysis });
623
+ return .done;
624
+ }
625
+
626
+ if (volatiles.Bide) {
627
+ assert(!volatiles.Thrashing and !volatiles.Rage);
628
+
629
+ if (showdown) {
630
+ // Pokémon Showdown doesn't implement Bide potentially overflowing in the event of
631
+ // OHKO-move damage, but we can fake this incorrect behavior by simply saturating the
632
+ // addition because 65535 is sufficient to faint any Pokémon anyway
633
+ volatiles.state +|= battle.last_damage;
634
+ } else {
635
+ volatiles.state +%= battle.last_damage;
636
+ }
637
+
638
+ if (options.calc.modify(player, .attacking)) |extend| {
639
+ if (!extend) volatiles.attacks = 0;
640
+ } else {
641
+ volatiles.attacks -= 1;
642
+ }
643
+ try options.chance.attacking(player, volatiles.attacks);
644
+
645
+ if (volatiles.attacks != 0) {
646
+ try log.activate(.{ ident, .Bide });
647
+ return .done;
648
+ }
649
+
650
+ volatiles.Bide = false;
651
+ try log.end(.{ ident, .Bide });
652
+
653
+ battle.last_damage = volatiles.state *% 2;
654
+ volatiles.state = 0;
655
+
656
+ if (battle.last_damage == 0) {
657
+ try log.fail(.{ ident, .None });
658
+ return .done;
659
+ }
660
+
661
+ const sub = showdown and foe.active.volatiles.Substitute;
662
+ _ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
663
+ if (foe.stored().hp > 0 and !sub) try buildRage(battle, player.foe(), options);
664
+
665
+ // For reasons passing understanding, Pokémon Showdown still inflicts residual damage to
666
+ // Bide's user even if the above damage has caused the foe to faint. It's simpler to always
667
+ // run residual here regardless of whether the foe fainted and opt-out of the default flow
668
+ if (showdown) {
669
+ residual.* = false;
670
+ try handleResidual(battle, player, options);
671
+ }
672
+
673
+ return .done;
674
+ }
675
+
676
+ if (volatiles.Thrashing) {
677
+ if (options.calc.modify(player, .attacking)) |extend| {
678
+ if (!extend) volatiles.attacks = 0;
679
+ } else {
680
+ volatiles.attacks -= 1;
681
+ }
682
+ try options.chance.attacking(player, volatiles.attacks);
683
+
684
+ if (!showdown and handleThrashing(battle, active, player, options)) {
685
+ try log.start(.{ battle.active(player), .ConfusionSilent });
686
+ }
687
+ try log.move(.{ ident, side.last_selected_move, battle.active(player.foe()) });
688
+ if (showdown) {
689
+ // This shouldn't actually set last_used_move, but Pokémon Showdown sets last
690
+ // used in useMove and doesn't have the notion of skipping canMove semantics
691
+ side.last_used_move = side.last_selected_move;
692
+ if (handleThrashing(battle, active, player, options)) {
693
+ try log.start(.{ battle.active(player), .ConfusionSilent });
694
+ }
695
+ }
696
+ return .skip_can;
697
+ }
698
+
699
+ if (volatiles.Binding) {
700
+ if (options.calc.modify(player, .binding)) |extend| {
701
+ if (!extend) volatiles.attacks = 0;
702
+ } else {
703
+ volatiles.attacks -= 1;
704
+ }
705
+ try options.chance.binding(player, volatiles.attacks);
706
+
707
+ try log.move(.{ ident, side.last_selected_move, battle.active(player.foe()) });
708
+ if (showdown or battle.last_damage != 0) {
709
+ const sub = showdown and foe.active.volatiles.Substitute;
710
+ _ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
711
+ if (battle.foe(player).stored().hp > 0 and !sub) {
712
+ try buildRage(battle, player.foe(), options);
713
+ }
714
+ }
715
+ return .done;
716
+ }
717
+
718
+ return if (volatiles.Rage) .skip_pp else .ok;
719
+ }
720
+
721
+ fn canMove(
722
+ battle: anytype,
723
+ player: Player,
724
+ mslot: u4,
725
+ auto: bool,
726
+ skip_pp: bool,
727
+ from: Move,
728
+ residual: *bool,
729
+ options: anytype,
730
+ ) !bool {
731
+ var side = battle.side(player);
732
+ const player_ident = battle.active(player);
733
+ const move = Move.get(side.last_selected_move);
734
+
735
+ if (side.active.volatiles.Charging) {
736
+ side.active.volatiles.Charging = false;
737
+ side.active.volatiles.Invulnerable = false;
738
+ } else if (move.effect == .Charge) {
739
+ try options.log.move(.{ player_ident, side.last_selected_move, ID{}, from });
740
+ setCounterable(battle, player, side, move);
741
+ try Effects.charge(battle, player, options);
742
+ return false;
743
+ }
744
+
745
+ side.last_used_move = side.last_selected_move;
746
+ if (!skip_pp) decrementPP(side, mslot, auto);
747
+
748
+ const target = if (move.target == .Self) player else player.foe();
749
+ try options.log.move(.{ player_ident, side.last_selected_move, battle.active(target), from });
750
+ setCounterable(battle, player, side, move);
751
+
752
+ if (move.effect.onBegin()) {
753
+ try onBegin(battle, player, move, mslot, residual, options);
754
+ return false;
755
+ }
756
+
757
+ if (move.effect == .Thrashing) {
758
+ Effects.thrashing(battle, player, options);
759
+ } else if (!showdown and move.effect == .Binding) {
760
+ // Pokémon Showdown handles this after hit/miss checks and damage calculation
761
+ try Effects.binding(battle, player, false, options);
762
+ }
763
+
764
+ return true;
765
+ }
766
+
767
+ fn setCounterable(battle: anytype, player: Player, side: *Side, move: Move.Data) void {
768
+ // The Counter desync is caused by the cartridge not calling GetCurrentMove until now, meaning
769
+ // in cases where an early return happens the data for a players last selected move does not get
770
+ // reloaded and HandleCounterMove actually bases its success/failure off of stale information.
771
+ // This boolean state we track here doesn't exist on the cartridge because it instead manifests
772
+ // as the desync results from actually having two separate battle states that subtly disagree
773
+ const counterable = side.last_selected_move != .Counter and move.bp > 0 and
774
+ (move.type == .Normal or move.type == .Fighting);
775
+ battle.lastMove(player).counterable = @intFromBool(counterable);
776
+ }
777
+
778
+ fn decrementPP(side: *Side, mslot: u4, auto: bool) void {
779
+ if (side.last_selected_move == .Struggle) return;
780
+
781
+ var active = &side.active;
782
+ const volatiles = &active.volatiles;
783
+
784
+ assert(!volatiles.Rage and !volatiles.Thrashing and !volatiles.MultiHit);
785
+ if (volatiles.Bide) return;
786
+
787
+ var move_slot = active.move(mslot);
788
+ assert(move_slot.pp > 0 or auto);
789
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
790
+ if (volatiles.Transform) return;
791
+
792
+ move_slot = side.stored().move(mslot);
793
+ assert(move_slot.pp > 0 or auto);
794
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
795
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
796
+ }
797
+
798
+ fn incrementPP(side: *Side, mslot: u4) void {
799
+ var active = &side.active;
800
+ const volatiles = &active.volatiles;
801
+
802
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) +% 1;
803
+ // GLITCH: No check for Transform means an empty/incorrect stored slot can get incremented
804
+ if (showdown and volatiles.Transform) return;
805
+
806
+ assert(mslot > 0 and mslot <= 4);
807
+ side.stored().moves[mslot - 1].pp = @as(u6, @intCast(side.stored().moves[mslot - 1].pp)) +% 1;
808
+ }
809
+
810
+ // Pokémon Showdown does hit/multi/crit/damage instead of crit/damage/hit/multi
811
+ fn doMove(
812
+ battle: anytype,
813
+ player: Player,
814
+ mslot: u4,
815
+ rewrap: bool,
816
+ auto: bool,
817
+ residual: *bool,
818
+ options: anytype,
819
+ ) !?Result {
820
+ var log = options.log;
821
+ var side = battle.side(player);
822
+ const foe = battle.foe(player);
823
+
824
+ var move = Move.get(side.last_selected_move);
825
+ const counter = side.last_selected_move == .Counter;
826
+ const status = move.bp == 0 and move.effect != .OHKO;
827
+
828
+ var crit = false;
829
+ var ohko = false;
830
+ var immune = false;
831
+ var mist = false;
832
+ var hits: u4 = 1;
833
+ var effectiveness = Effectiveness.neutral;
834
+
835
+ // Due to control flow shenanigans we need to clear last_damage for Pokémon Showdown
836
+ if (showdown and !counter) battle.last_damage = 0;
837
+
838
+ // The cartridge handles set damage moves in applyDamage but we short circuit to simplify things
839
+ if (move.effect == .SuperFang or move.effect == .SpecialDamage) {
840
+ return specialDamage(battle, player, move, options);
841
+ }
842
+
843
+ // Pokémon Showdown runs invulnerability / immunity checks before checking accuracy - simply
844
+ // calling moveHit early covers most of that but we also need to check type immunity first
845
+ var miss = showdown and miss: {
846
+ immune = move.target != .Self and !status and !counter and
847
+ (@intFromEnum(move.type.effectiveness(foe.active.types.type1)) == 0 or
848
+ @intFromEnum(move.type.effectiveness(foe.active.types.type2)) == 0);
849
+ if (immune and move.effect != .Binding) break :miss true;
850
+ if (move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe) {
851
+ battle.last_damage = 0;
852
+ break :miss true;
853
+ }
854
+ break :miss (move.target != .Self and
855
+ !moveHit(battle, player, move, &immune, &mist, options));
856
+ };
857
+ assert(!immune or miss or (showdown and move.effect == .Binding));
858
+
859
+ var late = showdown and move.effect != .Explode;
860
+ const skip = status or immune;
861
+ if ((!showdown or (!skip or counter)) and !miss) blk: {
862
+ if (showdown and move.effect.isMulti()) {
863
+ try Effects.multiHit(battle, player, move, options);
864
+ hits = side.active.volatiles.attacks;
865
+ late = false;
866
+ }
867
+
868
+ // Cartridge rolls for crit even for moves that can't crit (Counter/Metronome/status/OHKO)
869
+ const check = !showdown or (!counter and move.effect != .OHKO);
870
+ if (check) crit = try checkCriticalHit(battle, player, move, options);
871
+
872
+ if (counter) return counterDamage(battle, player, move, options);
873
+
874
+ battle.last_damage = 0;
875
+
876
+ // Disassembly does a check to allow 0 BP MultiHit moves but this isn't possible in practice
877
+ assert(move.effect != .MultiHit or move.bp > 0);
878
+ if (!skip) {
879
+ if (move.effect == .OHKO) {
880
+ ohko = if (!showdown) side.active.stats.spe >= foe.active.stats.spe else true;
881
+ // This can overflow after adjustDamage, but will still be sufficient to OHKO
882
+ battle.last_damage = if (ohko) 65535 else 0;
883
+ if (showdown) break :blk; // skip adjustDamage / randomizeDamage
884
+ } else if (!calcDamage(battle, player, player.foe(), move, crit)) {
885
+ return @as(?Result, Result.Error);
886
+ }
887
+ if (battle.last_damage == 0) {
888
+ immune = true;
889
+ effectiveness = 0;
890
+ } else {
891
+ effectiveness = adjustDamage(battle, player);
892
+ immune = effectiveness == 0;
893
+ }
894
+ try randomizeDamage(battle, player, options);
895
+ }
896
+ }
897
+
898
+ const zero = battle.last_damage == 0;
899
+ miss = if (showdown or skip)
900
+ miss
901
+ else
902
+ (!moveHit(battle, player, move, &immune, &mist, options) or zero);
903
+
904
+ assert(showdown or miss or battle.last_damage > 0 or skip);
905
+ assert((!showdown and miss) or !(ohko and immune));
906
+ assert(!immune or miss or move.effect == .Binding);
907
+
908
+ if (!showdown or !miss) {
909
+ if (move.effect == .MirrorMove) {
910
+ return mirrorMove(battle, player, mslot, rewrap, auto, residual, options);
911
+ } else if (move.effect == .Metronome) {
912
+ return metronome(battle, player, mslot, rewrap, auto, residual, options);
913
+ } else if (move.effect.onEnd()) {
914
+ try onEnd(battle, player, move, options);
915
+ return null;
916
+ }
917
+ }
918
+
919
+ if (miss) {
920
+ const foe_ident = battle.active(player.foe());
921
+ const invulnerable =
922
+ showdown and foe.active.volatiles.Invulnerable and move.effect != .Swift;
923
+ ohko = (!showdown or (!immune and !invulnerable)) and
924
+ move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe;
925
+ if (ohko) {
926
+ try log.immune(.{ foe_ident, .OHKO });
927
+ } else if (immune and !invulnerable and (!showdown or move.effect != .Binding)) {
928
+ try log.immune(.{ foe_ident, .None });
929
+ } else if (mist) {
930
+ if (!foe.active.volatiles.Substitute) try log.activate(.{ foe_ident, .Mist });
931
+ try log.fail(.{ foe_ident, .None });
932
+ } else {
933
+ if (showdown or !zero) try options.chance.commit(player, .miss);
934
+ try log.lastmiss(.{});
935
+ try log.miss(.{battle.active(player)});
936
+ }
937
+ if (move.effect == .JumpKick) {
938
+ // Recoil is supposed to be damage/8 but damage will always be 0 here
939
+ assert(showdown or battle.last_damage == 0);
940
+ battle.last_damage = 1;
941
+ _ = try applyDamage(battle, player, player.foe(), .None, options);
942
+ if (showdown and side.stored().hp == 0) residual.* = false;
943
+ } else if (move.effect == .Explode) {
944
+ try Effects.explode(battle, player);
945
+ try buildRage(battle, player.foe(), options);
946
+ } else if (showdown and move.effect == .Disable) {
947
+ try buildRage(battle, player.foe(), options);
948
+ } else if (!showdown and immune and move.effect == .Binding) {
949
+ try options.chance.commit(player, .binding);
950
+ }
951
+ return null;
952
+ } else {
953
+ try options.chance.commit(player, .hit);
954
+ }
955
+
956
+ // On the cartridge MultiHit doesn't get set up until after damage has been applied for the
957
+ // first time but its more convenient and efficient to set it up here (Pokémon Showdown sets
958
+ // it up above before damage calculation).
959
+ if (!showdown and move.effect.isMulti()) {
960
+ try Effects.multiHit(battle, player, move, options);
961
+ hits = side.active.volatiles.attacks;
962
+ }
963
+
964
+ // Pokémon Showdown only builds Rage for Disable/Explosion (hit/miss) when attacking into a sub
965
+ const sub = showdown and foe.active.volatiles.Substitute;
966
+
967
+ var nullified = false;
968
+ var hit: u4 = 0;
969
+ while (hit < hits) {
970
+ if (hit == 0) {
971
+ if (crit) try log.crit(.{battle.active(player.foe())});
972
+ if (effectiveness > Effectiveness.neutral) {
973
+ try log.supereffective(.{battle.active(player.foe())});
974
+ } else if (effectiveness < Effectiveness.neutral) {
975
+ try log.resisted(.{battle.active(player.foe())});
976
+ }
977
+ }
978
+ if (!skip) nullified = try applyDamage(battle, player.foe(), player.foe(), .None, options);
979
+ if (hit == 0 and ohko) try log.ohko(.{});
980
+ hit += 1;
981
+ if (foe.stored().hp == 0) break;
982
+ if (!late and (!sub or move.effect == .Explode)) {
983
+ try buildRage(battle, player.foe(), options);
984
+ }
985
+ // If the substitute breaks during a multi-hit attack, the attack ends
986
+ if (nullified) break;
987
+ }
988
+
989
+ if (side.active.volatiles.MultiHit) {
990
+ side.active.volatiles.MultiHit = false;
991
+ assert(nullified or foe.stored().hp == 0 or side.active.volatiles.attacks - hit == 0);
992
+ side.active.volatiles.attacks = 0;
993
+ if (showdown and move.effect == .Twineedle and !nullified and foe.stored().hp > 0) {
994
+ try Effects.poison(battle, player, Move.get(.PoisonSting), options);
995
+ }
996
+ try log.hitcount(.{ battle.active(player.foe()), hit });
997
+ } else if (showdown) {
998
+ // This should be handled much earlier but Pokémon Showdown does it here... ¯\_(ツ)_/¯
999
+ if (move.effect == .Binding) {
1000
+ try Effects.binding(battle, player, rewrap, options);
1001
+ if (immune) {
1002
+ battle.last_damage = 0;
1003
+ assert(foe.stored().hp > 0);
1004
+ // Pokémon Showdown logs |-damage| here instead of |-immune| because logic...
1005
+ if (sub) {
1006
+ try log.activate(.{ battle.active(player.foe()), .Substitute });
1007
+ } else {
1008
+ try log.damage(.{ battle.active(player.foe()), foe.stored(), .None });
1009
+ try buildRage(battle, player.foe(), options);
1010
+ }
1011
+ return null;
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ // Substitute being broken nullifies the move's effect completely so even
1017
+ // if an effect was intended to "always happen" it will still get skipped.
1018
+ if (nullified) return null;
1019
+
1020
+ // On the cartridge, "always happen" effect handlers are called in the applyDamage loop above,
1021
+ // but this is only done to setup the MultiHit looping in the first place. Moving the MultiHit
1022
+ // setup before the loop means we can avoid having to waste time doing no-op handler searches.
1023
+ if (move.effect.alwaysHappens()) try alwaysHappens(battle, player, move, residual, options);
1024
+
1025
+ if (foe.stored().hp == 0) return null;
1026
+
1027
+ // Pokémon Showdown builds Rage at the wrong time for non-MultiHit move
1028
+ if (late and !sub and move.effect != .Disable) try buildRage(battle, player.foe(), options);
1029
+
1030
+ if (!move.effect.isSpecial()) {
1031
+ // On the cartridge Rage is not considered to be "special" and thus gets executed for a
1032
+ // second time here (after being executed in the "always happens" block above) but that
1033
+ // doesn't matter since its idempotent (on the cartridge, but not in the implementation
1034
+ // below). For Twineedle we change the data to that of one with PoisonChance1 given its
1035
+ // MultiHit behavior is complete after the loop above, though Pokémon Showdown handles the
1036
+ // Twineedle secondary effect in the MultiHit cleanup block above because it incorrectly
1037
+ // puts the |-status| message before |-hitcount| instead of after.
1038
+ if (move.effect == .Twineedle) {
1039
+ if (!showdown) try Effects.poison(battle, player, Move.get(.PoisonSting), options);
1040
+ } else if (move.effect == .Disable) {
1041
+ const result = try Effects.disable(battle, player, move, options);
1042
+ if (showdown) try buildRage(battle, player.foe(), options);
1043
+ return result;
1044
+ } else {
1045
+ try moveEffect(battle, player, move, options);
1046
+ }
1047
+ }
1048
+
1049
+ return null;
1050
+ }
1051
+
1052
+ fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
1053
+ const side = battle.side(player);
1054
+
1055
+ // Base speed is used for the critical hit calculation, even when Transform-ed
1056
+ var rate: u16 = Species.chance(side.stored().species);
1057
+ // GLITCH: Focus Energy reduces critical hit rate instead of increasing it
1058
+ rate = if (side.active.volatiles.FocusEnergy) rate / 2 else @min(rate * 2, 255);
1059
+ rate = if (move.effect == .HighCritical) @min(rate * 4, 255) else rate / 2;
1060
+
1061
+ return Rolls.criticalHit(battle, player, @intCast(rate), options);
1062
+ }
1063
+
1064
+ fn calcDamage(
1065
+ battle: anytype,
1066
+ player: Player,
1067
+ target_player: Player,
1068
+ m: ?Move.Data,
1069
+ crit: bool,
1070
+ ) bool {
1071
+ // Confusion (indicated when m == null) just needs a 40 BP physical move
1072
+ const cfz = m == null;
1073
+ const move = m orelse Move.get(.Pound);
1074
+ assert(move.bp != 0);
1075
+
1076
+ const side = battle.side(player);
1077
+ const target = battle.side(target_player);
1078
+
1079
+ const special = move.type.special();
1080
+
1081
+ // zig fmt: off
1082
+ var atk: u32 =
1083
+ if (crit)
1084
+ if (special) side.stored().stats.spc
1085
+ else side.stored().stats.atk
1086
+ else
1087
+ if (special) side.active.stats.spc
1088
+ else side.active.stats.atk;
1089
+ var def: u32 =
1090
+ if (crit)
1091
+ if (special) target.stored().stats.spc
1092
+ else target.stored().stats.def
1093
+ else
1094
+ // GLITCH: not capped to MAX_STAT_VALUE, can be 999 * 2 = 1998
1095
+ if (special)
1096
+ target.active.stats.spc *
1097
+ @as(u2, if (target.active.volatiles.LightScreen) 2 else 1)
1098
+ // Pokémon Showdown doesn't apply the opponent's Reflect to confusion's self-hit
1099
+ else
1100
+ target.active.stats.def *
1101
+ @as(u2, if ((!showdown or !cfz) and target.active.volatiles.Reflect) 2 else 1);
1102
+ // zig fmt: on
1103
+
1104
+ // Pokémon Showdown erroneously skips this for confusion's self-hit damage, but thankfully we
1105
+ // will not overflow because the hit is only 40 BP and unboosted (the highest legal unboosted
1106
+ // attack is 366 from a level 100 Dragonite which has a max of 614,880 mid-calculation)
1107
+ if ((!showdown or !cfz) and (atk > 255 or def > 255)) {
1108
+ atk = @max((atk / 4) & 255, 1);
1109
+ // GLITCH: not adjusted to be a min of 1 on cartridge (can lead to division-by-zero freeze)
1110
+ def = @max((def / 4) & 255, if (showdown) 1 else 0);
1111
+ }
1112
+
1113
+ const lvl: u32 = side.stored().level * @as(u2, if (crit) 2 else 1);
1114
+
1115
+ def = if (move.effect == .Explode) @max(def / 2, 1) else def;
1116
+
1117
+ if (def == 0) return false;
1118
+
1119
+ var d: u32 = (lvl * 2 / 5) + 2;
1120
+ d *%= @as(u32, move.bp);
1121
+ d *%= atk;
1122
+ d /= def;
1123
+ d /= 50;
1124
+ d = @min(997, d);
1125
+ d += 2;
1126
+
1127
+ battle.last_damage = @intCast(d);
1128
+
1129
+ return true;
1130
+ }
1131
+
1132
+ fn adjustDamage(battle: anytype, player: Player) u16 {
1133
+ const side = battle.side(player);
1134
+ const foe = battle.foe(player);
1135
+ const types = foe.active.types;
1136
+ const move = Move.get(side.last_selected_move);
1137
+
1138
+ var d = battle.last_damage;
1139
+ if (side.active.types.includes(move.type)) d +%= d / 2;
1140
+
1141
+ const neutral = @intFromEnum(Effectiveness.Neutral);
1142
+ const eff1: u16 = @intFromEnum(move.type.effectiveness(types.type1));
1143
+ const eff2: u16 = @intFromEnum(move.type.effectiveness(types.type2));
1144
+
1145
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
1146
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
1147
+ Type.precedence(move.type, types.type1) > Type.precedence(move.type, types.type2))
1148
+ {
1149
+ assert(eff2 != neutral);
1150
+ d = d *% eff2 / 10;
1151
+ assert(types.type1 != types.type2);
1152
+ assert(eff1 != neutral);
1153
+ d = d *% eff1 / 10;
1154
+ } else {
1155
+ if (eff1 != neutral) d = d *% eff1 / 10;
1156
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
1157
+ }
1158
+
1159
+ battle.last_damage = d;
1160
+ return if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
1161
+ }
1162
+
1163
+ fn randomizeDamage(battle: anytype, player: Player, options: anytype) !void {
1164
+ if (battle.last_damage <= 1) return;
1165
+ const random = try Rolls.damage(battle, player, options);
1166
+ options.calc.base(player.foe(), battle.last_damage);
1167
+ battle.last_damage = @intCast(@as(u32, battle.last_damage) *% random / 255);
1168
+ options.calc.final(player.foe(), battle.last_damage);
1169
+ }
1170
+
1171
+ fn specialDamage(battle: anytype, player: Player, move: Move.Data, options: anytype) !?Result {
1172
+ const side = battle.side(player);
1173
+ const foe = battle.foe(player);
1174
+
1175
+ if (!try checkHit(battle, player, move, options)) return null;
1176
+ try options.chance.commit(player, .hit);
1177
+
1178
+ battle.last_damage = switch (side.last_selected_move) {
1179
+ .SuperFang => @max(foe.stored().hp / 2, 1),
1180
+ .SeismicToss, .NightShade => side.stored().level,
1181
+ .SonicBoom => 20,
1182
+ .DragonRage => 40,
1183
+ // GLITCH: if power = 0 then a desync occurs (or a miss on Pokémon Showdown)
1184
+ .Psywave => power: {
1185
+ const max: u8 = @intCast(@as(u16, side.stored().level) * 3 / 2);
1186
+ // GLITCH: Psywave infinite glitch loop
1187
+ if (!showdown and max <= 1) return Result.Error;
1188
+ break :power try Rolls.psywave(battle, player, max, options);
1189
+ },
1190
+ else => unreachable,
1191
+ };
1192
+
1193
+ if (battle.last_damage == 0) return if (showdown) null else Result.Error;
1194
+
1195
+ const sub = showdown and foe.active.volatiles.Substitute;
1196
+ _ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
1197
+ if (battle.foe(player).stored().hp > 0 and !sub) try buildRage(battle, player.foe(), options);
1198
+
1199
+ return null;
1200
+ }
1201
+
1202
+ fn counterDamage(battle: anytype, player: Player, move: Move.Data, options: anytype) !?Result {
1203
+ const foe = battle.foe(player);
1204
+
1205
+ if (battle.last_damage == 0) {
1206
+ try options.log.fail(.{ battle.active(player), .None });
1207
+ return null;
1208
+ }
1209
+
1210
+ // Pretend Splash was used as a stand-in when no move has been used to fail below with 0 BP
1211
+ const foe_last_selected_move =
1212
+ Move.get(if (foe.last_selected_move == .None or foe.last_selected_move == .SKIP_TURN)
1213
+ .Splash
1214
+ else
1215
+ foe.last_selected_move);
1216
+
1217
+ const used = battle.lastMove(player.foe()).counterable != 0;
1218
+ const selected = foe_last_selected_move.bp > 0 and
1219
+ foe.last_selected_move != .Counter and
1220
+ (foe_last_selected_move.type == .Normal or
1221
+ foe_last_selected_move.type == .Fighting);
1222
+
1223
+ if (!used and !selected) {
1224
+ try options.log.fail(.{ battle.active(player), .None });
1225
+ return null;
1226
+ }
1227
+
1228
+ if (!used or !selected) {
1229
+ // GLITCH: Counter desync (covered by Desync Clause Mod on Pokémon Showdown)
1230
+ if (!showdown) return Result.Error;
1231
+ try options.log.fail(.{ battle.active(player), .None });
1232
+ return null;
1233
+ }
1234
+
1235
+ battle.last_damage *|= 2;
1236
+
1237
+ // Pokémon Showdown calls checkHit before Counter
1238
+ if (!showdown and !try checkHit(battle, player, move, options)) return null;
1239
+ try options.chance.commit(player, .hit);
1240
+
1241
+ const sub = showdown and foe.active.volatiles.Substitute;
1242
+ _ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
1243
+ if (battle.foe(player).stored().hp > 0 and !sub) try buildRage(battle, player.foe(), options);
1244
+ return null;
1245
+ }
1246
+
1247
+ fn applyDamage(
1248
+ battle: anytype,
1249
+ target_player: Player,
1250
+ sub_player: Player,
1251
+ reason: Damage,
1252
+ options: anytype,
1253
+ ) !bool {
1254
+ assert(showdown or battle.last_damage != 0);
1255
+
1256
+ var target = battle.side(target_player);
1257
+ // GLITCH: Substitute + Confusion glitch
1258
+ // We check if the target has a Substitute but then apply damage to the "sub player" which
1259
+ // isn't guaranteed to be the same (e.g. crash or confusion damage) or to even have a Substitute
1260
+ if (target.active.volatiles.Substitute) {
1261
+ var subbed = battle.side(sub_player);
1262
+ if (!subbed.active.volatiles.Substitute) return false;
1263
+ if (battle.last_damage >= subbed.active.volatiles.substitute) {
1264
+ subbed.active.volatiles.substitute = 0;
1265
+ subbed.active.volatiles.Substitute = false;
1266
+ // battle.last_damage is not updated with the amount of HP the Substitute had
1267
+ try options.log.end(.{ battle.active(sub_player), .Substitute });
1268
+ options.calc.capped(target_player);
1269
+ return true;
1270
+ } else {
1271
+ // Safe to truncate since less than subbed.volatiles.substitute which is a u8
1272
+ subbed.active.volatiles.substitute -= @intCast(battle.last_damage);
1273
+ try options.log.activate(.{ battle.active(sub_player), .Substitute });
1274
+ return false;
1275
+ }
1276
+ }
1277
+
1278
+ if (battle.last_damage > target.stored().hp) battle.last_damage = target.stored().hp;
1279
+ target.stored().hp -= battle.last_damage;
1280
+ try options.log.damage(.{ battle.active(target_player), target.stored(), reason });
1281
+ return false;
1282
+ }
1283
+
1284
+ fn mirrorMove(
1285
+ battle: anytype,
1286
+ player: Player,
1287
+ mslot: u4,
1288
+ rewrap: bool,
1289
+ auto: bool,
1290
+ residual: *bool,
1291
+ options: anytype,
1292
+ ) anyerror!?Result {
1293
+ var side = battle.side(player);
1294
+ const foe = battle.foe(player);
1295
+
1296
+ side.last_selected_move = foe.last_used_move;
1297
+
1298
+ if (foe.last_used_move == .None or foe.last_used_move == .MirrorMove) {
1299
+ try options.log.fail(.{ battle.active(player), .None });
1300
+ return null;
1301
+ } else if (!showdown or foe.last_used_move != .Struggle) {
1302
+ incrementPP(side, mslot);
1303
+ }
1304
+
1305
+ if (!try canMove(battle, player, mslot, auto, false, .MirrorMove, residual, options)) {
1306
+ return null;
1307
+ }
1308
+ return doMove(battle, player, mslot, rewrap, auto, residual, options);
1309
+ }
1310
+
1311
+ fn metronome(
1312
+ battle: anytype,
1313
+ player: Player,
1314
+ mslot: u4,
1315
+ rewrap: bool,
1316
+ auto: bool,
1317
+ residual: *bool,
1318
+ options: anytype,
1319
+ ) anyerror!?Result {
1320
+ var side = battle.side(player);
1321
+
1322
+ side.last_selected_move = try Rolls.metronome(battle, player, options);
1323
+ incrementPP(side, mslot);
1324
+
1325
+ if (!try canMove(battle, player, mslot, auto, false, .Metronome, residual, options)) {
1326
+ return null;
1327
+ }
1328
+ return doMove(battle, player, mslot, rewrap, auto, residual, options);
1329
+ }
1330
+
1331
+ fn checkHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
1332
+ var immune = false;
1333
+ var mist = false;
1334
+
1335
+ if (moveHit(battle, player, move, &immune, &mist, options)) return true;
1336
+
1337
+ assert(!immune);
1338
+ if (mist) {
1339
+ assert(!showdown);
1340
+ const foe_ident = battle.active(player.foe());
1341
+ try options.log.activate(.{ foe_ident, .Mist });
1342
+ try options.log.fail(.{ foe_ident, .None });
1343
+ } else {
1344
+ try options.chance.commit(player, .miss);
1345
+ try options.log.lastmiss(.{});
1346
+ try options.log.miss(.{battle.active(player)});
1347
+ }
1348
+
1349
+ return false;
1350
+ }
1351
+
1352
+ fn moveHit(
1353
+ battle: anytype,
1354
+ player: Player,
1355
+ move: Move.Data,
1356
+ immune: *bool,
1357
+ mist: *bool,
1358
+ options: anytype,
1359
+ ) bool {
1360
+ var side = battle.side(player);
1361
+ const foe = battle.foe(player);
1362
+
1363
+ var miss = miss: {
1364
+ assert(!side.active.volatiles.Bide);
1365
+
1366
+ // Invulnerability trumps everything on Pokémon Showdown
1367
+ if (showdown) {
1368
+ if (move.effect == .Swift) return true;
1369
+ if (foe.active.volatiles.Invulnerable) break :miss true;
1370
+ }
1371
+ if (move.effect == .DreamEater and (!Status.is(foe.stored().status, .SLP) or
1372
+ (showdown and foe.active.volatiles.Substitute)))
1373
+ {
1374
+ immune.* = true;
1375
+ if (showdown) return false;
1376
+ break :miss true;
1377
+ }
1378
+ if (!showdown) {
1379
+ if (move.effect == .Swift) return true;
1380
+ if (foe.active.volatiles.Invulnerable) break :miss true;
1381
+ }
1382
+
1383
+ // Hyper Beam + Sleep glitch needs to be special cased here due to control flow differences
1384
+ if (showdown and move.effect == .Sleep and foe.active.volatiles.Recharging) return true;
1385
+
1386
+ // Conversion / Haze / Light Screen / Reflect qualify but do not call moveHit
1387
+ if (foe.active.volatiles.Mist and move.effect.isStatDown()) {
1388
+ mist.* = true;
1389
+ if (!showdown) break :miss true;
1390
+ }
1391
+
1392
+ // GLITCH: Thrash / Petal Dance / Rage get their accuracy overwritten on subsequent hits
1393
+ const state = side.active.volatiles.state;
1394
+ var overwrite = move.effect == .Rage or move.effect == .Thrashing;
1395
+ const overwritten = overwrite and state > 0;
1396
+ assert(!overwritten or (0 < state and state <= 255 and !side.active.volatiles.Bide));
1397
+
1398
+ var accuracy: u16 = if (overwritten) state else move.accuracy;
1399
+ var boost = BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
1400
+ accuracy = accuracy * boost[0] / boost[1];
1401
+ boost = BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
1402
+ accuracy = accuracy * boost[0] / boost[1];
1403
+ accuracy = @min(255, @max(1, accuracy));
1404
+
1405
+ // Pokémon Showdown only overwrites if the volatile is present
1406
+ if (showdown) overwrite = side.active.volatiles.Rage or side.active.volatiles.Thrashing;
1407
+ if (overwrite) side.active.volatiles.state = accuracy;
1408
+
1409
+ // GLITCH: max accuracy is 255 so 1/256 chance of miss
1410
+ break :miss !Rolls.hit(battle, player, @intCast(accuracy), options);
1411
+ };
1412
+
1413
+ // Pokémon Showdown reports miss instead of fail for moves blocked by Mist that 1/256 miss
1414
+ if (showdown and mist.*) {
1415
+ mist.* = !miss;
1416
+ miss = true;
1417
+ }
1418
+
1419
+ if (!miss) return true;
1420
+ if (!showdown or !foe.active.volatiles.Invulnerable) battle.last_damage = 0;
1421
+ side.active.volatiles.Binding = false;
1422
+ return false;
1423
+ }
1424
+
1425
+ fn checkFaint(
1426
+ battle: anytype,
1427
+ player: Player,
1428
+ options: anytype,
1429
+ ) @TypeOf(options.log).Error!?Result {
1430
+ const side = battle.side(player);
1431
+ if (side.stored().hp > 0) return null;
1432
+
1433
+ const foe = battle.foe(player);
1434
+ const foe_fainted = foe.stored().hp == 0;
1435
+
1436
+ const player_out = findFirstAlive(side) == 0;
1437
+ const foe_out = foe_fainted and findFirstAlive(foe) == 0;
1438
+ const more = player_out or foe_out;
1439
+
1440
+ if (try faint(battle, player, !(more or foe_fainted), options)) |r| return r;
1441
+ if (foe_fainted) if (try faint(battle, player.foe(), !more, options)) |r| return r;
1442
+
1443
+ assert(!side.active.volatiles.MultiHit);
1444
+ assert(!foe.active.volatiles.MultiHit);
1445
+
1446
+ if (player_out and foe_out) {
1447
+ try options.log.tie(.{});
1448
+ return Result.Tie;
1449
+ } else if (player_out) {
1450
+ try options.log.win(.{player.foe()});
1451
+ return if (player == .P1) Result.Lose else Result.Win;
1452
+ } else if (foe_out) {
1453
+ try options.log.win(.{player});
1454
+ return if (player == .P1) Result.Win else Result.Lose;
1455
+ }
1456
+
1457
+ const foe_choice: Choice.Type = if (foe_fainted) .Switch else .Pass;
1458
+ if (player == .P1) return .{ .p1 = .Switch, .p2 = foe_choice };
1459
+ return .{ .p1 = foe_choice, .p2 = .Switch };
1460
+ }
1461
+
1462
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !?Result {
1463
+ var side = battle.side(player);
1464
+ var foe = battle.foe(player);
1465
+ assert(side.stored().hp == 0);
1466
+
1467
+ var foe_volatiles = &foe.active.volatiles;
1468
+ assert(!foe_volatiles.MultiHit);
1469
+ if (foe_volatiles.Bide) {
1470
+ assert(!foe_volatiles.Thrashing and !foe_volatiles.Rage);
1471
+ foe_volatiles.state = if (showdown) 0 else foe_volatiles.state & 255;
1472
+ if (foe_volatiles.state != 0) return Result.Error;
1473
+ }
1474
+
1475
+ // Clearing these is not strictly necessary as provided the battle hasn't ended the side that
1476
+ // just fainted will need to switch in a replacement and all of this gets cleared in switchIn
1477
+ // anyway. However, we would like to ensure the battle state presented to the players at each
1478
+ // decision point is consistent so we avoid "optimizing" this out
1479
+ // (we do always need to clear status though for Pokémon Showdown's Sleep/Freeze Clause Mod)
1480
+ side.active.volatiles = .{};
1481
+ side.last_used_move = .None;
1482
+ foe.last_used_move = .None;
1483
+ const status = side.stored().status;
1484
+
1485
+ side.stored().status = 0;
1486
+ // This shouldn't matter, but Pokémon Showdown decides double switching priority based on speed,
1487
+ // and resets a Pokémon's stats when it faints... only it still factors in paralysis -_-
1488
+ if (showdown) {
1489
+ side.active.stats.spe = if (Status.is(status, .PAR))
1490
+ @max(side.stored().stats.spe / 4, 1)
1491
+ else
1492
+ side.stored().stats.spe;
1493
+ }
1494
+
1495
+ try options.log.faint(.{ battle.active(player), done });
1496
+ options.calc.capped(player);
1497
+ return null;
1498
+ }
1499
+
1500
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !void {
1501
+ var side = battle.side(player);
1502
+ var stored = side.stored();
1503
+ const ident = battle.active(player);
1504
+ var volatiles = &side.active.volatiles;
1505
+
1506
+ const brn = Status.is(stored.status, .BRN);
1507
+ if (brn or Status.is(stored.status, .PSN)) {
1508
+ var damage = @max(stored.stats.hp / 16, 1);
1509
+ if (volatiles.Toxic) {
1510
+ volatiles.toxic += 1;
1511
+ damage *= volatiles.toxic;
1512
+ }
1513
+ damage = @min(damage, stored.hp);
1514
+
1515
+ if (!showdown or damage > 0) {
1516
+ stored.hp -= damage;
1517
+ // Pokémon Showdown uses damage [of] here but its not relevant in Generation I
1518
+ try options.log.damage(.{ ident, stored, if (brn) Damage.Burn else Damage.Poison });
1519
+ }
1520
+ }
1521
+
1522
+ if (volatiles.LeechSeed) {
1523
+ var foe = battle.foe(player);
1524
+ var foe_stored = foe.stored();
1525
+ const foe_ident = battle.active(player.foe());
1526
+
1527
+ if (foe_stored.hp == 0) {
1528
+ assert(showdown);
1529
+ return;
1530
+ }
1531
+
1532
+ var damage = @max(stored.stats.hp / 16, 1);
1533
+
1534
+ // GLITCH: Leech Seed + Toxic glitch
1535
+ if (volatiles.Toxic) {
1536
+ volatiles.toxic += 1;
1537
+ damage *= volatiles.toxic;
1538
+ }
1539
+
1540
+ const amount = @min(damage, stored.hp);
1541
+ stored.hp -= amount;
1542
+
1543
+ // As above, Pokémon Showdown uses damage [of] but its not relevant
1544
+ if (amount > 0) try options.log.damage(.{ ident, stored, .LeechSeed });
1545
+
1546
+ const before = foe_stored.hp;
1547
+ // Uncapped damage is added back to the foe
1548
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
1549
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
1550
+ if (foe_stored.hp > before) try options.log.heal(.{ foe_ident, foe_stored, .Silent });
1551
+ }
1552
+ }
1553
+
1554
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
1555
+ assert(!battle.side(.P1).active.volatiles.MultiHit);
1556
+ assert(!battle.side(.P2).active.volatiles.MultiHit);
1557
+
1558
+ battle.turn += 1;
1559
+
1560
+ if (showdown and pkmn.options.ebc and checkEBC(battle)) {
1561
+ try options.log.tie(.{});
1562
+ return Result.Tie;
1563
+ }
1564
+
1565
+ if (showdown and battle.turn >= 1000) {
1566
+ try options.log.tie(.{});
1567
+ return Result.Tie;
1568
+ } else if (battle.turn >= 65535) {
1569
+ return Result.Error;
1570
+ }
1571
+
1572
+ try options.log.turn(.{battle.turn});
1573
+
1574
+ return Result.Default;
1575
+ }
1576
+
1577
+ fn checkEBC(battle: anytype) bool {
1578
+ for (battle.sides, 0..) |side, i| {
1579
+ const foe = battle.sides[~@as(u1, @intCast(i))];
1580
+
1581
+ var foe_all_ghosts = true;
1582
+ var foe_all_transform = true;
1583
+ for (foe.order, 0..) |id, j| {
1584
+ if (id == 0) break;
1585
+ const active = j == 0;
1586
+ const pokemon = foe.pokemon[id - 1];
1587
+
1588
+ const ghost = pokemon.hp == 0 or
1589
+ (if (active) foe.active.types else pokemon.types).includes(.Ghost);
1590
+ foe_all_ghosts = foe_all_ghosts and ghost;
1591
+ foe_all_transform = foe_all_transform and pokemon.hp == 0 or transform: {
1592
+ for (if (active) foe.active.moves else pokemon.moves) |m| {
1593
+ if (m.id == .None) break :transform true;
1594
+ if (m.id != .Transform) break :transform false;
1595
+ }
1596
+ break :transform true;
1597
+ };
1598
+ }
1599
+
1600
+ for (side.order, 0..) |id, j| {
1601
+ if (id == 0) break;
1602
+ const active = j == 0;
1603
+ const pokemon = side.pokemon[id - 1];
1604
+
1605
+ if (pokemon.hp == 0 or Status.is(pokemon.status, .FRZ)) continue;
1606
+ const transform = foe_all_transform and transform: {
1607
+ for (if (active) side.active.moves else pokemon.moves) |m| {
1608
+ if (m.id == .None) break :transform true;
1609
+ if (m.id != .Transform) break :transform false;
1610
+ }
1611
+ break :transform true;
1612
+ };
1613
+ if (transform) continue;
1614
+ const no_pp = foe_all_ghosts and no_pp: {
1615
+ for (if (active) side.active.moves else pokemon.moves) |m| {
1616
+ if (m.pp != 0) break :no_pp false;
1617
+ }
1618
+ break :no_pp true;
1619
+ };
1620
+ if (no_pp) continue;
1621
+
1622
+ return false;
1623
+ }
1624
+
1625
+ if (i == 1) return true;
1626
+ }
1627
+
1628
+ return false;
1629
+ }
1630
+
1631
+ fn disabled(side: *Side, ident: ID, options: anytype) !bool {
1632
+ if (side.active.volatiles.disable_move != 0) {
1633
+ // A Pokémon that transforms after being disabled may end up with less move slots
1634
+ const m = side.active.moves[side.active.volatiles.disable_move - 1].id;
1635
+ // side.last_selected_move can be Struggle here on Pokemon Showdown we need an extra check
1636
+ const last = if (showdown and m == .Bide and side.active.volatiles.Bide)
1637
+ m
1638
+ else
1639
+ side.last_selected_move;
1640
+ if (m != .None and m == last) {
1641
+ side.active.volatiles.Charging = false;
1642
+ try options.log.cant(.{ ident, .Disable, last });
1643
+ return true;
1644
+ }
1645
+ }
1646
+ return false;
1647
+ }
1648
+
1649
+ fn buildRage(battle: anytype, who: Player, options: anytype) !void {
1650
+ const side = battle.side(who);
1651
+ if (side.active.volatiles.Rage and side.active.boosts.atk < 6) {
1652
+ try Effects.boost(battle, who, Move.get(.Rage), options);
1653
+ }
1654
+ }
1655
+
1656
+ fn handleThrashing(battle: anytype, active: *ActivePokemon, player: Player, options: anytype) bool {
1657
+ var volatiles = &active.volatiles;
1658
+ assert(volatiles.Thrashing);
1659
+ if (volatiles.attacks > 0) return false;
1660
+
1661
+ volatiles.Thrashing = false;
1662
+ volatiles.Confusion = true;
1663
+ volatiles.confusion = Rolls.confusionDuration(battle, player, true, options);
1664
+ return true;
1665
+ }
1666
+
1667
+ fn onBegin(
1668
+ battle: anytype,
1669
+ player: Player,
1670
+ move: Move.Data,
1671
+ mslot: u8,
1672
+ residual: *bool,
1673
+ options: anytype,
1674
+ ) !void {
1675
+ return switch (move.effect) {
1676
+ .Confusion => Effects.confusion(battle, player, move, options),
1677
+ .Conversion => Effects.conversion(battle, player, options),
1678
+ .FocusEnergy => Effects.focusEnergy(battle, player, options),
1679
+ .Haze => Effects.haze(battle, player, options),
1680
+ .Heal => Effects.heal(battle, player, options),
1681
+ .LeechSeed => Effects.leechSeed(battle, player, move, options),
1682
+ .LightScreen => Effects.lightScreen(battle, player, options),
1683
+ .Mimic => Effects.mimic(battle, player, move, mslot, options),
1684
+ .Mist => Effects.mist(battle, player, options),
1685
+ .Paralyze => Effects.paralyze(battle, player, move, options),
1686
+ .Poison => Effects.poison(battle, player, move, options),
1687
+ .Reflect => Effects.reflect(battle, player, options),
1688
+ .Splash => Effects.splash(battle, player, options),
1689
+ .Substitute => Effects.substitute(battle, player, residual, options),
1690
+ .SwitchAndTeleport => Effects.switchAndTeleport(battle, player, move, options),
1691
+ .Transform => Effects.transform(battle, player, options),
1692
+ else => unreachable,
1693
+ };
1694
+ }
1695
+
1696
+ fn onEnd(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1697
+ return switch (move.effect) {
1698
+ .Bide => Effects.bide(battle, player, options),
1699
+ // zig fmt: off
1700
+ .AttackUp1, .AttackUp2, .DefenseUp1, .DefenseUp2,
1701
+ .EvasionUp1, .SpecialUp1, .SpecialUp2, .SpeedUp2 =>
1702
+ Effects.boost(battle, player, move, options),
1703
+ .AccuracyDown1, .AttackDown1, .DefenseDown1, .DefenseDown2, .SpeedDown1 =>
1704
+ Effects.unboost(battle, player, move, options),
1705
+ // zig fmt: on
1706
+ .Sleep => Effects.sleep(battle, player, move, options),
1707
+ else => unreachable,
1708
+ };
1709
+ }
1710
+
1711
+ fn alwaysHappens(
1712
+ battle: anytype,
1713
+ player: Player,
1714
+ move: Move.Data,
1715
+ residual: *bool,
1716
+ options: anytype,
1717
+ ) !void {
1718
+ return switch (move.effect) {
1719
+ .DrainHP, .DreamEater => Effects.drainHP(battle, player, options),
1720
+ .Explode => Effects.explode(battle, player),
1721
+ .PayDay => Effects.payDay(battle, player, options),
1722
+ .Rage => Effects.rage(battle, player),
1723
+ .Recoil => Effects.recoil(battle, player, residual, options),
1724
+ .JumpKick, .Binding => {},
1725
+ else => unreachable,
1726
+ };
1727
+ }
1728
+
1729
+ fn moveEffect(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1730
+ return switch (move.effect) {
1731
+ .BurnChance1, .BurnChance2 => Effects.burnChance(battle, player, move, options),
1732
+ .ConfusionChance => Effects.confusion(battle, player, move, options),
1733
+ .FlinchChance1, .FlinchChance2 => Effects.flinchChance(battle, player, move, options),
1734
+ .FreezeChance => Effects.freezeChance(battle, player, move, options),
1735
+ .HyperBeam => Effects.hyperBeam(battle, player, options),
1736
+ .MultiHit, .DoubleHit, .Twineedle => unreachable,
1737
+ .ParalyzeChance1, .ParalyzeChance2 => Effects.paralyzeChance(battle, player, move, options),
1738
+ .PoisonChance1, .PoisonChance2 => Effects.poison(battle, player, move, options),
1739
+ // zig fmt: off
1740
+ .AttackDownChance, .DefenseDownChance, .SpecialDownChance, .SpeedDownChance =>
1741
+ Effects.unboost(battle, player, move, options),
1742
+ // zig fmt: on
1743
+ else => {},
1744
+ };
1745
+ }
1746
+
1747
+ pub const Effects = struct {
1748
+ fn bide(battle: anytype, player: Player, options: anytype) !void {
1749
+ var side = battle.side(player);
1750
+
1751
+ side.active.volatiles.Bide = true;
1752
+ assert(!side.active.volatiles.Thrashing and !side.active.volatiles.Rage);
1753
+ side.active.volatiles.state = 0;
1754
+ side.active.volatiles.attacks = Rolls.attackingDuration(battle, player, options);
1755
+
1756
+ try options.log.start(.{ battle.active(player), .Bide });
1757
+ }
1758
+
1759
+ fn burnChance(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1760
+ var foe = battle.foe(player);
1761
+ var foe_stored = foe.stored();
1762
+
1763
+ if (foe.active.volatiles.Substitute) return;
1764
+
1765
+ if (Status.any(foe_stored.status)) {
1766
+ if (showdown and !foe.active.types.includes(move.type)) battle.rng.advance(1);
1767
+ // GLITCH: Freeze top move selection desync can occur if thawed Pokémon is slower
1768
+ if (Status.is(foe_stored.status, .FRZ)) {
1769
+ assert(move.type == .Fire);
1770
+ try options.log.curestatus(.{
1771
+ battle.active(player.foe()),
1772
+ foe_stored.status,
1773
+ .Message,
1774
+ });
1775
+ foe_stored.status = 0;
1776
+ }
1777
+ return;
1778
+ }
1779
+
1780
+ if (foe.active.types.includes(move.type)) return;
1781
+ if (!try Rolls.secondaryChance(battle, player, move.effect == .BurnChance1, options)) {
1782
+ return;
1783
+ }
1784
+
1785
+ foe_stored.status = Status.init(.BRN);
1786
+ foe.active.stats.atk = @max(foe.active.stats.atk / 2, 1);
1787
+
1788
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
1789
+ }
1790
+
1791
+ fn charge(battle: anytype, player: Player, options: anytype) !void {
1792
+ var side = battle.side(player);
1793
+ var volatiles = &side.active.volatiles;
1794
+
1795
+ volatiles.Charging = true;
1796
+ const move = side.last_selected_move;
1797
+ if (move == .Fly or move == .Dig) volatiles.Invulnerable = true;
1798
+ try options.log.laststill(.{});
1799
+ try options.log.prepare(.{ battle.active(player), move });
1800
+ }
1801
+
1802
+ fn confusion(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1803
+ var foe = battle.foe(player);
1804
+ const sub = foe.active.volatiles.Substitute;
1805
+
1806
+ if (move.effect == .ConfusionChance) {
1807
+ if (!try Rolls.confusionChance(battle, player, options)) return;
1808
+ } else {
1809
+ if (showdown) {
1810
+ if (!try checkHit(battle, player, move, options)) return;
1811
+ if (sub) return options.log.fail(.{ battle.active(player.foe()), .None });
1812
+ } else {
1813
+ if (sub) return options.log.fail(.{ battle.active(player.foe()), .None });
1814
+ if (!try checkHit(battle, player, move, options)) return;
1815
+ }
1816
+ try options.chance.commit(player, .hit);
1817
+ }
1818
+
1819
+ if (foe.active.volatiles.Confusion) return;
1820
+ foe.active.volatiles.Confusion = true;
1821
+ foe.active.volatiles.confusion = Rolls.confusionDuration(battle, player, false, options);
1822
+
1823
+ try options.log.start(.{ battle.active(player.foe()), .Confusion });
1824
+ }
1825
+
1826
+ fn conversion(battle: anytype, player: Player, options: anytype) !void {
1827
+ const foe = battle.foe(player);
1828
+
1829
+ if (foe.active.volatiles.Invulnerable) {
1830
+ try options.log.lastmiss(.{});
1831
+ return options.log.miss(.{battle.active(player)});
1832
+ }
1833
+
1834
+ battle.side(player).active.types = foe.active.types;
1835
+ return options.log.start(.{
1836
+ battle.active(player),
1837
+ .TypeChange,
1838
+ foe.active.types,
1839
+ battle.active(player.foe()),
1840
+ });
1841
+ }
1842
+
1843
+ fn disable(battle: anytype, player: Player, move: Move.Data, options: anytype) !?Result {
1844
+ var foe = battle.foe(player);
1845
+ var volatiles = &foe.active.volatiles;
1846
+ const foe_ident = battle.active(player.foe());
1847
+
1848
+ // Pokémon Showdown handles hit/miss earlier in doMove
1849
+ if (!showdown) {
1850
+ if (!try checkHit(battle, player, move, options)) return null;
1851
+ try options.chance.commit(player, .hit);
1852
+ }
1853
+
1854
+ if (volatiles.disable_move != 0) {
1855
+ try options.log.fail(.{ foe_ident, .None });
1856
+ return null;
1857
+ }
1858
+
1859
+ var n: u4 = 0;
1860
+ var err = true;
1861
+ for (foe.active.moves) |m| {
1862
+ if (m.pp > 0) {
1863
+ n += 1;
1864
+ if (m.id != .None) err = false;
1865
+ }
1866
+ }
1867
+
1868
+ // Technically this is still considered simply a "miss" on the cartridge,
1869
+ // but diverging from Pokémon Showdown here would mostly just be pedantic
1870
+ if (n == 0) {
1871
+ try options.log.fail(.{ foe_ident, .None });
1872
+ return null;
1873
+ } else if (err) {
1874
+ // GLITCH: Transform + Mirror Move / Metronome PP softlock
1875
+ assert(!showdown);
1876
+ return Result.Error;
1877
+ }
1878
+
1879
+ volatiles.disable_move =
1880
+ @intCast(try Rolls.moveSlot(battle, player, &foe.active.moves, n, options));
1881
+ volatiles.disable_duration = Rolls.disableDuration(battle, player, options);
1882
+
1883
+ const id = foe.active.move(volatiles.disable_move).id;
1884
+ try options.log.start(.{ foe_ident, .Disable, id });
1885
+ return null;
1886
+ }
1887
+
1888
+ fn drainHP(battle: anytype, player: Player, options: anytype) !void {
1889
+ var stored = battle.side(player).stored();
1890
+ const ident = battle.active(player);
1891
+
1892
+ if (battle.last_damage == 0) {
1893
+ assert(showdown);
1894
+ if (!battle.foe(player).active.volatiles.Substitute) return;
1895
+ }
1896
+
1897
+ const drain = @max(battle.last_damage / 2, 1);
1898
+ battle.last_damage = drain;
1899
+
1900
+ if (stored.hp == stored.stats.hp) return;
1901
+ stored.hp = @min(stored.stats.hp, stored.hp + drain);
1902
+
1903
+ try options.log.heal(.{ ident, stored, .Drain, battle.active(player.foe()) });
1904
+ }
1905
+
1906
+ fn explode(battle: anytype, player: Player) !void {
1907
+ var side = battle.side(player);
1908
+ var stored = side.stored();
1909
+
1910
+ stored.hp = 0;
1911
+ // Pokémon Showdown sets the status to 0 on faint(), and we need to do the same to be able
1912
+ // to correctly implement Pokémon Showdown's dumb speed-based switch mechanics
1913
+ if (!showdown) stored.status = 0;
1914
+ side.active.volatiles.LeechSeed = false;
1915
+ }
1916
+
1917
+ fn flinchChance(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1918
+ var volatiles = &battle.foe(player).active.volatiles;
1919
+
1920
+ if (volatiles.Substitute) return;
1921
+ if (!try Rolls.secondaryChance(battle, player, move.effect == .FlinchChance1, options)) {
1922
+ return;
1923
+ }
1924
+
1925
+ volatiles.Flinch = true;
1926
+ volatiles.Recharging = false;
1927
+ }
1928
+
1929
+ fn focusEnergy(battle: anytype, player: Player, options: anytype) !void {
1930
+ var side = battle.side(player);
1931
+
1932
+ if (side.active.volatiles.FocusEnergy) return;
1933
+ side.active.volatiles.FocusEnergy = true;
1934
+
1935
+ try options.log.start(.{ battle.active(player), .FocusEnergy });
1936
+ }
1937
+
1938
+ fn freezeChance(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1939
+ var foe = battle.foe(player);
1940
+ var foe_stored = foe.stored();
1941
+ const foe_ident = battle.active(player.foe());
1942
+
1943
+ if (foe.active.volatiles.Substitute) return;
1944
+
1945
+ if (Status.any(foe_stored.status)) {
1946
+ return if (showdown and !foe.active.types.includes(move.type)) battle.rng.advance(1);
1947
+ }
1948
+
1949
+ if (foe.active.types.includes(move.type)) return;
1950
+ if (!try Rolls.secondaryChance(battle, player, true, options)) return;
1951
+ // Freeze Clause Mod
1952
+ if (showdown) for (foe.pokemon) |p| if (Status.is(p.status, .FRZ)) return;
1953
+
1954
+ foe_stored.status = Status.init(.FRZ);
1955
+ // GLITCH: Hyper Beam recharging status is not cleared
1956
+
1957
+ try options.log.status(.{ foe_ident, foe_stored.status, .None });
1958
+ }
1959
+
1960
+ fn haze(battle: anytype, player: Player, options: anytype) !void {
1961
+ var log = options.log;
1962
+ var side = battle.side(player);
1963
+ var foe = battle.foe(player);
1964
+
1965
+ const side_stored = side.stored();
1966
+ var foe_stored = foe.stored();
1967
+
1968
+ const player_ident = battle.active(player);
1969
+ const foe_ident = battle.active(player.foe());
1970
+
1971
+ side.active.boosts = .{};
1972
+ foe.active.boosts = .{};
1973
+
1974
+ side.active.stats = side_stored.stats;
1975
+ foe.active.stats = foe_stored.stats;
1976
+
1977
+ try log.activate(.{ player_ident, .Haze });
1978
+ try log.clearallboost(.{});
1979
+
1980
+ // Pokémon Showdown clears P1 then P2 instead of status -> side -> foe
1981
+ if (showdown) {
1982
+ for (&battle.sides, 0..) |*s, i| {
1983
+ const p: Player = @enumFromInt(i);
1984
+ // Pokémon Showdown incorrectly does not prevent sleep/freeze from moving
1985
+ if (p != player and Status.any(s.stored().status)) {
1986
+ try log.curestatus(.{ foe_ident, foe_stored.status, .Silent });
1987
+ s.stored().status = 0;
1988
+ } else if (showdown and s.stored().status == Status.TOX) {
1989
+ s.stored().status = Status.init(.PSN);
1990
+ try log.status(.{ battle.active(p), s.stored().status, .None });
1991
+ }
1992
+ try clearVolatiles(battle, p, p != player, options);
1993
+ }
1994
+ } else {
1995
+ if (Status.any(foe_stored.status)) {
1996
+ if (Status.is(foe_stored.status, .FRZ) or Status.is(foe_stored.status, .SLP)) {
1997
+ foe.last_selected_move = .SKIP_TURN;
1998
+ }
1999
+ try log.curestatus(.{ foe_ident, foe_stored.status, .Silent });
2000
+ foe_stored.status = 0;
2001
+ }
2002
+ try clearVolatiles(battle, player, false, options);
2003
+ try clearVolatiles(battle, player.foe(), true, options);
2004
+ }
2005
+ }
2006
+
2007
+ fn heal(battle: anytype, player: Player, options: anytype) !void {
2008
+ var side = battle.side(player);
2009
+ var stored = side.stored();
2010
+ const ident = battle.active(player);
2011
+
2012
+ // GLITCH: HP recovery move failure glitches
2013
+ const delta = stored.stats.hp - stored.hp;
2014
+ if (delta == 0 or (delta & 255 == 255 and stored.hp % 256 != 0)) {
2015
+ return options.log.fail(.{ ident, .None });
2016
+ }
2017
+
2018
+ const rest = side.last_selected_move == .Rest;
2019
+ if (rest) {
2020
+ // Adding the sleep status runs the sleep condition handler to roll duration
2021
+ if (showdown) battle.rng.advance(1);
2022
+ stored.status = Status.slf(2);
2023
+ try options.log.status(.{ ident, stored.status, .From, Move.Rest });
2024
+ stored.hp = stored.stats.hp;
2025
+ } else {
2026
+ stored.hp = @min(stored.stats.hp, stored.hp + (stored.stats.hp / 2));
2027
+ }
2028
+ try options.log.heal(.{ ident, stored, if (rest) Heal.Silent else Heal.None });
2029
+ }
2030
+
2031
+ fn hyperBeam(battle: anytype, player: Player, options: anytype) !void {
2032
+ battle.side(player).active.volatiles.Recharging = true;
2033
+ try options.log.mustrecharge(.{battle.active(player)});
2034
+ }
2035
+
2036
+ fn leechSeed(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2037
+ var foe = battle.foe(player);
2038
+
2039
+ if (showdown) {
2040
+ // Invulnerability trumps type immunity on Pokémon Showdown
2041
+ if (!foe.active.volatiles.Invulnerable and foe.active.types.includes(.Grass)) {
2042
+ return options.log.immune(.{ battle.active(player.foe()), .None });
2043
+ }
2044
+ if (!try checkHit(battle, player, move, options)) return;
2045
+ if (foe.active.volatiles.LeechSeed) return;
2046
+ } else {
2047
+ if (!try checkHit(battle, player, move, options)) return;
2048
+ if (foe.active.types.includes(.Grass) or foe.active.volatiles.LeechSeed) {
2049
+ try options.log.lastmiss(.{});
2050
+ return options.log.miss(.{battle.active(player)});
2051
+ }
2052
+ }
2053
+
2054
+ try options.chance.commit(player, .hit);
2055
+ foe.active.volatiles.LeechSeed = true;
2056
+
2057
+ try options.log.start(.{ battle.active(player.foe()), .LeechSeed });
2058
+ }
2059
+
2060
+ fn lightScreen(battle: anytype, player: Player, options: anytype) !void {
2061
+ var side = battle.side(player);
2062
+ const ident = battle.active(player);
2063
+
2064
+ if (side.active.volatiles.LightScreen) return options.log.fail(.{ ident, .None });
2065
+ side.active.volatiles.LightScreen = true;
2066
+
2067
+ try options.log.start(.{ ident, .LightScreen });
2068
+ }
2069
+
2070
+ fn mimic(battle: anytype, player: Player, move: Move.Data, mslot: u8, options: anytype) !void {
2071
+ var side = battle.side(player);
2072
+ var foe = battle.foe(player);
2073
+
2074
+ // Pokémon Showdown incorrectly requires the user to have Mimic (but not necessarily at
2075
+ // mslot). In reality, Mimic can also be called via Metronome or Mirror Move
2076
+ assert(showdown or side.active.move(mslot).id == .Mimic or
2077
+ side.active.move(mslot).id == .Metronome or
2078
+ side.active.move(mslot).id == .MirrorMove);
2079
+
2080
+ // Pokémon Showdown incorrectly replaces the existing Mimic's slot instead of mslot
2081
+ var oslot = mslot;
2082
+ if (showdown) {
2083
+ const has_mimic = has_mimic: {
2084
+ for (side.active.moves, 0..) |m, i| {
2085
+ if (m.id == .Mimic) {
2086
+ oslot = @intCast(i + 1);
2087
+ break :has_mimic true;
2088
+ }
2089
+ }
2090
+ break :has_mimic false;
2091
+ };
2092
+ if (!has_mimic) {
2093
+ // Invulnerable foes or 1/256 miss can trigger |-miss| instead of |-fail|
2094
+ if (!try checkHit(battle, player, move, options)) return;
2095
+ try options.chance.commit(player, .hit);
2096
+ return options.log.fail(.{ battle.active(player.foe()), .None });
2097
+ }
2098
+ }
2099
+ if (!try checkHit(battle, player, move, options)) return;
2100
+ try options.chance.commit(player, .hit);
2101
+
2102
+ const rslot = try Rolls.moveSlot(battle, player, &foe.active.moves, 0, options);
2103
+ side.active.move(oslot).id = foe.active.move(rslot).id;
2104
+
2105
+ try options.log.start(.{ battle.active(player), .Mimic, side.active.move(oslot).id });
2106
+ }
2107
+
2108
+ fn mist(battle: anytype, player: Player, options: anytype) !void {
2109
+ var side = battle.side(player);
2110
+
2111
+ if (side.active.volatiles.Mist) return;
2112
+ side.active.volatiles.Mist = true;
2113
+
2114
+ try options.log.start(.{ battle.active(player), .Mist });
2115
+ }
2116
+
2117
+ fn multiHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2118
+ var side = battle.side(player);
2119
+
2120
+ assert(!side.active.volatiles.MultiHit);
2121
+ side.active.volatiles.MultiHit = true;
2122
+
2123
+ side.active.volatiles.attacks = if (move.effect == .MultiHit)
2124
+ try Rolls.distribution(battle, .MultiHit, player, options)
2125
+ else
2126
+ 2;
2127
+ }
2128
+
2129
+ fn paralyze(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2130
+ var log = options.log;
2131
+ var foe = battle.foe(player);
2132
+ var foe_stored = foe.stored();
2133
+ const foe_ident = battle.active(player.foe());
2134
+
2135
+ // Only Thunder Wave checks for type-immunity, not Glare
2136
+ const immune = move.type == .Electric and foe.active.types.immune(move.type);
2137
+
2138
+ if (showdown) {
2139
+ // Invulnerability trumps type immunity on Pokémon Showdown
2140
+ if (immune and !foe.active.volatiles.Invulnerable) {
2141
+ return log.immune(.{ foe_ident, .None });
2142
+ } else if (!try checkHit(battle, player, move, options)) return;
2143
+ }
2144
+ if (Status.any(foe_stored.status)) {
2145
+ return log.fail(.{
2146
+ foe_ident,
2147
+ if (Status.is(foe_stored.status, .PAR)) Fail.Paralysis else Fail.None,
2148
+ });
2149
+ }
2150
+ if (!showdown) {
2151
+ if (immune) return log.immune(.{ foe_ident, .None });
2152
+ if (!try checkHit(battle, player, move, options)) return;
2153
+ }
2154
+ try options.chance.commit(player, .hit);
2155
+
2156
+ foe_stored.status = Status.init(.PAR);
2157
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2158
+
2159
+ try log.status(.{ foe_ident, foe_stored.status, .None });
2160
+ }
2161
+
2162
+ fn paralyzeChance(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2163
+ var foe = battle.foe(player);
2164
+ var foe_stored = foe.stored();
2165
+
2166
+ if (foe.active.volatiles.Substitute) return;
2167
+
2168
+ if (Status.any(foe_stored.status)) {
2169
+ return if (showdown and !foe.active.types.includes(move.type)) battle.rng.advance(1);
2170
+ }
2171
+
2172
+ // Body Slam can't paralyze a Normal type Pokémon
2173
+ if (foe.active.types.includes(move.type)) return;
2174
+ if (!try Rolls.secondaryChance(battle, player, move.effect == .ParalyzeChance1, options)) {
2175
+ return;
2176
+ }
2177
+
2178
+ foe_stored.status = Status.init(.PAR);
2179
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2180
+
2181
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
2182
+ }
2183
+
2184
+ fn payDay(battle: anytype, player: Player, options: anytype) !void {
2185
+ if (!showdown or !battle.foe(player).active.volatiles.Substitute) {
2186
+ try options.log.fieldactivate(.{});
2187
+ }
2188
+ }
2189
+
2190
+ fn poison(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2191
+ var log = options.log;
2192
+ var foe = battle.foe(player);
2193
+ var foe_stored = foe.stored();
2194
+ const foe_ident = battle.active(player.foe());
2195
+ const toxic = battle.side(player).last_selected_move == .Toxic;
2196
+
2197
+ if (showdown and move.effect == .Poison and !try checkHit(battle, player, move, options)) {
2198
+ return;
2199
+ } else if (foe.active.volatiles.Substitute) {
2200
+ if (move.effect != .Poison) return;
2201
+ return log.fail(.{ foe_ident, .None });
2202
+ } else if (Status.any(foe_stored.status)) {
2203
+ if (move.effect != .Poison) return if (showdown) battle.rng.advance(1);
2204
+ // Pokémon Showdown considers Toxic to be a status even in Generation I and so
2205
+ // will not include a fail reason for Toxic vs. Poison or vice-versa...
2206
+ return log.fail(.{ foe_ident, if (Status.is(foe_stored.status, .PSN))
2207
+ if (!showdown)
2208
+ Fail.Poison
2209
+ else if (toxic == (foe_stored.status == Status.TOX))
2210
+ if (toxic) Fail.Toxic else Fail.Poison
2211
+ else
2212
+ Fail.None
2213
+ else
2214
+ Fail.None });
2215
+ } else if (foe.active.types.includes(.Poison)) {
2216
+ if (move.effect != .Poison) return if (showdown) battle.rng.advance(1);
2217
+ return log.immune(.{ foe_ident, .None });
2218
+ }
2219
+
2220
+ if (move.effect == .Poison) {
2221
+ if (!showdown and !try checkHit(battle, player, move, options)) return;
2222
+ try options.chance.commit(player, .hit);
2223
+ } else {
2224
+ if (!try Rolls.poisonChance(battle, player, move.effect == .PoisonChance1, options)) {
2225
+ return;
2226
+ }
2227
+ }
2228
+
2229
+ foe_stored.status = Status.init(.PSN);
2230
+ if (toxic) {
2231
+ if (showdown) foe_stored.status = Status.TOX;
2232
+ foe.active.volatiles.Toxic = true;
2233
+ foe.active.volatiles.toxic = 0;
2234
+ }
2235
+
2236
+ try log.status(.{ foe_ident, foe_stored.status, .None });
2237
+ }
2238
+
2239
+ fn rage(battle: anytype, player: Player) !void {
2240
+ var volatiles = &battle.side(player).active.volatiles;
2241
+ assert(!volatiles.Bide);
2242
+ volatiles.Rage = true;
2243
+ }
2244
+
2245
+ fn recoil(battle: anytype, player: Player, residual: *bool, options: anytype) !void {
2246
+ var side = battle.side(player);
2247
+ var stored = side.stored();
2248
+
2249
+ assert(showdown or battle.last_damage > 0);
2250
+ if (showdown and battle.last_damage == 0) return;
2251
+
2252
+ const damage: i16 = @intCast(@max(battle.last_damage /
2253
+ @as(u8, if (side.last_selected_move == .Struggle) 2 else 4), 1));
2254
+ stored.hp = @intCast(@max(@as(i16, @intCast(stored.hp)) - damage, 0));
2255
+
2256
+ try options.log.damage(.{
2257
+ battle.active(player),
2258
+ stored,
2259
+ .RecoilOf,
2260
+ battle.active(player.foe()),
2261
+ });
2262
+ if (showdown and stored.hp == 0) residual.* = false;
2263
+ }
2264
+
2265
+ fn reflect(battle: anytype, player: Player, options: anytype) !void {
2266
+ var side = battle.side(player);
2267
+ const ident = battle.active(player);
2268
+
2269
+ if (side.active.volatiles.Reflect) return options.log.fail(.{ ident, .None });
2270
+ side.active.volatiles.Reflect = true;
2271
+
2272
+ try options.log.start(.{ ident, .Reflect });
2273
+ }
2274
+
2275
+ fn sleep(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2276
+ var foe = battle.foe(player);
2277
+ var foe_stored = foe.stored();
2278
+ const foe_ident = battle.active(player.foe());
2279
+
2280
+ if (foe.active.volatiles.Recharging) {
2281
+ // Hit test not applied if the target is recharging (bypass)
2282
+ // The volatile itself actually gets cleared below since on Pokémon Showdown
2283
+ // the Sleep Clause Mod might activate, causing us to not actually bypass
2284
+ } else {
2285
+ if (Status.any(foe_stored.status)) {
2286
+ return options.log.fail(.{
2287
+ foe_ident,
2288
+ if (Status.is(foe_stored.status, .SLP)) Fail.Sleep else Fail.None,
2289
+ });
2290
+ }
2291
+ // If checkHit in doMove didn't return true Pokémon Showdown wouldn't be in here
2292
+ if (!showdown and !try checkHit(battle, player, move, options)) return;
2293
+ try options.chance.commit(player, .hit);
2294
+ }
2295
+
2296
+ // Sleep Clause Mod
2297
+ if (showdown) {
2298
+ for (foe.pokemon) |p| {
2299
+ if (Status.is(p.status, .SLP) and !Status.is(p.status, .EXT)) return;
2300
+ }
2301
+ }
2302
+ foe.active.volatiles.Recharging = false;
2303
+
2304
+ foe_stored.status = Status.slp(Rolls.sleepDuration(battle, player, options));
2305
+ const last = battle.side(player).last_selected_move;
2306
+ try options.log.status(.{ foe_ident, foe_stored.status, .From, last });
2307
+ }
2308
+
2309
+ fn splash(battle: anytype, player: Player, options: anytype) !void {
2310
+ try options.log.activate(.{ battle.active(player), .Splash });
2311
+ }
2312
+
2313
+ fn substitute(battle: anytype, player: Player, residual: *bool, options: anytype) !void {
2314
+ var side = battle.side(player);
2315
+ if (side.active.volatiles.Substitute) {
2316
+ return options.log.fail(.{ battle.active(player), .Substitute });
2317
+ }
2318
+
2319
+ assert(side.stored().stats.hp <= 1023);
2320
+ // Will be 0 if HP is <= 3 meaning that the user gets a 1 HP Substitute for "free"
2321
+ const hp: u8 = @intCast(side.stored().stats.hp / 4);
2322
+ // Pokénon Showdown incorrectly checks for 1/4 HP based on `target.maxhp / 4` which returns
2323
+ // a floating point value and thus only correctly implements the Substitute 1/4 glitch when
2324
+ // the target's HP is exactly divisible by 4 (here we're using an inlined divCeil routine to
2325
+ // avoid having to convert to floating point)
2326
+ const required_hp = if (showdown) @divFloor(side.stored().stats.hp - 1, 4) + 1 else hp;
2327
+ if (side.stored().hp < required_hp) {
2328
+ return options.log.fail(.{ battle.active(player), .Weak });
2329
+ }
2330
+
2331
+ // GLITCH: can leave the user with 0 HP (faints later) because didn't check '<=' above
2332
+ side.stored().hp -= hp;
2333
+ side.active.volatiles.substitute = hp + 1;
2334
+ side.active.volatiles.Substitute = true;
2335
+ try options.log.start(.{ battle.active(player), .Substitute });
2336
+ if (hp > 0) {
2337
+ try options.log.damage(.{ battle.active(player), side.stored(), .None });
2338
+ if (showdown and side.stored().hp == 0) residual.* = false;
2339
+ }
2340
+ }
2341
+
2342
+ fn switchAndTeleport(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2343
+ // Whirlwind/Roar should not roll to hit/reset damage but Pokémon Showdown does anyway
2344
+ if (showdown) {
2345
+ if (battle.side(player).last_selected_move == .Teleport) return;
2346
+ if (try checkHit(battle, player, move, options)) {
2347
+ try options.chance.commit(player, .hit);
2348
+ }
2349
+ battle.last_damage = 0;
2350
+ } else {
2351
+ try options.log.fail(.{ battle.active(player), .None });
2352
+ try options.log.laststill(.{});
2353
+ }
2354
+ }
2355
+
2356
+ fn thrashing(battle: anytype, player: Player, options: anytype) void {
2357
+ var volatiles = &battle.side(player).active.volatiles;
2358
+ assert(!volatiles.Thrashing);
2359
+ assert(!volatiles.Bide);
2360
+
2361
+ volatiles.Thrashing = true;
2362
+ volatiles.attacks = Rolls.attackingDuration(battle, player, options);
2363
+ }
2364
+
2365
+ fn transform(battle: anytype, player: Player, options: anytype) !void {
2366
+ var side = battle.side(player);
2367
+ const foe = battle.foe(player);
2368
+ const foe_ident = battle.active(player.foe());
2369
+
2370
+ side.active.volatiles.Transform = true;
2371
+ // foe could themselves be transformed
2372
+ side.active.volatiles.transform = if (foe.active.volatiles.transform != 0)
2373
+ foe.active.volatiles.transform
2374
+ else
2375
+ foe_ident.int();
2376
+
2377
+ // HP is not copied by Transform
2378
+ side.active.stats.atk = foe.active.stats.atk;
2379
+ side.active.stats.def = foe.active.stats.def;
2380
+ side.active.stats.spe = foe.active.stats.spe;
2381
+ side.active.stats.spc = foe.active.stats.spc;
2382
+
2383
+ side.active.species = foe.active.species;
2384
+ side.active.types = foe.active.types;
2385
+ side.active.boosts = foe.active.boosts;
2386
+ for (foe.active.moves, 0..) |m, i| {
2387
+ side.active.moves[i].id = m.id;
2388
+ side.active.moves[i].pp = if (m.id != .None) 5 else 0;
2389
+ }
2390
+
2391
+ try options.log.transform(.{ battle.active(player), foe_ident });
2392
+ }
2393
+
2394
+ fn binding(battle: anytype, player: Player, rewrap: bool, options: anytype) !void {
2395
+ var side = battle.side(player);
2396
+ var foe = battle.foe(player);
2397
+
2398
+ if (side.active.volatiles.Binding) return;
2399
+ side.active.volatiles.Binding = true;
2400
+ // GLITCH: Hyper Beam automatic selection glitch if Recharging gets cleared on miss
2401
+ // (Pokémon Showdown unitentionally patches this glitch, preventing automatic selection)
2402
+ if (!showdown) {
2403
+ foe.active.volatiles.Recharging = false;
2404
+ } else if (foe.stored().hp == 0) return if (!rewrap) battle.rng.advance(1);
2405
+
2406
+ side.active.volatiles.attacks =
2407
+ try Rolls.distribution(battle, .Binding, player, options) - 1;
2408
+ }
2409
+
2410
+ fn boost(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2411
+ var log = options.log;
2412
+ var side = battle.side(player);
2413
+ const ident = battle.active(player);
2414
+
2415
+ var stats = &side.active.stats;
2416
+ var boosts = &side.active.boosts;
2417
+
2418
+ switch (move.effect) {
2419
+ .AttackUp1, .AttackUp2, .Rage => {
2420
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2421
+ if (boosts.atk == 6) return log.fail(.{ ident, .None });
2422
+ const n: u2 = if (move.effect == .AttackUp2) 2 else 1;
2423
+ boosts.atk = @as(i4, @intCast(@min(6, @as(i8, boosts.atk) + n)));
2424
+ const reason: Boost = if (move.effect == .Rage) .Rage else .Attack;
2425
+ if (stats.atk == MAX_STAT_VALUE) {
2426
+ boosts.atk -= 1;
2427
+ if (showdown) {
2428
+ try log.boost(.{ ident, reason, n });
2429
+ try log.boost(.{ ident, .Attack, -1 });
2430
+ if (move.effect == .Rage) return;
2431
+ }
2432
+ return log.fail(.{ ident, .None });
2433
+ }
2434
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.atk) + 6))];
2435
+ const stat = unmodifiedStats(battle, side).atk;
2436
+ stats.atk = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2437
+ try log.boost(.{ ident, reason, n });
2438
+ // Pokémon Showdown doesn't re-apply status modifiers after Rage boosts
2439
+ if (showdown and move.effect == .Rage) return;
2440
+ },
2441
+ .DefenseUp1, .DefenseUp2 => {
2442
+ assert(boosts.def >= -6 and boosts.def <= 6);
2443
+ if (boosts.def == 6) return log.fail(.{ ident, .None });
2444
+ const n: u2 = if (move.effect == .DefenseUp2) 2 else 1;
2445
+ boosts.def = @intCast(@min(6, @as(i8, boosts.def) + n));
2446
+ if (stats.def == MAX_STAT_VALUE) {
2447
+ boosts.def -= 1;
2448
+ if (showdown) {
2449
+ try log.boost(.{ ident, .Defense, n });
2450
+ try log.boost(.{ ident, .Defense, -1 });
2451
+ }
2452
+ return log.fail(.{ ident, .None });
2453
+ }
2454
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.def) + 6))];
2455
+ const stat = unmodifiedStats(battle, side).def;
2456
+ stats.def = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2457
+ try log.boost(.{ ident, .Defense, n });
2458
+ },
2459
+ .SpeedUp2 => {
2460
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2461
+ if (boosts.spe == 6) return log.fail(.{ ident, .None });
2462
+ boosts.spe = @intCast(@min(6, @as(i8, boosts.spe) + 2));
2463
+ if (stats.spe == MAX_STAT_VALUE) {
2464
+ boosts.spe -= 1;
2465
+ if (showdown) {
2466
+ try log.boost(.{ ident, .Speed, 2 });
2467
+ try log.boost(.{ ident, .Speed, -1 });
2468
+ }
2469
+ return log.fail(.{ ident, .None });
2470
+ }
2471
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.spe) + 6))];
2472
+ const stat = unmodifiedStats(battle, side).spe;
2473
+ stats.spe = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2474
+ try log.boost(.{ ident, .Speed, 2 });
2475
+ },
2476
+ .SpecialUp1, .SpecialUp2 => {
2477
+ assert(boosts.spc >= -6 and boosts.spc <= 6);
2478
+ if (boosts.spc == 6) return log.fail(.{ ident, .None });
2479
+ const n: u2 = if (move.effect == .SpecialUp2) 2 else 1;
2480
+ boosts.spc = @intCast(@min(6, @as(i8, boosts.spc) + n));
2481
+ if (stats.spc == MAX_STAT_VALUE) {
2482
+ boosts.spc -= 1;
2483
+ if (showdown) {
2484
+ try log.boost(.{ ident, .SpecialAttack, n });
2485
+ try log.boost(.{ ident, .SpecialAttack, -1 });
2486
+ try log.boost(.{ ident, .SpecialDefense, n });
2487
+ try log.boost(.{ ident, .SpecialDefense, -1 });
2488
+ }
2489
+ return log.fail(.{ ident, .None });
2490
+ }
2491
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.spc) + 6))];
2492
+ const stat = unmodifiedStats(battle, side).spc;
2493
+ stats.spc = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2494
+ try log.boost(.{ ident, .SpecialAttack, n });
2495
+ try log.boost(.{ ident, .SpecialDefense, n });
2496
+ },
2497
+ .EvasionUp1 => {
2498
+ assert(boosts.evasion >= -6 and boosts.evasion <= 6);
2499
+ if (boosts.evasion == 6) return log.fail(.{ ident, .None });
2500
+ boosts.evasion = @intCast(@min(6, @as(i8, boosts.evasion) + 1));
2501
+ try log.boost(.{ ident, .Evasion, 1 });
2502
+ },
2503
+ else => unreachable,
2504
+ }
2505
+
2506
+ // GLITCH: Stat modification errors glitch
2507
+ statusModify(battle.foe(player).stored().status, &battle.foe(player).active.stats);
2508
+ }
2509
+
2510
+ fn unboost(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
2511
+ var log = options.log;
2512
+ var foe = battle.foe(player);
2513
+ const foe_ident = battle.active(player.foe());
2514
+ const secondary = move.effect.isStatDownChance();
2515
+
2516
+ if (foe.active.volatiles.Substitute) return if (!secondary) log.fail(.{ foe_ident, .None });
2517
+
2518
+ if (secondary) {
2519
+ const proc = try Rolls.unboost(battle, player, options);
2520
+ if (!proc or foe.active.volatiles.Invulnerable) return;
2521
+ } else {
2522
+ // checkHit already checks for Invulnerable
2523
+ if (!showdown and !try checkHit(battle, player, move, options)) return;
2524
+ try options.chance.commit(player, .hit);
2525
+ }
2526
+
2527
+ var stats = &foe.active.stats;
2528
+ var boosts = &foe.active.boosts;
2529
+ const fail = showdown or !secondary;
2530
+
2531
+ switch (move.effect) {
2532
+ .AttackDown1, .AttackDownChance => {
2533
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2534
+ if (boosts.atk == -6) return if (fail) try log.fail(.{ foe_ident, .None });
2535
+ boosts.atk = @intCast(@max(-6, @as(i8, boosts.atk) - 1));
2536
+ if (stats.atk == 1) {
2537
+ boosts.atk += 1;
2538
+ if (showdown) {
2539
+ try log.boost(.{ foe_ident, .Attack, -1 });
2540
+ try log.boost(.{ foe_ident, .Attack, 1 });
2541
+ }
2542
+ return log.fail(.{ foe_ident, .None });
2543
+ }
2544
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.atk) + 6))];
2545
+ const stat = unmodifiedStats(battle, foe).atk;
2546
+ stats.atk = @max(1, stat * mod[0] / mod[1]);
2547
+ try log.boost(.{ foe_ident, .Attack, -1 });
2548
+ },
2549
+ .DefenseDown1, .DefenseDown2, .DefenseDownChance => {
2550
+ assert(boosts.def >= -6 and boosts.def <= 6);
2551
+ if (boosts.def == -6) return if (fail) try log.fail(.{ foe_ident, .None });
2552
+ const n: u2 = if (move.effect == .DefenseDown2) 2 else 1;
2553
+ boosts.def = @intCast(@max(-6, @as(i8, boosts.def) - n));
2554
+ if (stats.def == 1) {
2555
+ boosts.def += 1;
2556
+ if (showdown) {
2557
+ try log.boost(.{ foe_ident, .Defense, -@as(i8, n) });
2558
+ try log.boost(.{ foe_ident, .Defense, 1 });
2559
+ }
2560
+ return log.fail(.{ foe_ident, .None });
2561
+ }
2562
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.def) + 6))];
2563
+ const stat = unmodifiedStats(battle, foe).def;
2564
+ stats.def = @max(1, stat * mod[0] / mod[1]);
2565
+ try log.boost(.{ foe_ident, .Defense, -@as(i8, n) });
2566
+ },
2567
+ .SpeedDown1, .SpeedDownChance => {
2568
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2569
+ if (boosts.spe == -6) return if (fail) try log.fail(.{ foe_ident, .None });
2570
+ boosts.spe = @intCast(@max(-6, @as(i8, boosts.spe) - 1));
2571
+ if (stats.spe == 1) {
2572
+ boosts.spe += 1;
2573
+ if (showdown) {
2574
+ try log.boost(.{ foe_ident, .Speed, -1 });
2575
+ try log.boost(.{ foe_ident, .Speed, 1 });
2576
+ }
2577
+ return log.fail(.{ foe_ident, .None });
2578
+ }
2579
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.spe) + 6))];
2580
+ const stat = unmodifiedStats(battle, foe).spe;
2581
+ stats.spe = @max(1, stat * mod[0] / mod[1]);
2582
+ try log.boost(.{ foe_ident, .Speed, -1 });
2583
+ assert(boosts.spe >= -6);
2584
+ },
2585
+ .SpecialDownChance => {
2586
+ assert(boosts.spc >= -6 and boosts.spc <= 6);
2587
+ if (boosts.spc == -6) return if (fail) try log.fail(.{ foe_ident, .None });
2588
+ boosts.spc = @intCast(@max(-6, @as(i8, boosts.spc) - 1));
2589
+ if (stats.spc == 1) {
2590
+ boosts.spc += 1;
2591
+ if (showdown) {
2592
+ try log.boost(.{ foe_ident, .SpecialAttack, -1 });
2593
+ try log.boost(.{ foe_ident, .SpecialAttack, 1 });
2594
+ try log.boost(.{ foe_ident, .SpecialDefense, -1 });
2595
+ try log.boost(.{ foe_ident, .SpecialDefense, 1 });
2596
+ }
2597
+ return log.fail(.{ foe_ident, .None });
2598
+ }
2599
+ const mod = BOOSTS[@as(u4, @intCast(@as(i8, boosts.spc) + 6))];
2600
+ const stat = unmodifiedStats(battle, foe).spc;
2601
+ stats.spc = @max(1, stat * mod[0] / mod[1]);
2602
+ try log.boost(.{ foe_ident, .SpecialAttack, -1 });
2603
+ try log.boost(.{ foe_ident, .SpecialDefense, -1 });
2604
+ },
2605
+ .AccuracyDown1 => {
2606
+ assert(boosts.accuracy >= -6 and boosts.accuracy <= 6);
2607
+ if (boosts.accuracy == -6) return if (fail) try log.fail(.{ foe_ident, .None });
2608
+ boosts.accuracy = @intCast(@max(-6, @as(i8, boosts.accuracy) - 1));
2609
+ try log.boost(.{ foe_ident, .Accuracy, -1 });
2610
+ },
2611
+ else => unreachable,
2612
+ }
2613
+
2614
+ // GLITCH: Stat modification errors glitch
2615
+ statusModify(foe.stored().status, stats);
2616
+ }
2617
+ };
2618
+
2619
+ fn unmodifiedStats(battle: anytype, side: *Side) *Stats(u16) {
2620
+ if (!side.active.volatiles.Transform) return &side.stored().stats;
2621
+ const id = ID.from(side.active.volatiles.transform);
2622
+ return &battle.side(id.player).pokemon[id.id - 1].stats;
2623
+ }
2624
+
2625
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
2626
+ if (Status.is(status, .PAR)) {
2627
+ stats.spe = @max(stats.spe / 4, 1);
2628
+ } else if (Status.is(status, .BRN)) {
2629
+ stats.atk = @max(stats.atk / 2, 1);
2630
+ }
2631
+ }
2632
+
2633
+ fn isForced(active: anytype) bool {
2634
+ return active.volatiles.Recharging or active.volatiles.Rage or
2635
+ active.volatiles.Thrashing or active.volatiles.Charging;
2636
+ }
2637
+
2638
+ fn clearVolatiles(battle: anytype, who: Player, clear: bool, options: anytype) !void {
2639
+ var log = options.log;
2640
+ var side = battle.side(who);
2641
+ var volatiles = &side.active.volatiles;
2642
+ const ident = battle.active(who);
2643
+
2644
+ options.chance.clearDurations(who, clear);
2645
+
2646
+ if (volatiles.disable_move != 0) {
2647
+ volatiles.disable_move = 0;
2648
+ volatiles.disable_duration = 0;
2649
+ try log.end(.{ ident, .DisableSilent });
2650
+ }
2651
+ if (volatiles.Confusion) {
2652
+ // volatiles.confusion is left unchanged
2653
+ volatiles.Confusion = false;
2654
+ try log.end(.{ ident, .ConfusionSilent });
2655
+ }
2656
+ if (volatiles.Mist) {
2657
+ volatiles.Mist = false;
2658
+ try log.end(.{ ident, .MistSilent });
2659
+ }
2660
+ if (volatiles.FocusEnergy) {
2661
+ volatiles.FocusEnergy = false;
2662
+ try log.end(.{ ident, .FocusEnergySilent });
2663
+ }
2664
+ if (volatiles.LeechSeed) {
2665
+ volatiles.LeechSeed = false;
2666
+ try log.end(.{ ident, .LeechSeedSilent });
2667
+ }
2668
+ if (!showdown and volatiles.Toxic) {
2669
+ volatiles.Toxic = false;
2670
+ // volatiles.toxic is left unchanged, except on Pokémon Showdown which clears it (below)
2671
+ }
2672
+ if (volatiles.LightScreen) {
2673
+ volatiles.LightScreen = false;
2674
+ try log.end(.{ ident, .LightScreenSilent });
2675
+ }
2676
+ if (volatiles.Reflect) {
2677
+ volatiles.Reflect = false;
2678
+ try log.end(.{ ident, .ReflectSilent });
2679
+ }
2680
+ if (showdown and volatiles.Toxic) {
2681
+ volatiles.Toxic = false;
2682
+ // Pokémon Showdown erroneously clears the toxic counter
2683
+ volatiles.toxic = 0;
2684
+ try log.end(.{ ident, .ToxicSilent });
2685
+ }
2686
+ }
2687
+
2688
+ pub const Rolls = struct {
2689
+ fn speedTie(battle: anytype, options: anytype) !bool {
2690
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
2691
+ player == .P1
2692
+ else if (@hasDecl(@TypeOf(battle.rng), "speedTie"))
2693
+ battle.rng.speedTie()
2694
+ else if (showdown)
2695
+ battle.rng.range(u8, 0, 2) == 0
2696
+ else
2697
+ battle.rng.next() < Gen12.percent(50) + 1;
2698
+
2699
+ try options.chance.speedTie(p1);
2700
+ return p1;
2701
+ }
2702
+
2703
+ fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
2704
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
2705
+ val == .true
2706
+ else if (@hasDecl(@TypeOf(battle.rng), "criticalHit"))
2707
+ battle.rng.criticalHit(player, rate)
2708
+ else if (showdown)
2709
+ battle.rng.chance(u8, rate, 256)
2710
+ else
2711
+ std.math.rotl(u8, battle.rng.next(), 3) < rate;
2712
+
2713
+ try options.chance.criticalHit(player, crit, rate);
2714
+ return crit;
2715
+ }
2716
+
2717
+ fn damage(battle: anytype, player: Player, options: anytype) !u8 {
2718
+ const roll = if (options.calc.overridden(player, .damage)) |val|
2719
+ val
2720
+ else if (@hasDecl(@TypeOf(battle.rng), "damage"))
2721
+ battle.rng.damage(player)
2722
+ else roll: {
2723
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
2724
+ while (true) {
2725
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
2726
+ if (r >= 217) break :roll r;
2727
+ }
2728
+ };
2729
+
2730
+ assert(roll >= 217 and roll <= 255);
2731
+ try options.chance.damage(player, roll);
2732
+ return roll;
2733
+ }
2734
+
2735
+ const uN = if (pkmn.options.miss) u8 else u9;
2736
+ fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) bool {
2737
+ const acc: uN = if (pkmn.options.miss) accuracy else @as(uN, accuracy) + 1;
2738
+ const ok = if (options.calc.overridden(player, .hit)) |val|
2739
+ val == .true
2740
+ else if (@hasDecl(@TypeOf(battle.rng), "hit"))
2741
+ battle.rng.hit(player, acc)
2742
+ else if (showdown)
2743
+ battle.rng.chance(uN, acc, 256)
2744
+ else
2745
+ battle.rng.next() < acc;
2746
+
2747
+ options.chance.hit(ok, acc);
2748
+ return ok;
2749
+ }
2750
+
2751
+ fn confused(battle: anytype, player: Player, options: anytype) !bool {
2752
+ const cfz = if (options.calc.overridden(player, .confused)) |val|
2753
+ val == .true
2754
+ else if (@hasDecl(@TypeOf(battle.rng), "confused"))
2755
+ battle.rng.confused(player)
2756
+ else if (showdown)
2757
+ !battle.rng.chance(u8, 128, 256)
2758
+ else
2759
+ battle.rng.next() >= Gen12.percent(50) + 1;
2760
+
2761
+ try options.chance.confused(player, cfz);
2762
+ return cfz;
2763
+ }
2764
+
2765
+ fn paralyzed(battle: anytype, player: Player, options: anytype) !bool {
2766
+ const par = if (options.calc.overridden(player, .paralyzed)) |val|
2767
+ val == .true
2768
+ else if (@hasDecl(@TypeOf(battle.rng), "paralyzed"))
2769
+ battle.rng.paralyzed(player)
2770
+ else if (showdown)
2771
+ battle.rng.chance(u8, 63, 256)
2772
+ else
2773
+ battle.rng.next() < Gen12.percent(25);
2774
+
2775
+ try options.chance.paralyzed(player, par);
2776
+ return par;
2777
+ }
2778
+
2779
+ fn confusionChance(battle: anytype, player: Player, options: anytype) !bool {
2780
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
2781
+ val == .true
2782
+ else if (@hasDecl(@TypeOf(battle.rng), "secondaryChance"))
2783
+ battle.rng.secondaryChance(player, 25)
2784
+ else if (showdown)
2785
+ battle.rng.chance(u8, 25, 256)
2786
+ else
2787
+ battle.rng.next() < Gen12.percent(10);
2788
+
2789
+ try options.chance.secondaryChance(player, proc, 25);
2790
+ return proc;
2791
+ }
2792
+
2793
+ fn secondaryChance(battle: anytype, player: Player, low: bool, options: anytype) !bool {
2794
+ const rate: u8 = if (low) 26 else 77;
2795
+
2796
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
2797
+ val == .true
2798
+ else if (@hasDecl(@TypeOf(battle.rng), "secondaryChance"))
2799
+ battle.rng.secondaryChance(player, rate)
2800
+ else if (showdown)
2801
+ battle.rng.chance(u8, rate, 256)
2802
+ else
2803
+ battle.rng.next() < 1 + (if (low) Gen12.percent(10) else Gen12.percent(30));
2804
+
2805
+ try options.chance.secondaryChance(player, proc, rate);
2806
+ return proc;
2807
+ }
2808
+
2809
+ fn poisonChance(battle: anytype, player: Player, low: bool, options: anytype) !bool {
2810
+ const rate: u8 = if (low) 52 else 103;
2811
+
2812
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
2813
+ val == .true
2814
+ else if (@hasDecl(@TypeOf(battle.rng), "secondaryChance"))
2815
+ battle.rng.secondaryChance(player, rate)
2816
+ else if (showdown)
2817
+ battle.rng.chance(u8, rate, 256)
2818
+ else
2819
+ battle.rng.next() < 1 + (if (low) Gen12.percent(20) else Gen12.percent(40));
2820
+
2821
+ try options.chance.secondaryChance(player, proc, rate);
2822
+ return proc;
2823
+ }
2824
+
2825
+ fn unboost(battle: anytype, player: Player, options: anytype) !bool {
2826
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
2827
+ val == .true
2828
+ else if (@hasDecl(@TypeOf(battle.rng), "secondaryChance"))
2829
+ battle.rng.secondaryChance(player, 85)
2830
+ else if (showdown)
2831
+ battle.rng.chance(u8, 85, 256)
2832
+ else
2833
+ battle.rng.next() < Gen12.percent(33) + 1;
2834
+
2835
+ try options.chance.secondaryChance(player, proc, 85);
2836
+ return proc;
2837
+ }
2838
+
2839
+ fn metronome(battle: anytype, player: Player, options: anytype) !Move {
2840
+ const move: Move = if (options.calc.overridden(player, .metronome)) |val|
2841
+ val
2842
+ else if (@hasDecl(@TypeOf(battle.rng), "metronome"))
2843
+ battle.rng.metronome(player)
2844
+ else if (showdown)
2845
+ Move.METRONOME[battle.rng.range(u8, 0, Move.METRONOME.len)]
2846
+ else move: {
2847
+ while (true) {
2848
+ const r = battle.rng.next();
2849
+ if (r == 0 or r == @intFromEnum(Move.Metronome)) continue;
2850
+ if (r >= @intFromEnum(Move.Struggle)) continue;
2851
+ break :move @enumFromInt(r);
2852
+ }
2853
+ };
2854
+
2855
+ try options.chance.metronome(player, move);
2856
+ return move;
2857
+ }
2858
+
2859
+ fn psywave(battle: anytype, player: Player, max: u8, options: anytype) !u8 {
2860
+ const power = if (options.calc.overridden(player, .psywave)) |val|
2861
+ val - 1
2862
+ else if (@hasDecl(@TypeOf(battle.rng), "psywave"))
2863
+ battle.rng.psywave(player)
2864
+ else if (showdown)
2865
+ battle.rng.range(u8, 0, max)
2866
+ else power: {
2867
+ while (true) {
2868
+ const r = battle.rng.next();
2869
+ if (r < max) break :power r;
2870
+ }
2871
+ };
2872
+
2873
+ assert(power < max);
2874
+ try options.chance.psywave(player, power, max);
2875
+ return power;
2876
+ }
2877
+
2878
+ fn sleepDuration(battle: anytype, player: Player, options: anytype) u3 {
2879
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
2880
+ @intCast(val)
2881
+ else if (@hasDecl(@TypeOf(battle.rng), "sleepDuration"))
2882
+ battle.rng.sleepDuration(player)
2883
+ else if (showdown)
2884
+ battle.rng.range(u3, 1, 8)
2885
+ else duration: {
2886
+ while (true) {
2887
+ const r = battle.rng.next() & 7;
2888
+ if (r != 0) break :duration @intCast(r);
2889
+ }
2890
+ };
2891
+
2892
+ assert(duration >= 1 and duration <= 7);
2893
+ options.chance.duration(.sleep, player, player.foe(), duration);
2894
+ return duration;
2895
+ }
2896
+
2897
+ fn disableDuration(battle: anytype, player: Player, options: anytype) u4 {
2898
+ const duration: u4 = if (options.calc.overridden(player, .duration)) |val|
2899
+ val
2900
+ else if (@hasDecl(@TypeOf(battle.rng), "disableDuration"))
2901
+ battle.rng.disableDuration(player)
2902
+ else if (showdown)
2903
+ battle.rng.range(u4, 1, 9)
2904
+ else
2905
+ @intCast((battle.rng.next() & 7) + 1);
2906
+
2907
+ assert(duration >= 1 and duration <= 8);
2908
+ options.chance.duration(.disable, player, player.foe(), duration);
2909
+ return duration;
2910
+ }
2911
+
2912
+ fn confusionDuration(battle: anytype, player: Player, self: bool, options: anytype) u3 {
2913
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
2914
+ @intCast(val)
2915
+ else if (@hasDecl(@TypeOf(battle.rng), "confusionDuration"))
2916
+ battle.rng.confusionDuration(player, self)
2917
+ else if (showdown)
2918
+ battle.rng.range(u3, 2, 6)
2919
+ else
2920
+ @intCast((battle.rng.next() & 3) + 2);
2921
+
2922
+ assert(duration >= 2 and duration <= 5);
2923
+ options.chance.duration(.confusion, player, if (self) player else player.foe(), duration);
2924
+ return duration;
2925
+ }
2926
+
2927
+ fn attackingDuration(battle: anytype, player: Player, options: anytype) u3 {
2928
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
2929
+ @intCast(val)
2930
+ else if (@hasDecl(@TypeOf(battle.rng), "attackingDuration"))
2931
+ battle.rng.attackingDuration(player)
2932
+ else if (showdown)
2933
+ battle.rng.range(u3, 2, 4)
2934
+ else
2935
+ @intCast((battle.rng.next() & 1) + 2);
2936
+
2937
+ assert(duration >= 2 and duration <= 3);
2938
+ options.chance.duration(.attacking, player, player, duration);
2939
+ return duration;
2940
+ }
2941
+
2942
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
2943
+
2944
+ fn distribution(
2945
+ battle: anytype,
2946
+ comptime effect: Move.Effect,
2947
+ player: Player,
2948
+ options: anytype,
2949
+ ) !u3 {
2950
+ const roll = if (effect == .Binding) .duration else .multi_hit;
2951
+ const n: u3 = if (options.calc.overridden(player, roll)) |val|
2952
+ @intCast(val)
2953
+ else if (@hasDecl(@TypeOf(battle.rng), "distribution"))
2954
+ battle.rng.distribution(player)
2955
+ else if (showdown)
2956
+ DISTRIBUTION[battle.rng.range(u3, 0, DISTRIBUTION.len)]
2957
+ else n: {
2958
+ const r = (battle.rng.next() & 3);
2959
+ break :n @intCast((if (r < 2) r else battle.rng.next() & 3) + 2);
2960
+ };
2961
+
2962
+ assert(n >= 2 and n <= 5);
2963
+ if (effect == .Binding) {
2964
+ options.chance.duration(.binding, player, player, n);
2965
+ } else {
2966
+ try options.chance.multiHit(player, n);
2967
+ }
2968
+ return n;
2969
+ }
2970
+
2971
+ fn moveSlot(
2972
+ battle: anytype,
2973
+ player: Player,
2974
+ moves: []MoveSlot,
2975
+ check_pp: u4,
2976
+ options: anytype,
2977
+ ) !u4 {
2978
+ // TODO: consider throwing error instead of rerolling?
2979
+ const overridden = if (options.calc.overridden(player, .move_slot)) |val|
2980
+ if (moves[val - 1].id != .None and (check_pp == 0 or moves[val - 1].pp > 0))
2981
+ val
2982
+ else
2983
+ null
2984
+ else
2985
+ null;
2986
+
2987
+ const slot: u4 = overridden orelse if (@hasDecl(@TypeOf(battle.rng), "moveSlot"))
2988
+ battle.rng.moveSlot(player, moves, check_pp)
2989
+ else slot: {
2990
+ if (showdown) {
2991
+ if (check_pp == 0) {
2992
+ var i: usize = moves.len;
2993
+ while (i > 0) {
2994
+ i -= 1;
2995
+ if (moves[i].id != .None) {
2996
+ break :slot battle.rng.range(u4, 0, @as(u4, @intCast(i + 1))) + 1;
2997
+ }
2998
+ }
2999
+ } else {
3000
+ var r = battle.rng.range(u4, 0, check_pp) + 1;
3001
+ var i: usize = 0;
3002
+ while (i < moves.len and r > 0) : (i += 1) {
3003
+ if (moves[i].pp > 0) {
3004
+ r -= 1;
3005
+ if (r == 0) break :slot @intCast(i + 1);
3006
+ }
3007
+ }
3008
+ }
3009
+ }
3010
+
3011
+ while (true) {
3012
+ const r: u4 = @intCast(battle.rng.next() & 3);
3013
+ if (moves[r].id != .None and (check_pp == 0 or moves[r].pp > 0)) break :slot r + 1;
3014
+ }
3015
+ };
3016
+
3017
+ try options.chance.moveSlot(player, slot, moves, check_pp);
3018
+ return slot;
3019
+ }
3020
+ };
3021
+
3022
+ test "RNG agreement" {
3023
+ if (!showdown) return;
3024
+ var expected: [256]u32 = undefined;
3025
+ for (0..expected.len) |i| {
3026
+ expected[i] = @intCast(i * 0x1000000);
3027
+ }
3028
+
3029
+ var spe: rng.FixedRNG(1, expected.len) = .{ .rolls = expected };
3030
+ var cfz: rng.FixedRNG(1, expected.len) = .{ .rolls = expected };
3031
+ var par: rng.FixedRNG(1, expected.len) = .{ .rolls = expected };
3032
+ var brn: rng.FixedRNG(1, expected.len) = .{ .rolls = expected };
3033
+ var eff: rng.FixedRNG(1, expected.len) = .{ .rolls = expected };
3034
+
3035
+ for (0..expected.len) |i| {
3036
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
3037
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
3038
+ try expectEqual(par.chance(u8, 63, 256), i < Gen12.percent(25));
3039
+ try expectEqual(brn.chance(u8, 26, 256), i < Gen12.percent(10) + 1);
3040
+ try expectEqual(eff.chance(u8, 85, 256), i < Gen12.percent(33) + 1);
3041
+ }
3042
+ }
3043
+
3044
+ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
3045
+ var n: u8 = 0;
3046
+ switch (request) {
3047
+ .Pass => {
3048
+ out[n] = .{};
3049
+ n += 1;
3050
+ },
3051
+ .Switch => {
3052
+ const side = battle.side(player);
3053
+ var slot: u4 = 2;
3054
+ while (slot <= 6) : (slot += 1) {
3055
+ const id = side.order[slot - 1];
3056
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
3057
+ out[n] = .{ .type = .Switch, .data = slot };
3058
+ n += 1;
3059
+ }
3060
+ if (n == 0) {
3061
+ out[n] = .{};
3062
+ n += 1;
3063
+ }
3064
+ },
3065
+ .Move => {
3066
+ const side = battle.side(player);
3067
+ const foe = battle.foe(player);
3068
+
3069
+ const active = &side.active;
3070
+ const stored = side.stored();
3071
+
3072
+ // While players are not given any input options on the cartridge in these cases,
3073
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
3074
+ //
3075
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
3076
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
3077
+ // between passing while waiting for an opponent's forced switch after fainting and
3078
+ // passing due to being forced into using a move. Instead of introducing another option
3079
+ // we simply repurpose Move with no move slot, even though pedantically this is not
3080
+ // strictly correct as the player would not have been presented the option to move or
3081
+ // switch at all.
3082
+ if (isForced(active)) {
3083
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
3084
+ n += 1;
3085
+ return n;
3086
+ }
3087
+
3088
+ var slot: u4 = 2;
3089
+ while (slot <= 6) : (slot += 1) {
3090
+ const id = side.order[slot - 1];
3091
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
3092
+ out[n] = .{ .type = .Switch, .data = slot };
3093
+ n += 1;
3094
+ }
3095
+
3096
+ const limited = active.volatiles.Bide or active.volatiles.Binding;
3097
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
3098
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
3099
+ // either disables all other moves in the case of limited or requires you to select a
3100
+ // move normally if sleeping/frozen/bound.
3101
+ if (!showdown and (limited or foe.active.volatiles.Binding or
3102
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
3103
+ {
3104
+ out[n] = .{ .type = .Move, .data = 0 };
3105
+ n += 1;
3106
+ return n;
3107
+ }
3108
+
3109
+ slot = 1;
3110
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
3111
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
3112
+ // Move will not result in forcing the subsequent use unless the user also had the
3113
+ // proc-ed move in their moveset) and disabling all other moves.
3114
+ if (limited) {
3115
+ assert(showdown);
3116
+ assert(side.last_selected_move != .None);
3117
+ while (slot <= 4) : (slot += 1) {
3118
+ const m = active.moves[slot - 1];
3119
+ if (m.id == .None) break;
3120
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
3121
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
3122
+ const struggle =
3123
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disable_move == slot);
3124
+ const s = if (struggle) 0 else slot;
3125
+ out[n] = .{ .type = .Move, .data = s };
3126
+ n += 1;
3127
+ return n;
3128
+ }
3129
+ }
3130
+ }
3131
+
3132
+ const before = n;
3133
+ slot = 1;
3134
+ while (slot <= 4) : (slot += 1) {
3135
+ const m = active.moves[slot - 1];
3136
+ if (m.id == .None) break;
3137
+ if (m.pp == 0) continue;
3138
+ if (active.volatiles.disable_move == slot) continue;
3139
+ out[n] = .{ .type = .Move, .data = slot };
3140
+ n += 1;
3141
+ }
3142
+ // Struggle (Pokémon Showdown would use 'move 1' here)
3143
+ if (n == before) {
3144
+ // GLITCH: Transform + Mirror Move / Metronome PP softlock
3145
+ if (!showdown) {
3146
+ while (slot <= 4) : (slot += 1) {
3147
+ if (active.moves[slot - 1].pp != 0) return n;
3148
+ }
3149
+ }
3150
+ out[n] = .{ .type = .Move, .data = 0 };
3151
+ n += 1;
3152
+ }
3153
+ },
3154
+ }
3155
+ return n;
3156
+ }