@pkmn/engine 0.1.0-dev.736f7a8b → 0.1.0-dev.77410aff

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +36 -14
  2. package/build/pkg/addon.js.map +1 -1
  3. package/build/pkg/data/ids.json +12 -12
  4. package/build/pkg/data/layout.json +2 -2
  5. package/build/pkg/data/protocol.json +69 -12
  6. package/build/pkg/data.d.ts +3 -2
  7. package/build/pkg/data.js.map +1 -1
  8. package/build/pkg/gen1.js +2 -2
  9. package/build/pkg/gen1.js.map +1 -1
  10. package/build/pkg/index.d.ts +2 -1
  11. package/build/pkg/index.js.map +1 -1
  12. package/build/pkg/protocol.js +57 -38
  13. package/build/pkg/protocol.js.map +1 -1
  14. package/build/test/display.js.map +1 -1
  15. package/build/tools/debug.js +3 -1
  16. package/build/tools/debug.js.map +1 -1
  17. package/build.zig +40 -23
  18. package/package.json +30 -17
  19. package/src/bin/install-pkmn-engine +1 -1
  20. package/src/lib/binding/node.zig +7 -11
  21. package/src/lib/common/data.zig +8 -20
  22. package/src/lib/common/optional.zig +8 -1
  23. package/src/lib/common/protocol.zig +725 -299
  24. package/src/lib/common/rational.zig +12 -8
  25. package/src/lib/common/rng.zig +15 -6
  26. package/src/lib/gen1/README.md +31 -29
  27. package/src/lib/gen1/calc.zig +9 -9
  28. package/src/lib/gen1/chance.zig +55 -39
  29. package/src/lib/gen1/data/moves.zig +192 -180
  30. package/src/lib/gen1/data/species.zig +2 -2
  31. package/src/lib/gen1/data/types.zig +7 -7
  32. package/src/lib/gen1/data.zig +31 -43
  33. package/src/lib/gen1/helpers.zig +26 -41
  34. package/src/lib/gen1/mechanics.zig +314 -365
  35. package/src/lib/gen2/README.md +18 -72
  36. package/src/lib/gen2/calc.zig +143 -0
  37. package/src/lib/gen2/chance.zig +1314 -0
  38. package/src/lib/gen2/data/items.zig +12 -18
  39. package/src/lib/gen2/data/moves.zig +649 -568
  40. package/src/lib/gen2/data/species.zig +1 -1
  41. package/src/lib/gen2/data/types.zig +134 -31
  42. package/src/lib/gen2/data.zig +80 -68
  43. package/src/lib/gen2/generated.zig +806 -0
  44. package/src/lib/gen2/helpers.zig +4 -9
  45. package/src/lib/gen2/mechanics.zig +3238 -85
@@ -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,81 @@ 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;
55
+
56
+ // zig fmt: off
57
+ const STAT_BOOSTS = &[_][2]u8{
58
+ .{ 25, 100 }, // -6
59
+ .{ 28, 100 }, // -5
60
+ .{ 33, 100 }, // -4
61
+ .{ 40, 100 }, // -3
62
+ .{ 50, 100 }, // -2
63
+ .{ 66, 100 }, // -1
64
+ .{ 1, 1 }, // 0
65
+ .{ 15, 10 }, // +1
66
+ .{ 2, 1 }, // +2
67
+ .{ 25, 10 }, // +3
68
+ .{ 3, 1 }, // +4
69
+ .{ 35, 10 }, // +5
70
+ .{ 4, 1 }, // +6
71
+ };
72
+
73
+ const ACCURACY_BOOSTS = &[_][2]u8{
74
+ .{ 33, 100 }, // -6
75
+ .{ 36, 100 }, // -5
76
+ .{ 43, 100 }, // -4
77
+ .{ 50, 100 }, // -3
78
+ .{ 60, 100 }, // -2
79
+ .{ 75, 100 }, // -1
80
+ .{ 1, 1 }, // 0
81
+ .{ 133, 100 }, // +1
82
+ .{ 166, 100 }, // +2
83
+ .{ 2, 1 }, // +3
84
+ .{ 233, 100 }, // +4
85
+ .{ 133, 50 }, // +5
86
+ .{ 3, 1 }, // +6
87
+ };
88
+
89
+ const CRITICAL_HITS = &[_]u8{
90
+ 256 / 15, // 0
91
+ 256 / 8, // +1
92
+ 256 / 4, // +2
93
+ 256 / 3, // +3
94
+ 256 / 2, // +4
95
+ };
96
+ // zig fmt: on
97
+
98
+ const MAX_STAT_VALUE = 999;
99
+
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
+ };
37
125
 
38
126
  pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
39
127
  assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
@@ -52,16 +140,16 @@ fn start(battle: anytype, options: anytype) !Result {
52
140
  const p1 = battle.side(.P1);
53
141
  const p2 = battle.side(.P2);
54
142
 
55
- var p1_slot = findFirstAlive(p1);
143
+ const p1_slot = findFirstAlive(p1);
56
144
  assert(!showdown or p1_slot == 1);
57
145
  if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
58
146
 
59
- var p2_slot = findFirstAlive(p2);
147
+ const p2_slot = findFirstAlive(p2);
60
148
  assert(!showdown or p2_slot == 1);
61
149
  if (p2_slot == 0) return Result.Win;
62
150
 
63
- try switchIn(battle, .P1, p1_slot, true, options);
64
- 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);
65
153
 
66
154
  return endTurn(battle, options);
67
155
  }
@@ -71,17 +159,73 @@ fn findFirstAlive(side: *const Side) u8 {
71
159
  return 0;
72
160
  }
73
161
 
74
- fn selectMove(battle: anytype) ?Result {
75
- _ = battle;
76
- return null;
77
- }
162
+ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
163
+ if (choice.type == .Pass) return; // FIXME BATON PASS
78
164
 
79
- fn saveMove(battle: anytype) void {
80
- _ = battle;
81
- return null;
165
+ var side = battle.side(player);
166
+ var volatiles = &side.active.volatiles;
167
+
168
+ // pre-battle menu
169
+ const forced = forced: {
170
+ if (volatiles.Recharging) break :forced true;
171
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
172
+ if (!showdown) {
173
+ volatiles.Flinch = false;
174
+ battle.foe(player).active.volatiles.Flinch = false;
175
+ }
176
+ break :forced (volatiles.Thrashing or volatiles.Charging or volatiles.Rollout);
177
+ };
178
+
179
+ // battle menu
180
+ if (choice.type == .Switch) return;
181
+ assert(choice.type == .Move and (!forced or choice.data == @intFromBool(showdown)));
182
+
183
+ done: {
184
+ if (forced) break :done;
185
+ // pre-move select
186
+ if (volatiles.Encore) {
187
+ // TODO wCurPlayerMove = side.lastMove(true);
188
+ // assert(wCurPlayerMove != .None);
189
+ volatiles.Bide = false; // FIXME wPlayerCharging vs. SUBSTATUS_BIDE?
190
+ const effect = Move.get(.Pound).effect; // TODO
191
+ if (effect != .FuryCutter) volatiles.fury_cutter = false;
192
+ if (effect != .Rage) {
193
+ volatiles.Rage = false;
194
+ volatiles.rage = 0;
195
+ }
196
+ if (effect != .Protect and effect != .Endure) volatiles.protect = 0;
197
+ return;
198
+ }
199
+ if (volatiles.Bide) break :done;
200
+ // move select
201
+ if (choice.data == 0) {
202
+ const struggle = ok: {
203
+ for (side.active.moves, 0..) |move, i| {
204
+ if (move.pp > 0 and volatiles.disable.move != i + 1) break :ok false;
205
+ }
206
+ break :ok true;
207
+ };
208
+ assert(struggle);
209
+ // TODO wCurPlayerMove = .Struggle;
210
+ } else {
211
+ assert(showdown or side.active.volatiles.disable.move != choice.data);
212
+ const move = side.active.move(choice.data);
213
+ // You cannot *select* a move with 0 PP
214
+ assert(move.pp != 0);
215
+ // TODO wCurPlayerMove = move.id;
216
+ // battle.lastMove(player).index = @intCast(c.data);
217
+ }
218
+ }
219
+
220
+ volatiles.Rage = false;
221
+ volatiles.rage = 0;
222
+ volatiles.fury_cutter = 0;
223
+ volatiles.protect = 0;
82
224
  }
83
225
 
84
- 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 {
85
229
  var side = battle.side(player);
86
230
  var foe = battle.foe(player);
87
231
 
@@ -89,7 +233,7 @@ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: a
89
233
  const incoming = side.get(slot);
90
234
 
91
235
  assert(incoming.hp != 0);
92
- assert(slot != 1 or initial);
236
+ assert(slot != 1 or kind == .Initial);
93
237
 
94
238
  const out = side.pokemon[0].position;
95
239
  side.pokemon[0].position = side.pokemon[slot - 1].position;
@@ -98,21 +242,25 @@ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: a
98
242
  side.last_used_move = .None;
99
243
  foe.active.volatiles.dirty = true;
100
244
 
101
- active.stats = incoming.stats;
102
- active.species = incoming.species;
103
- active.types = incoming.types;
104
- active.boosts = .{};
105
245
  active.volatiles = .{};
246
+ active.stats = incoming.stats;
106
247
  active.moves = incoming.moves;
248
+ active.boosts = .{};
249
+ active.types = incoming.types;
250
+ active.species = incoming.species;
107
251
 
108
252
  statusModify(incoming.status, &active.stats);
109
253
 
110
- try options.log.switched(battle.active(player), incoming);
111
- // TODO: options.chance.switched(player, side.order[0], out);
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
+ }
259
+ options.chance.switched(player, side.pokemon[0].position, out);
112
260
 
113
261
  if (side.conditions.Spikes and !active.types.includes(.Flying)) {
114
262
  incoming.hp -|= @max(incoming.stats.hp / 8, 1);
115
- try options.log.damage(battle.active(player), incoming, .Spikes);
263
+ try options.log.damage(.{ battle.active(player), incoming, .Spikes });
116
264
  }
117
265
  }
118
266
 
@@ -123,9 +271,16 @@ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player
123
271
  if (c2.type == .Pass) return .P1;
124
272
 
125
273
  // Pokémon Showdown always rolls for Quick Claw every turn, even if no Pokémon hold Quick Claw
274
+ // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
126
275
  const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
127
276
 
128
- 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
+ }
129
284
 
130
285
  // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
131
286
  // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
@@ -135,15 +290,15 @@ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player
135
290
  const double_switch = c1.type == .Switch and c2.type == .Switch;
136
291
  if (!showdown and double_switch) return .P1;
137
292
 
138
- const m1 = battle.side(.P1).last_selected_move;
139
- const m2 = battle.side(.P2).last_selected_move;
293
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
294
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
140
295
  if (!showdown or !double_switch) {
141
296
  const pri1 = Move.get(m1).priority;
142
297
  const pri2 = Move.get(m2).priority;
143
298
  if (pri1 != pri2) return if (pri1 > pri2) .P1 else .P2;
144
299
 
145
- const qkc1 = battle.side(.P1).active.item == .QuickClaw;
146
- const qkc2 = battle.side(.P2).active.item == .QuickClaw;
300
+ const qkc1 = battle.side(.P1).stored().item == .QuickClaw;
301
+ const qkc2 = battle.side(.P2).stored().item == .QuickClaw;
147
302
  if (!showdown and qkc1 and qkc2) {
148
303
  // If both Pokémon have Quick Claw the cartridge checks them in order and exits early if
149
304
  // the first one procs, meaning the host has a slightly higher chance of going first
@@ -200,89 +355,3087 @@ fn doTurn(
200
355
  foe_choice: Choice,
201
356
  options: anytype,
202
357
  ) !?Result {
203
- if (try executeMove(battle, player, player_choice, options)) |r| return r;
204
- if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
205
- return null;
358
+ assert(player_choice.type != .Pass);
359
+
360
+ const volatiles = &battle.side(player).active.volatiles;
361
+ const foe_volatiles = &battle.foe(player).active.volatiles;
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
+
368
+ volatiles.DestinyBond = false;
369
+ if (try executeMove(battle, player, player_choice, true, options)) |r| return r;
370
+ foe_volatiles.Protect = false;
371
+ foe_volatiles.Endure = false;
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
+ }
377
+
378
+ // foe_volatiles.DestinyBond = false;
379
+ if (try executeMove(battle, foe_player, foe_choice, false, options)) |r| return r;
380
+ volatiles.Protect = false;
381
+ volatiles.Endure = false;
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
+ }
387
+
388
+ // FIXME
389
+ return betweenTurns(battle, 0, options);
206
390
  }
207
391
 
208
- 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 {
209
399
  if (choice.type == .Switch) {
210
- try switchIn(battle, player, choice.data, false, options);
400
+ try switchIn(battle, player, choice.data, .Switch, options);
211
401
  return null;
212
402
  }
213
403
 
214
- @panic("TODO");
404
+ assert(choice.type == .Move);
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;
215
424
  }
216
425
 
217
- fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
218
- battle.turn += 1;
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
+ }
219
441
 
220
- if (showdown and battle.turn >= 1000) {
221
- try options.log.tie();
222
- return Result.Tie;
223
- } else if (battle.turn >= 65535) {
224
- return Result.Error;
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
+ }
225
467
  }
226
468
 
227
- try options.log.turn(battle.turn);
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
+ }
228
474
 
229
- return Result.Default;
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
+ }
553
+
554
+ return true;
230
555
  }
231
556
 
232
- fn statusModify(status: u8, stats: *Stats(u16)) void {
233
- if (Status.is(status, .PAR)) {
234
- stats.spe = @max(stats.spe / 4, 1);
235
- } else if (Status.is(status, .BRN)) {
236
- stats.atk = @max(stats.atk / 2, 1);
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;
564
+
565
+ volatiles.fury_cutter = 0;
566
+ }
567
+
568
+ pub fn canMove(battle: anytype, player: Player, state: *State, options: anytype) !bool {
569
+ var side = battle.side(player);
570
+ const volatiles = &side.active.volatiles;
571
+
572
+ // FIXME: pass in target to avoid lookup?
573
+ const target = if (Move.get(state.move).target == .Self) player else player.foe();
574
+ try options.log.move(.{ battle.active(player), state.move, battle.active(target), state.from });
575
+
576
+ const charging = false; // TODO charging uses doUse
577
+ const skip_pp = charging or state.move == .Struggle or
578
+ (volatiles.BeatUp or volatiles.Thrashing or volatiles.Bide);
579
+ if (!skip_pp) _ = decrementPP(side, state.move, state.mslot); // TODO if no pp return
580
+
581
+ return true;
582
+ }
583
+
584
+ pub fn canCharge(battle: anytype, player: Player, state: *State, options: anytype) !bool {
585
+ _ = battle;
586
+ _ = player;
587
+ _ = state;
588
+ _ = options;
589
+ // TODO skipsuncharge account for SolarBeam
590
+ return true;
591
+ }
592
+
593
+ pub fn decrementPP(side: *Side, move: Move, mslot: u4) bool {
594
+ var active = &side.active;
595
+ const volatiles = &active.volatiles;
596
+
597
+ assert(move != .Struggle);
598
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
599
+
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);
608
+
609
+ if (move_slot.id == .Mimic and move != .Mimic) return true;
610
+
611
+ move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
612
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
613
+
614
+ return true;
615
+ }
616
+
617
+ pub fn doMove(
618
+ comptime secondary: bool,
619
+ battle: anytype,
620
+ player: Player,
621
+ state: *State,
622
+ options: anytype,
623
+ ) !bool {
624
+ try checkCriticalHit(battle, player, state, options);
625
+ try calcDamage(battle, player, state, options);
626
+ try adjustDamage(battle, player, state, options);
627
+ try randomizeDamage(battle, player, state, options);
628
+ try checkHit(battle, player, state, options);
629
+ if (secondary) try effectChance(battle, player, state, options);
630
+ try applyDamage(battle, player, state, options);
631
+ try reportOutcome(battle, player, state, options);
632
+ if (try destinyBond(battle, player, state, options)) return false;
633
+ try buildRage(battle, player, state, options);
634
+ try kingsRock(battle, player, state, options);
635
+ return true;
636
+ }
637
+
638
+ pub fn afterMove(
639
+ comptime kings: bool,
640
+ battle: anytype,
641
+ player: Player,
642
+ state: *State,
643
+ options: anytype,
644
+ ) !bool {
645
+ if (try destinyBond(battle, player, state, options)) return false;
646
+ try buildRage(battle, player, state, options);
647
+ if (kings) try kingsRock(battle, player, state, options);
648
+ return true;
649
+ }
650
+
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;
654
+
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;
237
665
  }
666
+ assert(stage <= 4);
667
+
668
+ state.crit = try Rolls.criticalHit(battle, player, CRITICAL_HITS[stage], options);
238
669
  }
239
670
 
240
- inline fn isForced(active: anytype) bool {
241
- return active.volatiles.Recharging or active.volatiles.Rage or
242
- active.volatiles.Thrashing or active.volatiles.Charging or
243
- active.volatiles.Underground or active.volatiles.Flying or
244
- active.volatiles.Rollout;
671
+ pub fn calcDamage(
672
+ battle: anytype,
673
+ player: Player,
674
+ state: *State,
675
+ options: anytype,
676
+ ) !void {
677
+ _ = battle;
678
+ _ = player;
679
+ _ = state;
680
+ _ = options;
245
681
  }
246
682
 
247
- pub const Rolls = struct {
248
- inline fn speedTie(battle: anytype, options: anytype) !bool {
249
- const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
250
- player == .P1
251
- else if (showdown)
252
- battle.rng.range(u8, 0, 2) == 0
253
- else
254
- battle.rng.next() < Gen12.percent(50) + 1;
683
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
255
684
 
256
- try options.chance.speedTie(p1);
257
- return p1;
685
+ pub fn adjustDamage(battle: anytype, player: Player, state: *State, _: anytype) !void {
686
+ if (state.move == .Struggle) return;
687
+
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;
258
701
  }
259
702
 
260
- inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
261
- const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
262
- val == .true
263
- else if (showdown)
264
- battle.rng.chance(u8, 60, 256)
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);
740
+ }
741
+
742
+ pub fn applyDamage(
743
+ battle: anytype,
744
+ player: Player,
745
+ state: *State,
746
+ options: anytype,
747
+ ) !void {
748
+ // TODO failuretext (if not Bide) + applydamage
749
+ _ = battle;
750
+ _ = player;
751
+ _ = state;
752
+ _ = options;
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);
832
+ }
833
+
834
+ fn checkFaint(
835
+ battle: anytype,
836
+ player: Player,
837
+ options: anytype,
838
+ ) @TypeOf(options.log).Error!?Result {
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 };
867
+ }
868
+
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)
265
886
  else
266
- battle.rng.next() < 60;
887
+ side.stored().stats.spe;
888
+ }
267
889
 
268
- try options.chance.quickClaw(player, qkc);
269
- return qkc;
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
+ }
270
904
  }
271
- };
905
+ }
272
906
 
273
- test "RNG agreement" {
274
- if (!showdown) return;
275
- var expected: [256]u32 = undefined;
276
- for (0..expected.len) |i| {
277
- expected[i] = @intCast(i * 0x1000000);
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);
913
+ }
914
+
915
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !bool {
916
+ var side = battle.side(player);
917
+ var stored = side.stored();
918
+ const ident = battle.active(player);
919
+ var volatiles = &side.active.volatiles;
920
+
921
+ // TODO if (stored.hp == 0) return;
922
+ assert(stored.hp > 0);
923
+
924
+ const brn = Status.is(stored.status, .BRN);
925
+ if (brn or Status.is(stored.status, .PSN)) {
926
+ var damage: u16 = undefined;
927
+ if (volatiles.Toxic) {
928
+ volatiles.toxic += 1;
929
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
930
+ } else {
931
+ damage = @max(stored.stats.hp / 8, 1);
932
+ }
933
+
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;
278
938
  }
279
939
 
280
- var spe = rng.FixedRNG(2, expected.len){ .rolls = expected };
281
- var qkc = rng.FixedRNG(2, expected.len){ .rolls = expected };
940
+ if (volatiles.LeechSeed) {
941
+ var foe = battle.foe(player);
942
+ var foe_stored = foe.stored();
943
+ const foe_ident = battle.active(player.foe());
944
+
945
+ // if (foe_stored.hp == 0) {
946
+ // assert(showdown);
947
+ // return;
948
+ // }
949
+
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 });
954
+
955
+ const before = foe_stored.hp;
956
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
957
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
958
+ if (foe_stored.hp > before) try options.log.heal(.{ foe_ident, foe_stored, .Silent });
959
+ if (stored.hp == 0) return true;
960
+ }
282
961
 
283
- for (0..expected.len) |i| {
284
- try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
285
- try expectEqual(qkc.chance(u8, 60, 256), i < 60);
962
+ if (volatiles.Nightmare) {
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;
967
+ }
968
+
969
+ if (volatiles.Curse) {
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;
974
+ }
975
+
976
+ return false;
977
+ }
978
+
979
+ fn betweenTurns(battle: anytype, mslot: u4, options: anytype) !?Result {
980
+ const players = comptime std.enums.values(Player);
981
+
982
+ if (try checkFaint(battle, .P1, options)) |r| return r;
983
+
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;
999
+
1000
+ // Weather
1001
+ if (battle.field.weather != .None) {
1002
+ battle.field.weather_duration -= 1;
1003
+
1004
+ if (battle.field.weather_duration == 0) {
1005
+ battle.field.weather = .None;
1006
+ try options.log.weather(.{ battle.field.weather, protocol.Weather.None });
1007
+ } else {
1008
+ try options.log.weather(.{ battle.field.weather, protocol.Weather.Upkeep });
1009
+ if (battle.field.weather == .Sandstorm) {
1010
+ inline for (players) |player| {
1011
+ var side = battle.side(player);
1012
+ const active = side.active;
1013
+ if (!(active.volatiles.Underground or active.types.sandstormImmune())) {
1014
+ side.stored().hp -|= @max(side.stored().stats.hp / 8, 1);
1015
+ try options.log.damage(.{
1016
+ battle.active(player),
1017
+ side.stored(),
1018
+ .Sandstorm,
1019
+ });
1020
+ }
1021
+ }
1022
+ if (try checkFaint(battle, .P1, options)) |r| return r;
1023
+ }
1024
+ }
1025
+ }
1026
+
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;
1053
+
1054
+ // Perish Song
1055
+ inline for (players) |player| {
1056
+ var side = battle.side(player);
1057
+ var volatiles = &side.active.volatiles;
1058
+
1059
+ if (volatiles.PerishSong) {
1060
+ volatiles.perish_song -= 1;
1061
+
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)) });
1065
+
1066
+ if (volatiles.perish_song == 0) {
1067
+ volatiles.PerishSong = false;
1068
+ side.stored().hp = 0;
1069
+ }
1070
+ }
1071
+ }
1072
+ if (try checkFaint(battle, .P1, options)) |r| return r;
1073
+
1074
+ // Leftovers
1075
+ inline for (players) |player| {
1076
+ var stored = battle.side(player).stored();
1077
+
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
+ }
1086
+
1087
+ // Mystery Berry
1088
+ inline for (players) |player| {
1089
+ const stored = battle.side(player).stored();
1090
+
1091
+ if (stored.item == .MysteryBerry) {
1092
+ // TODO stored and active moves, transform, etc
1093
+ }
1094
+ }
1095
+
1096
+ // Defrost
1097
+ inline for (players) |player| {
1098
+ var side = battle.side(player);
1099
+
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
+ }
1107
+ }
1108
+
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
+ _ = .{ battle, player, state, options }; // TODO
1308
+ // assert(!state.miss);
1309
+ // var side = battle.side(player);
1310
+ // try boostStat(battle, side, &side.active.stats, &side.active.boosts, "atk", 2);
1311
+ // TODO
1312
+ // |-boost|p1a: Poliwag|atk|2|[silent]
1313
+ // |-fail|p1a: Poliwag
1314
+ //
1315
+ }
1316
+
1317
+ pub const bide = struct {
1318
+ pub fn store(battle: anytype, player: Player, state: *State, options: anytype) !void {
1319
+ var side = battle.side(player);
1320
+ var volatiles = &side.active.volatiles;
1321
+
1322
+ const ident = battle.active(player);
1323
+
1324
+ if (!volatiles.Bide) return;
1325
+
1326
+ // if (options.calc.modify(player, .attacking)) |extend| {
1327
+ // if (!extend) volatiles.attacks = 0;
1328
+ // } else {
1329
+ volatiles.attacks -= 1;
1330
+ // }
1331
+ try options.chance.attacking(player, volatiles.attacks);
1332
+
1333
+ if (volatiles.attacks != 0) return options.log.activate(.{ ident, .Bide });
1334
+
1335
+ volatiles.Bide = false;
1336
+ try options.log.end(.{ ident, .Bide });
1337
+
1338
+ state.damage = volatiles.bide *% 2;
1339
+ volatiles.bide = 0;
1340
+
1341
+ if (state.damage == 0) state.miss = true;
1342
+ }
1343
+
1344
+ pub fn unleash(battle: anytype, player: Player, state: *State, options: anytype) !void {
1345
+ _ = .{ battle, player, state, options }; // TODO
1346
+ }
1347
+ };
1348
+
1349
+ pub fn binding(battle: anytype, player: Player, state: *State, options: anytype) !void {
1350
+ var foe = battle.foe(player);
1351
+
1352
+ if (state.miss) return;
1353
+ if (foe.active.volatiles.bind.duration > 0) return;
1354
+ if (foe.active.volatiles.Substitute) return;
1355
+
1356
+ foe.active.volatiles.bind = .{
1357
+ .duration = Rolls.bindingDuration(battle, player, options),
1358
+ .reason = Move.get(state.move).extra.protocol,
1359
+ };
1360
+ }
1361
+
1362
+ pub fn burnChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1363
+ var foe = battle.foe(player);
1364
+ var foe_stored = foe.stored();
1365
+
1366
+ if (foe.active.volatiles.Substitute) return;
1367
+ if (Status.any(foe_stored.status)) {
1368
+ if (Status.is(foe_stored.status, .FRZ)) {
1369
+ assert(Move.get(state.move).type == .Fire or state.move == .TriAttack);
1370
+ try options.log.curestatus(.{
1371
+ battle.active(player.foe()),
1372
+ foe_stored.status,
1373
+ .Message,
1374
+ });
1375
+ foe_stored.status = 0;
1376
+ }
1377
+ return;
1378
+ }
1379
+ if (!state.proc) return;
1380
+ if (foe.conditions.Safeguard) return;
1381
+ // Nothing is immune to Fire-type, but Ghosts are immune to burnChance called by Tri Attack
1382
+ if (state.immune()) return;
1383
+ if (foe.active.types.includes(Move.get(state.move).type) and state.move != .TriAttack) {
1384
+ return;
1385
+ }
1386
+
1387
+ foe_stored.status = Status.init(.BRN);
1388
+ foe.active.stats.atk = @max(foe.active.stats.atk / 2, 1);
1389
+
1390
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
1391
+
1392
+ // TODO: check for status berry
1393
+ }
1394
+
1395
+ pub fn confusion(battle: anytype, player: Player, state: *State, options: anytype) !void {
1396
+ _ = .{ battle, player, state, options }; // TODO
1397
+ }
1398
+
1399
+ pub fn confusionChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1400
+ _ = .{ battle, player, state, options }; // TODO
1401
+ }
1402
+
1403
+ pub fn conversion(battle: anytype, player: Player, _: *State, options: anytype) !void {
1404
+ var side = battle.side(player);
1405
+
1406
+ var n: u3 = 0;
1407
+ for (side.active.moves) |m| {
1408
+ if (convertible(side.active, m.id)) n += 1;
1409
+ }
1410
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
1411
+
1412
+ side.active.types.type1 = try Rolls.conversion(battle, player, n, options);
1413
+ side.active.types.type2 = side.active.types.type1;
1414
+ }
1415
+
1416
+ pub fn conversion2(battle: anytype, player: Player, _: *State, options: anytype) !void {
1417
+ var side = battle.side(player);
1418
+
1419
+ const last = battle.foe(player).lastMove(false);
1420
+ if (last == .None) return options.log.fail(.{ battle.active(player), .None });
1421
+ const move = Move.get(last);
1422
+ if (move.type == .@"???") return options.log.fail(.{ battle.active(player), .None });
1423
+
1424
+ side.active.types.type1 = try Rolls.conversion2(battle, player, move.type, options);
1425
+ side.active.types.type2 = side.active.types.type1;
1426
+ }
1427
+
1428
+ pub fn counter(battle: anytype, player: Player, state: *State, _: anytype) !void {
1429
+ assert(state.move == .Counter or state.move == .MirrorCoat);
1430
+
1431
+ const foe = battle.foe(player);
1432
+
1433
+ state.miss = true;
1434
+ const last = foe.lastMove(false);
1435
+
1436
+ if (last == .None) return;
1437
+ if (last == state.move) return;
1438
+
1439
+ const immune = state.immune();
1440
+ state.effectiveness = Effectiveness.neutral;
1441
+ if (immune) {
1442
+ state.damage = 0;
1443
+ return;
1444
+ }
1445
+
1446
+ const move = Move.get(last);
1447
+ if (state.bp == 0) return;
1448
+ if (move.type.special() != (last == .MirrorCoat)) return;
1449
+ if (state.damage == 0) return;
1450
+
1451
+ state.damage *|= 2;
1452
+ state.miss = false;
1453
+ }
1454
+
1455
+ pub fn curse(battle: anytype, player: Player, state: *State, options: anytype) !void {
1456
+ var side = battle.side(player);
1457
+ var foe = battle.foe(player);
1458
+
1459
+ const ident = battle.active(player);
1460
+ const foe_ident = battle.active(player.foe());
1461
+
1462
+ if (side.active.types.includes(.Ghost)) {
1463
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1464
+ try options.log.lastmiss(.{});
1465
+ return options.log.miss(.{battle.active(player)});
1466
+ } else if (foe.active.volatiles.Substitute) {
1467
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1468
+ } else if (foe.active.volatiles.Curse) {
1469
+ return options.log.fail(.{ foe_ident, .None });
1470
+ }
1471
+
1472
+ foe.active.volatiles.Curse = true;
1473
+ try options.log.start(.{ foe_ident, .Curse });
1474
+
1475
+ side.stored().hp -= @max(side.stored().stats.hp / 2, 1);
1476
+ try options.log.damage(.{ ident, side.stored(), .Curse });
1477
+ } else {
1478
+ const stats = &side.active.stats;
1479
+ const boosts = &side.active.boosts;
1480
+
1481
+ const max_atk = boosts.atk == 6 or stats.atk == MAX_STAT_VALUE;
1482
+ const max_def = boosts.def == 6 or stats.def == MAX_STAT_VALUE;
1483
+ if (max_atk and max_def) return options.log.fail(.{ ident, .None });
1484
+
1485
+ if (!(boosts.spe == -6 or stats.spe == 1)) {
1486
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
1487
+ try unboostStat(battle, side, stats, boosts, "spe", 1);
1488
+ try options.log.boost(.{ ident, .Speed, @as(i8, -1) });
1489
+ }
1490
+ if (!max_atk) {
1491
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
1492
+ try boostStat(battle, side, stats, boosts, "atk", 1);
1493
+ try options.log.boost(.{ ident, .Attack, @as(i8, 1) });
1494
+ }
1495
+ if (!max_def) {
1496
+ assert(boosts.def >= -6 and boosts.def <= 6);
1497
+ try boostStat(battle, side, stats, boosts, "def", 1);
1498
+ try options.log.boost(.{ ident, .Defense, @as(i8, 1) });
1499
+ }
1500
+ }
1501
+ }
1502
+
1503
+ pub fn defenseCurl(battle: anytype, player: Player, _: *State, _: anytype) !void {
1504
+ battle.side(player).active.volatiles.DefenseCurl = true;
1505
+ }
1506
+
1507
+ pub fn defrost(battle: anytype, player: Player, _: *State, options: anytype) !void {
1508
+ var side = battle.side(player);
1509
+ assert(Status.is(side.stored().status, .FRZ));
1510
+ try options.log.curestatus(.{ battle.active(player), side.stored().status, .Message });
1511
+ side.stored().status = 0;
1512
+ }
1513
+
1514
+ pub fn destinyBond(battle: anytype, player: Player, _: *State, options: anytype) !void {
1515
+ battle.side(player).active.volatiles.DestinyBond = true;
1516
+ try options.log.singlemove(.{ battle.active(player), Move.DestinyBond });
1517
+ }
1518
+
1519
+ pub fn disable(battle: anytype, player: Player, _: *State, options: anytype) !void {
1520
+ var foe = battle.foe(player);
1521
+ var volatiles = &foe.active.volatiles;
1522
+ const foe_ident = battle.active(player.foe());
1523
+
1524
+ if (volatiles.disable.move != 0) return options.log.fail(.{ foe_ident, .None });
1525
+
1526
+ const last = battle.foe(player).lastMove(false);
1527
+ if (last == .None or last == .Struggle) return options.log.fail(.{ foe_ident, .None });
1528
+
1529
+ var slot: u3 = 0;
1530
+ for (foe.active.moves) |m| {
1531
+ assert(m.id != .None);
1532
+ slot += 1;
1533
+ if (m.id == last) break;
1534
+ }
1535
+ const move = foe.active.move(slot);
1536
+ if (move.pp == 0) return options.log.fail(.{ foe_ident, .None });
1537
+
1538
+ volatiles.disable.move = slot;
1539
+ volatiles.disable.duration = Rolls.disableDuration(battle, player, options);
1540
+
1541
+ try options.log.start(.{ foe_ident, .Disable, move.id });
1542
+ }
1543
+
1544
+ pub const double = struct {
1545
+ pub fn flying(battle: anytype, player: Player, state: *State, _: anytype) !void {
1546
+ if (battle.foe(player).active.volatiles.Flying) state.damage *|= 2;
1547
+ }
1548
+
1549
+ pub fn underground(battle: anytype, player: Player, state: *State, _: anytype) !void {
1550
+ if (battle.foe(player).active.volatiles.Underground) state.damage *|= 2;
1551
+ }
1552
+
1553
+ pub fn minimize(battle: anytype, player: Player, state: *State, _: anytype) !void {
1554
+ if (battle.foe(player).active.volatiles.minimized) state.damage *|= 2;
1555
+ }
1556
+ };
1557
+
1558
+ pub fn drainHP(battle: anytype, player: Player, state: *State, options: anytype) !void {
1559
+ var stored = battle.side(player).stored();
1560
+ const ident = battle.active(player);
1561
+
1562
+ assert(state.damage != 0);
1563
+
1564
+ if (stored.hp == stored.stats.hp) return;
1565
+ stored.hp = @min(stored.stats.hp, stored.hp + @max(state.damage / 2, 1));
1566
+
1567
+ try options.log.heal(.{ ident, stored, .Drain, battle.active(player.foe()) });
1568
+ }
1569
+
1570
+ pub fn encore(battle: anytype, player: Player, state: *State, options: anytype) !void {
1571
+ var foe = battle.foe(player);
1572
+ var volatiles = &foe.active.volatiles;
1573
+ const foe_ident = battle.active(player.foe());
1574
+
1575
+ const last = battle.foe(player).lastMove(true);
1576
+ const failed = volatiles.Encore or
1577
+ (last == .None or last == .Struggle or
1578
+ last == .Encore or .last == .MirrorMove);
1579
+ if (failed) return options.log.fail(.{ foe_ident, .None });
1580
+
1581
+ var slot: u3 = 0;
1582
+ for (foe.active.moves) |m| {
1583
+ assert(m.id != .None);
1584
+ slot += 1;
1585
+ if (m.id == last) break;
1586
+ }
1587
+ const move = foe.active.move(slot);
1588
+ if (move.pp == 0) return options.log.fail(.{ foe_ident, .None });
1589
+
1590
+ volatiles.Encore = true;
1591
+ volatiles.encore = Rolls.encoreDuration(battle, player, options);
1592
+
1593
+ // TODO ???
1594
+ _ = state;
1595
+
1596
+ try options.log.start(.{ foe_ident, .Encore, move.id });
1597
+ }
1598
+
1599
+ pub fn explode(battle: anytype, player: Player, state: *State, options: anytype) !void {
1600
+ _ = .{ battle, player, state, options }; // TODO
1601
+ }
1602
+
1603
+ pub fn falseSwipe(battle: anytype, player: Player, state: *State, _: anytype) !void {
1604
+ const foe = battle.foe(player);
1605
+ assert(foe.stored().hp > 0);
1606
+ // FIXME crit?
1607
+ if (state.damage > foe.stored().hp) state.damage = foe.stored().hp - 1;
1608
+ }
1609
+
1610
+ pub fn fixedDamage(battle: anytype, player: Player, state: *State, options: anytype) !void {
1611
+ const side = battle.side(player);
1612
+ const foe = battle.foe(player);
1613
+
1614
+ state.damage = switch (Move.get(state.move).effect) {
1615
+ .SuperFang => @max(foe.stored().hp / 2, 1),
1616
+ .LevelDamage => side.stored().level,
1617
+ .FixedDamage => if (state.move == .SonicBoom) 20 else 40,
1618
+ .Psywave => try Rolls.psywave(
1619
+ battle,
1620
+ player,
1621
+ @intCast(@as(u16, side.stored().level) * 3 / 2),
1622
+ options,
1623
+ ),
1624
+ else => unreachable,
1625
+ };
1626
+ }
1627
+
1628
+ pub fn flinchChance(battle: anytype, player: Player, state: *State, _: anytype) !void {
1629
+ const foe = battle.foe(player);
1630
+ const status = foe.stored().status;
1631
+ var volatiles = &foe.active.volatiles;
1632
+
1633
+ if (volatiles.Substitute) return;
1634
+ if (Status.is(status, .FRZ) or Status.is(status, .SLP)) return;
1635
+ if (!state.first) return;
1636
+ if (!state.proc) return;
1637
+
1638
+ volatiles.Flinch = true;
1639
+ volatiles.Recharging = false;
1640
+ }
1641
+
1642
+ pub fn flyDig(battle: anytype, player: Player, state: *State, options: anytype) !void {
1643
+ _ = .{ battle, player, state, options }; // TODO
1644
+ }
1645
+
1646
+ pub fn focusEnergy(battle: anytype, player: Player, _: *State, options: anytype) !void {
1647
+ var side = battle.side(player);
1648
+
1649
+ if (side.active.volatiles.FocusEnergy) {
1650
+ return if (!showdown) try options.log.fail(.{ battle.active(player), .None });
1651
+ }
1652
+
1653
+ side.active.volatiles.FocusEnergy = true;
1654
+ try options.log.start(.{ battle.active(player), .FocusEnergy });
1655
+ }
1656
+
1657
+ var SLOTS: [5]u4 = .{ 0, 0, 0, 0, 0 };
1658
+
1659
+ pub fn forceSwitch(battle: anytype, player: Player, state: *State, options: anytype) !void {
1660
+ assert(!state.miss); // FIXME ensure checkHit handles fail message
1661
+
1662
+ const foe = battle.foe(player);
1663
+
1664
+ if (state.first) return options.log.fail(.{ battle.active(player), .None });
1665
+
1666
+ var n: u4 = 0;
1667
+ var i: u4 = 0;
1668
+ for (foe.pokemon, 0..) |pokemon, j| {
1669
+ if (pokemon.species == .None) break;
1670
+ n += 1;
1671
+ if (pokemon.position == 1) continue;
1672
+ if (pokemon.hp > 0) {
1673
+ SLOTS[i] = @intCast(foe.pokemon[j].position);
1674
+ i += 1;
1675
+ }
1676
+ }
1677
+
1678
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
1679
+
1680
+ const slot = try Rolls.forceSwitch(battle, player, SLOTS[0..i], n, options);
1681
+ try switchIn(battle, player.foe(), slot, .Drag, options);
1682
+ }
1683
+
1684
+ pub fn foresight(battle: anytype, player: Player, _: *State, options: anytype) !void {
1685
+ var foe = battle.foe(player);
1686
+
1687
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1688
+ try options.log.lastmiss(.{});
1689
+ return options.log.miss(.{battle.active(player)});
1690
+ } else if (foe.active.volatiles.Foresight) {
1691
+ return options.log.fail(.{ battle.active(player), .None });
1692
+ }
1693
+
1694
+ foe.active.volatiles.Foresight = true;
1695
+ try options.log.start(.{ battle.active(player.foe()), .FocusEnergy });
1696
+ }
1697
+
1698
+ pub fn freezeChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
1699
+ var foe = battle.foe(player);
1700
+ var foe_stored = foe.stored();
1701
+ const foe_ident = battle.active(player.foe());
1702
+
1703
+ if (foe.active.volatiles.Substitute) return;
1704
+ if (Status.any(foe_stored.status)) return;
1705
+
1706
+ // Nothing is immune to Ice-type, but Ghosts are immune to freezeChance called by Tri Attack
1707
+ if (state.immune()) return;
1708
+ if (battle.field.weather == .Sun) return;
1709
+ if (foe.active.types.includes(Move.get(state.move).type) and state.move != .TriAttack) {
1710
+ return;
1711
+ }
1712
+ if (!state.proc) return;
1713
+ if (foe.conditions.Safeguard) return;
1714
+ // Freeze Clause Mod
1715
+ if (showdown) for (foe.pokemon) |p| if (Status.is(p.status, .FRZ)) return;
1716
+
1717
+ foe_stored.status = Status.init(.FRZ);
1718
+ try options.log.status(.{ foe_ident, foe_stored.status, .None });
1719
+
1720
+ // TODO: check for status berry
1721
+
1722
+ foe.active.volatiles.Recharging = false;
1723
+ foe.active.volatiles.frozen = true;
1724
+ }
1725
+
1726
+ pub fn furyCutter(battle: anytype, player: Player, state: *State, options: anytype) !void {
1727
+ _ = .{ battle, player, state, options }; // TODO
1728
+ }
1729
+
1730
+ pub fn futureSight(battle: anytype, player: Player, state: *State, options: anytype) !void {
1731
+ _ = .{ battle, player, state, options }; // TODO
1732
+ }
1733
+
1734
+ pub fn happiness(battle: anytype, player: Player, state: *State, _: anytype) !void {
1735
+ const val = battle.side(player).stored().happiness;
1736
+ const frustration = Move.get(state.move).effect == .Frustration;
1737
+ state.bp = ((if (frustration) 255 - val else val) * 10) / 25;
1738
+ }
1739
+
1740
+ pub fn haze(battle: anytype, player: Player, _: *State, options: anytype) !void {
1741
+ var side = battle.side(player);
1742
+ var stats = unmodifiedStats(battle, side);
1743
+ side.active.boosts = .{};
1744
+ inline for (STATS) |s| @field(side.active.stats, s) = @field(stats, s);
1745
+ statusModify(side.stored().status, &side.active.stats);
1746
+
1747
+ var foe = battle.foe(player);
1748
+ stats = unmodifiedStats(battle, foe);
1749
+ foe.active.boosts = .{};
1750
+ inline for (STATS) |s| @field(foe.active.stats, s) = @field(stats, s);
1751
+ statusModify(foe.stored().status, &foe.active.stats);
1752
+
1753
+ try options.log.clearallboost(.{});
1754
+ }
1755
+
1756
+ pub fn heal(battle: anytype, player: Player, state: *State, options: anytype) !void {
1757
+ var side = battle.side(player);
1758
+ var stored = side.stored();
1759
+ const ident = battle.active(player);
1760
+
1761
+ if (stored.stats.hp == stored.hp) return options.log.fail(.{ ident, .None });
1762
+
1763
+ const rest = state.move == .Rest;
1764
+ if (rest) {
1765
+ // Adding the sleep status runs the sleep condition handler to roll duration
1766
+ if (showdown) battle.rng.advance(1);
1767
+ side.active.volatiles.Toxic = false;
1768
+ stored.status = Status.slf(2);
1769
+ recomputeStats(battle, side);
1770
+ try options.log.status(.{ ident, stored.status, .From, Move.Rest });
1771
+ stored.hp = stored.stats.hp;
1772
+ } else {
1773
+ stored.hp = @min(stored.stats.hp, stored.hp + (stored.stats.hp / 2));
1774
+ }
1775
+ try options.log.heal(.{ ident, stored, if (rest) Heal.Silent else Heal.None });
1776
+ }
1777
+
1778
+ pub fn healBell(battle: anytype, player: Player, _: *State, options: anytype) !void {
1779
+ var side = battle.side(player);
1780
+ side.active.volatiles.Nightmare = false;
1781
+
1782
+ try options.log.cureteam(.{battle.active(player)});
1783
+ for (&side.pokemon) |*p| p.status = 0;
1784
+
1785
+ // We technically only need to recompute stats if the active Pokémon was burned/paralyzed,
1786
+ // but adding a branch to check for that is probably more expensive than just recomputing
1787
+ recomputeStats(battle, side);
1788
+ }
1789
+
1790
+ pub fn hiddenPower(battle: anytype, player: Player, state: *State, _: anytype) !void {
1791
+ const side = battle.side(player);
1792
+ state.bp = side.stored().dvs.power();
1793
+ state.type = side.stored().dvs.type;
1794
+ }
1795
+
1796
+ pub fn hyperBeam(battle: anytype, player: Player, _: *State, options: anytype) !void {
1797
+ battle.side(player).active.volatiles.Recharging = true;
1798
+ try options.log.mustrecharge(.{battle.active(player)});
1799
+ }
1800
+
1801
+ pub fn leechSeed(battle: anytype, player: Player, state: *State, options: anytype) !void {
1802
+ var foe = battle.foe(player);
1803
+
1804
+ if (showdown) {
1805
+ // Invulnerability trumps type immunity on Pokémon Showdown
1806
+ const invulnerable = foe.active.volatiles.Underground or foe.active.volatiles.Flying;
1807
+ if (!invulnerable and foe.active.types.includes(.Grass)) {
1808
+ return options.log.immune(.{ battle.active(player.foe()), .None });
1809
+ }
1810
+ try checkHit(battle, player, state, options);
1811
+ if (state.miss) {
1812
+ try options.log.lastmiss(.{});
1813
+ return options.log.miss(.{battle.active(player)});
1814
+ }
1815
+ if (foe.active.volatiles.LeechSeed) return;
1816
+ } else {
1817
+ try checkHit(battle, player, state, options);
1818
+ const miss =
1819
+ state.miss or foe.active.types.includes(.Grass) or foe.active.volatiles.LeechSeed;
1820
+ if (miss) {
1821
+ try options.log.lastmiss(.{});
1822
+ return options.log.miss(.{battle.active(player)});
1823
+ }
1824
+ }
1825
+
1826
+ foe.active.volatiles.LeechSeed = true;
1827
+
1828
+ try options.log.start(.{ battle.active(player.foe()), .LeechSeed });
1829
+ }
1830
+
1831
+ pub fn lockOn(battle: anytype, player: Player, state: *State, options: anytype) !void {
1832
+ var foe = battle.foe(player);
1833
+ const foe_ident = battle.active(player.foe());
1834
+
1835
+ if (foe.active.volatiles.Substitute) {
1836
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1837
+ } else if (state.miss) {
1838
+ return options.log.fail(.{ foe_ident, .None });
1839
+ }
1840
+
1841
+ foe.active.volatiles.LockOn = true;
1842
+ try options.log.activate(.{ battle.active(player), .LockOn });
1843
+ }
1844
+
1845
+ const MAGNITUDE_POWER = [_]u8{ 10, 30, 50, 70, 90, 110, 150 };
1846
+
1847
+ pub fn magnitude(battle: anytype, player: Player, state: *State, options: anytype) !void {
1848
+ const num = try Rolls.magnitude(battle, player, options);
1849
+ try options.log.activate(.{ battle.active(player), .Magnitude, num });
1850
+ state.bp = MAGNITUDE_POWER[num - 4];
1851
+ }
1852
+
1853
+ pub fn meanLook(battle: anytype, player: Player, _: *State, options: anytype) !void {
1854
+ var foe = battle.foe(player);
1855
+
1856
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
1857
+ if (!showdown) return options.log.fail(.{ battle.active(player.foe()), .None });
1858
+ try options.log.lastmiss(.{});
1859
+ return options.log.miss(.{battle.active(player)});
1860
+ } else if (foe.active.volatiles.Trapped) {
1861
+ return options.log.fail(.{ battle.active(player.foe()), .None });
1862
+ }
1863
+
1864
+ foe.active.volatiles.Trapped = true;
1865
+ }
1866
+
1867
+ pub fn metronome(
1868
+ battle: anytype,
1869
+ player: Player,
1870
+ state: *State,
1871
+ options: anytype,
1872
+ ) anyerror!void {
1873
+ var side = battle.side(player);
1874
+
1875
+ side.last_used_move = .None;
1876
+ side.active.volatiles.dirty = false;
1877
+
1878
+ // if (wPlayerCharging) ???
1879
+ // wPlayerCharging = 1
1880
+
1881
+ // FIXME
1882
+ state.move = try Rolls.metronome(battle, player, options);
1883
+ state.from = .Metronome;
1884
+ return generated.runMove(battle, player, state, options);
1885
+ }
1886
+
1887
+ pub fn mimic(battle: anytype, player: Player, state: *State, options: anytype) !void {
1888
+ _ = .{ battle, player, state, options }; // TODO
1889
+ }
1890
+
1891
+ pub fn mirrorMove(
1892
+ battle: anytype,
1893
+ player: Player,
1894
+ state: *State,
1895
+ options: anytype,
1896
+ ) anyerror!void {
1897
+ var side = battle.side(player);
1898
+ const foe = battle.foe(player);
1899
+
1900
+ side.last_used_move = .None;
1901
+ side.active.volatiles.dirty = false;
1902
+
1903
+ const last = foe.lastMove(false);
1904
+
1905
+ if (last == .None) return options.log.fail(.{ battle.active(player), .None });
1906
+ const knows = knows: for (side.active.moves) |m| {
1907
+ if (last == m.id) break :knows true;
1908
+ } else false;
1909
+ if (knows) return options.log.fail(.{ battle.active(player), .None });
1910
+
1911
+ // if (wPlayerCharging) ???
1912
+ // wPlayerCharging = 1
1913
+
1914
+ // FIXME
1915
+ state.move = last;
1916
+ state.from = .MirrorMove;
1917
+ return generated.runMove(battle, player, state, options);
1918
+ }
1919
+
1920
+ pub fn mist(battle: anytype, player: Player, _: *State, options: anytype) !void {
1921
+ var side = battle.side(player);
1922
+
1923
+ if (side.active.volatiles.Mist) return options.log.fail(.{ battle.active(player), .None });
1924
+ side.active.volatiles.Mist = true;
1925
+
1926
+ try options.log.start(.{ battle.active(player), .Mist });
1927
+ }
1928
+
1929
+ pub fn weatherHeal(battle: anytype, player: Player, _: *State, options: anytype) !void {
1930
+ var stored = battle.side(player).stored();
1931
+ const ident = battle.active(player);
1932
+
1933
+ if (stored.hp == stored.stats.hp) return options.log.fail(.{ ident, .None });
1934
+
1935
+ stored.hp = switch (battle.field.weather) {
1936
+ .Sun => stored.stats.hp,
1937
+ .None => @min(stored.stats.hp, stored.hp + (stored.stats.hp / 2)),
1938
+ else => @min(stored.stats.hp, stored.hp + (stored.stats.hp / 4)),
1939
+ };
1940
+
1941
+ try options.log.heal(.{ ident, stored, .None });
1942
+ }
1943
+
1944
+ pub fn multiHit(battle: anytype, player: Player, state: *State, options: anytype) !void {
1945
+ _ = .{ battle, player, state, options }; // TODO
1946
+ }
1947
+
1948
+ pub fn nightmare(battle: anytype, player: Player, state: *State, options: anytype) !void {
1949
+ var foe = battle.foe(player);
1950
+ var foe_volatiles = &foe.active.volatiles;
1951
+ const foe_ident = battle.active(player.foe());
1952
+
1953
+ if (foe_volatiles.Flying or foe_volatiles.Underground) {
1954
+ if (!showdown) return options.log.fail(.{ battle.active(player.foe()), .None });
1955
+ try options.log.lastmiss(.{});
1956
+ return options.log.miss(.{battle.active(player)});
1957
+ } else if (foe_volatiles.Substitute) {
1958
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
1959
+ } else if (!Status.is(foe.stored().status, .SLP) or foe_volatiles.Nightmare) {
1960
+ return options.log.fail(.{ foe_ident, .None });
1961
+ }
1962
+
1963
+ foe_volatiles.Nightmare = true;
1964
+ try options.log.start(.{ battle.active(player.foe()), .Nightmare });
1965
+ }
1966
+
1967
+ pub const ohko = struct {
1968
+ // OHKO calls adjustDamage but only actually cares about immunity
1969
+ pub fn immune(battle: anytype, player: Player, state: *State, _: anytype) !void {
1970
+ const move = Move.get(state.move);
1971
+
1972
+ assert(move.type == .Normal or move.type == .Ground);
1973
+ const foe = battle.foe(player);
1974
+ const zero = if (move.type == .Normal)
1975
+ foe.active.types.includes(.Ghost) and !foe.active.volatiles.Foresight
1976
+ else
1977
+ foe.active.types.includes(.Flying);
1978
+ state.effectiveness = if (zero) 0 else Effectiveness.neutral;
1979
+ }
1980
+
1981
+ pub fn damage(battle: anytype, player: Player, state: *State, options: anytype) !void {
1982
+ const side = battle.side(player);
1983
+ const foe = battle.foe(player);
1984
+
1985
+ const foe_ident = battle.active(player.foe());
1986
+
1987
+ state.damage = 0;
1988
+ if (state.immune()) return options.log.immune(.{ foe_ident, .None });
1989
+ const delta = side.stored().level -| foe.stored().level;
1990
+ if (delta == 0) return options.log.immune(.{ foe_ident, .OHKO });
1991
+
1992
+ state.accuracy = 2 * delta +| Gen12.percent(30);
1993
+ try checkHit(battle, player, state, options);
1994
+ if (!state.miss) state.damage = 65535;
1995
+ state.ohko = true;
1996
+ }
1997
+ };
1998
+
1999
+ pub fn painSplit(battle: anytype, player: Player, state: *State, options: anytype) !void {
2000
+ var side = battle.side(player);
2001
+ var foe = battle.foe(player);
2002
+
2003
+ const ident = battle.active(player);
2004
+ const foe_ident = battle.active(player.foe());
2005
+
2006
+ if (state.miss) return options.log.fail(.{ foe_ident, .None });
2007
+ if (foe.active.volatiles.Substitute) {
2008
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2009
+ }
2010
+
2011
+ const avg = @max((foe.stored().hp + side.stored().hp) / 2, 1);
2012
+ foe.stored().hp -= avg;
2013
+ side.stored().hp = avg;
2014
+
2015
+ try options.log.sethp(.{ foe_ident, foe.stored(), .Silent });
2016
+ try options.log.sethp(.{ ident, side.stored(), .None });
2017
+ }
2018
+
2019
+ pub fn paralyze(battle: anytype, player: Player, state: *State, options: anytype) !void {
2020
+ var foe = battle.foe(player);
2021
+ const foe_ident = battle.active(player.foe());
2022
+
2023
+ if (Status.is(foe.stored().status, .PAR)) {
2024
+ return options.log.fail(.{ foe_ident, .Paralysis });
2025
+ }
2026
+ if (state.immune()) return options.log.immune(.{ foe_ident, .None });
2027
+ if (Status.any(foe.stored().status)) return options.log.fail(.{ foe_ident, .None });
2028
+ if (state.miss) {
2029
+ try options.log.lastmiss(.{});
2030
+ return options.log.miss(.{battle.active(player)});
2031
+ } else if (foe.active.volatiles.Substitute) {
2032
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2033
+ }
2034
+
2035
+ foe.stored().status = Status.init(.PAR);
2036
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2037
+
2038
+ try options.log.status(.{ foe_ident, foe.stored().status, .None });
2039
+ }
2040
+
2041
+ pub fn paralyzeChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2042
+ var foe = battle.foe(player);
2043
+ var foe_stored = foe.stored();
2044
+
2045
+ if (foe.active.volatiles.Substitute) return;
2046
+ if (Status.any(foe_stored.status)) return;
2047
+ if (state.immune()) return;
2048
+ if (!state.proc) return;
2049
+ if (foe.conditions.Safeguard) return;
2050
+
2051
+ foe_stored.status = Status.init(.PAR);
2052
+ foe.active.stats.spe = @max(foe.active.stats.spe / 4, 1);
2053
+
2054
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
2055
+
2056
+ // TODO: check for status berry
2057
+ }
2058
+
2059
+ pub fn payDay(battle: anytype, player: Player, _: *State, options: anytype) !void {
2060
+ if (!showdown or !battle.foe(player).active.volatiles.Substitute) {
2061
+ try options.log.fieldactivate(.{}); // FIXME .PayDay
2062
+ }
2063
+ }
2064
+
2065
+ pub fn perishSong(battle: anytype, player: Player, _: *State, options: anytype) !void {
2066
+ var side = battle.side(player);
2067
+ var foe = battle.foe(player);
2068
+
2069
+ if (foe.active.volatiles.PerishSong) {
2070
+ return options.log.fail(.{ battle.active(player.foe()), .None });
2071
+ } else if (!side.active.volatiles.PerishSong) {
2072
+ side.active.volatiles.PerishSong = true;
2073
+ side.active.volatiles.perish_song = 4;
2074
+ try options.log.start(.{ battle.active(player), .PerishSong3Silent });
2075
+ }
2076
+ foe.active.volatiles.PerishSong = true;
2077
+ foe.active.volatiles.perish_song = 4;
2078
+ try options.log.start(.{ battle.active(player.foe()), .PerishSong3Silent });
2079
+
2080
+ try options.log.fieldactivate(.{}); // FIXME .PerishSong
2081
+ }
2082
+
2083
+ pub fn poison(battle: anytype, player: Player, state: *State, options: anytype) !void {
2084
+ var foe = battle.foe(player);
2085
+ var foe_stored = foe.stored();
2086
+ const foe_ident = battle.active(player.foe());
2087
+
2088
+ const toxic = state.move == .Toxic;
2089
+ if (state.immune() or foe.active.types.includes(.Poison)) {
2090
+ return options.log.immune(.{ foe_ident, .None });
2091
+ } else if (Status.any(foe_stored.status)) {
2092
+ // Pokémon Showdown considers Toxic to be a status even in Generation II and so
2093
+ // will not include a fail reason for Toxic vs. Poison or vice-versa...
2094
+ return options.log.fail(.{ foe_ident, if (Status.is(foe_stored.status, .PSN))
2095
+ if (!showdown)
2096
+ Fail.Poison
2097
+ else if (toxic == (foe_stored.status == Status.TOX))
2098
+ if (toxic) Fail.Toxic else Fail.Poison
2099
+ else
2100
+ Fail.None
2101
+ else
2102
+ Fail.None });
2103
+ } else if (foe.active.volatiles.Substitute) {
2104
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2105
+ } else if (state.miss) {
2106
+ try options.log.lastmiss(.{});
2107
+ return options.log.miss(.{battle.active(player)});
2108
+ }
2109
+
2110
+ foe_stored.status = Status.init(.PSN);
2111
+ if (toxic) {
2112
+ if (showdown) foe_stored.status = Status.TOX;
2113
+ foe.active.volatiles.Toxic = true;
2114
+ foe.active.volatiles.toxic = 0;
2115
+ }
2116
+
2117
+ try options.log.status(.{ foe_ident, foe_stored.status, .None });
2118
+
2119
+ // TODO: check for status berry
2120
+ }
2121
+
2122
+ pub fn poisonChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2123
+ var foe = battle.foe(player);
2124
+ var foe_stored = foe.stored();
2125
+
2126
+ if (foe.active.volatiles.Substitute) return;
2127
+ if (Status.any(foe_stored.status)) return if (showdown) battle.rng.advance(1);
2128
+ if (state.immune() or foe.active.types.includes(.Poison)) return;
2129
+ if (!state.proc) return;
2130
+ if (foe.conditions.Safeguard) return;
2131
+
2132
+ foe_stored.status = Status.init(.PSN);
2133
+
2134
+ try options.log.status(.{ battle.active(player.foe()), foe_stored.status, .None });
2135
+
2136
+ // TODO: check for status berry
2137
+ }
2138
+
2139
+ pub fn present(battle: anytype, player: Player, state: *State, options: anytype) !void {
2140
+ _ = .{ battle, player, state, options }; // TODO
2141
+ }
2142
+
2143
+ pub fn protect(battle: anytype, player: Player, state: *State, options: anytype) !void {
2144
+ var side = battle.side(player);
2145
+ var volatiles = &side.active.volatiles;
2146
+
2147
+ const failed = !state.first or volatiles.Substitute or
2148
+ !try Rolls.protect(battle, player, volatiles.protect, options);
2149
+ if (failed) return options.log.fail(.{ battle.active(player), .None });
2150
+
2151
+ volatiles.protect = @max(8, volatiles.protect + 1);
2152
+ if (state.move == .Endure) {
2153
+ volatiles.Endure = true;
2154
+ } else {
2155
+ volatiles.Protect = true;
2156
+ }
2157
+ try options.log.singleturn(.{ battle.active(player), state.move });
2158
+ }
2159
+
2160
+ pub fn psychUp(battle: anytype, player: Player, _: *State, options: anytype) !void {
2161
+ var side = battle.side(player);
2162
+ const foe = battle.foe(player);
2163
+
2164
+ // Pokémon Showdown should fail when the enemy has no boosts/unboosts but doesn't
2165
+ if (!showdown and @as(u32, @bitCast(foe.active.boosts)) == 0) {
2166
+ return options.log.fail(.{ battle.active(player), .None });
2167
+ }
2168
+
2169
+ side.active.boosts = foe.active.boosts;
2170
+ try options.log.copyboost(.{ battle.active(player), battle.active(player.foe()) });
2171
+ }
2172
+
2173
+ pub fn pursuit(battle: anytype, player: Player, state: *State, _: anytype) !void {
2174
+ // TODO: remove switching variable and just look at Choice saved in Battle struct?
2175
+ if (battle.foe(player).active.volatiles.switching) state.damage *|= 2;
2176
+ }
2177
+
2178
+ pub const rage = struct {
2179
+ pub fn start(battle: anytype, player: Player, _: *State, options: anytype) !void {
2180
+ battle.side(player).active.volatiles.Rage = true;
2181
+ try options.log.singlemove(.{ battle.active(player), Move.Rage });
2182
+ }
2183
+
2184
+ pub fn damage(battle: anytype, player: Player, state: *State, _: anytype) !void {
2185
+ const side = battle.side(player);
2186
+
2187
+ assert(side.active.volatiles.Rage);
2188
+ state.damage *|= (side.active.volatiles.rage +| 1);
2189
+ }
2190
+ };
2191
+
2192
+ pub fn rainDance(battle: anytype, _: Player, _: *State, options: anytype) !void {
2193
+ return weather(battle, .Rain, options);
2194
+ }
2195
+
2196
+ pub fn rapidSpin(battle: anytype, player: Player, _: *State, options: anytype) !void {
2197
+ var side = battle.side(player);
2198
+
2199
+ if (side.active.volatiles.LeechSeed) {
2200
+ try options.log.end(.{ battle.active(player), .LeechSeedFrom });
2201
+ side.active.volatiles.LeechSeed = false;
2202
+ }
2203
+
2204
+ if (side.conditions.Spikes) {
2205
+ try options.log.sideend(.{ player, protocol.Side.Spikes, battle.active(player) });
2206
+ side.conditions.Spikes = false;
2207
+ }
2208
+
2209
+ if (side.active.volatiles.bind.duration > 0) {
2210
+ const reason = @intFromEnum(End.Bind) + side.active.volatiles.bind.reason - 1;
2211
+ try options.log.end(.{ battle.active(player), @as(End, @enumFromInt(reason)) });
2212
+ side.active.volatiles.bind = .{};
2213
+ }
2214
+ }
2215
+
2216
+ pub fn recoil(battle: anytype, player: Player, state: *State, options: anytype) !void {
2217
+ var side = battle.side(player);
2218
+ var stored = side.stored();
2219
+ const ident = battle.active(player);
2220
+
2221
+ assert(state.damage > 0);
2222
+
2223
+ const damage: i16 = @intCast(@max(state.damage / 4, 1));
2224
+ stored.hp = @intCast(@max(@as(i16, @intCast(stored.hp)) - damage, 0));
2225
+
2226
+ try options.log.damage(.{ ident, stored, .RecoilOf, battle.active(player.foe()) });
2227
+ }
2228
+
2229
+ pub fn reversal(battle: anytype, player: Player, state: *State, options: anytype) !void {
2230
+ const stored = battle.side(player).stored();
2231
+
2232
+ // Pokémon Showdown Gen II implementation incorrectly inherits Gen IV's table instead
2233
+ state.bp = if (showdown) power: {
2234
+ const x = @max(1, stored.hp * 64 / stored.stats.hp);
2235
+ if (x < 2) break :power 200;
2236
+ if (x < 6) break :power 150;
2237
+ if (x < 13) break :power 100;
2238
+ if (x < 22) break :power 80;
2239
+ if (x < 43) break :power 40;
2240
+ break :power 20;
2241
+ } else power: {
2242
+ const x = @max(1, stored.hp * 48 / stored.stats.hp);
2243
+ if (x < 1) break :power 200;
2244
+ if (x < 4) break :power 150;
2245
+ if (x < 9) break :power 100;
2246
+ if (x < 16) break :power 80;
2247
+ if (x < 32) break :power 40;
2248
+ break :power 20;
2249
+ };
2250
+
2251
+ try calcDamage(battle, player, state, options);
2252
+ }
2253
+
2254
+ pub const rollout = struct {
2255
+ pub fn check(battle: anytype, player: Player, _: *State, _: anytype) !void {
2256
+ var side = battle.side(player);
2257
+
2258
+ if (!side.active.volatiles.Rollout) {
2259
+ side.active.volatiles.attacks = 0;
2260
+ } else {
2261
+ // TODO SkipToBattleCommand(doturn_command)
2262
+ }
2263
+ }
2264
+
2265
+ pub fn power(battle: anytype, player: Player, state: *State, _: anytype) !void {
2266
+ var side = battle.side(player);
2267
+
2268
+ if (Status.is(side.stored().status, .SLP)) return;
2269
+
2270
+ if (side.active.volatiles.attacks > 0) {
2271
+ // TODO set wSomeoneIsRampaging
2272
+ }
2273
+
2274
+ if (state.miss) {
2275
+ side.active.volatiles.Rollout = false;
2276
+ return;
2277
+ }
2278
+
2279
+ assert(side.active.volatiles.attacks < 5);
2280
+ side.active.volatiles.attacks += 1;
2281
+ side.active.volatiles.Rollout = side.active.volatiles.attacks != 5;
2282
+
2283
+ if (side.active.volatiles.DefenseCurl) state.damage *|= 2;
2284
+ }
2285
+ };
2286
+
2287
+ pub fn sandstorm(battle: anytype, player: Player, _: *State, options: anytype) !void {
2288
+ if (battle.field.weather != .Sandstorm) return weather(battle, .Sandstorm, options);
2289
+ return options.log.fail(.{ battle.active(player), .None });
2290
+ }
2291
+
2292
+ pub fn safeguard(battle: anytype, player: Player, _: *State, options: anytype) !void {
2293
+ return screens(battle, player, "Safeguard", "safeguard", options);
2294
+ }
2295
+
2296
+ pub fn reflect(battle: anytype, player: Player, _: *State, options: anytype) !void {
2297
+ return screens(battle, player, "Reflect", "reflect", options);
2298
+ }
2299
+
2300
+ pub fn lightScreen(battle: anytype, player: Player, _: *State, options: anytype) !void {
2301
+ return screens(battle, player, "LightScreen", "light_screen", options);
2302
+ }
2303
+
2304
+ fn screens(
2305
+ battle: anytype,
2306
+ player: Player,
2307
+ comptime key: []const u8,
2308
+ comptime value: []const u8,
2309
+ options: anytype,
2310
+ ) !void {
2311
+ var side = battle.side(player);
2312
+
2313
+ if (@field(side.conditions, key)) {
2314
+ return options.log.fail(.{ battle.active(player), .None });
2315
+ }
2316
+
2317
+ @field(side.conditions, key) = true;
2318
+ @field(side.conditions, value) = 5;
2319
+ try options.log.sidestart(.{ player, @field(protocol.Side, key) });
2320
+ }
2321
+
2322
+ pub fn sketch(battle: anytype, player: Player, _: *State, options: anytype) !void {
2323
+ var side = battle.side(player);
2324
+
2325
+ side.last_used_move = .None;
2326
+ side.active.volatiles.dirty = false;
2327
+
2328
+ if (showdown) {
2329
+ // yes, actually "Splash". '|nothing' gets blindly mapped to '|-activate||move:Splash'
2330
+ try options.log.activate(.{ battle.active(player), .Splash });
2331
+ } else {
2332
+ try options.log.fail(.{ battle.active(player), .None });
2333
+ }
2334
+ }
2335
+
2336
+ pub fn sleep(battle: anytype, player: Player, state: *State, options: anytype) !void {
2337
+ var foe = battle.foe(player);
2338
+ var foe_stored = foe.stored();
2339
+ const foe_ident = battle.active(player.foe());
2340
+
2341
+ if (Status.any(foe_stored.status)) {
2342
+ return options.log.fail(.{
2343
+ foe_ident,
2344
+ if (Status.is(foe_stored.status, .SLP)) Fail.Sleep else Fail.None,
2345
+ });
2346
+ }
2347
+
2348
+ if (foe.active.volatiles.Substitute) {
2349
+ return options.log.activate(.{ foe_ident, .SubstituteBlock, state.move });
2350
+ }
2351
+
2352
+ // Sleep Clause Mod
2353
+ if (showdown) {
2354
+ for (foe.pokemon) |p| {
2355
+ if (Status.is(p.status, .SLP) and !Status.is(p.status, .EXT)) return;
2356
+ }
2357
+ }
2358
+
2359
+ foe_stored.status = Status.slp(Rolls.sleepDuration(battle, player, options));
2360
+ try options.log.status(.{ foe_ident, foe_stored.status, .From, state.move });
2361
+ }
2362
+
2363
+ pub fn sleepTalk(battle: anytype, player: Player, state: *State, options: anytype) !void {
2364
+ const side = battle.side(player);
2365
+
2366
+ if (!Status.is(side.stored().status, .SLP)) {
2367
+ return if (!showdown) try options.log.fail(.{ battle.active(player), .None });
2368
+ }
2369
+
2370
+ var n: u3 = 0;
2371
+ for (side.active.moves, 0..) |m, i| {
2372
+ if (state.mslot - 1 != i and Move.get(m.id).extra.sleep_talk) n += 1;
2373
+ }
2374
+ if (n == 0) return options.log.fail(.{ battle.active(player), .None });
2375
+
2376
+ _ = try Rolls.sleepTalk(battle, player, n, state.mslot, options); // TODO
2377
+ }
2378
+
2379
+ pub fn snore(battle: anytype, player: Player, state: *State, options: anytype) !bool {
2380
+ if (Status.is(battle.side(player).stored().status, .SLP)) return true;
2381
+ state.damage = 0;
2382
+ state.miss = true; // TODO is this necessary?
2383
+ if (!showdown) try options.log.fail(.{ battle.active(player), .None });
2384
+ return false;
2385
+ }
2386
+
2387
+ pub fn spikes(battle: anytype, player: Player, _: *State, options: anytype) !void {
2388
+ var foe = battle.foe(player);
2389
+ if (foe.conditions.Spikes) return options.log.fail(.{ battle.active(player), .None });
2390
+
2391
+ foe.conditions.Spikes = true;
2392
+ try options.log.sidestart(.{ player.foe(), protocol.Side.Spikes });
2393
+ }
2394
+
2395
+ pub fn spite(battle: anytype, player: Player, state: *State, options: anytype) !void {
2396
+ _ = .{ battle, player, state, options }; // TODO
2397
+ // var foe = battle.foe(player);
2398
+
2399
+ // if (state.miss) return options.log.fail(.{ battle.active(player), .None });
2400
+
2401
+ // const last = foe.lastMove(false);
2402
+ // if (showdown) {
2403
+ // const roll = try Rolls.spite(battle, player, options);
2404
+ // } else {
2405
+ // if (last != .None) {}
2406
+ // }
2407
+ }
2408
+
2409
+ pub fn splash(battle: anytype, player: Player, _: *State, options: anytype) !void {
2410
+ try options.log.activate(.{ battle.active(player), .Splash });
2411
+ }
2412
+
2413
+ pub fn substitute(battle: anytype, player: Player, _: *State, options: anytype) !void {
2414
+ var side = battle.side(player);
2415
+ if (side.active.volatiles.Substitute) {
2416
+ return options.log.fail(.{ battle.active(player), .Substitute });
2417
+ }
2418
+
2419
+ assert(side.stored().stats.hp <= 1023);
2420
+ const hp: u8 = @intCast(side.stored().stats.hp / 4);
2421
+
2422
+ if (hp == 0 or side.stored().hp <= hp) {
2423
+ return options.log.fail(.{ battle.active(player), .Weak });
2424
+ }
2425
+
2426
+ side.stored().hp -= hp;
2427
+ side.active.volatiles.substitute = hp;
2428
+ side.active.volatiles.Substitute = true;
2429
+ side.active.volatiles.bind = .{};
2430
+ try options.log.start(.{ battle.active(player), .Substitute });
2431
+ try options.log.damage(.{ battle.active(player), side.stored(), .None });
2432
+ }
2433
+
2434
+ pub fn sunnyDay(battle: anytype, _: Player, _: *State, options: anytype) !void {
2435
+ return weather(battle, .Sun, options);
2436
+ }
2437
+
2438
+ fn weather(battle: anytype, w: Weather, options: anytype) !void {
2439
+ battle.field.weather = w;
2440
+ battle.field.weather_duration = 5;
2441
+ try options.log.weather(.{ w, protocol.Weather.None });
2442
+ }
2443
+
2444
+ pub fn teleport(battle: anytype, player: Player, _: *State, options: anytype) !void {
2445
+ if (showdown) return;
2446
+
2447
+ try options.log.fail(.{ battle.active(player), .None });
2448
+ try options.log.laststill(.{});
2449
+ }
2450
+
2451
+ pub fn thief(battle: anytype, player: Player, state: *State, options: anytype) !void {
2452
+ const side = battle.side(player);
2453
+ const foe = battle.foe(player);
2454
+
2455
+ if (side.stored().item != .None or foe.stored().item == .None) return;
2456
+ // Pokémon Showdown incorrectly allows you steal Mail
2457
+ if (!showdown and foe.stored().item.isMail()) return;
2458
+ if (!state.proc) return;
2459
+
2460
+ side.stored().item = foe.stored().item;
2461
+ foe.stored().item = .None;
2462
+
2463
+ try options.log.item(.{
2464
+ battle.active(player),
2465
+ side.stored().item,
2466
+ battle.active(player.foe()),
2467
+ });
2468
+ }
2469
+
2470
+ pub fn thrashing(battle: anytype, player: Player, _: *State, options: anytype) !void {
2471
+ var side = battle.side(player);
2472
+ if (Status.is(side.stored().status, .SLP)) return;
2473
+
2474
+ assert(!side.active.volatiles.Thrashing);
2475
+ side.active.volatiles.Thrashing = true;
2476
+ side.active.volatiles.attacks = Rolls.attackingDuration(battle, player, options);
2477
+ // TODO wSomeoneIsRampaging = true;
2478
+ }
2479
+
2480
+ pub fn transform(battle: anytype, player: Player, _: *State, options: anytype) !void {
2481
+ var side = battle.side(player);
2482
+ const foe = battle.foe(player);
2483
+ const foe_ident = battle.active(player.foe());
2484
+
2485
+ side.last_used_move = .None;
2486
+ side.active.volatiles.dirty = false;
2487
+
2488
+ if (foe.active.volatiles.Transform) {
2489
+ return options.log.fail(.{ battle.active(player), .None });
2490
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2491
+ if (!showdown) return options.log.fail(.{ battle.active(player), .None });
2492
+ try options.log.lastmiss(.{});
2493
+ return options.log.miss(.{battle.active(player)});
2494
+ }
2495
+
2496
+ side.active.volatiles.Transform = true;
2497
+ side.active.volatiles.transform = foe_ident.int();
2498
+ side.active.volatiles.disable = .{};
2499
+
2500
+ // HP is not copied by Transform
2501
+ side.active.stats.atk = foe.active.stats.atk;
2502
+ side.active.stats.def = foe.active.stats.def;
2503
+ side.active.stats.spe = foe.active.stats.spe;
2504
+ side.active.stats.spa = foe.active.stats.spa;
2505
+ side.active.stats.spd = foe.active.stats.spd;
2506
+
2507
+ side.active.species = foe.active.species;
2508
+ side.active.types = foe.active.types;
2509
+ side.active.boosts = foe.active.boosts;
2510
+ for (foe.active.moves, 0..) |m, i| {
2511
+ side.active.moves[i].id = m.id;
2512
+ side.active.moves[i].pp = if (m.id != .None) if (m.id == .Sketch) 1 else 5 else 0;
2513
+ }
2514
+
2515
+ try options.log.transform(.{ battle.active(player), foe_ident });
2516
+ }
2517
+
2518
+ pub fn triAttack(battle: anytype, player: Player, state: *State, options: anytype) !void {
2519
+ // FIXME only commit effectchance and triattack rolls if actually does something...
2520
+ try effectChance(battle, player, state, options);
2521
+ if (state.proc) {
2522
+ try switch (try Rolls.triAttack(battle, player, options)) {
2523
+ .PAR => paralyzeChance(battle, player, state, options),
2524
+ .FRZ => freezeChance(battle, player, state, options),
2525
+ .BRN => burnChance(battle, player, state, options),
2526
+ };
2527
+ } else if (!showdown) battle.rng.advance(1);
2528
+ }
2529
+
2530
+ pub fn tripleKick(battle: anytype, player: Player, state: *State, options: anytype) !void {
2531
+ _ = .{ battle, player, state, options }; // TODO
2532
+ }
2533
+
2534
+ const STAT_UP_REASONS =
2535
+ [_]Boost{ .Attack, .Defense, .Speed, .SpecialAttack, .SpecialDefense };
2536
+
2537
+ pub fn allStatUpChance(battle: anytype, player: Player, state: *State, options: anytype) !void {
2538
+ var side = battle.side(player);
2539
+
2540
+ const stats = &side.active.stats;
2541
+ const boosts = &side.active.boosts;
2542
+
2543
+ if (!state.proc) return;
2544
+ inline for (STATS, STAT_UP_REASONS) |s, r| {
2545
+ assert(@field(boosts, s) >= -6 and @field(boosts, s) <= 6);
2546
+ if (@field(boosts, s) == 6 or @field(stats, s) == MAX_STAT_VALUE) {
2547
+ try options.log.boost(.{ battle.active(player), r, 0 });
2548
+ } else {
2549
+ try boostStat(battle, side, stats, boosts, s, 1);
2550
+ try options.log.boost(.{ battle.active(player), r, 1 });
2551
+ }
2552
+ }
2553
+ }
2554
+
2555
+ pub fn boost(battle: anytype, player: Player, state: *State, options: anytype) !void {
2556
+ var log = options.log;
2557
+ var side = battle.side(player);
2558
+ const ident = battle.active(player);
2559
+
2560
+ if (state.miss) return log.fail(.{ ident, .None });
2561
+
2562
+ const stats = &side.active.stats;
2563
+ var boosts = &side.active.boosts;
2564
+
2565
+ const move = Move.get(state.move);
2566
+ switch (move.effect) {
2567
+ .AttackUp1, .AttackUp2, .Rage, .Swagger => {
2568
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2569
+ if (boosts.atk == 6 or stats.atk == MAX_STAT_VALUE) {
2570
+ return log.fail(.{ ident, .None });
2571
+ }
2572
+ const n: u2 = if (move.effect == .AttackUp2 or move.effect == .Swagger) 2 else 1;
2573
+ try boostStat(battle, side, stats, boosts, "atk", n);
2574
+ const reason = if (showdown and move.effect == .Rage) Boost.Rage else Boost.Attack;
2575
+ try log.boost(.{ ident, reason, n });
2576
+ },
2577
+ .DefenseUp1, .DefenseUp2, .SkullBash => {
2578
+ assert(boosts.def >= -6 and boosts.def <= 6);
2579
+ if (boosts.def == 6 or stats.def == MAX_STAT_VALUE) {
2580
+ return log.fail(.{ ident, .None });
2581
+ }
2582
+ const n: u2 = if (move.effect == .DefenseUp2) 2 else 1;
2583
+ try boostStat(battle, side, stats, boosts, "def", n);
2584
+ try log.boost(.{ ident, .Defense, n });
2585
+ },
2586
+ .SpeedUp2 => {
2587
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2588
+ if (boosts.spe == 6 or stats.spe == MAX_STAT_VALUE) {
2589
+ return log.fail(.{ ident, .None });
2590
+ }
2591
+ try boostStat(battle, side, stats, boosts, "spe", 2);
2592
+ try log.boost(.{ ident, .Speed, 2 });
2593
+ },
2594
+ .SpAtkUp1 => {
2595
+ assert(boosts.spa >= -6 and boosts.spa <= 6);
2596
+ if (boosts.spa == 6 or stats.spa == MAX_STAT_VALUE) {
2597
+ return log.fail(.{ ident, .None });
2598
+ }
2599
+ try boostStat(battle, side, stats, boosts, "spa", 1);
2600
+ try log.boost(.{ ident, .SpecialAttack, 1 });
2601
+ },
2602
+ .SpDefUp2 => {
2603
+ assert(boosts.spd >= -6 and boosts.spd <= 6);
2604
+ if (boosts.spd == 6 or stats.spd == MAX_STAT_VALUE) {
2605
+ return log.fail(.{ ident, .None });
2606
+ }
2607
+ try boostStat(battle, side, stats, boosts, "spd", 2);
2608
+ try log.boost(.{ ident, .SpecialDefense, 2 });
2609
+ },
2610
+ .EvasionUp1 => {
2611
+ assert(boosts.evasion >= -6 and boosts.evasion <= 6);
2612
+ if (boosts.evasion == 6) return log.fail(.{ ident, .None });
2613
+ boosts.evasion = @intCast(@min(6, @as(i8, boosts.evasion) + 1));
2614
+ try log.boost(.{ ident, .Evasion, 1 });
2615
+ if (state.move == .Minimize) side.active.volatiles.minimized = true;
2616
+ },
2617
+ else => unreachable,
2618
+ }
2619
+ }
2620
+
2621
+ pub fn unboost(battle: anytype, player: Player, state: *State, options: anytype) !void {
2622
+ var log = options.log;
2623
+ var foe = battle.foe(player);
2624
+ const foe_ident = battle.active(player.foe());
2625
+
2626
+ if (foe.active.volatiles.Mist) {
2627
+ try log.activate(.{ foe_ident, .Mist });
2628
+ return log.fail(.{ foe_ident, .None });
2629
+ }
2630
+
2631
+ const fail = foe.active.volatiles.Substitute or state.miss or !state.proc;
2632
+
2633
+ const stats = &foe.active.stats;
2634
+ var boosts = &foe.active.boosts;
2635
+
2636
+ const move = Move.get(state.move);
2637
+ const none: Fail = .None;
2638
+ switch (move.effect) {
2639
+ .AttackDown1, .AttackDown2, .AttackDownChance => {
2640
+ assert(boosts.atk >= -6 and boosts.atk <= 6);
2641
+ if (fail or boosts.atk == -6) {
2642
+ return if (move.effect != .AttackDownChance) try log.fail(.{ foe_ident, none });
2643
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2644
+ try options.log.lastmiss(.{});
2645
+ return options.log.miss(.{battle.active(player)});
2646
+ } else if (stats.atk == 1) {
2647
+ return if (move.effect != .AttackDownChance) try log.fail(.{ foe_ident, none });
2648
+ }
2649
+ const n: u2 = if (move.effect == .AttackDown2) 2 else 1;
2650
+ try unboostStat(battle, foe, stats, boosts, "atk", n);
2651
+ try log.boost(.{ foe_ident, .Attack, -@as(i8, n) });
2652
+ },
2653
+ .DefenseDown1, .DefenseDown2, .DefenseDownChance => {
2654
+ assert(boosts.def >= -6 and boosts.def <= 6);
2655
+ if (fail or boosts.def == -6) {
2656
+ if (move.effect != .DefenseDownChance) try log.fail(.{ foe_ident, none });
2657
+ return;
2658
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2659
+ try options.log.lastmiss(.{});
2660
+ return options.log.miss(.{battle.active(player)});
2661
+ } else if (stats.def == 1) {
2662
+ if (move.effect != .DefenseDownChance) try log.fail(.{ foe_ident, none });
2663
+ return;
2664
+ }
2665
+ const n: u2 = if (move.effect == .DefenseDown2) 2 else 1;
2666
+ try unboostStat(battle, foe, stats, boosts, "def", n);
2667
+ try log.boost(.{ foe_ident, .Defense, -@as(i8, n) });
2668
+ },
2669
+ .SpeedDown1, .SpeedDown2, .SpeedDownChance => {
2670
+ assert(boosts.spe >= -6 and boosts.spe <= 6);
2671
+ if (fail or boosts.spe == -6) {
2672
+ return if (move.effect != .SpeedDownChance) try log.fail(.{ foe_ident, none });
2673
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2674
+ try options.log.lastmiss(.{});
2675
+ return options.log.miss(.{battle.active(player)});
2676
+ } else if (stats.spe == 1) {
2677
+ return if (move.effect != .SpeedDownChance) try log.fail(.{ foe_ident, none });
2678
+ }
2679
+ const n: u2 = if (move.effect == .SpeedDown2) 2 else 1;
2680
+ try unboostStat(battle, foe, stats, boosts, "spe", n);
2681
+ try log.boost(.{ foe_ident, .Speed, -@as(i8, n) });
2682
+ },
2683
+ .SpDefDownChance => {
2684
+ assert(boosts.spd >= -6 and boosts.spd <= 6);
2685
+ if (fail or boosts.spd == -6) return;
2686
+ if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2687
+ try options.log.lastmiss(.{});
2688
+ return options.log.miss(.{battle.active(player)});
2689
+ } else if (stats.spd == 1) return;
2690
+ try unboostStat(battle, foe, stats, boosts, "spd", 1);
2691
+ try log.boost(.{ foe_ident, .SpecialDefense, -1 });
2692
+ },
2693
+ .AccuracyDown1, .AccuracyDownChance => {
2694
+ assert(boosts.accuracy >= -6 and boosts.accuracy <= 6);
2695
+ if (fail or boosts.accuracy == -6) {
2696
+ if (move.effect != .AccuracyDownChance) try log.fail(.{ foe_ident, none });
2697
+ return;
2698
+ } else if (foe.active.volatiles.Flying or foe.active.volatiles.Underground) {
2699
+ try options.log.lastmiss(.{});
2700
+ return options.log.miss(.{battle.active(player)});
2701
+ }
2702
+ boosts.accuracy = @intCast(@max(-6, @as(i8, boosts.accuracy) - 1));
2703
+ try log.boost(.{ foe_ident, .Accuracy, -1 });
2704
+ },
2705
+ else => unreachable,
2706
+ }
2707
+ }
2708
+ };
2709
+
2710
+ fn unmodifiedStats(battle: anytype, side: *Side) *Stats(u16) {
2711
+ if (!side.active.volatiles.Transform) return &side.stored().stats;
2712
+ const id = ID.from(side.active.volatiles.transform);
2713
+ return &battle.side(id.player).pokemon[id.id - 1].stats;
2714
+ }
2715
+
2716
+ fn recomputeStats(battle: anytype, side: *Side) void {
2717
+ const stats = unmodifiedStats(battle, side);
2718
+ inline for (STATS) |s| {
2719
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(side.active.boosts, s)) + 6))];
2720
+ const val = @field(stats, s) * mod[0] / mod[1];
2721
+ @field(side.active.stats, s) = @max(1, @min(MAX_STAT_VALUE, val));
2722
+ }
2723
+ }
2724
+
2725
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
2726
+ if (Status.is(status, .PAR)) {
2727
+ stats.spe = @max(stats.spe / 4, 1);
2728
+ } else if (Status.is(status, .BRN)) {
2729
+ stats.atk = @max(stats.atk / 2, 1);
2730
+ }
2731
+ }
2732
+
2733
+ fn boostStat(
2734
+ battle: anytype,
2735
+ side: *Side,
2736
+ stats: *Stats(u16),
2737
+ boosts: *Boosts,
2738
+ comptime s: []const u8,
2739
+ n: u2,
2740
+ ) !void {
2741
+ @field(boosts, s) = @intCast(@min(6, @as(i8, @field(boosts, s)) + n));
2742
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(boosts, s)) + 6))];
2743
+ const stat = @field(unmodifiedStats(battle, side), s);
2744
+ @field(stats, s) = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2745
+ if (comptime std.mem.eql(u8, s, "atk")) {
2746
+ if (Status.is(side.stored().status, .BRN)) {
2747
+ @field(stats, s) = @max(@field(stats, s) / 2, 1);
2748
+ }
2749
+ } else if (comptime std.mem.eql(u8, s, "spe")) {
2750
+ if (Status.is(side.stored().status, .PAR)) {
2751
+ @field(stats, s) = @max(@field(stats, s) / 4, 1);
2752
+ }
2753
+ }
2754
+ }
2755
+
2756
+ fn unboostStat(
2757
+ battle: anytype,
2758
+ side: *Side,
2759
+ stats: *Stats(u16),
2760
+ boosts: *Boosts,
2761
+ comptime s: []const u8,
2762
+ n: u2,
2763
+ ) !void {
2764
+ @field(boosts, s) = @intCast(@max(-6, @as(i8, @field(boosts, s)) - n));
2765
+ const mod = STAT_BOOSTS[@as(u4, @intCast(@as(i8, @field(boosts, s)) + 6))];
2766
+ const stat = @field(unmodifiedStats(battle, side), s);
2767
+ @field(stats, s) = @max(1, stat * mod[0] / mod[1]);
2768
+ if (comptime std.mem.eql(u8, s, "atk")) {
2769
+ if (Status.is(side.stored().status, .BRN)) {
2770
+ @field(stats, s) = @max(@field(stats, s) / 2, 1);
2771
+ }
2772
+ } else if (comptime std.mem.eql(u8, s, "spe")) {
2773
+ if (Status.is(side.stored().status, .PAR)) {
2774
+ @field(stats, s) = @max(@field(stats, s) / 4, 1);
2775
+ }
2776
+ }
2777
+ }
2778
+
2779
+ fn isForced(active: anytype) bool {
2780
+ return active.volatiles.Recharging or active.volatiles.Rage or
2781
+ active.volatiles.Thrashing or active.volatiles.Charging or
2782
+ active.volatiles.Rollout;
2783
+ }
2784
+
2785
+ fn convertible(active: ActivePokemon, m: Move) bool {
2786
+ if (m == .None) return false;
2787
+ const t = Move.get(m).type;
2788
+ return t != .@"???" and !active.types.includes(t);
2789
+ }
2790
+
2791
+ pub const Rolls = struct {
2792
+ fn speedTie(battle: anytype, options: anytype) !bool {
2793
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
2794
+ player == .P1
2795
+ else if (showdown)
2796
+ battle.rng.range(u8, 0, 2) == 0
2797
+ else
2798
+ battle.rng.next() < Gen12.percent(50) + 1;
2799
+
2800
+ try options.chance.speedTie(p1);
2801
+ return p1;
2802
+ }
2803
+
2804
+ fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
2805
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
2806
+ val == .true
2807
+ else if (showdown)
2808
+ battle.rng.chance(u8, 60, 256)
2809
+ else
2810
+ battle.rng.next() < 60;
2811
+
2812
+ try options.chance.quickClaw(player, qkc);
2813
+ return qkc;
2814
+ }
2815
+
2816
+ fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
2817
+ const ok = if (options.calc.overridden(player, .hit)) |val|
2818
+ val == .true
2819
+ else if (showdown)
2820
+ battle.rng.chance(u8, accuracy, 256)
2821
+ else
2822
+ battle.rng.next() < accuracy;
2823
+
2824
+ try options.chance.hit(player, ok, accuracy);
2825
+ return ok;
2826
+ }
2827
+
2828
+ fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
2829
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
2830
+ val == .true
2831
+ else if (showdown)
2832
+ battle.rng.chance(u8, rate, 256)
2833
+ else
2834
+ battle.rng.next() < rate;
2835
+
2836
+ try options.chance.criticalHit(player, crit, rate);
2837
+ return crit;
2838
+ }
2839
+
2840
+ fn damage(battle: anytype, player: Player, options: anytype) !u8 {
2841
+ const roll = if (options.calc.overridden(player, .damage)) |val|
2842
+ val
2843
+ else roll: {
2844
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
2845
+ while (true) {
2846
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
2847
+ if (r >= 217) break :roll r;
2848
+ }
2849
+ };
2850
+
2851
+ assert(roll >= 217 and roll <= 255);
2852
+ try options.chance.damage(player, roll);
2853
+ return roll;
2854
+ }
2855
+
2856
+ fn confused(battle: anytype, player: Player, options: anytype) !bool {
2857
+ const cfz = if (options.calc.overridden(player, .confused)) |val|
2858
+ val == .true
2859
+ else if (showdown)
2860
+ !battle.rng.chance(u8, 128, 256)
2861
+ else
2862
+ battle.rng.next() >= Gen12.percent(50) + 1;
2863
+
2864
+ try options.chance.confused(player, cfz);
2865
+ return cfz;
2866
+ }
2867
+
2868
+ fn attract(battle: anytype, player: Player, options: anytype) !bool {
2869
+ const cant = if (options.calc.overridden(player, .attract)) |val|
2870
+ val == .true
2871
+ else if (showdown)
2872
+ battle.rng.chance(u8, 1, 2)
2873
+ else
2874
+ battle.rng.next() > Gen12.percent(50) + 1;
2875
+
2876
+ try options.chance.attract(player, cant);
2877
+ return cant;
2878
+ }
2879
+
2880
+ fn paralyzed(battle: anytype, player: Player, options: anytype) !bool {
2881
+ const par = if (options.calc.overridden(player, .paralyzed)) |val|
2882
+ val == .true
2883
+ else if (showdown)
2884
+ battle.rng.chance(u8, 63, 256)
2885
+ else
2886
+ battle.rng.next() < Gen12.percent(25);
2887
+
2888
+ try options.chance.paralyzed(player, par);
2889
+ return par;
2890
+ }
2891
+
2892
+ fn defrost(battle: anytype, player: Player, options: anytype) !bool {
2893
+ const thaw = if (options.calc.overridden(player, .defrost)) |val|
2894
+ val == .true
2895
+ else if (showdown)
2896
+ battle.rng.chance(u8, 25, 256)
2897
+ else
2898
+ battle.rng.next() < Gen12.percent(10);
2899
+
2900
+ try options.chance.defrost(player, thaw);
2901
+ return thaw;
2902
+ }
2903
+
2904
+ fn secondaryChance(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
2905
+ // GLITCH: 100% secondary chance will still fail 1/256 of the time
2906
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
2907
+ val == .true
2908
+ else if (showdown)
2909
+ battle.rng.chance(u8, rate, 256)
2910
+ else
2911
+ battle.rng.next() < rate;
2912
+
2913
+ try options.chance.secondaryChance(player, proc, rate);
2914
+ return proc;
2915
+ }
2916
+
2917
+ fn item(battle: anytype, player: Player, options: anytype) !bool {
2918
+ const proc = if (options.calc.overridden(player, .item)) |val|
2919
+ val == .true
2920
+ else if (showdown)
2921
+ battle.rng.chance(u8, 30, 256)
2922
+ else
2923
+ battle.rng.next() < 30;
2924
+
2925
+ try options.chance.item(player, proc);
2926
+ return proc;
2927
+ }
2928
+
2929
+ fn triAttack(battle: anytype, player: Player, options: anytype) !TriAttack {
2930
+ const status: TriAttack = if (options.calc.overridden(player, .tri_attack)) |val|
2931
+ @enumFromInt(@intFromEnum(val) - 1)
2932
+ else if (showdown)
2933
+ @enumFromInt(battle.rng.range(u2, 0, 2))
2934
+ else loop: {
2935
+ while (true) {
2936
+ const r = std.math.rotr(u8, battle.rng.next(), 4) & 3;
2937
+ if (r != 0) break :loop @enumFromInt(r - 1);
2938
+ }
2939
+ };
2940
+
2941
+ try options.chance.triAttack(player, status);
2942
+ return status;
2943
+ }
2944
+
2945
+ fn present(battle: anytype, player: Player, options: anytype) !u8 {
2946
+ const power = if (options.calc.overridden(player, .present)) |val|
2947
+ (val - 1) * 40
2948
+ else if (showdown) power: {
2949
+ const r = battle.rng.range(u8, 0, 10);
2950
+ if (r < 2) break :power 0;
2951
+ if (r < 6) break :power 40;
2952
+ if (r < 9) break :power 80;
2953
+ break :power 120;
2954
+ } else power: {
2955
+ const r = battle.rng.next();
2956
+ if (r <= Gen12.percent(40)) break :power 40;
2957
+ if (r <= Gen12.percent(70) + 1) break :power 80;
2958
+ if (r <= Gen12.percent(80)) break :power 120;
2959
+ break :power 0;
2960
+ };
2961
+
2962
+ assert(power <= 120);
2963
+ try options.chance.present(player, power);
2964
+ return power;
2965
+ }
2966
+
2967
+ fn magnitude(battle: anytype, player: Player, options: anytype) !u8 {
2968
+ const num: u8 = if (options.calc.overridden(player, .magnitude)) |val|
2969
+ val + 3
2970
+ else if (showdown) num: {
2971
+ const r = battle.rng.range(u8, 0, 100);
2972
+ if (r < 5) break :num 4;
2973
+ if (r < 15) break :num 5;
2974
+ if (r < 35) break :num 6;
2975
+ if (r < 65) break :num 7;
2976
+ if (r < 85) break :num 8;
2977
+ if (r < 95) break :num 9;
2978
+ break :num 10;
2979
+ } else num: {
2980
+ const r = battle.rng.next();
2981
+ if (r <= Gen12.percent(5) + 1) break :num 4;
2982
+ if (r <= Gen12.percent(15)) break :num 5;
2983
+ if (r <= Gen12.percent(35)) break :num 6;
2984
+ if (r <= Gen12.percent(65) + 1) break :num 7;
2985
+ if (r <= Gen12.percent(85) + 1) break :num 8;
2986
+ if (r <= Gen12.percent(95)) break :num 9;
2987
+ break :num 10;
2988
+ };
2989
+
2990
+ assert(num >= 4 and num <= 10);
2991
+ try options.chance.magnitude(player, num);
2992
+ return num;
2993
+ }
2994
+
2995
+ fn tripleKick(battle: anytype, player: Player, options: anytype) !u2 {
2996
+ const hits = if (options.calc.overridden(player, .triple_kick)) |val|
2997
+ val
2998
+ else if (showdown)
2999
+ battle.rng.range(u2, 1, 4)
3000
+ else power: {
3001
+ while (true) {
3002
+ const r = battle.rng.next() & 3;
3003
+ if (r != 0) break :power r - 1;
3004
+ }
3005
+ };
3006
+
3007
+ assert(hits >= 1 and hits <= 3);
3008
+ try options.chance.tripleKick(player, hits);
3009
+ return hits;
3010
+ }
3011
+
3012
+ fn spite(battle: anytype, player: Player, options: anytype) !u8 {
3013
+ const pp = if (options.calc.overridden(player, .spite)) |val|
3014
+ val + 1
3015
+ else if (showdown)
3016
+ battle.rng.range(u8, 2, 6)
3017
+ else
3018
+ (battle.rng.next() & 3) + 2;
3019
+
3020
+ assert(pp >= 2 and pp <= 5);
3021
+ try options.chance.spite(player, pp);
3022
+ return pp;
3023
+ }
3024
+
3025
+ // Conversion 2 can at most choose between 7 types (vs. a Grass-type attack)
3026
+ var CONVERSION_2: [7]Type = [_]Type{.@"???"} ** 7;
3027
+
3028
+ fn conversion2(battle: anytype, player: Player, mtype: Type, options: anytype) !Type {
3029
+ var i: u8 = 0;
3030
+ const neutral = @intFromEnum(Effectiveness.Neutral);
3031
+ assert(mtype != .@"???");
3032
+ const ty: Type = if (options.calc.overridden(player, .conversion_2)) |val|
3033
+ @enumFromInt(@intFromEnum(val) - 1)
3034
+ else if (showdown) ty: {
3035
+ for (Type.SHOWDOWN) |t| {
3036
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
3037
+ CONVERSION_2[i] = t;
3038
+ i += 1;
3039
+ }
3040
+ }
3041
+ assert(i > 0 and i <= 7);
3042
+ break :ty CONVERSION_2[battle.rng.range(u8, 0, i)];
3043
+ } else ty: {
3044
+ while (true) {
3045
+ const r = battle.rng.next() & 0b11111;
3046
+ if (r == 6) continue; // BIRD
3047
+ if (r > 9 and r < 20) continue; // UNUSED_TYPES
3048
+ if (r > 27) continue; // TYPES_END
3049
+
3050
+ const t = Type.conversion2(r);
3051
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
3052
+ break :ty t;
3053
+ }
3054
+ }
3055
+ };
3056
+
3057
+ assert(ty != .@"???");
3058
+ try options.chance.conversion2(player, ty, mtype, i);
3059
+ return ty;
3060
+ }
3061
+
3062
+ fn protect(battle: anytype, player: Player, count: u8, options: anytype) !bool {
3063
+ assert(count <= 8);
3064
+ const num = if (count == 8) 0 else @as(u8, 255) >> @intCast(count);
3065
+
3066
+ const ok = if (options.calc.overridden(player, .protect)) |val|
3067
+ val == .true
3068
+ else if (showdown)
3069
+ battle.rng.chance(u8, num, 255)
3070
+ else protected: {
3071
+ while (true) {
3072
+ const r = battle.rng.next();
3073
+ if (r != 0) break :protected !(num <= r - 1);
3074
+ }
3075
+ };
3076
+
3077
+ try options.chance.protect(player, num, ok);
3078
+ return ok;
3079
+ }
3080
+
3081
+ fn conversion(battle: anytype, player: Player, n: u4, options: anytype) !Type {
3082
+ assert(n > 0);
3083
+
3084
+ const active = battle.side(player).active;
3085
+ const moves = active.moves;
3086
+
3087
+ // TODO: consider throwing error instead of rerolling?
3088
+ const overridden = if (options.calc.overridden(player, .move_slot)) |val|
3089
+ if (convertible(active, moves[val - 1].id)) val else null
3090
+ else
3091
+ null;
3092
+
3093
+ const slot: u4 = overridden orelse slot: {
3094
+ if (showdown) {
3095
+ var r = battle.rng.range(u4, 0, n) + 1;
3096
+ var i: usize = 0;
3097
+ while (i < moves.len and r > 0) : (i += 1) {
3098
+ if (convertible(active, moves[i].id)) {
3099
+ r -= 1;
3100
+ if (r == 0) break :slot @intCast(i + 1);
3101
+ }
3102
+ }
3103
+ break :slot @intCast(i + 1);
3104
+ } else {
3105
+ while (true) {
3106
+ const r: u4 = @intCast(battle.rng.next() & 3);
3107
+ if (convertible(active, moves[r].id)) break :slot @intCast(r + 1);
3108
+ }
3109
+ }
3110
+ };
3111
+
3112
+ assert(n >= 1 and n <= 4);
3113
+ assert(slot >= 1 and slot <= 4);
3114
+ try options.chance.moveSlot(player, slot, n);
3115
+ return Move.get(active.move(slot).id).type;
3116
+ }
3117
+
3118
+ fn sleepTalk(battle: anytype, player: Player, n: u4, mslot: u4, options: anytype) !u4 {
3119
+ assert(n > 0);
3120
+
3121
+ const active = battle.side(player).active;
3122
+ const moves = active.moves;
3123
+
3124
+ // TODO: consider throwing error instead of rerolling?
3125
+ const overridden = if (options.calc.overridden(player, .move_slot)) |val|
3126
+ if (val != mslot and Move.get(moves[val - 1].id).extra.sleep_talk) val else null
3127
+ else
3128
+ null;
3129
+
3130
+ const slot: u4 = overridden orelse slot: {
3131
+ if (showdown) {
3132
+ var r = battle.rng.range(u4, 0, n) + 1;
3133
+ var i: usize = 0;
3134
+ while (i < moves.len and r > 0) : (i += 1) {
3135
+ if (i + 1 != mslot and Move.get(moves[i].id).extra.sleep_talk) {
3136
+ r -= 1;
3137
+ if (r == 0) break :slot @intCast(i + 1);
3138
+ }
3139
+ }
3140
+ break :slot @intCast(i + 1);
3141
+ } else {
3142
+ while (true) {
3143
+ const r: u4 = @intCast(battle.rng.next() & 3);
3144
+ if (r + 1 == mslot or !Move.get(moves[r].id).extra.sleep_talk) continue;
3145
+ break :slot @intCast(r + 1);
3146
+ }
3147
+ }
3148
+ };
3149
+
3150
+ assert(n >= 1 and n <= 4);
3151
+ assert(slot >= 1 and slot <= 4);
3152
+ try options.chance.moveSlot(player, slot, n);
3153
+ return slot;
3154
+ }
3155
+
3156
+ fn forceSwitch(
3157
+ battle: anytype,
3158
+ player: Player,
3159
+ slots: []u4,
3160
+ n: u4,
3161
+ options: anytype,
3162
+ ) !u4 {
3163
+ const foe = battle.foe(player);
3164
+
3165
+ assert(slots.len < 5);
3166
+ assert(n > 0 and n <= 6);
3167
+
3168
+ // TODO: consider throwing error instead of rerolling?
3169
+ const overridden = if (options.calc.overridden(player, .force_switch)) |val| val: {
3170
+ for (slots) |slot| if (slot == val) break :val if (foe.get(slot).hp > 0) val else null;
3171
+ break :val null;
3172
+ } else null;
3173
+
3174
+ const slot: u4 = overridden orelse slot: {
3175
+ if (showdown) {
3176
+ break :slot slots[battle.rng.range(u4, 0, @as(u4, @intCast(slots.len)))];
3177
+ } else {
3178
+ while (true) {
3179
+ const r = battle.rng.next() & 7;
3180
+ if (r > n or r == 1) continue;
3181
+ if (foe.get(r).hp > 0) break :slot @intCast(r);
3182
+ }
3183
+ }
3184
+ };
3185
+
3186
+ assert(n >= 1 and n <= 6);
3187
+ assert(slot >= 1 and slot <= 6);
3188
+ try options.chance.forceSwitch(player, slot, n);
3189
+ return slot;
3190
+ }
3191
+
3192
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
3193
+
3194
+ fn multiHit(battle: anytype, player: Player, options: anytype) !u3 {
3195
+ const n: u3 = if (options.calc.overridden(player, .multi_hit)) |val|
3196
+ @intCast(val)
3197
+ else if (showdown)
3198
+ DISTRIBUTION[battle.rng.range(u3, 0, DISTRIBUTION.len)]
3199
+ else n: {
3200
+ const r = (battle.rng.next() & 3);
3201
+ break :n @intCast((if (r < 2) r else battle.rng.next() & 3) + 2);
3202
+ };
3203
+
3204
+ assert(n >= 2 and n <= 5);
3205
+ try options.chance.multiHit(player, n);
3206
+ return n;
3207
+ }
3208
+
3209
+ fn psywave(battle: anytype, player: Player, max: u8, options: anytype) !u8 {
3210
+ const power = if (options.calc.overridden(player, .psywave)) |val|
3211
+ val
3212
+ else if (showdown)
3213
+ battle.rng.range(u8, 1, max)
3214
+ else power: {
3215
+ while (true) {
3216
+ const r = battle.rng.next();
3217
+ if (r != 0 and r < max) break :power r;
3218
+ }
3219
+ };
3220
+
3221
+ assert(power != 0 and power < max);
3222
+ try options.chance.psywave(player, power, max);
3223
+ return power;
3224
+ }
3225
+
3226
+ fn metronome(battle: anytype, player: Player, options: anytype) !Move {
3227
+ const moves = battle.side(player).active.moves;
3228
+
3229
+ var n: u2 = 0;
3230
+ for (moves) |m| {
3231
+ if (m.id == .None) break;
3232
+ if (Move.get(m.id).extra.metronome) n += 1;
3233
+ }
3234
+
3235
+ // TODO: consider throwing error instead of rerolling?
3236
+ const overridden = if (options.calc.overridden(player, .metronome)) |val| val: {
3237
+ for (moves) |m| if (m.id == val) break :val null;
3238
+ break :val val;
3239
+ } else null;
3240
+
3241
+ const move: Move = overridden orelse move: {
3242
+ if (showdown) {
3243
+ var r = battle.rng.range(u8, 0, @as(u8, @intCast(Move.METRONOME.len - n)));
3244
+ for (moves) |m| {
3245
+ if (m.id == .None) break;
3246
+ if (@intFromEnum(m.id) > @intFromEnum(Move.METRONOME[r])) break;
3247
+ if (Move.get(m.id).extra.metronome) r -= 1;
3248
+ }
3249
+ break :move Move.METRONOME[r];
3250
+ } else {
3251
+ outer: while (true) {
3252
+ const r = battle.rng.next();
3253
+ if (r == 0 or r >= Move.size) continue;
3254
+ const selected: Move = @enumFromInt(r);
3255
+ if (!Move.get(selected).extra.metronome) continue;
3256
+ for (moves) |m| if (m.id == selected) continue :outer;
3257
+ break :move selected;
3258
+ }
3259
+ }
3260
+ };
3261
+
3262
+ assert(Move.get(move).extra.metronome);
3263
+ try options.chance.metronome(player, move, n);
3264
+ return move;
3265
+ }
3266
+
3267
+ fn sleepDuration(battle: anytype, player: Player, options: anytype) u3 {
3268
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
3269
+ @intCast(val)
3270
+ else if (showdown)
3271
+ battle.rng.range(u3, 1, 7)
3272
+ else duration: {
3273
+ while (true) {
3274
+ const r = battle.rng.next() & 7;
3275
+ if (r != 0 and r != 7) break :duration @intCast(r);
3276
+ }
3277
+ };
3278
+
3279
+ assert(duration >= 1 and duration <= 6);
3280
+ options.chance.duration(.sleep, player, player.foe(), duration);
3281
+ return duration + 1;
3282
+ }
3283
+
3284
+ fn confusionDuration(battle: anytype, player: Player, self: bool, options: anytype) u3 {
3285
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
3286
+ @intCast(val)
3287
+ else if (showdown)
3288
+ // Pokémon Showdown incorrectly uses the same duration for self-confusion
3289
+ battle.rng.range(u3, 2, 6)
3290
+ else
3291
+ @intCast((battle.rng.next() & if (self) 1 else 3) + 2);
3292
+
3293
+ assert(duration >= 2 and duration <= if (!showdown and self) 3 else 5);
3294
+ options.chance.duration(.confusion, player, if (self) player else player.foe(), duration);
3295
+ return duration;
3296
+ }
3297
+
3298
+ fn disableDuration(battle: anytype, player: Player, options: anytype) u4 {
3299
+ const duration: u4 = if (options.calc.overridden(player, .duration)) |val|
3300
+ @intCast(val)
3301
+ else if (showdown)
3302
+ // Pokémon Showdown incorrectly inherits Generation III's Disable duration
3303
+ battle.rng.range(u4, 2, 6)
3304
+ else duration: {
3305
+ while (true) {
3306
+ const r = battle.rng.next() & 7;
3307
+ if (r != 0) break :duration @intCast(r + 1);
3308
+ }
3309
+ };
3310
+
3311
+ assert(duration >= 2 and duration <= (if (showdown) 5 else 7));
3312
+ options.chance.duration(.disable, player, player.foe(), duration);
3313
+ return duration;
3314
+ }
3315
+
3316
+ fn attackingDuration(battle: anytype, player: Player, options: anytype) u3 {
3317
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
3318
+ @intCast(val)
3319
+ else if (showdown)
3320
+ battle.rng.range(u3, 2, 4)
3321
+ else
3322
+ @intCast((battle.rng.next() & 1) + 2); // BUG: thrash is + 1 not +2
3323
+
3324
+ assert(duration >= 2 and duration <= 3);
3325
+ options.chance.duration(.attacking, player, player, duration);
3326
+ return duration;
3327
+ }
3328
+
3329
+ fn bindingDuration(battle: anytype, player: Player, options: anytype) u3 {
3330
+ const duration: u3 = (if (options.calc.overridden(player, .duration)) |val|
3331
+ @intCast(val)
3332
+ else if (showdown)
3333
+ // TODO: PS does range(3, 6) here which after subtracting 1 is actually 2-4 not 2-5!
3334
+ battle.rng.range(u3, 2, 5)
3335
+ else
3336
+ @intCast(battle.rng.next() & 3 + 2));
3337
+
3338
+ assert(duration >= 2 and duration <= 5);
3339
+ options.chance.duration(.binding, player, player.foe(), duration);
3340
+ return duration + 1;
3341
+ }
3342
+
3343
+ // TODO: consider sharing implementation with bindingDuration
3344
+ fn encoreDuration(battle: anytype, player: Player, options: anytype) u3 {
3345
+ const duration: u3 = (if (options.calc.overridden(player, .duration)) |val|
3346
+ @intCast(val)
3347
+ else if (showdown)
3348
+ battle.rng.range(u3, 2, 6)
3349
+ else
3350
+ @intCast(battle.rng.next() & 3 + 2));
3351
+
3352
+ assert(duration >= 2 and duration <= 5);
3353
+ options.chance.duration(.encore, player, player.foe(), duration);
3354
+ return duration + 1;
3355
+ }
3356
+ };
3357
+
3358
+ test "RNG agreement" {
3359
+ if (!showdown) return;
3360
+ var expected: [256]u32 = undefined;
3361
+ for (0..expected.len) |i| {
3362
+ expected[i] = @intCast(i * 0x1000000);
3363
+ }
3364
+
3365
+ var spe: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3366
+ var qkc: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3367
+ var cfz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3368
+ var atr: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3369
+ var frz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3370
+ var fcb: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
3371
+
3372
+ for (0..expected.len) |i| {
3373
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
3374
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
3375
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
3376
+ try expectEqual(atr.chance(u8, 1, 2), i < Gen12.percent(50) + 1);
3377
+ try expectEqual(frz.chance(u8, 25, 256), i < Gen12.percent(10));
3378
+ try expectEqual(fcb.chance(u8, 30, 256), !(30 <= i));
3379
+ }
3380
+ }
3381
+
3382
+ test "Roll probabilities" {
3383
+ if (showdown) return;
3384
+
3385
+ var present = [4]u8{ 0, 0, 0, 0 };
3386
+ var magnitude = [7]u8{ 0, 0, 0, 0, 0, 0, 0 };
3387
+ for (0..256) |i| {
3388
+ present[
3389
+ if (i <= Gen12.percent(40))
3390
+ 1
3391
+ else if (i <= Gen12.percent(70) + 1)
3392
+ 2
3393
+ else if (i <= Gen12.percent(80))
3394
+ 3
3395
+ else
3396
+ 0
3397
+ ] += 1;
3398
+ magnitude[
3399
+ if (i <= Gen12.percent(5) + 1)
3400
+ 0
3401
+ else if (i <= Gen12.percent(15) + 1)
3402
+ 1
3403
+ else if (i <= Gen12.percent(35))
3404
+ 2
3405
+ else if (i <= Gen12.percent(65) + 1)
3406
+ 3
3407
+ else if (i <= Gen12.percent(85) + 1)
3408
+ 4
3409
+ else if (i <= Gen12.percent(95))
3410
+ 5
3411
+ else
3412
+ 6
3413
+ ] += 1;
3414
+ }
3415
+
3416
+ try expectEqualSlices(u8, &.{ 51, 103, 77, 25 }, &present);
3417
+ try expectEqualSlices(u8, &.{ 14, 26, 50, 77, 51, 25, 13 }, &magnitude);
3418
+ }
3419
+
3420
+ test "Reasons" {
3421
+ const moves = [_]Move{ .Bind, .Wrap, .FireSpin, .Clamp, .Whirlpool };
3422
+ for (moves) |move| {
3423
+ const reason = Move.get(move).extra.protocol - 1;
3424
+
3425
+ const activate: Activate = @enumFromInt(@intFromEnum(Activate.Bind) + reason);
3426
+ try expectEqualStrings(@tagName(move), @tagName(activate));
3427
+
3428
+ const damage: Damage = @enumFromInt(@intFromEnum(Damage.Bind) + reason);
3429
+ try expectEqualStrings(@tagName(move), @tagName(damage));
3430
+
3431
+ const end: End = @enumFromInt(@intFromEnum(End.Bind) + reason);
3432
+ try expectEqualStrings(@tagName(move), @tagName(end));
3433
+ }
3434
+
3435
+ const perish_song = [_]Start{ .PerishSong0, .PerishSong1, .PerishSong2, .PerishSong3 };
3436
+ for (perish_song, 0..) |ps, i| {
3437
+ const reason: Start = @enumFromInt(@intFromEnum(Start.PerishSong0) + i);
3438
+ try expectEqualStrings(@tagName(ps), @tagName(reason));
286
3439
  }
287
3440
  }
288
3441
 
@@ -310,7 +3463,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
310
3463
  .Move => {
311
3464
  const side = battle.side(player);
312
3465
 
313
- var active = &side.active;
3466
+ const active = &side.active;
314
3467
  const stored = side.stored();
315
3468
 
316
3469
  // While players are not given any input options on the cartridge in these cases,
@@ -330,7 +3483,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
330
3483
  }
331
3484
 
332
3485
  var slot: u4 = 2;
333
- while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
3486
+ while (!active.volatiles.Trapped and slot <= 6) : (slot += 1) {
334
3487
  const id = side.order[slot - 1];
335
3488
  if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
336
3489
  out[n] = .{ .type = .Switch, .data = slot };
@@ -364,7 +3517,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
364
3517
  if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
365
3518
  // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
366
3519
  const struggle =
367
- m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
3520
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disable.move == slot);
368
3521
  const s = if (struggle) 0 else slot;
369
3522
  out[n] = .{ .type = .Move, .data = s };
370
3523
  n += 1;
@@ -379,7 +3532,7 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
379
3532
  const m = active.moves[slot - 1];
380
3533
  if (m.id == .None) break;
381
3534
  if (m.pp == 0) continue;
382
- if (active.volatiles.disabled_move == slot) continue;
3535
+ if (active.volatiles.disable.move == slot) continue;
383
3536
  out[n] = .{ .type = .Move, .data = slot };
384
3537
  n += 1;
385
3538
  }