@pkmn/engine 0.1.0-dev.305a932f → 0.1.0-dev.32adfe77

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