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

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