@pkmn/engine 0.1.0-dev.63cef311 → 0.1.0-dev.6e63f5e4

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