@pkmn/engine 0.1.0-dev.d3e796d5 → 0.1.0-dev.d4bd80b1

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 (84) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +51 -23
  3. package/build/pkg/addon/browser.d.ts +3 -0
  4. package/build/pkg/addon/browser.js +47 -0
  5. package/build/pkg/addon/browser.js.map +1 -0
  6. package/build/pkg/addon/node.d.ts +3 -0
  7. package/build/pkg/addon/node.js +110 -0
  8. package/build/pkg/addon/node.js.map +1 -0
  9. package/build/pkg/addon/wasm.d.ts +2 -0
  10. package/build/pkg/addon/wasm.js +53 -0
  11. package/build/pkg/addon/wasm.js.map +1 -0
  12. package/build/pkg/addon.d.ts +25 -3
  13. package/build/pkg/addon.js +39 -71
  14. package/build/pkg/addon.js.map +1 -1
  15. package/build/pkg/data/ids.json +12 -12
  16. package/build/pkg/data/layout.json +17 -4
  17. package/build/pkg/data/protocol.json +84 -13
  18. package/build/pkg/data.d.ts +27 -5
  19. package/build/pkg/data.js.map +1 -1
  20. package/build/pkg/gen1.d.ts +15 -18
  21. package/build/pkg/gen1.js +30 -21
  22. package/build/pkg/gen1.js.map +1 -1
  23. package/build/pkg/index.d.ts +42 -91
  24. package/build/pkg/index.js +23 -70
  25. package/build/pkg/index.js.map +1 -1
  26. package/build/pkg/protocol.d.ts +20 -1
  27. package/build/pkg/protocol.js +123 -102
  28. package/build/pkg/protocol.js.map +1 -1
  29. package/build/tools/debug.js +53 -76
  30. package/build/tools/debug.js.map +1 -1
  31. package/build/tools/display/debug.jsx +152 -0
  32. package/build/tools/display/debug.jsx.map +1 -0
  33. package/build/tools/display/index.js +152 -0
  34. package/build/tools/display/index.js.map +1 -0
  35. package/build/tools/display/ui.jsx +359 -0
  36. package/build/tools/display/ui.jsx.map +1 -0
  37. package/build/tools/display/util.js +33 -0
  38. package/build/tools/display/util.js.map +1 -0
  39. package/build.zig +347 -104
  40. package/package.json +62 -123
  41. package/src/bin/install-pkmn-engine +31 -20
  42. package/src/bin/pkmn-debug +1 -1
  43. package/src/lib/bindings/c.zig +255 -0
  44. package/src/lib/{binding → bindings}/node.zig +9 -22
  45. package/src/lib/bindings/wasm.zig +59 -0
  46. package/src/lib/common/array.zig +77 -0
  47. package/src/lib/common/data.zig +12 -24
  48. package/src/lib/common/debug.zig +39 -8
  49. package/src/lib/common/js.zig +4 -2
  50. package/src/lib/common/optional.zig +21 -10
  51. package/src/lib/common/options.zig +6 -0
  52. package/src/lib/common/protocol.zig +746 -324
  53. package/src/lib/common/rational.zig +132 -36
  54. package/src/lib/common/rng.zig +22 -15
  55. package/src/lib/common/util.zig +50 -1
  56. package/src/lib/gen1/calc.zig +688 -161
  57. package/src/lib/gen1/chance.zig +436 -295
  58. package/src/lib/gen1/data/moves.zig +193 -183
  59. package/src/lib/gen1/data/species.zig +4 -6
  60. package/src/lib/gen1/data/types.zig +8 -9
  61. package/src/lib/gen1/data.zig +55 -70
  62. package/src/lib/gen1/helpers.zig +91 -562
  63. package/src/lib/gen1/mechanics.zig +658 -575
  64. package/src/lib/gen2/calc.zig +153 -0
  65. package/src/lib/gen2/chance.zig +902 -0
  66. package/src/lib/gen2/data/items.zig +13 -21
  67. package/src/lib/gen2/data/moves.zig +650 -571
  68. package/src/lib/gen2/data/species.zig +2 -4
  69. package/src/lib/gen2/data/types.zig +135 -33
  70. package/src/lib/gen2/data.zig +88 -88
  71. package/src/lib/gen2/generated.zig +801 -0
  72. package/src/lib/gen2/helpers.zig +50 -34
  73. package/src/lib/gen2/mechanics.zig +3212 -125
  74. package/src/lib/node.zig +18 -0
  75. package/src/lib/pkmn.zig +37 -15
  76. package/src/lib/wasm.zig +17 -0
  77. package/src/tools/display/dom.ts +95 -0
  78. package/src/tools/display/ui.css +354 -0
  79. package/build/test/display.js +0 -400
  80. package/build/test/display.js.map +0 -1
  81. package/src/lib/binding/wasm.zig +0 -12
  82. package/src/lib/gen1/README.md +0 -892
  83. package/src/lib/gen2/README.md +0 -383
  84. package/src/test/display/pkmn.html.tmpl +0 -368
@@ -1,39 +1,115 @@
1
- const std = @import("std");
2
-
3
- const pkmn = @import("../pkmn.zig");
1
+ const DEBUG = @import("../common/debug.zig").print;
4
2
 
3
+ const builtin = @import("builtin");
5
4
  const common = @import("../common/data.zig");
6
- const DEBUG = @import("../common/debug.zig").print;
5
+ const data = @import("data.zig");
6
+ const generated = @import("generated.zig");
7
+ const pkmn = @import("../pkmn.zig");
7
8
  const protocol = @import("../common/protocol.zig");
8
9
  const rng = @import("../common/rng.zig");
10
+ const std = @import("std");
9
11
 
10
- const data = @import("data.zig");
11
-
12
+ const Activate = protocol.Activate;
13
+ const ActivePokemon = data.ActivePokemon;
12
14
  const assert = std.debug.assert;
13
-
14
- const expectEqual = std.testing.expectEqual;
15
-
15
+ const Boost = protocol.Boost;
16
+ const Boosts = data.Boosts;
16
17
  const Choice = common.Choice;
18
+ const Damage = protocol.Damage;
19
+ const Effectiveness = data.Effectiveness;
20
+ const End = protocol.End;
21
+ const expectEqual = std.testing.expectEqual;
22
+ const expectEqualSlices = std.testing.expectEqualSlices;
23
+ const expectEqualStrings = std.testing.expectEqualStrings;
24
+ const Fail = protocol.Fail;
25
+ const Gen12 = rng.Gen12;
26
+ const Heal = protocol.Heal;
17
27
  const ID = common.ID;
28
+ const Item = data.Item;
29
+ const Move = data.Move;
18
30
  const Player = common.Player;
19
31
  const Result = common.Result;
20
-
21
32
  const showdown = pkmn.options.showdown;
22
-
23
- const Damage = protocol.Damage;
24
- const Heal = protocol.Heal;
25
-
26
- const Gen12 = rng.Gen12;
27
-
28
- const ActivePokemon = data.ActivePokemon;
29
- const Effectiveness = data.Effectiveness;
30
- const Move = data.Move;
31
- const MoveSlot = data.MoveSlot;
32
- const Pokemon = data.Pokemon;
33
33
  const Side = data.Side;
34
- const Species = data.Species;
34
+ const Start = protocol.Start;
35
35
  const Stats = data.Stats;
36
36
  const Status = data.Status;
37
+ const TriAttack = data.TriAttack;
38
+ const Type = data.Type;
39
+ const Types = data.Types;
40
+ const Volatiles = data.Volatiles;
41
+ const Weather = data.Weather;
42
+
43
+ // zig fmt: off
44
+ const STAT_BOOSTS = &[_][2]u8{
45
+ .{ 25, 100 }, // -6
46
+ .{ 28, 100 }, // -5
47
+ .{ 33, 100 }, // -4
48
+ .{ 40, 100 }, // -3
49
+ .{ 50, 100 }, // -2
50
+ .{ 66, 100 }, // -1
51
+ .{ 1, 1 }, // 0
52
+ .{ 15, 10 }, // +1
53
+ .{ 2, 1 }, // +2
54
+ .{ 25, 10 }, // +3
55
+ .{ 3, 1 }, // +4
56
+ .{ 35, 10 }, // +5
57
+ .{ 4, 1 }, // +6
58
+ };
59
+
60
+ const ACCURACY_BOOSTS = &[_][2]u8{
61
+ .{ 33, 100 }, // -6
62
+ .{ 36, 100 }, // -5
63
+ .{ 43, 100 }, // -4
64
+ .{ 50, 100 }, // -3
65
+ .{ 60, 100 }, // -2
66
+ .{ 75, 100 }, // -1
67
+ .{ 1, 1 }, // 0
68
+ .{ 133, 100 }, // +1
69
+ .{ 166, 100 }, // +2
70
+ .{ 2, 1 }, // +3
71
+ .{ 233, 100 }, // +4
72
+ .{ 133, 50 }, // +5
73
+ .{ 3, 1 }, // +6
74
+ };
75
+
76
+ const CRITICAL_HITS = &[_]u8{
77
+ 256 / 15, // 0
78
+ 256 / 8, // +1
79
+ 256 / 4, // +2
80
+ 256 / 3, // +3
81
+ 256 / 2, // +4
82
+ };
83
+ // zig fmt: on
84
+
85
+ const MAX_STAT_VALUE = 999;
86
+
87
+ const STATS = [_][]const u8{ "atk", "def", "spe", "spa", "spd" };
88
+
89
+ pub const State = struct {
90
+ damage: u16 = 0, // wCurDamage
91
+ effectiveness: u16 = Effectiveness.neutral, // wTypeModifier
92
+ bp: u8, // wPlayerMoveStructPower
93
+ type: Type, // BATTLE_VARS_MOVE_TYPE
94
+ accuracy: u8, // wEnemyMoveStruct + MOVE_ACC
95
+ move: Move, // wCurPlayerMove
96
+ hit: u3 = 0,
97
+ from: Move = .None,
98
+ mslot: u4, // wCurMoveNum
99
+ first: bool, // wEnemyGoesFirst
100
+ miss: bool = false, // wAttackMissed
101
+ crit: bool = false, // wCriticalHit = 1
102
+ ohko: bool = false, // wCriticalHit = 2
103
+ proc: bool = true, // wEffectFailed
104
+
105
+ comptime {
106
+ assert(@sizeOf(State) == 16);
107
+ }
108
+
109
+ pub fn immune(self: *State) bool {
110
+ return self.effectiveness == 0;
111
+ }
112
+ };
37
113
 
38
114
  pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
39
115
  assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
@@ -52,16 +128,16 @@ fn start(battle: anytype, options: anytype) !Result {
52
128
  const p1 = battle.side(.P1);
53
129
  const p2 = battle.side(.P2);
54
130
 
55
- var p1_slot = findFirstAlive(p1);
131
+ const p1_slot = findFirstAlive(p1);
56
132
  assert(!showdown or p1_slot == 1);
57
133
  if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
58
134
 
59
- var p2_slot = findFirstAlive(p2);
135
+ const p2_slot = findFirstAlive(p2);
60
136
  assert(!showdown or p2_slot == 1);
61
137
  if (p2_slot == 0) return Result.Win;
62
138
 
63
- try switchIn(battle, .P1, p1_slot, true, options);
64
- try switchIn(battle, .P2, p2_slot, true, options);
139
+ try switchIn(battle, .P1, p1_slot, .Initial, options);
140
+ try switchIn(battle, .P2, p2_slot, .Initial, options);
65
141
 
66
142
  return endTurn(battle, options);
67
143
  }
@@ -113,14 +189,14 @@ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
113
189
  if (choice.data == 0) {
114
190
  const struggle = ok: {
115
191
  for (side.active.moves, 0..) |move, i| {
116
- if (move.pp > 0 and volatiles.disabled_move != i + 1) break :ok false;
192
+ if (move.pp > 0 and volatiles.disable.move != i + 1) break :ok false;
117
193
  }
118
194
  break :ok true;
119
195
  };
120
196
  assert(struggle);
121
197
  // TODO wCurPlayerMove = .Struggle;
122
198
  } else {
123
- assert(showdown or side.active.volatiles.disabled_move != choice.data);
199
+ assert(showdown or side.active.volatiles.disable.move != choice.data);
124
200
  const move = side.active.move(choice.data);
125
201
  // You cannot *select* a move with 0 PP
126
202
  assert(move.pp != 0);
@@ -135,12 +211,9 @@ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
135
211
  volatiles.protect = 0;
136
212
  }
137
213
 
138
- fn saveMove(battle: anytype) void {
139
- _ = battle;
140
- return null;
141
- }
214
+ const SwitchIn = enum { Initial, Switch, Drag };
142
215
 
143
- fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
216
+ fn switchIn(battle: anytype, player: Player, slot: u8, kind: SwitchIn, options: anytype) !void {
144
217
  var side = battle.side(player);
145
218
  var foe = battle.foe(player);
146
219
 
@@ -148,7 +221,7 @@ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: a
148
221
  const incoming = side.get(slot);
149
222
 
150
223
  assert(incoming.hp != 0);
151
- assert(slot != 1 or initial);
224
+ assert(slot != 1 or kind == .Initial);
152
225
 
153
226
  const out = side.pokemon[0].position;
154
227
  side.pokemon[0].position = side.pokemon[slot - 1].position;
@@ -166,12 +239,15 @@ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: a
166
239
 
167
240
  statusModify(incoming.status, &active.stats);
168
241
 
169
- try options.log.switched(battle.active(player), incoming);
170
- // TODO: options.chance.switched(player, side.order[0], out);
242
+ if (kind == .Drag) {
243
+ try options.log.drag(.{ battle.active(player), incoming });
244
+ } else {
245
+ try options.log.switched(.{ battle.active(player), incoming });
246
+ }
171
247
 
172
248
  if (side.conditions.Spikes and !active.types.includes(.Flying)) {
173
249
  incoming.hp -|= @max(incoming.stats.hp / 8, 1);
174
- try options.log.damage(battle.active(player), incoming, .Spikes);
250
+ try options.log.damage(.{ battle.active(player), incoming, .Spikes });
175
251
  }
176
252
  }
177
253
 
@@ -185,7 +261,13 @@ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player
185
261
  // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
186
262
  const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
187
263
 
188
- if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
264
+ if ((c1.type == .Switch) != (c2.type == .Switch)) {
265
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
266
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
267
+ return if (c1.type == .Switch)
268
+ if (m1 == .Pursuit) .P2 else .P1
269
+ else if (m2 == .Pursuit) .P1 else .P2;
270
+ }
189
271
 
190
272
  // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
191
273
  // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
@@ -265,148 +347,3153 @@ fn doTurn(
265
347
  const volatiles = &battle.side(player).active.volatiles;
266
348
  const foe_volatiles = &battle.foe(player).active.volatiles;
267
349
 
350
+ // Technically this happens at the very beginning of update but its unused until now
351
+ // TODO: move into state and pass into betweenTurns
352
+ volatiles.frozen = false;
353
+ foe_volatiles.frozen = false;
354
+
268
355
  volatiles.DestinyBond = false;
269
- if (try executeMove(battle, player, player_choice, options)) |r| return r;
356
+ if (try executeMove(battle, player, player_choice, true, options)) |r| return r;
270
357
  foe_volatiles.Protect = false;
271
358
  foe_volatiles.Endure = false;
272
359
  foe_volatiles.DestinyBond = false;
360
+ if (try checkFaint(battle, foe_player, options)) |r| return r;
361
+ if (try handleResidual(battle, player, options)) {
362
+ if (try checkFaint(battle, player, options)) |r| return r;
363
+ }
273
364
 
274
365
  // foe_volatiles.DestinyBond = false;
275
- if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
366
+ if (try executeMove(battle, foe_player, foe_choice, false, options)) |r| return r;
276
367
  volatiles.Protect = false;
277
368
  volatiles.Endure = false;
278
369
  volatiles.DestinyBond = false;
370
+ if (try checkFaint(battle, player, options)) |r| return r;
371
+ if (try handleResidual(battle, foe_player, options)) {
372
+ if (try checkFaint(battle, foe_player, options)) |r| return r;
373
+ }
279
374
 
280
- return null;
375
+ // FIXME
376
+ return betweenTurns(battle, 0, options);
281
377
  }
282
378
 
283
- fn executeMove(battle: anytype, player: Player, choice: Choice, options: anytype) !?Result {
379
+ fn executeMove(
380
+ battle: anytype,
381
+ player: Player,
382
+ choice: Choice,
383
+ first: bool,
384
+ options: anytype,
385
+ ) !?Result {
284
386
  if (choice.type == .Switch) {
285
- try switchIn(battle, player, choice.data, false, options);
387
+ try switchIn(battle, player, choice.data, .Switch, options);
286
388
  return null;
287
389
  }
288
390
 
289
391
  assert(choice.type == .Move);
290
392
  var mslot: u4 = @intCast(choice.data);
393
+ _ = &mslot;
394
+ var move = Move.Pound; // TODO
395
+ _ = &move;
396
+
397
+ if (!try beforeMove(battle, player, move, options)) return null;
398
+
399
+ // FIXME: need damage from doTurn
400
+ const m = Move.get(move);
401
+ var state: State = .{
402
+ .move = move,
403
+ .mslot = mslot,
404
+ .first = first,
405
+ .accuracy = m.accuracy,
406
+ .bp = m.bp,
407
+ .type = m.type,
408
+ };
409
+ try generated.runMove(battle, player, &state, options);
410
+ return null;
411
+ }
412
+
413
+ fn beforeMove(battle: anytype, player: Player, move: Move, options: anytype) !bool {
414
+ var log = options.log;
415
+ var side = battle.side(player);
416
+ // const foe = battle.foe(player);
417
+ var active = &side.active;
418
+ var stored = side.stored();
419
+ const ident = battle.active(player);
420
+ var volatiles = &active.volatiles;
421
+
422
+ if (volatiles.Recharging) {
423
+ volatiles.Recharging = false;
424
+ resetCant(volatiles);
425
+ try log.cant(.{ ident, .Recharge });
426
+ return false;
427
+ }
428
+
429
+ if (Status.is(stored.status, .SLP)) slp: {
430
+ const before = stored.status;
431
+ // Even if the EXT bit is set this will still correctly modify the sleep duration
432
+ stored.status -= 1;
433
+
434
+ if (Status.duration(stored.status) == 0) {
435
+ try log.curestatus(.{ ident, before, .Message });
436
+ stored.status = 0; // clears EXT if present
437
+ resetCant(volatiles);
438
+ volatiles.Nightmare = false;
439
+ } else {
440
+ try log.cant(.{ ident, .Sleep });
441
+ if (move == .Snore or move == .SleepTalk) break :slp;
442
+ resetCant(volatiles);
443
+ return false;
444
+ }
445
+ }
446
+
447
+ if (Status.is(stored.status, .FRZ) and !(move == .FlameWheel or move == .SacredFire)) {
448
+ resetCant(volatiles);
449
+ try log.cant(.{ ident, .Freeze });
450
+ return false;
451
+ }
452
+
453
+ if (volatiles.Flinch) {
454
+ // Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
455
+ // Pokémon can sometimes flinch multiple times from the same original hit
456
+ // if (!showdown) volatiles.Flinch = false;
457
+ volatiles.Flinch = false;
458
+ resetCant(volatiles);
459
+ try log.cant(.{ ident, .Flinch });
460
+ return false;
461
+ }
462
+
463
+ if (volatiles.disable.duration > 0) {
464
+ volatiles.disable.duration -= 1;
465
+
466
+ if (volatiles.disable.duration == 0) {
467
+ volatiles.disable.move = 0;
468
+ try log.end(.{ ident, .Disable });
469
+ }
470
+ }
471
+
472
+ if (volatiles.Confusion) {
473
+ assert(volatiles.confusion > 0);
474
+ volatiles.confusion -= 1;
475
+
476
+ if (volatiles.confusion == 0) {
477
+ volatiles.Confusion = false;
478
+ try log.end(.{ ident, .Confusion });
479
+ } else {
480
+ try log.activate(.{ ident, .Confusion });
481
+
482
+ if (try Rolls.confused(battle, player, options)) {
483
+ volatiles.BeatUp = false;
484
+ volatiles.Flinch = false;
485
+ resetCant(volatiles);
486
+
487
+ // TODO HitConfusion
488
+
489
+ return false;
490
+ }
491
+ }
492
+ }
493
+
494
+ if (volatiles.Attract) {
495
+ try log.activate(.{ ident, .Attract });
496
+
497
+ if (try Rolls.attract(battle, player, options)) {
498
+ resetCant(volatiles);
499
+ try log.cant(.{ ident, .Attract });
500
+ return false;
501
+ }
502
+ }
503
+
504
+ if (side.active.volatiles.disable.move != 0) {
505
+ // A Pokémon that transforms after being disable may end up with less move slots
506
+ const m = side.active.moves[side.active.volatiles.disable.move - 1].id;
507
+ if (m != .None and m == move) {
508
+ side.active.volatiles.Charging = false;
509
+ resetCant(volatiles);
510
+ try options.log.cant(.{ ident, .Disable, move });
511
+ return false;
512
+ }
513
+ }
514
+
515
+ if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
516
+ resetCant(volatiles);
517
+ try log.cant(.{ ident, .Paralysis });
518
+ return false;
519
+ }
520
+
521
+ return true;
522
+ }
523
+
524
+ fn resetCant(volatiles: *align(8) Volatiles) void {
525
+ volatiles.Bide = false;
526
+ volatiles.Thrashing = false;
527
+ volatiles.Charging = false;
528
+ volatiles.Underground = false;
529
+ volatiles.Flying = false;
530
+ volatiles.Rollout = false;
531
+
532
+ volatiles.fury_cutter = 0;
533
+ }
534
+
535
+ pub fn canMove(battle: anytype, player: Player, state: *State, options: anytype) !bool {
536
+ var side = battle.side(player);
537
+ const volatiles = &side.active.volatiles;
538
+
539
+ // FIXME: pass in target to avoid lookup?
540
+ const target = if (Move.get(state.move).target == .Self) player else player.foe();
541
+ try options.log.move(.{ battle.active(player), state.move, battle.active(target), state.from });
291
542
 
292
- // const move = Move.get(side.last_selected_move);
543
+ const charging = false; // TODO charging uses doUse
544
+ const skip_pp = charging or state.move == .Struggle or
545
+ (volatiles.BeatUp or volatiles.Thrashing or volatiles.Bide);
546
+ if (!skip_pp) _ = decrementPP(side, state.move, state.mslot); // TODO if no pp return
293
547
 
294
- // CheckTurn
548
+ return true;
549
+ }
295
550
 
296
- return doMove(battle, player, options, mslot);
551
+ pub fn canCharge(battle: anytype, player: Player, state: *State, options: anytype) !bool {
552
+ _ = battle;
553
+ _ = player;
554
+ _ = state;
555
+ _ = options;
556
+ // TODO skipsuncharge account for SolarBeam
557
+ return true;
297
558
  }
298
559
 
299
- fn decrementPP(side: *Side, mslot: u4) void {
560
+ pub fn decrementPP(side: *Side, move: Move, mslot: u4) bool {
300
561
  var active = &side.active;
301
562
  const volatiles = &active.volatiles;
302
563
 
303
- // TODO assert(side.last_selected_move != .Struggle);
564
+ assert(move != .Struggle);
304
565
  assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
305
566
 
306
- assert(active.move(mslot).pp > 0);
307
- active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
308
- if (volatiles.Transform) return;
567
+ var move_slot = active.move(mslot);
568
+ if (move_slot.pp == 0) return false;
569
+
570
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
571
+ if (volatiles.Transform) return true;
309
572
 
310
- // FIXME mimic
573
+ move_slot = side.stored().move(mslot);
574
+ assert(move_slot.pp > 0);
311
575
 
312
- assert(side.stored().move(mslot).pp > 0);
313
- side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
576
+ if (move_slot.id == .Mimic and move != .Mimic) return true;
577
+
578
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
314
579
  assert(active.move(mslot).pp == side.stored().move(mslot).pp);
580
+
581
+ return true;
315
582
  }
316
583
 
317
- fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
318
- _ = options;
319
- var side = battle.side(player);
320
- const move = Move.get(.Teleport); // side.last_selected_move
321
- switch (move.effect) {
322
- .Teleport => {
323
- // side.useMove();
324
- decrementPP(side, mslot);
325
- },
326
- else => @panic("TODO"),
584
+ pub fn doMove(
585
+ comptime secondary: bool,
586
+ battle: anytype,
587
+ player: Player,
588
+ state: *State,
589
+ options: anytype,
590
+ ) !bool {
591
+ try checkCriticalHit(battle, player, state, options);
592
+ try calcDamage(battle, player, state, options);
593
+ try adjustDamage(battle, player, state, options);
594
+ try randomizeDamage(battle, player, state, options);
595
+ try checkHit(battle, player, state, options);
596
+ if (secondary) try effectChance(battle, player, state, options);
597
+ try applyDamage(battle, player, state, options);
598
+ try reportOutcome(battle, player, state, options);
599
+ if (try destinyBond(battle, player, state, options)) return false;
600
+ try buildRage(battle, player, state, options);
601
+ try kingsRock(battle, player, state, options);
602
+ return true;
603
+ }
604
+
605
+ pub fn afterMove(
606
+ comptime kings: bool,
607
+ battle: anytype,
608
+ player: Player,
609
+ state: *State,
610
+ options: anytype,
611
+ ) !bool {
612
+ if (try destinyBond(battle, player, state, options)) return false;
613
+ try buildRage(battle, player, state, options);
614
+ if (kings) try kingsRock(battle, player, state, options);
615
+ return true;
616
+ }
617
+
618
+ pub fn checkCriticalHit(battle: anytype, player: Player, state: *State, options: anytype) !void {
619
+ const move = Move.get(state.move);
620
+ if (state.bp == 0) return;
621
+
622
+ const side = battle.side(player);
623
+ const pokemon = side.stored();
624
+
625
+ var stage: u8 =
626
+ if ((pokemon.species == .Chansey and pokemon.item == .LuckyPunch) or
627
+ (pokemon.species == .Farfetchd and pokemon.item == .Stick)) 2 else 0;
628
+ if (stage == 0) {
629
+ if (side.active.volatiles.FocusEnergy) stage += 1;
630
+ if (move.effect.isHighCritical()) stage += 2;
631
+ if (pokemon.item == .ScopeLens) stage += 1;
327
632
  }
328
- return null;
633
+ assert(stage <= 4);
634
+
635
+ state.crit = try Rolls.criticalHit(battle, player, state.hit, CRITICAL_HITS[stage], options);
329
636
  }
330
637
 
331
- fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
332
- battle.turn += 1;
638
+ pub fn calcDamage(
639
+ battle: anytype,
640
+ player: Player,
641
+ state: *State,
642
+ options: anytype,
643
+ ) !void {
644
+ _ = battle;
645
+ _ = player;
646
+ _ = state;
647
+ _ = options;
648
+ }
333
649
 
334
- if (showdown and battle.turn >= 1000) {
335
- try options.log.tie();
336
- return Result.Tie;
337
- } else if (battle.turn >= 65535) {
338
- return Result.Error;
650
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
651
+
652
+ pub fn adjustDamage(battle: anytype, player: Player, state: *State, _: anytype) !void {
653
+ if (state.move == .Struggle) return;
654
+
655
+ const side = battle.side(player);
656
+ const foe = battle.foe(player);
657
+ const types = foe.active.types;
658
+
659
+ var d = state.damage;
660
+ if ((state.type == .Water and battle.field.weather == .Rain) or
661
+ (state.type == .Fire and battle.field.weather == .Sun))
662
+ {
663
+ d = d *% @intFromEnum(Effectiveness.Super) / 10;
664
+ } else if ((state.type == .Water and battle.field.weather == .Sun) or
665
+ ((state.type == .Fire or state.move == .SolarBeam) and battle.field.weather == .Rain))
666
+ {
667
+ d = d *% @intFromEnum(Effectiveness.Resisted) / 10;
339
668
  }
340
669
 
341
- try options.log.turn(battle.turn);
670
+ if (side.active.types.includes(state.type)) d +%= d / 2;
671
+
672
+ const neutral = @intFromEnum(Effectiveness.Neutral);
673
+ const foresight = foe.active.volatiles.Foresight and FORESIGHT.includes(state.type);
674
+ const eff1: u16 = if (foresight and types.type1 == .Ghost)
675
+ neutral
676
+ else
677
+ @intFromEnum(state.type.effectiveness(types.type1));
678
+ const eff2: u16 = if (foresight and types.type2 == .Ghost)
679
+ neutral
680
+ else
681
+ @intFromEnum(state.type.effectiveness(types.type2));
682
+
683
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
684
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
685
+ types.type1.precedence() > types.type2.precedence())
686
+ {
687
+ assert(eff2 != neutral);
688
+ d = d *% eff2 / 10;
689
+ assert(types.type1 != types.type2);
690
+ assert(eff1 != neutral);
691
+ d = d *% eff1 / 10;
692
+ } else {
693
+ if (eff1 != neutral) d = d *% eff1 / 10;
694
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
695
+ }
342
696
 
343
- return Result.Default;
697
+ state.effectiveness = if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
698
+ state.damage = d;
344
699
  }
345
700
 
346
- pub const Effects = struct {
347
- fn teleport(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
348
- _ = battle;
349
- _ = player;
350
- _ = move;
351
- _ = options;
701
+ pub fn randomizeDamage(battle: anytype, player: Player, state: *State, options: anytype) !void {
702
+ if (state.damage <= 1) return;
703
+ const random = try Rolls.damage(battle, player, state.hit, options);
704
+ options.calc.base(player.foe(), state.damage);
705
+ state.damage = @intCast(@as(u32, state.damage) *% random / 255);
706
+ options.calc.final(player.foe(), state.damage);
707
+ }
708
+
709
+ pub fn applyDamage(
710
+ battle: anytype,
711
+ player: Player,
712
+ state: *State,
713
+ options: anytype,
714
+ ) !void {
715
+ // TODO failuretext (if not Bide) + applydamage
716
+ _ = battle;
717
+ _ = player;
718
+ _ = state;
719
+ _ = options;
720
+ }
721
+
722
+ // TODO: set damage = 0 if missed and not (High) Jump Kick
723
+ pub fn checkHit(
724
+ battle: anytype,
725
+ player: Player,
726
+ state: *State,
727
+ options: anytype,
728
+ ) !void {
729
+ const side = battle.side(player);
730
+ const foe = battle.foe(player);
731
+
732
+ const move = Move.get(state.move);
733
+
734
+ if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) {
735
+ state.miss = true;
736
+ return;
737
+ }
738
+ if (foe.active.volatiles.Protect) {
739
+ state.miss = true;
740
+ return;
741
+ }
742
+ const drain = move.effect == .DrainHP or move.effect == .DreamEater;
743
+ if (drain and foe.active.volatiles.Substitute) {
744
+ state.miss = true;
745
+ return;
746
+ }
747
+ if (side.active.volatiles.LockOn) {
748
+ state.miss = !(foe.active.volatiles.Flying and move.extra.underground);
749
+ return;
750
+ }
751
+ assert(!(foe.active.volatiles.Flying and foe.active.volatiles.Underground));
752
+ if (foe.active.volatiles.Flying) {
753
+ if (!move.extra.flying) {
754
+ state.miss = true;
755
+ return;
756
+ }
757
+ } else if (foe.active.volatiles.Underground) {
758
+ if (!move.extra.underground) {
759
+ state.miss = true;
760
+ return;
761
+ }
762
+ }
763
+ if (move.effect == .Thunder) {
764
+ if (battle.field.weather == .Rain) {
765
+ state.miss = false;
766
+ return;
767
+ } else if (battle.field.weather == .Sun) {
768
+ // This latter part gets applied in a separate Thunder accuracy handler
769
+ // on the cartridge but it makes more sense to just do it here
770
+ state.accuracy = Gen12.percent(50) + 1;
771
+ }
772
+ }
773
+ if (move.effect == .AlwaysHit) {
774
+ state.miss = false;
775
+ return;
352
776
  }
353
- };
354
777
 
355
- fn statusModify(status: u8, stats: *Stats(u16)) void {
356
- if (Status.is(status, .PAR)) {
357
- stats.spe = @max(stats.spe / 4, 1);
358
- } else if (Status.is(status, .BRN)) {
359
- stats.atk = @max(stats.atk / 2, 1);
778
+ var accuracy: u16 = state.accuracy;
779
+ assert(accuracy > 0);
780
+ if (foe.active.boosts.evasion <= side.active.boosts.accuracy or
781
+ !foe.active.volatiles.Foresight)
782
+ {
783
+ var boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
784
+ accuracy = accuracy * boost[0] / boost[1];
785
+ boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
786
+ accuracy = accuracy * boost[0] / boost[1];
787
+ accuracy = @min(255, @max(1, accuracy));
788
+ }
789
+
790
+ if (foe.stored().item == .BrightPowder) {
791
+ accuracy -|= 20;
360
792
  }
793
+
794
+ // The accuracy roll is skipped entirely if maxed
795
+ state.miss = if (accuracy == 255)
796
+ false
797
+ else
798
+ !try Rolls.hit(battle, player, @intCast(accuracy), options);
361
799
  }
362
800
 
363
- inline fn isForced(active: anytype) bool {
364
- return active.volatiles.Recharging or active.volatiles.Rage or
365
- active.volatiles.Thrashing or active.volatiles.Charging or
366
- // FIXME TODO Underground or Flying?
367
- active.volatiles.Underground or active.volatiles.Flying or
368
- active.volatiles.Rollout;
801
+ fn checkFaint(
802
+ battle: anytype,
803
+ player: Player,
804
+ options: anytype,
805
+ ) @TypeOf(options.log).Error!?Result {
806
+ const side = battle.side(player);
807
+ const foe = battle.foe(player);
808
+
809
+ const player_fainted = side.stored().hp == 0;
810
+ const foe_fainted = foe.stored().hp == 0;
811
+ if (!(player_fainted or foe_fainted)) return null;
812
+
813
+ const player_out = player_fainted and findFirstAlive(side) == 0;
814
+ const foe_out = foe_fainted and findFirstAlive(foe) == 0;
815
+ const more = player_out or foe_out;
816
+
817
+ if (player_fainted) try faint(battle, player, !(more or foe_fainted), options);
818
+ if (foe_fainted) try faint(battle, player.foe(), !more, options);
819
+
820
+ if (player_out and foe_out) {
821
+ try options.log.tie(.{});
822
+ return Result.Tie;
823
+ } else if (player_out) {
824
+ try options.log.win(.{player.foe()});
825
+ return if (player == .P1) Result.Lose else Result.Win;
826
+ } else if (foe_out) {
827
+ try options.log.win(.{player});
828
+ return if (player == .P1) Result.Win else Result.Lose;
829
+ }
830
+
831
+ const foe_choice: Choice.Type = if (foe_fainted) .Switch else .Pass;
832
+ if (player == .P1) return .{ .p1 = .Switch, .p2 = foe_choice };
833
+ return .{ .p1 = foe_choice, .p2 = .Switch };
369
834
  }
370
835
 
371
- pub const Rolls = struct {
372
- inline fn speedTie(battle: anytype, options: anytype) !bool {
373
- const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
374
- player == .P1
375
- else if (showdown)
376
- battle.rng.range(u8, 0, 2) == 0
836
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !void {
837
+ var side = battle.side(player);
838
+ var foe = battle.foe(player);
839
+ assert(side.stored().hp == 0);
840
+
841
+ var foe_volatiles = &foe.active.volatiles;
842
+ foe_volatiles.BeatUp = false;
843
+
844
+ // We always need to clear status for Pokémon Showdown's Sleep/Freeze Clause Mod
845
+ const status = side.stored().status;
846
+
847
+ side.stored().status = 0;
848
+ // This shouldn't matter, but Pokémon Showdown decides double switching priority based on speed,
849
+ // and resets a Pokémon's stats when it faints... only it still factors in paralysis -_-
850
+ if (showdown) {
851
+ side.active.stats.spe = if (Status.is(status, .PAR))
852
+ @max(side.stored().stats.spe / 4, 1)
377
853
  else
378
- battle.rng.next() < Gen12.percent(50) + 1;
854
+ side.stored().stats.spe;
855
+ }
379
856
 
380
- try options.chance.speedTie(p1);
381
- return p1;
857
+ try options.log.faint(.{ battle.active(player), done });
858
+ options.calc.capped(player);
859
+ }
860
+
861
+ // TODO: see if we can move *before* applyDamage and include failuretext logic
862
+ pub fn reportOutcome(battle: anytype, player: Player, state: *State, options: anytype) !void {
863
+ const foe_ident = battle.active(player.foe());
864
+ if (state.crit) try options.log.crit(.{foe_ident});
865
+ if (!state.immune()) {
866
+ if (state.effectiveness > Effectiveness.neutral) {
867
+ try options.log.supereffective(.{foe_ident});
868
+ } else if (state.effectiveness < Effectiveness.neutral) {
869
+ try options.log.resisted(.{foe_ident});
870
+ }
382
871
  }
872
+ }
383
873
 
384
- inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
385
- const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
386
- val == .true
387
- else if (showdown)
388
- battle.rng.chance(u8, 60, 256)
389
- else
390
- battle.rng.next() < 60;
874
+ pub fn effectChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
875
+ const rate = Move.get(state.move).chance;
876
+ assert(rate > 0);
877
+ // FIXME: only commit secondary chance roll if effect actually is successful (doesn't fail)
878
+ state.proc = !battle.foe(player).active.volatiles.Substitute and
879
+ try Rolls.secondaryChance(battle, player, rate, options);
880
+ }
391
881
 
392
- try options.chance.quickClaw(player, qkc);
393
- return qkc;
882
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !bool {
883
+ var side = battle.side(player);
884
+ var stored = side.stored();
885
+ const ident = battle.active(player);
886
+ var volatiles = &side.active.volatiles;
887
+
888
+ // TODO if (stored.hp == 0) return;
889
+ assert(stored.hp > 0);
890
+
891
+ const brn = Status.is(stored.status, .BRN);
892
+ if (brn or Status.is(stored.status, .PSN)) {
893
+ var damage: u16 = undefined;
894
+ if (volatiles.Toxic) {
895
+ volatiles.toxic += 1;
896
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
897
+ } else {
898
+ damage = @max(stored.stats.hp / 8, 1);
899
+ }
900
+
901
+ stored.hp -|= damage;
902
+ // Pokémon Showdown uses damage [of] here but its not relevant in Generation II
903
+ try options.log.damage(.{ ident, stored, if (brn) Damage.Burn else Damage.Poison });
904
+ if (stored.hp == 0) return true;
394
905
  }
395
- };
396
906
 
397
- test "RNG agreement" {
398
- if (!showdown) return;
399
- var expected: [256]u32 = undefined;
400
- for (0..expected.len) |i| {
401
- expected[i] = @intCast(i * 0x1000000);
907
+ if (volatiles.LeechSeed) {
908
+ var foe = battle.foe(player);
909
+ var foe_stored = foe.stored();
910
+ const foe_ident = battle.active(player.foe());
911
+
912
+ // if (foe_stored.hp == 0) {
913
+ // assert(showdown);
914
+ // return;
915
+ // }
916
+
917
+ const damage = @max(stored.stats.hp / 8, 1);
918
+ stored.hp -|= damage;
919
+ // As above, Pokémon Showdown uses damage [of] but its not relevant
920
+ try options.log.damage(.{ ident, stored, .LeechSeed });
921
+
922
+ const before = foe_stored.hp;
923
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
924
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
925
+ if (foe_stored.hp > before) try options.log.heal(.{ foe_ident, foe_stored, .Silent });
926
+ if (stored.hp == 0) return true;
402
927
  }
403
928
 
404
- var spe = rng.FixedRNG(2, expected.len){ .rolls = expected };
405
- var qkc = rng.FixedRNG(2, expected.len){ .rolls = expected };
929
+ if (volatiles.Nightmare) {
930
+ stored.hp -= @max(stored.stats.hp / 4, 1);
931
+ // ibid
932
+ try options.log.damage(.{ ident, stored, .Nightmare });
933
+ if (stored.hp == 0) return true;
934
+ }
406
935
 
407
- for (0..expected.len) |i| {
408
- try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
409
- try expectEqual(qkc.chance(u8, 60, 256), i < 60);
936
+ if (volatiles.Curse) {
937
+ stored.hp -= @max(stored.stats.hp / 4, 1);
938
+ // ibid
939
+ try options.log.damage(.{ ident, stored, .Curse });
940
+ if (stored.hp == 0) return true;
941
+ }
942
+
943
+ return false;
944
+ }
945
+
946
+ fn betweenTurns(battle: anytype, mslot: u4, options: anytype) !?Result {
947
+ const players = comptime std.enums.values(Player);
948
+
949
+ if (try checkFaint(battle, .P1, options)) |r| return r;
950
+
951
+ // Future Sight
952
+ inline for (players) |player| {
953
+ var side = battle.side(player);
954
+ var future_sight = &side.conditions.future_sight;
955
+
956
+ if (future_sight.count > 0) {
957
+ future_sight.count -= 1;
958
+ assert(future_sight.count != 0);
959
+ if (future_sight.count == 1) {
960
+ try options.log.end(.{ battle.active(player), .FutureSight });
961
+ // TODO doMove
962
+ }
963
+ }
964
+ }
965
+ if (try checkFaint(battle, .P1, options)) |r| return r;
966
+
967
+ // Weather
968
+ if (battle.field.weather != .None) {
969
+ battle.field.weather_duration -= 1;
970
+
971
+ if (battle.field.weather_duration == 0) {
972
+ battle.field.weather = .None;
973
+ try options.log.weather(.{ battle.field.weather, protocol.Weather.None });
974
+ } else {
975
+ try options.log.weather(.{ battle.field.weather, protocol.Weather.Upkeep });
976
+ if (battle.field.weather == .Sandstorm) {
977
+ inline for (players) |player| {
978
+ var side = battle.side(player);
979
+ const active = side.active;
980
+ if (!(active.volatiles.Underground or active.types.sandstormImmune())) {
981
+ side.stored().hp -|= @max(side.stored().stats.hp / 8, 1);
982
+ try options.log.damage(.{
983
+ battle.active(player),
984
+ side.stored(),
985
+ .Sandstorm,
986
+ });
987
+ }
988
+ }
989
+ if (try checkFaint(battle, .P1, options)) |r| return r;
990
+ }
991
+ }
992
+ }
993
+
994
+ // Binding
995
+ inline for (players) |player| {
996
+ var side = battle.side(player);
997
+ var volatiles = &side.active.volatiles;
998
+ const ident = battle.active(player);
999
+
1000
+ if (volatiles.bind.duration > 0 and !volatiles.Substitute) {
1001
+ volatiles.bind.duration -= 1;
1002
+ if (volatiles.bind.duration == 0) {
1003
+ const reason = @intFromEnum(End.Bind) + volatiles.bind.reason - 1;
1004
+ try options.log.end(.{ ident, @as(End, @enumFromInt(reason)) });
1005
+ } else {
1006
+ var reason = @intFromEnum(Activate.Bind) + volatiles.bind.reason - 1;
1007
+ try options.log.activate(.{ ident, @as(Activate, @enumFromInt(reason)) });
1008
+
1009
+ reason = @intFromEnum(Damage.Bind) + volatiles.bind.reason - 1;
1010
+ side.stored().hp -|= @max(side.stored().stats.hp / 16, 1);
1011
+ try options.log.damage(.{
1012
+ ident,
1013
+ side.stored(),
1014
+ @as(Damage, @enumFromInt(reason)),
1015
+ });
1016
+ }
1017
+ }
1018
+ }
1019
+ if (try checkFaint(battle, .P1, options)) |r| return r;
1020
+
1021
+ // Perish Song
1022
+ inline for (players) |player| {
1023
+ var side = battle.side(player);
1024
+ var volatiles = &side.active.volatiles;
1025
+
1026
+ if (volatiles.PerishSong) {
1027
+ volatiles.perish_song -= 1;
1028
+
1029
+ assert(volatiles.perish_song < 3);
1030
+ const reason = @intFromEnum(Start.PerishSong0) + volatiles.perish_song;
1031
+ try options.log.start(.{ battle.active(player), @as(Start, @enumFromInt(reason)) });
1032
+
1033
+ if (volatiles.perish_song == 0) {
1034
+ volatiles.PerishSong = false;
1035
+ side.stored().hp = 0;
1036
+ }
1037
+ }
1038
+ }
1039
+ if (try checkFaint(battle, .P1, options)) |r| return r;
1040
+
1041
+ // Leftovers
1042
+ inline for (players) |player| {
1043
+ var stored = battle.side(player).stored();
1044
+
1045
+ if (stored.item == .Leftovers) {
1046
+ const before = stored.hp;
1047
+ stored.hp = @min(stored.hp + @max(stored.stats.hp / 16, 1), stored.stats.hp);
1048
+ if (stored.hp > before) {
1049
+ try options.log.heal(.{ battle.active(player), stored, .Leftovers });
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ // Mystery Berry
1055
+ inline for (players) |player| {
1056
+ const stored = battle.side(player).stored();
1057
+
1058
+ if (stored.item == .MysteryBerry) {
1059
+ // TODO stored and active moves, transform, etc
1060
+ }
1061
+ }
1062
+
1063
+ // Defrost
1064
+ inline for (players) |player| {
1065
+ var side = battle.side(player);
1066
+
1067
+ if (Status.is(side.stored().status, .FRZ) and
1068
+ !side.active.volatiles.frozen and
1069
+ try Rolls.defrost(battle, player, options))
1070
+ {
1071
+ try options.log.curestatus(.{ battle.active(player), side.stored().status, .Message });
1072
+ side.stored().status = 0;
1073
+ }
1074
+ }
1075
+
1076
+ // Side Conditions
1077
+ if (showdown) {
1078
+ inline for (players) |player| {
1079
+ try updateSideCondition(battle, player, "Reflect", "reflect", options);
1080
+ }
1081
+ inline for (players) |player| {
1082
+ try updateSideCondition(battle, player, "LightScreen", "light_screen", options);
1083
+ }
1084
+ inline for (players) |player| {
1085
+ try updateSideCondition(battle, player, "Safeguard", "safeguard", options);
1086
+ }
1087
+ } else {
1088
+ inline for (players) |player| {
1089
+ try updateSideCondition(battle, player, "Safeguard", "safeguard", options);
1090
+ }
1091
+ inline for (players) |player| {
1092
+ try updateSideCondition(battle, player, "LightScreen", "light_screen", options);
1093
+ try updateSideCondition(battle, player, "Reflect", "reflect", options);
1094
+ }
1095
+ }
1096
+
1097
+ // Healing items
1098
+ inline for (players) |player| {
1099
+ var side = battle.side(player);
1100
+ var stored = side.stored();
1101
+ const ident = battle.active(player);
1102
+
1103
+ const num = @intFromEnum(stored.item);
1104
+ if (num > @intFromEnum(Item.Berry)) {
1105
+ if (num <= @intFromEnum(Item.GoldBerry)) {
1106
+ const proc = if (showdown)
1107
+ stored.hp <= stored.stats.hp
1108
+ else
1109
+ stored.hp < stored.stats.hp;
1110
+ if (proc) {
1111
+ assert(stored.hp != 0);
1112
+ try options.log.enditem(.{ ident, stored.item, .Eat });
1113
+ stored.item = .None;
1114
+
1115
+ const offset = num - @intFromEnum(Item.Berry);
1116
+ assert(offset < 3);
1117
+ stored.hp = @min(stored.hp + ((offset + 1) * 10), stored.stats.hp);
1118
+ const reason: Heal = @enumFromInt(@intFromEnum(Heal.Berry) + offset);
1119
+ try options.log.heal(.{ ident, stored, reason });
1120
+ }
1121
+ } else if (num < @intFromEnum(Item.BitterBerry)) {
1122
+ const proc = if (stored.item == .MiracleBerry)
1123
+ Status.any(stored.status)
1124
+ else
1125
+ Status.is(stored.status, @enumFromInt(num - @intFromEnum(Item.MintBerry) + 2));
1126
+
1127
+ if (proc) {
1128
+ assert(Status.any(stored.status));
1129
+ try options.log.enditem(.{ ident, stored.item, .Eat });
1130
+ stored.item = .None;
1131
+
1132
+ // FIXME wtf?
1133
+ // side.active.volatiles.Toxic = false;
1134
+ // side.active.volatiles.Nightmare = false;
1135
+ if (stored.item == .MiracleBerry) {
1136
+ side.active.volatiles.Confusion = false;
1137
+ try options.log.end(.{ ident, .Confusion });
1138
+ }
1139
+ stored.status = 0;
1140
+
1141
+ // FIXME recalc stats
1142
+
1143
+ try options.log.curestatus(.{ ident, stored.status, .Message });
1144
+ }
1145
+ } else if (num == @intFromEnum(Item.BitterBerry)) {
1146
+ if (side.active.volatiles.Confusion) {
1147
+ try options.log.enditem(.{ ident, stored.item, .Eat });
1148
+ stored.item = .None;
1149
+
1150
+ side.active.volatiles.Confusion = false;
1151
+ try options.log.end(.{ ident, .Confusion });
1152
+ }
1153
+ }
1154
+ }
1155
+ }
1156
+
1157
+ // Encore
1158
+ inline for (players) |player| {
1159
+ var side = battle.side(player);
1160
+ var volatiles = &side.active.volatiles;
1161
+
1162
+ if (volatiles.Encore) {
1163
+ volatiles.encore -= 1;
1164
+
1165
+ if (volatiles.encore == 0 or side.active.move(mslot).pp == 0) {
1166
+ volatiles.Encore = false;
1167
+ try options.log.end(.{ battle.active(player), .Encore });
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ return null;
1173
+ }
1174
+
1175
+ fn updateSideCondition(
1176
+ battle: anytype,
1177
+ player: Player,
1178
+ comptime key: []const u8,
1179
+ comptime value: []const u8,
1180
+ options: anytype,
1181
+ ) !void {
1182
+ var side = battle.side(player);
1183
+ if (@field(side.conditions, key)) {
1184
+ @field(side.conditions, value) -= 1;
1185
+
1186
+ if (@field(side.conditions, value) == 0) {
1187
+ @field(side.conditions, key) = false;
1188
+ try options.log.sideend(.{ player, @field(protocol.Side, key) });
1189
+ }
1190
+ }
1191
+ }
1192
+
1193
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
1194
+ battle.turn += 1;
1195
+
1196
+ if (pkmn.options.mod and battle.turn >= 1000) {
1197
+ try options.log.tie(.{});
1198
+ return Result.Tie;
1199
+ } else if (battle.turn >= 65535) {
1200
+ return Result.Error;
1201
+ }
1202
+
1203
+ try options.log.turn(.{battle.turn});
1204
+
1205
+ return Result.Default;
1206
+ }
1207
+
1208
+ pub fn buildRage(battle: anytype, player: Player, state: *State, options: anytype) !void {
1209
+ assert(!state.miss); // TODO
1210
+ var foe = battle.foe(player);
1211
+ if (foe.active.volatiles.Rage) {
1212
+ if (showdown) {
1213
+ // TODO if showdown boost
1214
+ if (foe.active.boosts.atk < 6) {
1215
+ try Effects.boost(battle, player, state, options);
1216
+ }
1217
+ } else {
1218
+ foe.active.volatiles.rage +|= 1;
1219
+ try options.log.activate(.{ battle.active(player), .Rage });
1220
+ }
1221
+ }
1222
+ }
1223
+
1224
+ pub fn kingsRock(battle: anytype, player: Player, state: *State, options: anytype) !void {
1225
+ assert(!state.miss); // TODO
1226
+ var foe = battle.foe(player);
1227
+ const flinch = battle.side(player).stored().item == .KingsRock and
1228
+ !foe.active.volatiles.Substitute and
1229
+ try Rolls.item(battle, player, options);
1230
+ if (flinch) {
1231
+ foe.active.volatiles.Recharging = false;
1232
+ foe.active.volatiles.Flinch = true;
1233
+ }
1234
+ }
1235
+
1236
+ pub fn destinyBond(battle: anytype, player: Player, _: *State, options: anytype) !bool {
1237
+ const foe = battle.foe(player);
1238
+ if (foe.stored().hp > 0) return false;
1239
+
1240
+ if (foe.active.volatiles.DestinyBond) {
1241
+ battle.side(player).stored().hp = 0;
1242
+ try options.log.activate(.{ battle.active(player.foe()), .DestinyBond });
1243
+ }
1244
+ return true;
1245
+ }
1246
+
1247
+ pub const Effects = struct {
1248
+ pub fn attract(battle: anytype, player: Player, _: *State, options: anytype) !void {
1249
+ const side = battle.side(player);
1250
+ var foe = battle.foe(player);
1251
+
1252
+ const gender: u8 = @intFromEnum(side.stored().dvs.gender);
1253
+ const foe_gender: u8 = @intFromEnum(foe.stored().dvs.gender);
1254
+ if (gender + foe_gender != 1) {
1255
+ return options.log.immune(.{ battle.active(player.foe()), .None });
1256
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1257
+ try options.log.lastmiss(.{});
1258
+ return options.log.miss(.{battle.active(player)});
1259
+ }
1260
+
1261
+ foe.active.volatiles.Attract = true;
1262
+ try options.log.start(.{ battle.active(player.foe()), .Attract });
1263
+ }
1264
+
1265
+ pub fn batonPass(battle: anytype, player: Player, state: *State, options: anytype) !void {
1266
+ _ = .{ battle, player, state, options }; // TODO
1267
+ }
1268
+
1269
+ pub fn beatUp(battle: anytype, player: Player, state: *State, options: anytype) !void {
1270
+ _ = .{ battle, player, state, options }; // TODO
1271
+ }
1272
+
1273
+ pub fn bellyDrum(battle: anytype, player: Player, state: *State, options: anytype) !void {
1274
+ assert(!state.miss);
1275
+ var side = battle.side(player);
1276
+
1277
+ const ident = battle.active(player);
1278
+
1279
+ assert(side.active.boosts.atk >= -6 and side.active.boosts.atk <= 6);
1280
+ if (side.active.boosts.atk == 6 or side.active.boosts.atk == MAX_STAT_VALUE) {
1281
+ return options.log.fail(.{ ident, .None });
1282
+ }
1283
+
1284
+ const hp = @max(side.stored().stats.hp / 2, 1);
1285
+ if (side.stored().hp <= hp) {
1286
+ try boostStat(battle, side, &side.active.stats, &side.active.boosts, "atk", 2);
1287
+ try options.log.boost(.{ ident, .Attack, @as(i8, 2), .Silent });
1288
+ return options.log.fail(.{ ident, .None });
1289
+ } else {
1290
+ side.stored().hp -= hp;
1291
+ try options.log.damage(.{ ident, side.stored(), .None });
1292
+
1293
+ const before = side.active.boosts.atk;
1294
+ var i: usize = 0;
1295
+ while (i < 6 and side.active.stats.atk < MAX_STAT_VALUE) : (i += 1) {
1296
+ try boostStat(battle, side, &side.active.stats, &side.active.boosts, "atk", 2);
1297
+ }
1298
+ try options.log.boost(.{ ident, .Attack, @as(i8, side.active.boosts.atk - before) });
1299
+ }
1300
+ }
1301
+
1302
+ pub const bide = struct {
1303
+ pub fn store(battle: anytype, player: Player, state: *State, options: anytype) !void {
1304
+ var side = battle.side(player);
1305
+ var volatiles = &side.active.volatiles;
1306
+
1307
+ const ident = battle.active(player);
1308
+
1309
+ if (!volatiles.Bide) return;
1310
+
1311
+ volatiles.attacks -= 1;
1312
+ if (volatiles.attacks != 0) return options.log.activate(.{ ident, .Bide });
1313
+
1314
+ volatiles.Bide = false;
1315
+ try options.log.end(.{ ident, .Bide });
1316
+
1317
+ state.damage = volatiles.bide *% 2;
1318
+ volatiles.bide = 0;
1319
+
1320
+ if (state.damage == 0) state.miss = true;
1321
+ }
1322
+
1323
+ pub fn unleash(battle: anytype, player: Player, state: *State, options: anytype) !void {
1324
+ _ = .{ battle, player, state, options }; // TODO
1325
+ }
1326
+ };
1327
+
1328
+ pub fn binding(battle: anytype, player: Player, state: *State, options: anytype) !void {
1329
+ var foe = battle.foe(player);
1330
+
1331
+ if (state.miss) return;
1332
+ if (foe.active.volatiles.bind.duration > 0) return;
1333
+ if (foe.active.volatiles.Substitute) return;
1334
+
1335
+ foe.active.volatiles.bind = .{
1336
+ .duration = Rolls.bindingDuration(battle, player, options),
1337
+ .reason = Move.get(state.move).extra.protocol,
1338
+ };
1339
+ }
1340
+
1341
+ pub fn burnChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1342
+ var foe = battle.foe(player);
1343
+ var foe_stored = foe.stored();
1344
+
1345
+ if (foe.active.volatiles.Substitute) return;
1346
+ if (Status.any(foe_stored.status)) {
1347
+ if (Status.is(foe_stored.status, .FRZ)) {
1348
+ assert(Move.get(state.move).type == .Fire or state.move == .TriAttack);
1349
+ try options.log.curestatus(.{
1350
+ battle.active(player.foe()),
1351
+ foe_stored.status,
1352
+ .Message,
1353
+ });
1354
+ foe_stored.status = 0;
1355
+ }
1356
+ return;
1357
+ }
1358
+ if (!state.proc) return;
1359
+ if (foe.conditions.Safeguard) return;
1360
+ // Nothing is immune to Fire-type, but Ghosts are immune to burnChance called by Tri Attack
1361
+ if (state.immune()) return;
1362
+ if (foe.active.types.includes(Move.get(state.move).type) and state.move != .TriAttack) {
1363
+ return;
1364
+ }
1365
+
1366
+ foe_stored.status = Status.init(.BRN);
1367
+ foe.active.stats.atk = @max(foe.active.stats.atk / 2, 1);
1368
+
1369
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
1370
+
1371
+ // TODO: check for status berry
1372
+ }
1373
+
1374
+ pub fn confusion(battle: anytype, player: Player, state: *State, options: anytype) !void {
1375
+ _ = .{ battle, player, state, options }; // TODO
1376
+ }
1377
+
1378
+ pub fn confusionChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1379
+ _ = .{ battle, player, state, options }; // TODO
1380
+ }
1381
+
1382
+ pub fn conversion(battle: anytype, player: Player, _: *State, options: anytype) !void {
1383
+ var side = battle.side(player);
1384
+
1385
+ var n: u3 = 0;
1386
+ for (side.active.moves) |m| {
1387
+ if (convertible(side.active, m.id)) n += 1;
1388
+ }
1389
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
1390
+
1391
+ side.active.types.type1 = try Rolls.conversion(battle, player, n, options);
1392
+ side.active.types.type2 = side.active.types.type1;
1393
+ }
1394
+
1395
+ pub fn conversion2(battle: anytype, player: Player, _: *State, options: anytype) !void {
1396
+ var side = battle.side(player);
1397
+
1398
+ const last = battle.foe(player).lastMove(false);
1399
+ if (last == .None) return options.log.fail(.{ battle.active(player), .None });
1400
+ const move = Move.get(last);
1401
+ if (move.type == .@"???") return options.log.fail(.{ battle.active(player), .None });
1402
+
1403
+ side.active.types.type1 = try Rolls.conversion2(battle, player, move.type, options);
1404
+ side.active.types.type2 = side.active.types.type1;
1405
+ }
1406
+
1407
+ pub fn counter(battle: anytype, player: Player, state: *State, _: anytype) !void {
1408
+ assert(state.move == .Counter or state.move == .MirrorCoat);
1409
+
1410
+ const foe = battle.foe(player);
1411
+
1412
+ state.miss = true;
1413
+ const last = foe.lastMove(false);
1414
+
1415
+ if (last == .None) return;
1416
+ if (last == state.move) return;
1417
+
1418
+ const immune = state.immune();
1419
+ state.effectiveness = Effectiveness.neutral;
1420
+ if (immune) {
1421
+ state.damage = 0;
1422
+ return;
1423
+ }
1424
+
1425
+ const move = Move.get(last);
1426
+ if (state.bp == 0) return;
1427
+ if (move.type.special() != (last == .MirrorCoat)) return;
1428
+ if (state.damage == 0) return;
1429
+
1430
+ // NOTE: llvm/llvm-project#58557
1431
+ state.damage = smul(state.damage, 2);
1432
+ state.miss = false;
1433
+ }
1434
+
1435
+ pub fn curse(battle: anytype, player: Player, state: *State, options: anytype) !void {
1436
+ var side = battle.side(player);
1437
+ var foe = battle.foe(player);
1438
+
1439
+ const ident = battle.active(player);
1440
+ const foe_ident = battle.active(player.foe());
1441
+
1442
+ if (side.active.types.includes(.Ghost)) {
1443
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1444
+ try options.log.lastmiss(.{});
1445
+ return options.log.miss(.{battle.active(player)});
1446
+ } else if (foe.active.volatiles.Substitute) {
1447
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1448
+ } else if (foe.active.volatiles.Curse) {
1449
+ return options.log.fail(.{ foe_ident, .None });
1450
+ }
1451
+
1452
+ foe.active.volatiles.Curse = true;
1453
+ try options.log.start(.{ foe_ident, .Curse });
1454
+
1455
+ side.stored().hp -= @max(side.stored().stats.hp / 2, 1);
1456
+ try options.log.damage(.{ ident, side.stored(), .Curse });
1457
+ } else {
1458
+ const stats = &side.active.stats;
1459
+ const boosts = &side.active.boosts;
1460
+
1461
+ const max_atk = boosts.atk == 6 or stats.atk == MAX_STAT_VALUE;
1462
+ const max_def = boosts.def == 6 or stats.def == MAX_STAT_VALUE;
1463
+ if (max_atk and max_def) return options.log.fail(.{ ident, .None });
1464
+
1465
+ if (!(boosts.spe == -6 or stats.spe == 1)) {
1466
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
1467
+ try unboostStat(battle, side, stats, boosts, "spe", 1);
1468
+ try options.log.boost(.{ ident, .Speed, @as(i8, -1) });
1469
+ }
1470
+ if (!max_atk) {
1471
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
1472
+ try boostStat(battle, side, stats, boosts, "atk", 1);
1473
+ try options.log.boost(.{ ident, .Attack, @as(i8, 1) });
1474
+ }
1475
+ if (!max_def) {
1476
+ assert(boosts.def >= -6 and boosts.def <= 6);
1477
+ try boostStat(battle, side, stats, boosts, "def", 1);
1478
+ try options.log.boost(.{ ident, .Defense, @as(i8, 1) });
1479
+ }
1480
+ }
1481
+ }
1482
+
1483
+ pub fn defenseCurl(battle: anytype, player: Player, _: *State, _: anytype) !void {
1484
+ battle.side(player).active.volatiles.DefenseCurl = true;
1485
+ }
1486
+
1487
+ pub fn defrost(battle: anytype, player: Player, _: *State, options: anytype) !void {
1488
+ var side = battle.side(player);
1489
+ assert(Status.is(side.stored().status, .FRZ));
1490
+ try options.log.curestatus(.{ battle.active(player), side.stored().status, .Message });
1491
+ side.stored().status = 0;
1492
+ }
1493
+
1494
+ pub fn destinyBond(battle: anytype, player: Player, _: *State, options: anytype) !void {
1495
+ battle.side(player).active.volatiles.DestinyBond = true;
1496
+ try options.log.singlemove(.{ battle.active(player), Move.DestinyBond });
1497
+ }
1498
+
1499
+ pub fn disable(battle: anytype, player: Player, _: *State, options: anytype) !void {
1500
+ var foe = battle.foe(player);
1501
+ var volatiles = &foe.active.volatiles;
1502
+ const foe_ident = battle.active(player.foe());
1503
+
1504
+ if (volatiles.disable.move != 0) return options.log.fail(.{ foe_ident, .None });
1505
+
1506
+ const last = battle.foe(player).lastMove(false);
1507
+ if (last == .None or last == .Struggle) return options.log.fail(.{ foe_ident, .None });
1508
+
1509
+ var slot: u3 = 0;
1510
+ for (foe.active.moves) |m| {
1511
+ assert(m.id != .None);
1512
+ slot += 1;
1513
+ if (m.id == last) break;
1514
+ }
1515
+ const move = foe.active.move(slot);
1516
+ if (move.pp == 0) return options.log.fail(.{ foe_ident, .None });
1517
+
1518
+ volatiles.disable.move = slot;
1519
+ volatiles.disable.duration = Rolls.disableDuration(battle, player, options);
1520
+
1521
+ try options.log.start(.{ foe_ident, .Disable, move.id });
1522
+ }
1523
+
1524
+ pub const double = struct {
1525
+ pub fn flying(battle: anytype, player: Player, state: *State, _: anytype) !void {
1526
+ if (!battle.foe(player).active.volatiles.Flying) return;
1527
+ state.damage = smul(state.damage, 2);
1528
+ }
1529
+
1530
+ pub fn underground(battle: anytype, player: Player, state: *State, _: anytype) !void {
1531
+ if (!battle.foe(player).active.volatiles.Underground) return;
1532
+ state.damage = smul(state.damage, 2);
1533
+ }
1534
+
1535
+ pub fn minimize(battle: anytype, player: Player, state: *State, _: anytype) !void {
1536
+ if (!battle.foe(player).active.volatiles.minimized) return;
1537
+ state.damage = smul(state.damage, 2);
1538
+ }
1539
+ };
1540
+
1541
+ pub fn drainHP(battle: anytype, player: Player, state: *State, options: anytype) !void {
1542
+ var stored = battle.side(player).stored();
1543
+ const ident = battle.active(player);
1544
+
1545
+ assert(state.damage != 0);
1546
+
1547
+ if (stored.hp == stored.stats.hp) return;
1548
+ stored.hp = @min(stored.stats.hp, stored.hp + @max(state.damage / 2, 1));
1549
+
1550
+ try options.log.heal(.{ ident, stored, .Drain, battle.active(player.foe()) });
1551
+ }
1552
+
1553
+ pub fn encore(battle: anytype, player: Player, state: *State, options: anytype) !void {
1554
+ var foe = battle.foe(player);
1555
+ var volatiles = &foe.active.volatiles;
1556
+ const foe_ident = battle.active(player.foe());
1557
+
1558
+ const last = battle.foe(player).lastMove(true);
1559
+ const failed = volatiles.Encore or
1560
+ (last == .None or last == .Struggle or
1561
+ last == .Encore or .last == .MirrorMove);
1562
+ if (failed) return options.log.fail(.{ foe_ident, .None });
1563
+
1564
+ var slot: u3 = 0;
1565
+ for (foe.active.moves) |m| {
1566
+ assert(m.id != .None);
1567
+ slot += 1;
1568
+ if (m.id == last) break;
1569
+ }
1570
+ const move = foe.active.move(slot);
1571
+ if (move.pp == 0) return options.log.fail(.{ foe_ident, .None });
1572
+
1573
+ volatiles.Encore = true;
1574
+ volatiles.encore = Rolls.encoreDuration(battle, player, options);
1575
+
1576
+ // TODO ???
1577
+ _ = state;
1578
+
1579
+ try options.log.start(.{ foe_ident, .Encore, move.id });
1580
+ }
1581
+
1582
+ pub fn explode(battle: anytype, player: Player, _: *State, _: anytype) !void {
1583
+ var side = battle.side(player);
1584
+ var stored = side.stored();
1585
+
1586
+ stored.hp = 0;
1587
+ // Pokémon Showdown sets the status to 0 on faint(), and we need to do the same to be able
1588
+ // to correctly implement Pokémon Showdown's dumb speed-based switch mechanics
1589
+ if (!showdown) stored.status = 0;
1590
+ side.active.volatiles.LeechSeed = false;
1591
+ side.active.volatiles.DestinyBond = false;
1592
+ }
1593
+
1594
+ pub fn falseSwipe(battle: anytype, player: Player, state: *State, _: anytype) !void {
1595
+ const foe = battle.foe(player);
1596
+ assert(foe.stored().hp > 0);
1597
+ // FIXME crit?
1598
+ if (state.damage > foe.stored().hp) state.damage = foe.stored().hp - 1;
1599
+ }
1600
+
1601
+ pub fn fixedDamage(battle: anytype, player: Player, state: *State, options: anytype) !void {
1602
+ const side = battle.side(player);
1603
+ const foe = battle.foe(player);
1604
+
1605
+ state.damage = switch (Move.get(state.move).effect) {
1606
+ .SuperFang => @max(foe.stored().hp / 2, 1),
1607
+ .LevelDamage => side.stored().level,
1608
+ .FixedDamage => if (state.move == .SonicBoom) 20 else 40,
1609
+ .Psywave => try Rolls.psywave(
1610
+ battle,
1611
+ player,
1612
+ @intCast(@as(u16, side.stored().level) * 3 / 2),
1613
+ options,
1614
+ ),
1615
+ else => unreachable,
1616
+ };
1617
+ }
1618
+
1619
+ pub fn flinchChance(battle: anytype, player: Player, state: *State, _: anytype) !void {
1620
+ const foe = battle.foe(player);
1621
+ const status = foe.stored().status;
1622
+ var volatiles = &foe.active.volatiles;
1623
+
1624
+ if (volatiles.Substitute) return;
1625
+ if (Status.is(status, .FRZ) or Status.is(status, .SLP)) return;
1626
+ if (!state.first) return;
1627
+ if (!state.proc) return;
1628
+
1629
+ volatiles.Flinch = true;
1630
+ volatiles.Recharging = false;
1631
+ }
1632
+
1633
+ pub fn flyDig(battle: anytype, player: Player, state: *State, options: anytype) !void {
1634
+ _ = .{ battle, player, state, options }; // TODO
1635
+ }
1636
+
1637
+ pub fn focusEnergy(battle: anytype, player: Player, _: *State, options: anytype) !void {
1638
+ var side = battle.side(player);
1639
+
1640
+ if (side.active.volatiles.FocusEnergy) {
1641
+ return if (!showdown) try options.log.fail(.{ battle.active(player), .None });
1642
+ }
1643
+
1644
+ side.active.volatiles.FocusEnergy = true;
1645
+ try options.log.start(.{ battle.active(player), .FocusEnergy });
1646
+ }
1647
+
1648
+ var SLOTS: [5]u4 = .{ 0, 0, 0, 0, 0 };
1649
+
1650
+ pub fn forceSwitch(battle: anytype, player: Player, state: *State, options: anytype) !void {
1651
+ assert(!state.miss); // FIXME ensure checkHit handles fail message
1652
+
1653
+ const foe = battle.foe(player);
1654
+
1655
+ if (state.first) return options.log.fail(.{ battle.active(player), .None });
1656
+
1657
+ var n: u4 = 0;
1658
+ var i: u4 = 0;
1659
+ for (foe.pokemon, 0..) |pokemon, j| {
1660
+ if (pokemon.species == .None) break;
1661
+ n += 1;
1662
+ if (pokemon.position == 1) continue;
1663
+ if (pokemon.hp > 0) {
1664
+ SLOTS[i] = @intCast(foe.pokemon[j].position);
1665
+ i += 1;
1666
+ }
1667
+ }
1668
+
1669
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
1670
+
1671
+ const slot = try Rolls.forceSwitch(battle, player, SLOTS[0..i], n, options);
1672
+ try switchIn(battle, player.foe(), slot, .Drag, options);
1673
+ }
1674
+
1675
+ pub fn foresight(battle: anytype, player: Player, _: *State, options: anytype) !void {
1676
+ var foe = battle.foe(player);
1677
+
1678
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1679
+ try options.log.lastmiss(.{});
1680
+ return options.log.miss(.{battle.active(player)});
1681
+ } else if (foe.active.volatiles.Foresight) {
1682
+ return options.log.fail(.{ battle.active(player), .None });
1683
+ }
1684
+
1685
+ foe.active.volatiles.Foresight = true;
1686
+ try options.log.start(.{ battle.active(player.foe()), .FocusEnergy });
1687
+ }
1688
+
1689
+ pub fn freezeChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1690
+ var foe = battle.foe(player);
1691
+ var foe_stored = foe.stored();
1692
+ const foe_ident = battle.active(player.foe());
1693
+
1694
+ if (foe.active.volatiles.Substitute) return;
1695
+ if (Status.any(foe_stored.status)) return;
1696
+
1697
+ // Nothing is immune to Ice-type, but Ghosts are immune to freezeChance called by Tri Attack
1698
+ if (state.immune()) return;
1699
+ if (battle.field.weather == .Sun) return;
1700
+ if (foe.active.types.includes(Move.get(state.move).type) and state.move != .TriAttack) {
1701
+ return;
1702
+ }
1703
+ if (!state.proc) return;
1704
+ if (foe.conditions.Safeguard) return;
1705
+ // Freeze Clause Mod
1706
+ if (pkmn.options.mod) for (foe.pokemon) |p| if (Status.is(p.status, .FRZ)) return;
1707
+
1708
+ foe_stored.status = Status.init(.FRZ);
1709
+ try options.log.status(.{ foe_ident, foe_stored.status, .None });
1710
+
1711
+ // TODO: check for status berry
1712
+
1713
+ foe.active.volatiles.Recharging = false;
1714
+ foe.active.volatiles.frozen = true;
1715
+ }
1716
+
1717
+ // TODO FIXME showdown calls this before calcDamage (after checkHit) and modifies state.bp!
1718
+ pub fn furyCutter(battle: anytype, player: Player, state: *State, _: anytype) !void {
1719
+ var side = battle.side(player);
1720
+ var volatiles = &side.active.volatiles;
1721
+
1722
+ if (state.miss) {
1723
+ volatiles.fury_cutter = 0;
1724
+ return;
1725
+ }
1726
+
1727
+ assert(volatiles.fury_cutter >= 0 and volatiles.fury_cutter <= 5);
1728
+ if (volatiles.fury_cutter == 5) return;
1729
+ volatiles.fury_cutter += 1;
1730
+
1731
+ if (showdown) {
1732
+ state.bp *= 2;
1733
+ assert(state.bp <= 160);
1734
+ } else {
1735
+ state.damage = smul(state.damage, 2);
1736
+ }
1737
+ }
1738
+
1739
+ pub fn futureSight(battle: anytype, player: Player, state: *State, options: anytype) !void {
1740
+ _ = .{ battle, player, state, options }; // TODO
1741
+ }
1742
+
1743
+ pub fn happiness(battle: anytype, player: Player, state: *State, _: anytype) !void {
1744
+ const val = battle.side(player).stored().happiness;
1745
+ const frustration = Move.get(state.move).effect == .Frustration;
1746
+ state.bp = ((if (frustration) 255 - val else val) * 10) / 25;
1747
+ }
1748
+
1749
+ pub fn haze(battle: anytype, player: Player, _: *State, options: anytype) !void {
1750
+ var side = battle.side(player);
1751
+ var stats = unmodifiedStats(battle, side);
1752
+ side.active.boosts = .{};
1753
+ inline for (STATS) |s| @field(side.active.stats, s) = @field(stats, s);
1754
+ statusModify(side.stored().status, &side.active.stats);
1755
+
1756
+ var foe = battle.foe(player);
1757
+ stats = unmodifiedStats(battle, foe);
1758
+ foe.active.boosts = .{};
1759
+ inline for (STATS) |s| @field(foe.active.stats, s) = @field(stats, s);
1760
+ statusModify(foe.stored().status, &foe.active.stats);
1761
+
1762
+ try options.log.clearallboost(.{});
1763
+ }
1764
+
1765
+ pub fn heal(battle: anytype, player: Player, state: *State, options: anytype) !void {
1766
+ var side = battle.side(player);
1767
+ var stored = side.stored();
1768
+ const ident = battle.active(player);
1769
+
1770
+ if (stored.stats.hp == stored.hp) return options.log.fail(.{ ident, .None });
1771
+
1772
+ const rest = state.move == .Rest;
1773
+ if (rest) {
1774
+ // Adding the sleep status runs the sleep condition handler to roll duration
1775
+ if (showdown) battle.rng.advance(1);
1776
+ side.active.volatiles.Toxic = false;
1777
+ stored.status = Status.slf(2);
1778
+ recomputeStats(battle, side);
1779
+ try options.log.status(.{ ident, stored.status, .From, Move.Rest });
1780
+ stored.hp = stored.stats.hp;
1781
+ } else {
1782
+ stored.hp = @min(stored.stats.hp, stored.hp + (stored.stats.hp / 2));
1783
+ }
1784
+ try options.log.heal(.{ ident, stored, if (rest) Heal.Silent else Heal.None });
1785
+ }
1786
+
1787
+ pub fn healBell(battle: anytype, player: Player, _: *State, options: anytype) !void {
1788
+ var side = battle.side(player);
1789
+ side.active.volatiles.Nightmare = false;
1790
+
1791
+ try options.log.cureteam(.{battle.active(player)});
1792
+ for (&side.pokemon) |*p| p.status = 0;
1793
+
1794
+ // We technically only need to recompute stats if the active Pokémon was burned/paralyzed,
1795
+ // but adding a branch to check for that is probably more expensive than just recomputing
1796
+ recomputeStats(battle, side);
1797
+ }
1798
+
1799
+ pub fn hiddenPower(battle: anytype, player: Player, state: *State, _: anytype) !void {
1800
+ const side = battle.side(player);
1801
+ state.bp = side.stored().dvs.power();
1802
+ state.type = side.stored().dvs.type;
1803
+ }
1804
+
1805
+ pub fn hyperBeam(battle: anytype, player: Player, _: *State, options: anytype) !void {
1806
+ battle.side(player).active.volatiles.Recharging = true;
1807
+ try options.log.mustrecharge(.{battle.active(player)});
1808
+ }
1809
+
1810
+ pub fn leechSeed(battle: anytype, player: Player, state: *State, options: anytype) !void {
1811
+ var foe = battle.foe(player);
1812
+
1813
+ if (showdown) {
1814
+ // Invulnerability trumps type immunity on Pokémon Showdown
1815
+ const invulnerable = foe.active.volatiles.Underground or foe.active.volatiles.Flying;
1816
+ if (!invulnerable and foe.active.types.includes(.Grass)) {
1817
+ return options.log.immune(.{ battle.active(player.foe()), .None });
1818
+ }
1819
+ try checkHit(battle, player, state, options);
1820
+ if (state.miss) {
1821
+ try options.log.lastmiss(.{});
1822
+ return options.log.miss(.{battle.active(player)});
1823
+ }
1824
+ if (foe.active.volatiles.LeechSeed) return;
1825
+ } else {
1826
+ try checkHit(battle, player, state, options);
1827
+ const miss =
1828
+ state.miss or foe.active.types.includes(.Grass) or foe.active.volatiles.LeechSeed;
1829
+ if (miss) {
1830
+ try options.log.lastmiss(.{});
1831
+ return options.log.miss(.{battle.active(player)});
1832
+ }
1833
+ }
1834
+
1835
+ foe.active.volatiles.LeechSeed = true;
1836
+
1837
+ try options.log.start(.{ battle.active(player.foe()), .LeechSeed });
1838
+ }
1839
+
1840
+ pub fn lockOn(battle: anytype, player: Player, state: *State, options: anytype) !void {
1841
+ var foe = battle.foe(player);
1842
+ const foe_ident = battle.active(player.foe());
1843
+
1844
+ if (foe.active.volatiles.Substitute) {
1845
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1846
+ } else if (state.miss) {
1847
+ return options.log.fail(.{ foe_ident, .None });
1848
+ }
1849
+
1850
+ foe.active.volatiles.LockOn = true;
1851
+ try options.log.activate(.{ battle.active(player), .LockOn });
1852
+ }
1853
+
1854
+ const MAGNITUDE_POWER = [_]u8{ 10, 30, 50, 70, 90, 110, 150 };
1855
+
1856
+ pub fn magnitude(battle: anytype, player: Player, state: *State, options: anytype) !void {
1857
+ const num = try Rolls.magnitude(battle, player, options);
1858
+ try options.log.activate(.{ battle.active(player), .Magnitude, num });
1859
+ state.bp = MAGNITUDE_POWER[num - 4];
1860
+ }
1861
+
1862
+ pub fn meanLook(battle: anytype, player: Player, _: *State, options: anytype) !void {
1863
+ var foe = battle.foe(player);
1864
+
1865
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1866
+ if (!showdown) return options.log.fail(.{ battle.active(player.foe()), .None });
1867
+ try options.log.lastmiss(.{});
1868
+ return options.log.miss(.{battle.active(player)});
1869
+ } else if (foe.active.volatiles.Trapped) {
1870
+ return options.log.fail(.{ battle.active(player.foe()), .None });
1871
+ }
1872
+
1873
+ foe.active.volatiles.Trapped = true;
1874
+ }
1875
+
1876
+ pub fn metronome(
1877
+ battle: anytype,
1878
+ player: Player,
1879
+ state: *State,
1880
+ options: anytype,
1881
+ ) anyerror!void {
1882
+ var side = battle.side(player);
1883
+
1884
+ side.last_used_move = .None;
1885
+ side.active.volatiles.dirty = false;
1886
+
1887
+ // if (wPlayerCharging) ???
1888
+ // wPlayerCharging = 1
1889
+
1890
+ // FIXME
1891
+ state.move = try Rolls.metronome(battle, player, options);
1892
+ state.from = .Metronome;
1893
+ return generated.runMove(battle, player, state, options);
1894
+ }
1895
+
1896
+ pub fn mimic(battle: anytype, player: Player, state: *State, options: anytype) !void {
1897
+ var side = battle.side(player);
1898
+
1899
+ if (state.miss) {
1900
+ if (!showdown) return options.log.fail(.{ battle.active(player.foe()), .None });
1901
+ try options.log.lastmiss(.{});
1902
+ return options.log.miss(.{battle.active(player)});
1903
+ }
1904
+
1905
+ const move = battle.foe(player).lastMove(false);
1906
+ if (move == .None or move == .Struggle) {
1907
+ return options.log.fail(.{ battle.active(player.foe()), .None });
1908
+ }
1909
+
1910
+ var slot: u4 = 0;
1911
+ for (side.active.moves, 0..) |m, i| {
1912
+ if (m.id == move) return options.log.fail(.{ battle.active(player.foe()), .None });
1913
+ if (m.id == .Mimic) slot = @intCast(i + 1);
1914
+ }
1915
+ assert(slot != 0 and slot == state.mslot);
1916
+
1917
+ side.active.move(slot).id = move;
1918
+ side.active.move(slot).pp = 5;
1919
+ try options.log.start(.{ battle.active(player), .Mimic, move });
1920
+ }
1921
+
1922
+ pub fn mirrorMove(
1923
+ battle: anytype,
1924
+ player: Player,
1925
+ state: *State,
1926
+ options: anytype,
1927
+ ) anyerror!void {
1928
+ var side = battle.side(player);
1929
+ const foe = battle.foe(player);
1930
+
1931
+ side.last_used_move = .None;
1932
+ side.active.volatiles.dirty = false;
1933
+
1934
+ const last = foe.lastMove(false);
1935
+
1936
+ if (last == .None) return options.log.fail(.{ battle.active(player), .None });
1937
+ const knows = knows: for (side.active.moves) |m| {
1938
+ if (last == m.id) break :knows true;
1939
+ } else false;
1940
+ if (knows) return options.log.fail(.{ battle.active(player), .None });
1941
+
1942
+ // if (wPlayerCharging) ???
1943
+ // wPlayerCharging = 1
1944
+
1945
+ // FIXME
1946
+ state.move = last;
1947
+ state.from = .MirrorMove;
1948
+ return generated.runMove(battle, player, state, options);
1949
+ }
1950
+
1951
+ pub fn mist(battle: anytype, player: Player, _: *State, options: anytype) !void {
1952
+ var side = battle.side(player);
1953
+
1954
+ if (side.active.volatiles.Mist) return options.log.fail(.{ battle.active(player), .None });
1955
+ side.active.volatiles.Mist = true;
1956
+
1957
+ try options.log.start(.{ battle.active(player), .Mist });
1958
+ }
1959
+
1960
+ pub fn weatherHeal(battle: anytype, player: Player, _: *State, options: anytype) !void {
1961
+ var stored = battle.side(player).stored();
1962
+ const ident = battle.active(player);
1963
+
1964
+ if (stored.hp == stored.stats.hp) return options.log.fail(.{ ident, .None });
1965
+
1966
+ stored.hp = switch (battle.field.weather) {
1967
+ .Sun => stored.stats.hp,
1968
+ .None => @min(stored.stats.hp, stored.hp + (stored.stats.hp / 2)),
1969
+ else => @min(stored.stats.hp, stored.hp + (stored.stats.hp / 4)),
1970
+ };
1971
+
1972
+ try options.log.heal(.{ ident, stored, .None });
1973
+ }
1974
+
1975
+ pub fn multiHit(battle: anytype, player: Player, state: *State, options: anytype) !void {
1976
+ _ = .{ battle, player, state, options }; // TODO
1977
+ }
1978
+
1979
+ pub fn nightmare(battle: anytype, player: Player, state: *State, options: anytype) !void {
1980
+ var foe = battle.foe(player);
1981
+ var foe_volatiles = &foe.active.volatiles;
1982
+ const foe_ident = battle.active(player.foe());
1983
+
1984
+ if (foe_volatiles.Flying or foe_volatiles.Underground) {
1985
+ if (!showdown) return options.log.fail(.{ battle.active(player.foe()), .None });
1986
+ try options.log.lastmiss(.{});
1987
+ return options.log.miss(.{battle.active(player)});
1988
+ } else if (foe_volatiles.Substitute) {
1989
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1990
+ } else if (!Status.is(foe.stored().status, .SLP) or foe_volatiles.Nightmare) {
1991
+ return options.log.fail(.{ foe_ident, .None });
1992
+ }
1993
+
1994
+ foe_volatiles.Nightmare = true;
1995
+ try options.log.start(.{ battle.active(player.foe()), .Nightmare });
1996
+ }
1997
+
1998
+ pub const ohko = struct {
1999
+ // OHKO calls adjustDamage but only actually cares about immunity
2000
+ pub fn immune(battle: anytype, player: Player, state: *State, _: anytype) !void {
2001
+ const move = Move.get(state.move);
2002
+
2003
+ assert(move.type == .Normal or move.type == .Ground);
2004
+ const foe = battle.foe(player);
2005
+ const zero = if (move.type == .Normal)
2006
+ foe.active.types.includes(.Ghost) and !foe.active.volatiles.Foresight
2007
+ else
2008
+ foe.active.types.includes(.Flying);
2009
+ state.effectiveness = if (zero) 0 else Effectiveness.neutral;
2010
+ }
2011
+
2012
+ pub fn damage(battle: anytype, player: Player, state: *State, options: anytype) !void {
2013
+ const side = battle.side(player);
2014
+ const foe = battle.foe(player);
2015
+
2016
+ const foe_ident = battle.active(player.foe());
2017
+
2018
+ state.damage = 0;
2019
+ if (state.immune()) return options.log.immune(.{ foe_ident, .None });
2020
+ const delta = side.stored().level -| foe.stored().level;
2021
+ if (delta == 0) return options.log.immune(.{ foe_ident, .OHKO });
2022
+
2023
+ state.accuracy = 2 * delta +| Gen12.percent(30);
2024
+ try checkHit(battle, player, state, options);
2025
+ if (!state.miss) state.damage = 65535;
2026
+ state.ohko = true;
2027
+ }
2028
+ };
2029
+
2030
+ pub fn painSplit(battle: anytype, player: Player, state: *State, options: anytype) !void {
2031
+ var side = battle.side(player);
2032
+ var foe = battle.foe(player);
2033
+
2034
+ const ident = battle.active(player);
2035
+ const foe_ident = battle.active(player.foe());
2036
+
2037
+ if (state.miss) return options.log.fail(.{ foe_ident, .None });
2038
+ if (foe.active.volatiles.Substitute) {
2039
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2040
+ }
2041
+
2042
+ const avg = @max((foe.stored().hp + side.stored().hp) / 2, 1);
2043
+ foe.stored().hp -= avg;
2044
+ side.stored().hp = avg;
2045
+
2046
+ try options.log.sethp(.{ foe_ident, foe.stored(), .Silent });
2047
+ try options.log.sethp(.{ ident, side.stored(), .None });
2048
+ }
2049
+
2050
+ pub fn paralyze(battle: anytype, player: Player, state: *State, options: anytype) !void {
2051
+ var foe = battle.foe(player);
2052
+ const foe_ident = battle.active(player.foe());
2053
+
2054
+ if (Status.is(foe.stored().status, .PAR)) {
2055
+ return options.log.fail(.{ foe_ident, .Paralysis });
2056
+ }
2057
+ if (state.immune()) return options.log.immune(.{ foe_ident, .None });
2058
+ if (Status.any(foe.stored().status)) return options.log.fail(.{ foe_ident, .None });
2059
+ if (state.miss) {
2060
+ try options.log.lastmiss(.{});
2061
+ return options.log.miss(.{battle.active(player)});
2062
+ } else if (foe.active.volatiles.Substitute) {
2063
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2064
+ }
2065
+
2066
+ foe.stored().status = Status.init(.PAR);
2067
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2068
+
2069
+ try options.log.status(.{ foe_ident, foe.stored().status, .None });
2070
+ }
2071
+
2072
+ pub fn paralyzeChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2073
+ var foe = battle.foe(player);
2074
+ var foe_stored = foe.stored();
2075
+
2076
+ if (foe.active.volatiles.Substitute) return;
2077
+ if (Status.any(foe_stored.status)) return;
2078
+ if (state.immune()) return;
2079
+ if (!state.proc) return;
2080
+ if (foe.conditions.Safeguard) return;
2081
+
2082
+ foe_stored.status = Status.init(.PAR);
2083
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2084
+
2085
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
2086
+
2087
+ // TODO: check for status berry
2088
+ }
2089
+
2090
+ pub fn payDay(battle: anytype, player: Player, _: *State, options: anytype) !void {
2091
+ if (!showdown or !battle.foe(player).active.volatiles.Substitute) {
2092
+ try options.log.fieldactivate(.{}); // FIXME .PayDay
2093
+ }
2094
+ }
2095
+
2096
+ pub fn perishSong(battle: anytype, player: Player, _: *State, options: anytype) !void {
2097
+ var side = battle.side(player);
2098
+ var foe = battle.foe(player);
2099
+
2100
+ if (foe.active.volatiles.PerishSong) {
2101
+ return options.log.fail(.{ battle.active(player.foe()), .None });
2102
+ } else if (!side.active.volatiles.PerishSong) {
2103
+ side.active.volatiles.PerishSong = true;
2104
+ side.active.volatiles.perish_song = 4;
2105
+ try options.log.start(.{ battle.active(player), .PerishSong3Silent });
2106
+ }
2107
+ foe.active.volatiles.PerishSong = true;
2108
+ foe.active.volatiles.perish_song = 4;
2109
+ try options.log.start(.{ battle.active(player.foe()), .PerishSong3Silent });
2110
+
2111
+ try options.log.fieldactivate(.{}); // FIXME .PerishSong
2112
+ }
2113
+
2114
+ pub fn poison(battle: anytype, player: Player, state: *State, options: anytype) !void {
2115
+ var foe = battle.foe(player);
2116
+ var foe_stored = foe.stored();
2117
+ const foe_ident = battle.active(player.foe());
2118
+
2119
+ const toxic = state.move == .Toxic;
2120
+ if (state.immune() or foe.active.types.includes(.Poison)) {
2121
+ return options.log.immune(.{ foe_ident, .None });
2122
+ } else if (Status.any(foe_stored.status)) {
2123
+ // Pokémon Showdown considers Toxic to be a status even in Generation II and so
2124
+ // will not include a fail reason for Toxic vs. Poison or vice-versa...
2125
+ return options.log.fail(.{ foe_ident, if (Status.is(foe_stored.status, .PSN))
2126
+ if (!showdown)
2127
+ Fail.Poison
2128
+ else if (toxic == (foe_stored.status == Status.TOX))
2129
+ if (toxic) Fail.Toxic else Fail.Poison
2130
+ else
2131
+ Fail.None
2132
+ else
2133
+ Fail.None });
2134
+ } else if (foe.active.volatiles.Substitute) {
2135
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2136
+ } else if (state.miss) {
2137
+ try options.log.lastmiss(.{});
2138
+ return options.log.miss(.{battle.active(player)});
2139
+ }
2140
+
2141
+ foe_stored.status = Status.init(.PSN);
2142
+ if (toxic) {
2143
+ if (showdown) foe_stored.status = Status.TOX;
2144
+ foe.active.volatiles.Toxic = true;
2145
+ foe.active.volatiles.toxic = 0;
2146
+ }
2147
+
2148
+ try options.log.status(.{ foe_ident, foe_stored.status, .None });
2149
+
2150
+ // TODO: check for status berry
2151
+ }
2152
+
2153
+ pub fn poisonChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2154
+ var foe = battle.foe(player);
2155
+ var foe_stored = foe.stored();
2156
+
2157
+ if (foe.active.volatiles.Substitute) return;
2158
+ if (Status.any(foe_stored.status)) return if (showdown) battle.rng.advance(1);
2159
+ if (state.immune() or foe.active.types.includes(.Poison)) return;
2160
+ if (!state.proc) return;
2161
+ if (foe.conditions.Safeguard) return;
2162
+
2163
+ foe_stored.status = Status.init(.PSN);
2164
+
2165
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
2166
+
2167
+ // TODO: check for status berry
2168
+ }
2169
+
2170
+ pub fn present(battle: anytype, player: Player, state: *State, options: anytype) !void {
2171
+ _ = .{ battle, player, state, options }; // TODO
2172
+ }
2173
+
2174
+ pub fn protect(battle: anytype, player: Player, state: *State, options: anytype) !void {
2175
+ var side = battle.side(player);
2176
+ var volatiles = &side.active.volatiles;
2177
+
2178
+ const failed = !state.first or volatiles.Substitute or
2179
+ !try Rolls.protect(battle, player, volatiles.protect, options);
2180
+ if (failed) return options.log.fail(.{ battle.active(player), .None });
2181
+
2182
+ volatiles.protect = @max(8, volatiles.protect + 1);
2183
+ if (state.move == .Endure) {
2184
+ volatiles.Endure = true;
2185
+ } else {
2186
+ volatiles.Protect = true;
2187
+ }
2188
+ try options.log.singleturn(.{ battle.active(player), state.move });
2189
+ }
2190
+
2191
+ pub fn psychUp(battle: anytype, player: Player, _: *State, options: anytype) !void {
2192
+ var side = battle.side(player);
2193
+ const foe = battle.foe(player);
2194
+
2195
+ // Pokémon Showdown should fail when the enemy has no boosts/unboosts but doesn't
2196
+ if (!showdown and @as(u32, @bitCast(foe.active.boosts)) == 0) {
2197
+ return options.log.fail(.{ battle.active(player), .None });
2198
+ }
2199
+
2200
+ side.active.boosts = foe.active.boosts;
2201
+ try options.log.copyboost(.{ battle.active(player), battle.active(player.foe()) });
2202
+ }
2203
+
2204
+ pub fn pursuit(battle: anytype, player: Player, state: *State, _: anytype) !void {
2205
+ // TODO: remove switching variable and just look at Choice saved in Battle struct?
2206
+ if (battle.foe(player).active.volatiles.switching) state.damage = smul(state.damage, 2);
2207
+ }
2208
+
2209
+ pub const rage = struct {
2210
+ pub fn start(battle: anytype, player: Player, _: *State, options: anytype) !void {
2211
+ battle.side(player).active.volatiles.Rage = true;
2212
+ try options.log.singlemove(.{ battle.active(player), Move.Rage });
2213
+ }
2214
+
2215
+ pub fn damage(battle: anytype, player: Player, state: *State, _: anytype) !void {
2216
+ const side = battle.side(player);
2217
+
2218
+ assert(side.active.volatiles.Rage);
2219
+ state.damage = smul(state.damage, (side.active.volatiles.rage +| 1)); // TODO: |+
2220
+ }
2221
+ };
2222
+
2223
+ pub fn rainDance(battle: anytype, _: Player, _: *State, options: anytype) !void {
2224
+ return weather(battle, .Rain, options);
2225
+ }
2226
+
2227
+ pub fn rapidSpin(battle: anytype, player: Player, _: *State, options: anytype) !void {
2228
+ var side = battle.side(player);
2229
+
2230
+ if (side.active.volatiles.LeechSeed) {
2231
+ try options.log.end(.{ battle.active(player), .LeechSeedFrom });
2232
+ side.active.volatiles.LeechSeed = false;
2233
+ }
2234
+
2235
+ if (side.conditions.Spikes) {
2236
+ try options.log.sideend(.{ player, protocol.Side.Spikes, battle.active(player) });
2237
+ side.conditions.Spikes = false;
2238
+ }
2239
+
2240
+ if (side.active.volatiles.bind.duration > 0) {
2241
+ const reason = @intFromEnum(End.Bind) + side.active.volatiles.bind.reason - 1;
2242
+ try options.log.end(.{ battle.active(player), @as(End, @enumFromInt(reason)) });
2243
+ side.active.volatiles.bind = .{};
2244
+ }
2245
+ }
2246
+
2247
+ pub fn recoil(battle: anytype, player: Player, state: *State, options: anytype) !void {
2248
+ var side = battle.side(player);
2249
+ var stored = side.stored();
2250
+ const ident = battle.active(player);
2251
+
2252
+ assert(state.damage > 0);
2253
+
2254
+ const damage: i16 = @intCast(@max(state.damage / 4, 1));
2255
+ stored.hp = @intCast(@max(@as(i16, @intCast(stored.hp)) - damage, 0));
2256
+
2257
+ try options.log.damage(.{ ident, stored, .RecoilOf, battle.active(player.foe()) });
2258
+ }
2259
+
2260
+ pub fn reversal(battle: anytype, player: Player, state: *State, options: anytype) !void {
2261
+ const stored = battle.side(player).stored();
2262
+
2263
+ // Pokémon Showdown Gen II implementation incorrectly inherits Gen IV's table instead
2264
+ state.bp = if (showdown) power: {
2265
+ const x = @max(1, stored.hp * 64 / stored.stats.hp);
2266
+ if (x < 2) break :power 200;
2267
+ if (x < 6) break :power 150;
2268
+ if (x < 13) break :power 100;
2269
+ if (x < 22) break :power 80;
2270
+ if (x < 43) break :power 40;
2271
+ break :power 20;
2272
+ } else power: {
2273
+ const x = @max(1, stored.hp * 48 / stored.stats.hp);
2274
+ if (x < 1) break :power 200;
2275
+ if (x < 4) break :power 150;
2276
+ if (x < 9) break :power 100;
2277
+ if (x < 16) break :power 80;
2278
+ if (x < 32) break :power 40;
2279
+ break :power 20;
2280
+ };
2281
+
2282
+ try calcDamage(battle, player, state, options);
2283
+ }
2284
+
2285
+ pub const rollout = struct {
2286
+ pub fn check(battle: anytype, player: Player, _: *State, _: anytype) !void {
2287
+ var side = battle.side(player);
2288
+
2289
+ if (!side.active.volatiles.Rollout) {
2290
+ side.active.volatiles.attacks = 0;
2291
+ } else {
2292
+ // TODO SkipToBattleCommand(doturn_command)
2293
+ }
2294
+ }
2295
+
2296
+ pub fn power(battle: anytype, player: Player, state: *State, _: anytype) !void {
2297
+ var side = battle.side(player);
2298
+
2299
+ if (Status.is(side.stored().status, .SLP)) return;
2300
+
2301
+ if (side.active.volatiles.attacks > 0) {
2302
+ // TODO set wSomeoneIsRampaging
2303
+ }
2304
+
2305
+ if (state.miss) {
2306
+ side.active.volatiles.Rollout = false;
2307
+ return;
2308
+ }
2309
+
2310
+ assert(side.active.volatiles.attacks < 5);
2311
+ side.active.volatiles.attacks += 1;
2312
+ side.active.volatiles.Rollout = side.active.volatiles.attacks != 5;
2313
+
2314
+ if (side.active.volatiles.DefenseCurl) state.damage = smul(state.damage, 2);
2315
+ }
2316
+ };
2317
+
2318
+ pub fn sandstorm(battle: anytype, player: Player, _: *State, options: anytype) !void {
2319
+ if (battle.field.weather != .Sandstorm) return weather(battle, .Sandstorm, options);
2320
+ return options.log.fail(.{ battle.active(player), .None });
2321
+ }
2322
+
2323
+ pub fn safeguard(battle: anytype, player: Player, _: *State, options: anytype) !void {
2324
+ return screens(battle, player, "Safeguard", "safeguard", options);
2325
+ }
2326
+
2327
+ pub fn reflect(battle: anytype, player: Player, _: *State, options: anytype) !void {
2328
+ return screens(battle, player, "Reflect", "reflect", options);
2329
+ }
2330
+
2331
+ pub fn lightScreen(battle: anytype, player: Player, _: *State, options: anytype) !void {
2332
+ return screens(battle, player, "LightScreen", "light_screen", options);
2333
+ }
2334
+
2335
+ fn screens(
2336
+ battle: anytype,
2337
+ player: Player,
2338
+ comptime key: []const u8,
2339
+ comptime value: []const u8,
2340
+ options: anytype,
2341
+ ) !void {
2342
+ var side = battle.side(player);
2343
+
2344
+ if (@field(side.conditions, key)) {
2345
+ return options.log.fail(.{ battle.active(player), .None });
2346
+ }
2347
+
2348
+ @field(side.conditions, key) = true;
2349
+ @field(side.conditions, value) = 5;
2350
+ try options.log.sidestart(.{ player, @field(protocol.Side, key) });
2351
+ }
2352
+
2353
+ pub fn sketch(battle: anytype, player: Player, _: *State, options: anytype) !void {
2354
+ var side = battle.side(player);
2355
+
2356
+ side.last_used_move = .None;
2357
+ side.active.volatiles.dirty = false;
2358
+
2359
+ if (showdown) {
2360
+ // yes, actually "Splash". '|nothing' gets blindly mapped to '|-activate||move:Splash'
2361
+ try options.log.activate(.{ battle.active(player), .Splash });
2362
+ } else {
2363
+ try options.log.fail(.{ battle.active(player), .None });
2364
+ }
2365
+ }
2366
+
2367
+ pub fn sleep(battle: anytype, player: Player, state: *State, options: anytype) !void {
2368
+ var foe = battle.foe(player);
2369
+ var foe_stored = foe.stored();
2370
+ const foe_ident = battle.active(player.foe());
2371
+
2372
+ if (Status.any(foe_stored.status)) {
2373
+ return options.log.fail(.{
2374
+ foe_ident,
2375
+ if (Status.is(foe_stored.status, .SLP)) Fail.Sleep else Fail.None,
2376
+ });
2377
+ }
2378
+
2379
+ if (foe.active.volatiles.Substitute) {
2380
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2381
+ }
2382
+
2383
+ // Sleep Clause Mod
2384
+ if (pkmn.options.mod) {
2385
+ for (foe.pokemon) |p| {
2386
+ if (Status.is(p.status, .SLP) and !Status.is(p.status, .EXT)) return;
2387
+ }
2388
+ }
2389
+
2390
+ foe_stored.status = Status.slp(Rolls.sleepDuration(battle, player, options));
2391
+ try options.log.status(.{ foe_ident, foe_stored.status, .From, state.move });
2392
+ }
2393
+
2394
+ pub fn sleepTalk(battle: anytype, player: Player, state: *State, options: anytype) !void {
2395
+ const side = battle.side(player);
2396
+
2397
+ if (!Status.is(side.stored().status, .SLP)) {
2398
+ return if (!showdown) try options.log.fail(.{ battle.active(player), .None });
2399
+ }
2400
+
2401
+ var n: u3 = 0;
2402
+ for (side.active.moves, 0..) |m, i| {
2403
+ if (state.mslot - 1 != i and Move.get(m.id).extra.sleep_talk) n += 1;
2404
+ }
2405
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
2406
+
2407
+ _ = try Rolls.sleepTalk(battle, player, n, state.mslot, options); // TODO
2408
+ }
2409
+
2410
+ pub fn snore(battle: anytype, player: Player, state: *State, options: anytype) !bool {
2411
+ if (Status.is(battle.side(player).stored().status, .SLP)) return true;
2412
+ state.damage = 0;
2413
+ state.miss = true; // TODO is this necessary?
2414
+ if (!showdown) try options.log.fail(.{ battle.active(player), .None });
2415
+ return false;
2416
+ }
2417
+
2418
+ pub fn spikes(battle: anytype, player: Player, _: *State, options: anytype) !void {
2419
+ var foe = battle.foe(player);
2420
+ if (foe.conditions.Spikes) return options.log.fail(.{ battle.active(player), .None });
2421
+
2422
+ foe.conditions.Spikes = true;
2423
+ try options.log.sidestart(.{ player.foe(), protocol.Side.Spikes });
2424
+ }
2425
+
2426
+ pub fn spite(battle: anytype, player: Player, state: *State, options: anytype) !void {
2427
+ var foe = battle.foe(player);
2428
+
2429
+ const last = foe.lastMove(false);
2430
+ if (state.miss or last == .None or last == .Struggle) {
2431
+ return options.log.fail(.{ battle.active(player.foe()), .None });
2432
+ }
2433
+
2434
+ var slot: u4 = 0;
2435
+ for (foe.active.moves, 0..) |m, i| {
2436
+ if (m.id == last) slot = @intCast(i + 1);
2437
+ }
2438
+ // If the move was called via Metronome it might not exist
2439
+ if (slot == 0 or foe.active.move(slot).pp == 0) {
2440
+ return options.log.fail(.{ battle.active(player.foe()), .None });
2441
+ }
2442
+
2443
+ // Pokémon Showdown always deducts 4 instead of randomizing
2444
+ const pp = @min(
2445
+ foe.active.move(slot).pp,
2446
+ if (showdown) 4 else try Rolls.spite(battle, player, options),
2447
+ );
2448
+ foe.active.move(slot).pp -= pp;
2449
+ if (!foe.active.volatiles.Transform) {
2450
+ var move_slot = foe.stored().move(slot);
2451
+ assert(move_slot.pp > 0);
2452
+
2453
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
2454
+ assert(foe.active.move(slot).pp == foe.stored().move(slot).pp);
2455
+ }
2456
+
2457
+ try options.log.activate(.{ battle.active(player.foe()), .Spite, last, pp });
2458
+ }
2459
+
2460
+ pub fn splash(battle: anytype, player: Player, _: *State, options: anytype) !void {
2461
+ try options.log.activate(.{ battle.active(player), .Splash });
2462
+ }
2463
+
2464
+ pub fn substitute(battle: anytype, player: Player, _: *State, options: anytype) !void {
2465
+ var side = battle.side(player);
2466
+ if (side.active.volatiles.Substitute) {
2467
+ return options.log.fail(.{ battle.active(player), .Substitute });
2468
+ }
2469
+
2470
+ assert(side.stored().stats.hp <= 1023);
2471
+ const hp: u8 = @intCast(side.stored().stats.hp / 4);
2472
+
2473
+ if (hp == 0 or side.stored().hp <= hp) {
2474
+ return options.log.fail(.{ battle.active(player), .Weak });
2475
+ }
2476
+
2477
+ side.stored().hp -= hp;
2478
+ side.active.volatiles.substitute = hp;
2479
+ side.active.volatiles.Substitute = true;
2480
+ side.active.volatiles.bind = .{};
2481
+ try options.log.start(.{ battle.active(player), .Substitute });
2482
+ try options.log.damage(.{ battle.active(player), side.stored(), .None });
2483
+ }
2484
+
2485
+ pub fn sunnyDay(battle: anytype, _: Player, _: *State, options: anytype) !void {
2486
+ return weather(battle, .Sun, options);
2487
+ }
2488
+
2489
+ fn weather(battle: anytype, w: Weather, options: anytype) !void {
2490
+ battle.field.weather = w;
2491
+ battle.field.weather_duration = 5;
2492
+ try options.log.weather(.{ w, protocol.Weather.None });
2493
+ }
2494
+
2495
+ pub fn teleport(battle: anytype, player: Player, _: *State, options: anytype) !void {
2496
+ if (showdown) return;
2497
+
2498
+ try options.log.fail(.{ battle.active(player), .None });
2499
+ try options.log.laststill(.{});
2500
+ }
2501
+
2502
+ pub fn thief(battle: anytype, player: Player, state: *State, options: anytype) !void {
2503
+ const side = battle.side(player);
2504
+ const foe = battle.foe(player);
2505
+
2506
+ if (side.stored().item != .None or foe.stored().item == .None) return;
2507
+ // Pokémon Showdown incorrectly allows you steal Mail
2508
+ if (!showdown and foe.stored().item.isMail()) return;
2509
+ if (!state.proc) return;
2510
+
2511
+ side.stored().item = foe.stored().item;
2512
+ foe.stored().item = .None;
2513
+
2514
+ try options.log.item(.{
2515
+ battle.active(player),
2516
+ side.stored().item,
2517
+ battle.active(player.foe()),
2518
+ });
2519
+ }
2520
+
2521
+ pub fn thrashing(battle: anytype, player: Player, _: *State, options: anytype) !void {
2522
+ var side = battle.side(player);
2523
+ if (Status.is(side.stored().status, .SLP)) return;
2524
+
2525
+ assert(!side.active.volatiles.Thrashing);
2526
+ side.active.volatiles.Thrashing = true;
2527
+ side.active.volatiles.attacks = Rolls.attackingDuration(battle, player, options);
2528
+ // TODO wSomeoneIsRampaging = true;
2529
+ }
2530
+
2531
+ pub fn transform(battle: anytype, player: Player, _: *State, options: anytype) !void {
2532
+ var side = battle.side(player);
2533
+ const foe = battle.foe(player);
2534
+ const foe_ident = battle.active(player.foe());
2535
+
2536
+ side.last_used_move = .None;
2537
+ side.active.volatiles.dirty = false;
2538
+
2539
+ if (foe.active.volatiles.Transform) {
2540
+ return options.log.fail(.{ battle.active(player), .None });
2541
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2542
+ if (!showdown) return options.log.fail(.{ battle.active(player), .None });
2543
+ try options.log.lastmiss(.{});
2544
+ return options.log.miss(.{battle.active(player)});
2545
+ }
2546
+
2547
+ side.active.volatiles.Transform = true;
2548
+ side.active.volatiles.transform = foe_ident.int();
2549
+ side.active.volatiles.disable = .{};
2550
+
2551
+ // HP is not copied by Transform
2552
+ side.active.stats.atk = foe.active.stats.atk;
2553
+ side.active.stats.def = foe.active.stats.def;
2554
+ side.active.stats.spe = foe.active.stats.spe;
2555
+ side.active.stats.spa = foe.active.stats.spa;
2556
+ side.active.stats.spd = foe.active.stats.spd;
2557
+
2558
+ side.active.species = foe.active.species;
2559
+ side.active.types = foe.active.types;
2560
+ side.active.boosts = foe.active.boosts;
2561
+ for (foe.active.moves, 0..) |m, i| {
2562
+ side.active.moves[i].id = m.id;
2563
+ side.active.moves[i].pp = if (m.id != .None) if (m.id == .Sketch) 1 else 5 else 0;
2564
+ }
2565
+
2566
+ try options.log.transform(.{ battle.active(player), foe_ident });
2567
+ }
2568
+
2569
+ pub fn triAttack(battle: anytype, player: Player, state: *State, options: anytype) !void {
2570
+ // FIXME only commit effectchance and triattack rolls if actually does something...
2571
+ try effectChance(battle, player, state, options);
2572
+ if (state.proc) {
2573
+ try switch (try Rolls.triAttack(battle, player, options)) {
2574
+ .PAR => paralyzeChance(battle, player, state, options),
2575
+ .FRZ => freezeChance(battle, player, state, options),
2576
+ .BRN => burnChance(battle, player, state, options),
2577
+ };
2578
+ } else if (!showdown) battle.rng.advance(1);
2579
+ }
2580
+
2581
+ pub fn tripleKick(battle: anytype, player: Player, state: *State, options: anytype) !void {
2582
+ _ = .{ battle, player, state, options }; // TODO
2583
+ }
2584
+
2585
+ const STAT_UP_REASONS =
2586
+ [_]Boost{ .Attack, .Defense, .Speed, .SpecialAttack, .SpecialDefense };
2587
+
2588
+ pub fn allStatUpChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2589
+ var side = battle.side(player);
2590
+
2591
+ const stats = &side.active.stats;
2592
+ const boosts = &side.active.boosts;
2593
+
2594
+ if (!state.proc) return;
2595
+ inline for (STATS, STAT_UP_REASONS) |s, r| {
2596
+ assert(@field(boosts, s) >= -6 and @field(boosts, s) <= 6);
2597
+ if (@field(boosts, s) == 6 or @field(stats, s) == MAX_STAT_VALUE) {
2598
+ try options.log.boost(.{ battle.active(player), r, 0 });
2599
+ } else {
2600
+ try boostStat(battle, side, stats, boosts, s, 1);
2601
+ try options.log.boost(.{ battle.active(player), r, 1 });
2602
+ }
2603
+ }
2604
+ }
2605
+
2606
+ pub fn boost(battle: anytype, player: Player, state: *State, options: anytype) !void {
2607
+ var log = options.log;
2608
+ var side = battle.side(player);
2609
+ const ident = battle.active(player);
2610
+
2611
+ if (state.miss) return log.fail(.{ ident, .None });
2612
+
2613
+ const stats = &side.active.stats;
2614
+ var boosts = &side.active.boosts;
2615
+
2616
+ const move = Move.get(state.move);
2617
+ switch (move.effect) {
2618
+ .AttackUp1, .AttackUp2, .Rage, .Swagger => {
2619
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2620
+ if (boosts.atk == 6 or stats.atk == MAX_STAT_VALUE) {
2621
+ return log.fail(.{ ident, .None });
2622
+ }
2623
+ const n: u2 = if (move.effect == .AttackUp2 or move.effect == .Swagger) 2 else 1;
2624
+ try boostStat(battle, side, stats, boosts, "atk", n);
2625
+ const reason = if (showdown and move.effect == .Rage) Boost.Rage else Boost.Attack;
2626
+ try log.boost(.{ ident, reason, n });
2627
+ },
2628
+ .DefenseUp1, .DefenseUp2, .SkullBash => {
2629
+ assert(boosts.def >= -6 and boosts.def <= 6);
2630
+ if (boosts.def == 6 or stats.def == MAX_STAT_VALUE) {
2631
+ return log.fail(.{ ident, .None });
2632
+ }
2633
+ const n: u2 = if (move.effect == .DefenseUp2) 2 else 1;
2634
+ try boostStat(battle, side, stats, boosts, "def", n);
2635
+ try log.boost(.{ ident, .Defense, n });
2636
+ },
2637
+ .SpeedUp2 => {
2638
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2639
+ if (boosts.spe == 6 or stats.spe == MAX_STAT_VALUE) {
2640
+ return log.fail(.{ ident, .None });
2641
+ }
2642
+ try boostStat(battle, side, stats, boosts, "spe", 2);
2643
+ try log.boost(.{ ident, .Speed, 2 });
2644
+ },
2645
+ .SpAtkUp1 => {
2646
+ assert(boosts.spa >= -6 and boosts.spa <= 6);
2647
+ if (boosts.spa == 6 or stats.spa == MAX_STAT_VALUE) {
2648
+ return log.fail(.{ ident, .None });
2649
+ }
2650
+ try boostStat(battle, side, stats, boosts, "spa", 1);
2651
+ try log.boost(.{ ident, .SpecialAttack, 1 });
2652
+ },
2653
+ .SpDefUp2 => {
2654
+ assert(boosts.spd >= -6 and boosts.spd <= 6);
2655
+ if (boosts.spd == 6 or stats.spd == MAX_STAT_VALUE) {
2656
+ return log.fail(.{ ident, .None });
2657
+ }
2658
+ try boostStat(battle, side, stats, boosts, "spd", 2);
2659
+ try log.boost(.{ ident, .SpecialDefense, 2 });
2660
+ },
2661
+ .EvasionUp1 => {
2662
+ assert(boosts.evasion >= -6 and boosts.evasion <= 6);
2663
+ if (boosts.evasion == 6) return log.fail(.{ ident, .None });
2664
+ boosts.evasion = @intCast(@min(6, @as(i8, boosts.evasion) + 1));
2665
+ try log.boost(.{ ident, .Evasion, 1 });
2666
+ if (state.move == .Minimize) side.active.volatiles.minimized = true;
2667
+ },
2668
+ else => unreachable,
2669
+ }
2670
+ }
2671
+
2672
+ pub fn unboost(battle: anytype, player: Player, state: *State, options: anytype) !void {
2673
+ var log = options.log;
2674
+ var foe = battle.foe(player);
2675
+ const foe_ident = battle.active(player.foe());
2676
+
2677
+ if (foe.active.volatiles.Mist) {
2678
+ try log.activate(.{ foe_ident, .Mist });
2679
+ return log.fail(.{ foe_ident, .None });
2680
+ }
2681
+
2682
+ const fail = foe.active.volatiles.Substitute or state.miss or !state.proc;
2683
+
2684
+ const stats = &foe.active.stats;
2685
+ var boosts = &foe.active.boosts;
2686
+
2687
+ const move = Move.get(state.move);
2688
+ const none: Fail = .None;
2689
+ switch (move.effect) {
2690
+ .AttackDown1, .AttackDown2, .AttackDownChance => {
2691
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2692
+ if (fail or boosts.atk == -6) {
2693
+ return if (move.effect != .AttackDownChance) try log.fail(.{ foe_ident, none });
2694
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2695
+ try options.log.lastmiss(.{});
2696
+ return options.log.miss(.{battle.active(player)});
2697
+ } else if (stats.atk == 1) {
2698
+ return if (move.effect != .AttackDownChance) try log.fail(.{ foe_ident, none });
2699
+ }
2700
+ const n: u2 = if (move.effect == .AttackDown2) 2 else 1;
2701
+ try unboostStat(battle, foe, stats, boosts, "atk", n);
2702
+ try log.boost(.{ foe_ident, .Attack, -@as(i8, n) });
2703
+ },
2704
+ .DefenseDown1, .DefenseDown2, .DefenseDownChance => {
2705
+ assert(boosts.def >= -6 and boosts.def <= 6);
2706
+ if (fail or boosts.def == -6) {
2707
+ if (move.effect != .DefenseDownChance) try log.fail(.{ foe_ident, none });
2708
+ return;
2709
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2710
+ try options.log.lastmiss(.{});
2711
+ return options.log.miss(.{battle.active(player)});
2712
+ } else if (stats.def == 1) {
2713
+ if (move.effect != .DefenseDownChance) try log.fail(.{ foe_ident, none });
2714
+ return;
2715
+ }
2716
+ const n: u2 = if (move.effect == .DefenseDown2) 2 else 1;
2717
+ try unboostStat(battle, foe, stats, boosts, "def", n);
2718
+ try log.boost(.{ foe_ident, .Defense, -@as(i8, n) });
2719
+ },
2720
+ .SpeedDown1, .SpeedDown2, .SpeedDownChance => {
2721
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2722
+ if (fail or boosts.spe == -6) {
2723
+ return if (move.effect != .SpeedDownChance) try log.fail(.{ foe_ident, none });
2724
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2725
+ try options.log.lastmiss(.{});
2726
+ return options.log.miss(.{battle.active(player)});
2727
+ } else if (stats.spe == 1) {
2728
+ return if (move.effect != .SpeedDownChance) try log.fail(.{ foe_ident, none });
2729
+ }
2730
+ const n: u2 = if (move.effect == .SpeedDown2) 2 else 1;
2731
+ try unboostStat(battle, foe, stats, boosts, "spe", n);
2732
+ try log.boost(.{ foe_ident, .Speed, -@as(i8, n) });
2733
+ },
2734
+ .SpDefDownChance => {
2735
+ assert(boosts.spd >= -6 and boosts.spd <= 6);
2736
+ if (fail or boosts.spd == -6) return;
2737
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2738
+ try options.log.lastmiss(.{});
2739
+ return options.log.miss(.{battle.active(player)});
2740
+ } else if (stats.spd == 1) return;
2741
+ try unboostStat(battle, foe, stats, boosts, "spd", 1);
2742
+ try log.boost(.{ foe_ident, .SpecialDefense, -1 });
2743
+ },
2744
+ .AccuracyDown1, .AccuracyDownChance => {
2745
+ assert(boosts.accuracy >= -6 and boosts.accuracy <= 6);
2746
+ if (fail or boosts.accuracy == -6) {
2747
+ if (move.effect != .AccuracyDownChance) try log.fail(.{ foe_ident, none });
2748
+ return;
2749
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2750
+ try options.log.lastmiss(.{});
2751
+ return options.log.miss(.{battle.active(player)});
2752
+ }
2753
+ boosts.accuracy = @intCast(@max(-6, @as(i8, boosts.accuracy) - 1));
2754
+ try log.boost(.{ foe_ident, .Accuracy, -1 });
2755
+ },
2756
+ else => unreachable,
2757
+ }
2758
+ }
2759
+ };
2760
+
2761
+ fn unmodifiedStats(battle: anytype, side: *Side) *Stats(u16) {
2762
+ if (!side.active.volatiles.Transform) return &side.stored().stats;
2763
+ const id = ID.from(side.active.volatiles.transform);
2764
+ return &battle.side(id.player).pokemon[id.id - 1].stats;
2765
+ }
2766
+
2767
+ fn recomputeStats(battle: anytype, side: *Side) void {
2768
+ const stats = unmodifiedStats(battle, side);
2769
+ inline for (STATS) |s| {
2770
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(side.active.boosts, s)) + 6))];
2771
+ const val = @field(stats, s) * mod[0] / mod[1];
2772
+ @field(side.active.stats, s) = @max(1, @min(MAX_STAT_VALUE, val));
2773
+ }
2774
+ }
2775
+
2776
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
2777
+ if (Status.is(status, .PAR)) {
2778
+ stats.spe = @max(stats.spe / 4, 1);
2779
+ } else if (Status.is(status, .BRN)) {
2780
+ stats.atk = @max(stats.atk / 2, 1);
2781
+ }
2782
+ }
2783
+
2784
+ fn boostStat(
2785
+ battle: anytype,
2786
+ side: *Side,
2787
+ stats: *Stats(u16),
2788
+ boosts: *Boosts,
2789
+ comptime s: []const u8,
2790
+ n: u2,
2791
+ ) !void {
2792
+ @field(boosts, s) = @intCast(@min(6, @as(i8, @field(boosts, s)) + n));
2793
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(boosts, s)) + 6))];
2794
+ const stat = @field(unmodifiedStats(battle, side), s);
2795
+ @field(stats, s) = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2796
+ if (comptime std.mem.eql(u8, s, "atk")) {
2797
+ if (Status.is(side.stored().status, .BRN)) {
2798
+ @field(stats, s) = @max(@field(stats, s) / 2, 1);
2799
+ }
2800
+ } else if (comptime std.mem.eql(u8, s, "spe")) {
2801
+ if (Status.is(side.stored().status, .PAR)) {
2802
+ @field(stats, s) = @max(@field(stats, s) / 4, 1);
2803
+ }
2804
+ }
2805
+ }
2806
+
2807
+ fn unboostStat(
2808
+ battle: anytype,
2809
+ side: *Side,
2810
+ stats: *Stats(u16),
2811
+ boosts: *Boosts,
2812
+ comptime s: []const u8,
2813
+ n: u2,
2814
+ ) !void {
2815
+ @field(boosts, s) = @intCast(@max(-6, @as(i8, @field(boosts, s)) - n));
2816
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(boosts, s)) + 6))];
2817
+ const stat = @field(unmodifiedStats(battle, side), s);
2818
+ @field(stats, s) = @max(1, stat * mod[0] / mod[1]);
2819
+ if (comptime std.mem.eql(u8, s, "atk")) {
2820
+ if (Status.is(side.stored().status, .BRN)) {
2821
+ @field(stats, s) = @max(@field(stats, s) / 2, 1);
2822
+ }
2823
+ } else if (comptime std.mem.eql(u8, s, "spe")) {
2824
+ if (Status.is(side.stored().status, .PAR)) {
2825
+ @field(stats, s) = @max(@field(stats, s) / 4, 1);
2826
+ }
2827
+ }
2828
+ }
2829
+
2830
+ fn isForced(active: anytype) bool {
2831
+ return active.volatiles.Recharging or active.volatiles.Rage or
2832
+ active.volatiles.Thrashing or active.volatiles.Charging or
2833
+ active.volatiles.Rollout;
2834
+ }
2835
+
2836
+ fn convertible(active: ActivePokemon, m: Move) bool {
2837
+ if (m == .None) return false;
2838
+ const t = Move.get(m).type;
2839
+ return t != .@"???" and !active.types.includes(t);
2840
+ }
2841
+
2842
+ // NOTE: llvm/llvm-project#58557
2843
+ fn smul(a: anytype, b: @TypeOf(a)) @TypeOf(a) {
2844
+ if (!comptime builtin.target.isWasm()) return a *| b;
2845
+ return @max(a *% b, std.math.maxInt(@TypeOf(a)));
2846
+ }
2847
+
2848
+ pub const Rolls = struct {
2849
+ fn speedTie(battle: anytype, options: anytype) !bool {
2850
+ const p1 = if (options.calc.overridden(.P1, 0, .speed_tie)) |player|
2851
+ player == .P1
2852
+ else if (showdown)
2853
+ battle.rng.range(u8, 0, 2) == 0
2854
+ else
2855
+ battle.rng.next() < Gen12.percent(50) + 1;
2856
+
2857
+ try options.chance.speedTie(p1);
2858
+ return p1;
2859
+ }
2860
+
2861
+ fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
2862
+ const qkc = if (options.calc.overridden(player, 0, .quick_claw)) |val|
2863
+ val == .true
2864
+ else if (showdown)
2865
+ battle.rng.chance(u8, 60, 256)
2866
+ else
2867
+ battle.rng.next() < 60;
2868
+
2869
+ try options.chance.quickClaw(player, qkc);
2870
+ return qkc;
2871
+ }
2872
+
2873
+ fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
2874
+ const ok = if (options.calc.overridden(player, 0, .hit)) |val|
2875
+ val == .true
2876
+ else if (showdown)
2877
+ battle.rng.chance(u8, accuracy, 256)
2878
+ else
2879
+ battle.rng.next() < accuracy;
2880
+
2881
+ try options.chance.hit(player, ok, accuracy);
2882
+ return ok;
2883
+ }
2884
+
2885
+ fn criticalHit(battle: anytype, player: Player, i: u3, rate: u8, options: anytype) !bool {
2886
+ _ = .{ player, options };
2887
+ const crit = if (options.calc.overridden(player, i, .critical_hits)) |val|
2888
+ val == .true
2889
+ else if (showdown)
2890
+ battle.rng.chance(u8, rate, 256)
2891
+ else
2892
+ battle.rng.next() < rate;
2893
+
2894
+ try options.chance.criticalHit(player, i, crit, rate);
2895
+ return crit;
2896
+ }
2897
+
2898
+ fn damage(battle: anytype, player: Player, i: u3, options: anytype) !u8 {
2899
+ _ = .{ player, options };
2900
+ const roll = if (options.calc.overridden(player, i, .damages)) |val|
2901
+ val
2902
+ else roll: {
2903
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
2904
+ while (true) {
2905
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
2906
+ if (r >= 217) break :roll r;
2907
+ }
2908
+ };
2909
+
2910
+ assert(roll >= 217 and roll <= 255);
2911
+ try options.chance.damage(player, i, roll);
2912
+ return roll;
2913
+ }
2914
+
2915
+ fn confused(battle: anytype, player: Player, options: anytype) !bool {
2916
+ const cfz = if (options.calc.overridden(player, 0, .confused)) |val|
2917
+ val == .true
2918
+ else if (showdown)
2919
+ !battle.rng.chance(u8, 128, 256)
2920
+ else
2921
+ battle.rng.next() >= Gen12.percent(50) + 1;
2922
+
2923
+ try options.chance.confused(player, cfz);
2924
+ return cfz;
2925
+ }
2926
+
2927
+ fn attract(battle: anytype, player: Player, options: anytype) !bool {
2928
+ const cant = if (options.calc.overridden(player, 0, .attract)) |val|
2929
+ val == .true
2930
+ else if (showdown)
2931
+ battle.rng.chance(u8, 1, 2)
2932
+ else
2933
+ battle.rng.next() > Gen12.percent(50) + 1;
2934
+
2935
+ try options.chance.attract(player, cant);
2936
+ return cant;
2937
+ }
2938
+
2939
+ fn paralyzed(battle: anytype, player: Player, options: anytype) !bool {
2940
+ const par = if (options.calc.overridden(player, 0, .paralyzed)) |val|
2941
+ val == .true
2942
+ else if (showdown)
2943
+ battle.rng.chance(u8, 63, 256)
2944
+ else
2945
+ battle.rng.next() < Gen12.percent(25);
2946
+
2947
+ try options.chance.paralyzed(player, par);
2948
+ return par;
2949
+ }
2950
+
2951
+ fn defrost(battle: anytype, player: Player, options: anytype) !bool {
2952
+ const thaw = if (options.calc.overridden(player, 0, .defrost)) |val|
2953
+ val == .true
2954
+ else if (showdown)
2955
+ battle.rng.chance(u8, 25, 256)
2956
+ else
2957
+ battle.rng.next() < Gen12.percent(10);
2958
+
2959
+ try options.chance.defrost(player, thaw);
2960
+ return thaw;
2961
+ }
2962
+
2963
+ fn secondaryChance(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
2964
+ // GLITCH: 100% secondary chance will still fail 1/256 of the time
2965
+ const proc = if (options.calc.overridden(player, 0, .secondary_chance)) |val|
2966
+ val == .true
2967
+ else if (showdown)
2968
+ battle.rng.chance(u8, rate, 256)
2969
+ else
2970
+ battle.rng.next() < rate;
2971
+
2972
+ try options.chance.secondaryChance(player, proc, rate);
2973
+ return proc;
2974
+ }
2975
+
2976
+ fn item(battle: anytype, player: Player, options: anytype) !bool {
2977
+ const proc = if (options.calc.overridden(player, 0, .item)) |val|
2978
+ val == .true
2979
+ else if (showdown)
2980
+ battle.rng.chance(u8, 30, 256)
2981
+ else
2982
+ battle.rng.next() < 30;
2983
+
2984
+ try options.chance.item(player, proc);
2985
+ return proc;
2986
+ }
2987
+
2988
+ fn triAttack(battle: anytype, player: Player, options: anytype) !TriAttack {
2989
+ const status: TriAttack = if (options.calc.overridden(player, 0, .tri_attack)) |val|
2990
+ @enumFromInt(@intFromEnum(val) - 1)
2991
+ else if (showdown)
2992
+ @enumFromInt(battle.rng.range(u2, 0, 2))
2993
+ else loop: {
2994
+ while (true) {
2995
+ const r = std.math.rotr(u8, battle.rng.next(), 4) & 3;
2996
+ if (r != 0) break :loop @enumFromInt(r - 1);
2997
+ }
2998
+ };
2999
+
3000
+ try options.chance.triAttack(player, status);
3001
+ return status;
3002
+ }
3003
+
3004
+ fn present(battle: anytype, player: Player, options: anytype) !u8 {
3005
+ const power = if (options.calc.overridden(player, 0, .present)) |val|
3006
+ (val - 1) * 40
3007
+ else if (showdown) power: {
3008
+ const r = battle.rng.range(u8, 0, 10);
3009
+ if (r < 2) break :power 0;
3010
+ if (r < 6) break :power 40;
3011
+ if (r < 9) break :power 80;
3012
+ break :power 120;
3013
+ } else power: {
3014
+ const r = battle.rng.next();
3015
+ if (r <= Gen12.percent(40)) break :power 40;
3016
+ if (r <= Gen12.percent(70) + 1) break :power 80;
3017
+ if (r <= Gen12.percent(80)) break :power 120;
3018
+ break :power 0;
3019
+ };
3020
+
3021
+ assert(power <= 120);
3022
+ try options.chance.present(player, power);
3023
+ return power;
3024
+ }
3025
+
3026
+ fn magnitude(battle: anytype, player: Player, options: anytype) !u8 {
3027
+ const num: u8 = if (options.calc.overridden(player, 0, .magnitude)) |val|
3028
+ val + 3
3029
+ else if (showdown) num: {
3030
+ const r = battle.rng.range(u8, 0, 100);
3031
+ if (r < 5) break :num 4;
3032
+ if (r < 15) break :num 5;
3033
+ if (r < 35) break :num 6;
3034
+ if (r < 65) break :num 7;
3035
+ if (r < 85) break :num 8;
3036
+ if (r < 95) break :num 9;
3037
+ break :num 10;
3038
+ } else num: {
3039
+ const r = battle.rng.next();
3040
+ if (r <= Gen12.percent(5) + 1) break :num 4;
3041
+ if (r <= Gen12.percent(15)) break :num 5;
3042
+ if (r <= Gen12.percent(35)) break :num 6;
3043
+ if (r <= Gen12.percent(65) + 1) break :num 7;
3044
+ if (r <= Gen12.percent(85) + 1) break :num 8;
3045
+ if (r <= Gen12.percent(95)) break :num 9;
3046
+ break :num 10;
3047
+ };
3048
+
3049
+ assert(num >= 4 and num <= 10);
3050
+ try options.chance.magnitude(player, num);
3051
+ return num;
3052
+ }
3053
+
3054
+ fn tripleKick(battle: anytype, player: Player, options: anytype) !u2 {
3055
+ const hits = if (options.calc.overridden(player, 0, .triple_kick)) |val|
3056
+ val
3057
+ else if (showdown)
3058
+ battle.rng.range(u2, 1, 4)
3059
+ else power: {
3060
+ while (true) {
3061
+ const r = battle.rng.next() & 3;
3062
+ if (r != 0) break :power r - 1;
3063
+ }
3064
+ };
3065
+
3066
+ assert(hits >= 1 and hits <= 3);
3067
+ try options.chance.tripleKick(player, hits);
3068
+ return hits;
3069
+ }
3070
+
3071
+ fn spite(battle: anytype, player: Player, options: anytype) !u3 {
3072
+ assert(!showdown);
3073
+ const pp: u3 = if (options.calc.overridden(player, 0, .spite)) |val|
3074
+ val + 1
3075
+ else
3076
+ @intCast((battle.rng.next() & 3) + 2);
3077
+
3078
+ assert(pp >= 2 and pp <= 5);
3079
+ try options.chance.spite(player, pp);
3080
+ return pp;
3081
+ }
3082
+
3083
+ // Conversion 2 can at most choose between 7 types (vs. a Grass-type attack)
3084
+ var CONVERSION_2: [7]Type = [_]Type{.@"???"} ** 7;
3085
+
3086
+ fn conversion2(battle: anytype, player: Player, mtype: Type, options: anytype) !Type {
3087
+ var i: u8 = 0;
3088
+ const neutral = @intFromEnum(Effectiveness.Neutral);
3089
+ assert(mtype != .@"???");
3090
+ const ty: Type = if (options.calc.overridden(player, 0, .conversion_2)) |val|
3091
+ @enumFromInt(@intFromEnum(val) - 1)
3092
+ else if (showdown) ty: {
3093
+ for (Type.SHOWDOWN) |t| {
3094
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
3095
+ CONVERSION_2[i] = t;
3096
+ i += 1;
3097
+ }
3098
+ }
3099
+ assert(i > 0 and i <= 7);
3100
+ break :ty CONVERSION_2[battle.rng.range(u8, 0, i)];
3101
+ } else ty: {
3102
+ while (true) {
3103
+ const r = battle.rng.next() & 0b11111;
3104
+ if (r == 6) continue; // BIRD
3105
+ if (r > 9 and r < 20) continue; // UNUSED_TYPES
3106
+ if (r > 27) continue; // TYPES_END
3107
+
3108
+ const t = Type.conversion2(r);
3109
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
3110
+ break :ty t;
3111
+ }
3112
+ }
3113
+ };
3114
+
3115
+ assert(ty != .@"???");
3116
+ try options.chance.conversion2(player, ty, mtype, i);
3117
+ return ty;
3118
+ }
3119
+
3120
+ fn protect(battle: anytype, player: Player, count: u8, options: anytype) !bool {
3121
+ assert(count <= 8);
3122
+ const num = if (count == 8) 0 else @as(u8, 255) >> @intCast(count);
3123
+
3124
+ const ok = if (options.calc.overridden(player, 0, .protect)) |val|
3125
+ val == .true
3126
+ else if (showdown)
3127
+ battle.rng.chance(u8, num, 255)
3128
+ else protected: {
3129
+ while (true) {
3130
+ const r = battle.rng.next();
3131
+ if (r != 0) break :protected !(num <= r - 1);
3132
+ }
3133
+ };
3134
+
3135
+ try options.chance.protect(player, num, ok);
3136
+ return ok;
3137
+ }
3138
+
3139
+ fn conversion(battle: anytype, player: Player, n: u4, options: anytype) !Type {
3140
+ assert(n > 0);
3141
+
3142
+ const active = battle.side(player).active;
3143
+ const moves = active.moves;
3144
+
3145
+ // TODO: consider throwing error instead of rerolling?
3146
+ const overridden = if (options.calc.overridden(player, 0, .move_slot)) |val|
3147
+ if (convertible(active, moves[val - 1].id)) val else null
3148
+ else
3149
+ null;
3150
+
3151
+ const slot: u4 = overridden orelse slot: {
3152
+ if (showdown) {
3153
+ var r = battle.rng.range(u4, 0, n) + 1;
3154
+ var i: usize = 0;
3155
+ while (i < moves.len and r > 0) : (i += 1) {
3156
+ if (convertible(active, moves[i].id)) {
3157
+ r -= 1;
3158
+ if (r == 0) break :slot @intCast(i + 1);
3159
+ }
3160
+ }
3161
+ break :slot @intCast(i + 1);
3162
+ } else {
3163
+ while (true) {
3164
+ const r: u4 = @intCast(battle.rng.next() & 3);
3165
+ if (convertible(active, moves[r].id)) break :slot @intCast(r + 1);
3166
+ }
3167
+ }
3168
+ };
3169
+
3170
+ assert(n >= 1 and n <= 4);
3171
+ assert(slot >= 1 and slot <= 4);
3172
+ try options.chance.moveSlot(player, slot, n);
3173
+ return Move.get(active.move(slot).id).type;
3174
+ }
3175
+
3176
+ fn sleepTalk(battle: anytype, player: Player, n: u4, mslot: u4, options: anytype) !u4 {
3177
+ assert(n > 0);
3178
+
3179
+ const active = battle.side(player).active;
3180
+ const moves = active.moves;
3181
+
3182
+ // TODO: consider throwing error instead of rerolling?
3183
+ const overridden = if (options.calc.overridden(player, 0, .move_slot)) |val|
3184
+ if (val != mslot and Move.get(moves[val - 1].id).extra.sleep_talk) val else null
3185
+ else
3186
+ null;
3187
+
3188
+ const slot: u4 = overridden orelse slot: {
3189
+ if (showdown) {
3190
+ var r = battle.rng.range(u4, 0, n) + 1;
3191
+ var i: usize = 0;
3192
+ while (i < moves.len and r > 0) : (i += 1) {
3193
+ if (i + 1 != mslot and Move.get(moves[i].id).extra.sleep_talk) {
3194
+ r -= 1;
3195
+ if (r == 0) break :slot @intCast(i + 1);
3196
+ }
3197
+ }
3198
+ break :slot @intCast(i + 1);
3199
+ } else {
3200
+ while (true) {
3201
+ const r: u4 = @intCast(battle.rng.next() & 3);
3202
+ if (r + 1 == mslot or !Move.get(moves[r].id).extra.sleep_talk) continue;
3203
+ break :slot @intCast(r + 1);
3204
+ }
3205
+ }
3206
+ };
3207
+
3208
+ assert(n >= 1 and n <= 4);
3209
+ assert(slot >= 1 and slot <= 4);
3210
+ try options.chance.moveSlot(player, slot, n);
3211
+ return slot;
3212
+ }
3213
+
3214
+ fn forceSwitch(
3215
+ battle: anytype,
3216
+ player: Player,
3217
+ slots: []u4,
3218
+ n: u4,
3219
+ options: anytype,
3220
+ ) !u4 {
3221
+ const foe = battle.foe(player);
3222
+
3223
+ assert(slots.len < 5);
3224
+ assert(n > 0 and n <= 6);
3225
+
3226
+ // TODO: consider throwing error instead of rerolling?
3227
+ const overridden = if (options.calc.overridden(player, 0, .force_switch)) |val| val: {
3228
+ for (slots) |slot| if (slot == val) break :val if (foe.get(slot).hp > 0) val else null;
3229
+ break :val null;
3230
+ } else null;
3231
+
3232
+ const slot: u4 = overridden orelse slot: {
3233
+ if (showdown) {
3234
+ break :slot slots[battle.rng.range(u4, 0, @as(u4, @intCast(slots.len)))];
3235
+ } else {
3236
+ while (true) {
3237
+ const r = battle.rng.next() & 7;
3238
+ if (r > n or r == 1) continue;
3239
+ if (foe.get(r).hp > 0) break :slot @intCast(r);
3240
+ }
3241
+ }
3242
+ };
3243
+
3244
+ assert(n >= 1 and n <= 6);
3245
+ assert(slot >= 1 and slot <= 6);
3246
+ try options.chance.forceSwitch(player, slot, n);
3247
+ return slot;
3248
+ }
3249
+
3250
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
3251
+
3252
+ fn multiHit(battle: anytype, player: Player, options: anytype) !u3 {
3253
+ const n: u3 = if (options.calc.overridden(player, 0, .multi_hit)) |val|
3254
+ @intCast(val)
3255
+ else if (showdown)
3256
+ DISTRIBUTION[battle.rng.range(u3, 0, DISTRIBUTION.len)]
3257
+ else n: {
3258
+ const r = (battle.rng.next() & 3);
3259
+ break :n @intCast((if (r < 2) r else battle.rng.next() & 3) + 2);
3260
+ };
3261
+
3262
+ assert(n >= 2 and n <= 5);
3263
+ try options.chance.multiHit(player, n);
3264
+ return n;
3265
+ }
3266
+
3267
+ fn psywave(battle: anytype, player: Player, max: u8, options: anytype) !u8 {
3268
+ const power = if (options.calc.overridden(player, 0, .psywave)) |val|
3269
+ val
3270
+ else if (showdown)
3271
+ battle.rng.range(u8, 1, max)
3272
+ else power: {
3273
+ while (true) {
3274
+ const r = battle.rng.next();
3275
+ if (r != 0 and r < max) break :power r;
3276
+ }
3277
+ };
3278
+
3279
+ assert(power != 0 and power < max);
3280
+ try options.chance.psywave(player, power, max);
3281
+ return power;
3282
+ }
3283
+
3284
+ fn metronome(battle: anytype, player: Player, options: anytype) !Move {
3285
+ const moves = battle.side(player).active.moves;
3286
+
3287
+ var n: u2 = 0;
3288
+ for (moves) |m| {
3289
+ if (m.id == .None) break;
3290
+ if (Move.get(m.id).extra.metronome) n += 1;
3291
+ }
3292
+
3293
+ // TODO: consider throwing error instead of rerolling?
3294
+ const overridden = if (options.calc.overridden(player, 0, .metronome)) |val| val: {
3295
+ for (moves) |m| if (m.id == val) break :val null;
3296
+ break :val val;
3297
+ } else null;
3298
+
3299
+ const move: Move = overridden orelse move: {
3300
+ if (showdown) {
3301
+ var r = battle.rng.range(u8, 0, @as(u8, @intCast(Move.METRONOME.len - n)));
3302
+ for (moves) |m| {
3303
+ if (m.id == .None) break;
3304
+ if (@intFromEnum(m.id) > @intFromEnum(Move.METRONOME[r])) break;
3305
+ if (Move.get(m.id).extra.metronome) r -= 1;
3306
+ }
3307
+ break :move Move.METRONOME[r];
3308
+ } else {
3309
+ outer: while (true) {
3310
+ const r = battle.rng.next();
3311
+ if (r == 0 or r >= Move.size) continue;
3312
+ const selected: Move = @enumFromInt(r);
3313
+ if (!Move.get(selected).extra.metronome) continue;
3314
+ for (moves) |m| if (m.id == selected) continue :outer;
3315
+ break :move selected;
3316
+ }
3317
+ }
3318
+ };
3319
+
3320
+ assert(Move.get(move).extra.metronome);
3321
+ try options.chance.metronome(player, move, n);
3322
+ return move;
3323
+ }
3324
+
3325
+ fn sleepDuration(battle: anytype, player: Player, options: anytype) u3 {
3326
+ const duration: u3 = if (options.calc.overridden(player, 0, .duration)) |val|
3327
+ @intCast(val)
3328
+ else if (showdown)
3329
+ battle.rng.range(u3, 1, 7)
3330
+ else duration: {
3331
+ while (true) {
3332
+ const r = battle.rng.next() & 7;
3333
+ if (r != 0 and r != 7) break :duration @intCast(r);
3334
+ }
3335
+ };
3336
+
3337
+ assert(duration >= 1 and duration <= 6);
3338
+ options.chance.duration(player, duration);
3339
+ return duration + 1;
3340
+ }
3341
+
3342
+ fn confusionDuration(battle: anytype, player: Player, self: bool, options: anytype) u3 {
3343
+ const duration: u3 = if (options.calc.overridden(player, 0, .duration)) |val|
3344
+ @intCast(val)
3345
+ else if (showdown)
3346
+ // Pokémon Showdown incorrectly uses the same duration for self-confusion
3347
+ battle.rng.range(u3, 2, 6)
3348
+ else
3349
+ @intCast((battle.rng.next() & if (self) 1 else 3) + 2);
3350
+
3351
+ assert(duration >= 2 and duration <= if (!showdown and self) 3 else 5);
3352
+ options.chance.duration(player, duration);
3353
+ return duration;
3354
+ }
3355
+
3356
+ fn disableDuration(battle: anytype, player: Player, options: anytype) u4 {
3357
+ const duration: u3 = if (options.calc.overridden(player, 0, .duration)) |val|
3358
+ @intCast(val)
3359
+ else if (showdown)
3360
+ // Pokémon Showdown incorrectly inherits Generation III's Disable duration
3361
+ battle.rng.range(u3, 2, 6)
3362
+ else duration: {
3363
+ while (true) {
3364
+ const r = battle.rng.next() & 7;
3365
+ if (r != 0) break :duration @intCast(r + 1);
3366
+ }
3367
+ };
3368
+
3369
+ assert(duration >= 2 and duration <= (if (showdown) 5 else 7));
3370
+ options.chance.duration(player, duration);
3371
+ return duration;
3372
+ }
3373
+
3374
+ fn attackingDuration(battle: anytype, player: Player, options: anytype) u3 {
3375
+ const duration: u3 = if (options.calc.overridden(player, 0, .duration)) |val|
3376
+ @intCast(val)
3377
+ else if (showdown)
3378
+ battle.rng.range(u3, 2, 4)
3379
+ else
3380
+ @intCast((battle.rng.next() & 1) + 2); // BUG: thrash is + 1 not +2
3381
+
3382
+ assert(duration >= 2 and duration <= 3);
3383
+ options.chance.duration(player, duration);
3384
+ return duration;
3385
+ }
3386
+
3387
+ fn bindingDuration(battle: anytype, player: Player, options: anytype) u3 {
3388
+ const duration: u3 = (if (options.calc.overridden(player, 0, .duration)) |val|
3389
+ @intCast(val)
3390
+ else if (showdown)
3391
+ // TODO: PS does range(3, 6) here which after subtracting 1 is actually 2-4 not 2-5!
3392
+ battle.rng.range(u3, 2, 5)
3393
+ else
3394
+ @intCast(battle.rng.next() & 3 + 2));
3395
+
3396
+ assert(duration >= 2 and duration <= 5);
3397
+ options.chance.duration(player, duration);
3398
+ return duration + 1;
3399
+ }
3400
+
3401
+ // TODO: consider sharing implementation with bindingDuration
3402
+ fn encoreDuration(battle: anytype, player: Player, options: anytype) u3 {
3403
+ const duration: u3 = (if (options.calc.overridden(player, 0, .duration)) |val|
3404
+ @intCast(val)
3405
+ else if (showdown)
3406
+ battle.rng.range(u3, 2, 6)
3407
+ else
3408
+ @intCast(battle.rng.next() & 3 + 2));
3409
+
3410
+ assert(duration >= 2 and duration <= 5);
3411
+ options.chance.duration(player, duration);
3412
+ return duration + 1;
3413
+ }
3414
+ };
3415
+
3416
+ test "RNG agreement" {
3417
+ if (!showdown) return;
3418
+ var expected: [256]u32 = undefined;
3419
+ for (0..expected.len) |i| {
3420
+ expected[i] = @intCast(i * 0x1000000);
3421
+ }
3422
+
3423
+ var spe: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3424
+ var qkc: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3425
+ var cfz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3426
+ var atr: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3427
+ var frz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3428
+ var fcb: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3429
+
3430
+ for (0..expected.len) |i| {
3431
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
3432
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
3433
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
3434
+ try expectEqual(atr.chance(u8, 1, 2), i < Gen12.percent(50) + 1);
3435
+ try expectEqual(frz.chance(u8, 25, 256), i < Gen12.percent(10));
3436
+ try expectEqual(fcb.chance(u8, 30, 256), !(30 <= i));
3437
+ }
3438
+ }
3439
+
3440
+ test "Roll probabilities" {
3441
+ if (showdown) return;
3442
+
3443
+ var present = [4]u8{ 0, 0, 0, 0 };
3444
+ var magnitude = [7]u8{ 0, 0, 0, 0, 0, 0, 0 };
3445
+ for (0..256) |i| {
3446
+ present[
3447
+ if (i <= Gen12.percent(40))
3448
+ 1
3449
+ else if (i <= Gen12.percent(70) + 1)
3450
+ 2
3451
+ else if (i <= Gen12.percent(80))
3452
+ 3
3453
+ else
3454
+ 0
3455
+ ] += 1;
3456
+ magnitude[
3457
+ if (i <= Gen12.percent(5) + 1)
3458
+ 0
3459
+ else if (i <= Gen12.percent(15) + 1)
3460
+ 1
3461
+ else if (i <= Gen12.percent(35))
3462
+ 2
3463
+ else if (i <= Gen12.percent(65) + 1)
3464
+ 3
3465
+ else if (i <= Gen12.percent(85) + 1)
3466
+ 4
3467
+ else if (i <= Gen12.percent(95))
3468
+ 5
3469
+ else
3470
+ 6
3471
+ ] += 1;
3472
+ }
3473
+
3474
+ try expectEqualSlices(u8, &.{ 51, 103, 77, 25 }, &present);
3475
+ try expectEqualSlices(u8, &.{ 14, 26, 50, 77, 51, 25, 13 }, &magnitude);
3476
+ }
3477
+
3478
+ test "Reasons" {
3479
+ const moves = [_]Move{ .Bind, .Wrap, .FireSpin, .Clamp, .Whirlpool };
3480
+ for (moves) |move| {
3481
+ const reason = Move.get(move).extra.protocol - 1;
3482
+
3483
+ const activate: Activate = @enumFromInt(@intFromEnum(Activate.Bind) + reason);
3484
+ try expectEqualStrings(@tagName(move), @tagName(activate));
3485
+
3486
+ const damage: Damage = @enumFromInt(@intFromEnum(Damage.Bind) + reason);
3487
+ try expectEqualStrings(@tagName(move), @tagName(damage));
3488
+
3489
+ const end: End = @enumFromInt(@intFromEnum(End.Bind) + reason);
3490
+ try expectEqualStrings(@tagName(move), @tagName(end));
3491
+ }
3492
+
3493
+ const perish_song = [_]Start{ .PerishSong0, .PerishSong1, .PerishSong2, .PerishSong3 };
3494
+ for (perish_song, 0..) |ps, i| {
3495
+ const reason: Start = @enumFromInt(@intFromEnum(Start.PerishSong0) + i);
3496
+ try expectEqualStrings(@tagName(ps), @tagName(reason));
410
3497
  }
411
3498
  }
412
3499
 
@@ -434,7 +3521,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
434
3521
  .Move => {
435
3522
  const side = battle.side(player);
436
3523
 
437
- var active = &side.active;
3524
+ const active = &side.active;
438
3525
  const stored = side.stored();
439
3526
 
440
3527
  // While players are not given any input options on the cartridge in these cases,
@@ -454,7 +3541,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
454
3541
  }
455
3542
 
456
3543
  var slot: u4 = 2;
457
- while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
3544
+ while (!active.volatiles.Trapped and slot <= 6) : (slot += 1) {
458
3545
  const id = side.order[slot - 1];
459
3546
  if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
460
3547
  out[n] = .{ .type = .Switch, .data = slot };
@@ -488,7 +3575,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
488
3575
  if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
489
3576
  // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
490
3577
  const struggle =
491
- m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
3578
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disable.move == slot);
492
3579
  const s = if (struggle) 0 else slot;
493
3580
  out[n] = .{ .type = .Move, .data = s };
494
3581
  n += 1;
@@ -503,7 +3590,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
503
3590
  const m = active.moves[slot - 1];
504
3591
  if (m.id == .None) break;
505
3592
  if (m.pp == 0) continue;
506
- if (active.volatiles.disabled_move == slot) continue;
3593
+ if (active.volatiles.disable.move == slot) continue;
507
3594
  out[n] = .{ .type = .Move, .data = slot };
508
3595
  n += 1;
509
3596
  }