@pkmn/engine 0.1.0-dev.028ab165

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