@pkmn/engine 0.1.0-dev.d716e940 → 0.1.0-dev.d952b7c9

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