@pkmn/engine 0.1.0-dev.84cc1a02 → 0.1.0-dev.89cc1c98

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