@pkmn/engine 0.1.0-dev.dd5b9081 → 0.1.0-dev.e0e37c1b

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