@pkmn/engine 0.1.0-dev.9a0c07c3 → 0.1.0-dev.9f75c7ae

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