@pkmn/engine 0.1.0-dev.c5fe6d07 → 0.1.0-dev.cdc837af

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