@pkmn/engine 0.1.0-dev.b9fb6eab → 0.1.0-dev.bcb16a6c

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 (57) hide show
  1. package/README.md +98 -59
  2. package/build/pkg/addon.d.ts +7 -0
  3. package/build/pkg/addon.js +112 -0
  4. package/build/pkg/addon.js.map +1 -0
  5. package/build/pkg/data/ids.json +12 -12
  6. package/build/pkg/data/layout.json +25 -3
  7. package/build/pkg/data/protocol.json +69 -12
  8. package/build/pkg/data.d.ts +3 -4
  9. package/build/pkg/data.js +3 -5
  10. package/build/pkg/data.js.map +1 -1
  11. package/build/pkg/gen1.d.ts +5 -4
  12. package/build/pkg/gen1.js +47 -31
  13. package/build/pkg/gen1.js.map +1 -1
  14. package/build/pkg/index.d.ts +15 -12
  15. package/build/pkg/index.js.map +1 -1
  16. package/build/pkg/protocol.d.ts +4 -2
  17. package/build/pkg/protocol.js +60 -39
  18. package/build/pkg/protocol.js.map +1 -1
  19. package/build/test/display.js +400 -0
  20. package/build/test/display.js.map +1 -0
  21. package/build/tools/debug.js +133 -0
  22. package/build/tools/debug.js.map +1 -0
  23. package/build.zig +98 -79
  24. package/package.json +65 -36
  25. package/src/bin/install-pkmn-engine +11 -6
  26. package/src/bin/pkmn-debug +62 -0
  27. package/src/lib/binding/node.zig +47 -142
  28. package/src/lib/binding/wasm.zig +6 -4
  29. package/src/lib/common/battle.zig +17 -0
  30. package/src/lib/common/data.zig +15 -27
  31. package/src/lib/common/debug.zig +21 -11
  32. package/src/lib/common/js.zig +118 -0
  33. package/src/lib/common/optional.zig +69 -0
  34. package/src/lib/common/options.zig +12 -3
  35. package/src/lib/common/protocol.zig +752 -237
  36. package/src/lib/common/rational.zig +353 -0
  37. package/src/lib/common/rng.zig +15 -15
  38. package/src/lib/common/util.zig +12 -0
  39. package/src/lib/gen1/README.md +268 -154
  40. package/src/lib/gen1/calc.zig +426 -0
  41. package/src/lib/gen1/chance.zig +1058 -0
  42. package/src/lib/gen1/data/moves.zig +178 -180
  43. package/src/lib/gen1/data/species.zig +2 -2
  44. package/src/lib/gen1/data/types.zig +5 -5
  45. package/src/lib/gen1/data.zig +78 -64
  46. package/src/lib/gen1/helpers.zig +592 -32
  47. package/src/lib/gen1/mechanics.zig +1020 -658
  48. package/src/lib/gen2/README.md +106 -85
  49. package/src/lib/gen2/data/items.zig +12 -18
  50. package/src/lib/gen2/data/moves.zig +640 -563
  51. package/src/lib/gen2/data/species.zig +1 -1
  52. package/src/lib/gen2/data/types.zig +130 -28
  53. package/src/lib/gen2/data.zig +131 -87
  54. package/src/lib/gen2/helpers.zig +16 -22
  55. package/src/lib/gen2/mechanics.zig +1532 -11
  56. package/src/lib/pkmn.zig +68 -9
  57. package/src/test/display/pkmn.html.tmpl +368 -0
@@ -1,8 +1,9 @@
1
1
  const std = @import("std");
2
2
 
3
+ const pkmn = @import("../pkmn.zig");
4
+
3
5
  const common = @import("../common/data.zig");
4
6
  const DEBUG = @import("../common/debug.zig").print;
5
- const options = @import("../common/options.zig");
6
7
  const protocol = @import("../common/protocol.zig");
7
8
  const rng = @import("../common/rng.zig");
8
9
 
@@ -11,21 +12,27 @@ const data = @import("data.zig");
11
12
  const assert = std.debug.assert;
12
13
 
13
14
  const expectEqual = std.testing.expectEqual;
15
+ const expectEqualSlices = std.testing.expectEqualSlices;
14
16
 
15
17
  const Choice = common.Choice;
16
18
  const ID = common.ID;
17
19
  const Player = common.Player;
18
20
  const Result = common.Result;
19
21
 
20
- const showdown = options.showdown;
22
+ const showdown = pkmn.options.showdown;
21
23
 
24
+ const Activate = protocol.Activate;
25
+ const Cant = protocol.Cant;
22
26
  const Damage = protocol.Damage;
27
+ const End = protocol.End;
23
28
  const Heal = protocol.Heal;
29
+ const Start = protocol.Start;
24
30
 
25
31
  const Gen12 = rng.Gen12;
26
32
 
27
33
  const ActivePokemon = data.ActivePokemon;
28
34
  const Effectiveness = data.Effectiveness;
35
+ const Item = data.Item;
29
36
  const Move = data.Move;
30
37
  const MoveSlot = data.MoveSlot;
31
38
  const Pokemon = data.Pokemon;
@@ -33,21 +40,1535 @@ const Side = data.Side;
33
40
  const Species = data.Species;
34
41
  const Stats = data.Stats;
35
42
  const Status = data.Status;
43
+ const TriAttack = data.TriAttack;
44
+ const Type = data.Type;
45
+ const Types = data.Types;
46
+ const Volatiles = data.Volatiles;
36
47
 
37
- pub fn update(battle: anytype, c1: Choice, c2: Choice, log: anytype) !Result {
38
- _ = battle;
39
- _ = c1;
40
- _ = c2;
41
- _ = log;
48
+ // zig fmt: off
49
+ const STAT_BOOSTS = &[_][2]u8{
50
+ .{ 25, 100 }, // -6
51
+ .{ 28, 100 }, // -5
52
+ .{ 33, 100 }, // -4
53
+ .{ 40, 100 }, // -3
54
+ .{ 50, 100 }, // -2
55
+ .{ 66, 100 }, // -1
56
+ .{ 1, 1 }, // 0
57
+ .{ 15, 10 }, // +1
58
+ .{ 2, 1 }, // +2
59
+ .{ 25, 10 }, // +3
60
+ .{ 3, 1 }, // +4
61
+ .{ 35, 10 }, // +5
62
+ .{ 4, 1 }, // +6
63
+ };
42
64
 
43
- return Result.Default;
65
+ const ACCURACY_BOOSTS = &[_][2]u8{
66
+ .{ 33, 100 }, // -6
67
+ .{ 36, 100 }, // -5
68
+ .{ 43, 100 }, // -4
69
+ .{ 50, 100 }, // -3
70
+ .{ 60, 100 }, // -2
71
+ .{ 75, 100 }, // -1
72
+ .{ 1, 1 }, // 0
73
+ .{ 133, 100 }, // +1
74
+ .{ 166, 100 }, // +2
75
+ .{ 2, 1 }, // +3
76
+ .{ 233, 100 }, // +4
77
+ .{ 133, 50 }, // +5
78
+ .{ 3, 1 }, // +6
79
+ };
80
+
81
+ const CRITICAL_HITS = &[_]u8{
82
+ 256 / 15, // 0
83
+ 256 / 8, // +1
84
+ 256 / 4, // +2
85
+ 256 / 3, // +3
86
+ 256 / 2, // +4
87
+ };
88
+ // zig fmt: on
89
+
90
+ const MAX_STAT_VALUE = 999;
91
+
92
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
93
+
94
+ pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
95
+ assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
96
+ if (battle.turn == 0) return start(battle, options);
97
+
98
+ if (try turnOrder(battle, c1, c2, options) == .P1) {
99
+ if (try doTurn(battle, .P1, c1, .P2, c2, options)) |r| return r;
100
+ } else {
101
+ if (try doTurn(battle, .P2, c2, .P1, c1, options)) |r| return r;
102
+ }
103
+
104
+ return endTurn(battle, options);
44
105
  }
45
106
 
46
- pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
107
+ fn start(battle: anytype, options: anytype) !Result {
108
+ const p1 = battle.side(.P1);
109
+ const p2 = battle.side(.P2);
110
+
111
+ var p1_slot = findFirstAlive(p1);
112
+ assert(!showdown or p1_slot == 1);
113
+ if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
114
+
115
+ var p2_slot = findFirstAlive(p2);
116
+ assert(!showdown or p2_slot == 1);
117
+ if (p2_slot == 0) return Result.Win;
118
+
119
+ try switchIn(battle, .P1, p1_slot, true, options);
120
+ try switchIn(battle, .P2, p2_slot, true, options);
121
+
122
+ return endTurn(battle, options);
123
+ }
124
+
125
+ fn findFirstAlive(side: *const Side) u8 {
126
+ for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.pokemon[i].position;
127
+ return 0;
128
+ }
129
+
130
+ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
131
+ if (choice.type == .Pass) return; // FIXME BATON PASS
132
+
133
+ var side = battle.side(player);
134
+ var volatiles = &side.active.volatiles;
135
+
136
+ // pre-battle menu
137
+ const forced = forced: {
138
+ if (volatiles.Recharging) break :forced true;
139
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
140
+ if (!showdown) {
141
+ volatiles.Flinch = false;
142
+ battle.foe(player).active.volatiles.Flinch = false;
143
+ }
144
+ break :forced (volatiles.Thrashing or volatiles.Charging or volatiles.Rollout);
145
+ };
146
+
147
+ // battle menu
148
+ if (choice.type == .Switch) return;
149
+ assert(choice.type == .Move and (!forced or choice.data == @intFromBool(showdown)));
150
+
151
+ done: {
152
+ if (forced) break :done;
153
+ // pre-move select
154
+ if (volatiles.Encore) {
155
+ // TODO wCurPlayerMove = side.lastMove(true);
156
+ // assert(wCurPlayerMove != .None);
157
+ volatiles.Bide = false; // FIXME wPlayerCharging vs. SUBSTATUS_BIDE?
158
+ const effect = Move.get(.Pound).effect; // TODO
159
+ if (effect != .FuryCutter) volatiles.fury_cutter = false;
160
+ if (effect != .Rage) {
161
+ volatiles.Rage = false;
162
+ volatiles.rage = 0;
163
+ }
164
+ if (effect != .Protect and effect != .Endure) volatiles.protect = 0;
165
+ return;
166
+ }
167
+ if (volatiles.Bide) break :done;
168
+ // move select
169
+ if (choice.data == 0) {
170
+ const struggle = ok: {
171
+ for (side.active.moves, 0..) |move, i| {
172
+ if (move.pp > 0 and volatiles.disabled_move != i + 1) break :ok false;
173
+ }
174
+ break :ok true;
175
+ };
176
+ assert(struggle);
177
+ // TODO wCurPlayerMove = .Struggle;
178
+ } else {
179
+ assert(showdown or side.active.volatiles.disabled_move != choice.data);
180
+ const move = side.active.move(choice.data);
181
+ // You cannot *select* a move with 0 PP
182
+ assert(move.pp != 0);
183
+ // TODO wCurPlayerMove = move.id;
184
+ // battle.lastMove(player).index = @intCast(c.data);
185
+ }
186
+ }
187
+
188
+ volatiles.Rage = false;
189
+ volatiles.rage = 0;
190
+ volatiles.fury_cutter = 0;
191
+ volatiles.protect = 0;
192
+ }
193
+
194
+ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
195
+ var side = battle.side(player);
196
+ var foe = battle.foe(player);
197
+
198
+ var active = &side.active;
199
+ const incoming = side.get(slot);
200
+
201
+ assert(incoming.hp != 0);
202
+ assert(slot != 1 or initial);
203
+
204
+ const out = side.pokemon[0].position;
205
+ side.pokemon[0].position = side.pokemon[slot - 1].position;
206
+ side.pokemon[slot - 1].position = out;
207
+
208
+ side.last_used_move = .None;
209
+ foe.active.volatiles.dirty = true;
210
+
211
+ active.volatiles = .{};
212
+ active.stats = incoming.stats;
213
+ active.moves = incoming.moves;
214
+ active.boosts = .{};
215
+ active.types = incoming.types;
216
+ active.species = incoming.species;
217
+
218
+ statusModify(incoming.status, &active.stats);
219
+
220
+ try options.log.switched(battle.active(player), incoming);
221
+ options.chance.switched(player, side.pokemon[0].position, out);
222
+
223
+ if (side.conditions.Spikes and !active.types.includes(.Flying)) {
224
+ incoming.hp -|= @max(incoming.stats.hp / 8, 1);
225
+ try options.log.damage(battle.active(player), incoming, .Spikes);
226
+ }
227
+ }
228
+
229
+ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
230
+ assert(c1.type != .Pass or c2.type != .Pass);
231
+
232
+ if (c1.type == .Pass) return .P2;
233
+ if (c2.type == .Pass) return .P1;
234
+
235
+ // Pokémon Showdown always rolls for Quick Claw every turn, even if no Pokémon hold Quick Claw
236
+ // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
237
+ const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
238
+
239
+ if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
240
+
241
+ // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
242
+ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
243
+ // > your own screen without waiting for the other player's choice (and their choice will appear
244
+ // > to happen first for them too, unless they attacked in which case your switch happens first)
245
+ // A cartridge-compatible implemention must not advance the RNG so we simply default to P1
246
+ const double_switch = c1.type == .Switch and c2.type == .Switch;
247
+ if (!showdown and double_switch) return .P1;
248
+
249
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
250
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
251
+ if (!showdown or !double_switch) {
252
+ const pri1 = Move.get(m1).priority;
253
+ const pri2 = Move.get(m2).priority;
254
+ if (pri1 != pri2) return if (pri1 > pri2) .P1 else .P2;
255
+
256
+ const qkc1 = battle.side(.P1).stored().item == .QuickClaw;
257
+ const qkc2 = battle.side(.P2).stored().item == .QuickClaw;
258
+ if (!showdown and qkc1 and qkc2) {
259
+ // If both Pokémon have Quick Claw the cartridge checks them in order and exits early if
260
+ // the first one procs, meaning the host has a slightly higher chance of going first
261
+ if (try Rolls.quickClaw(battle, .P1, options)) return .P1;
262
+ if (try Rolls.quickClaw(battle, .P2, options)) return .P2;
263
+ } else if (qkc1) {
264
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P1, options);
265
+ if (proc) return .P1;
266
+ } else if (qkc2) {
267
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P2, options);
268
+ if (proc) return .P2;
269
+ }
270
+ }
271
+
272
+ const spe1 = battle.side(.P1).active.stats.spe;
273
+ const spe2 = battle.side(.P2).active.stats.spe;
274
+ if (spe1 == spe2) {
275
+ // Pokémon Showdown's beforeTurnCallback shenanigans
276
+ if (showdown and !double_switch and hasCallback(m1) and hasCallback(m2)) {
277
+ battle.rng.advance(1);
278
+ }
279
+
280
+ const p1 = try Rolls.speedTie(battle, options);
281
+ if (!showdown) return if (p1) .P1 else .P2;
282
+
283
+ // Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
284
+ // meaning that if a side is locked into a thrashing move and wins the speed tie, it
285
+ // actually uses its priority to simply insert its actual changed action into the queue,
286
+ // causing it to then execute *after* the side which should go second...
287
+ const t1 = battle.side(.P1).active.volatiles.Thrashing;
288
+ const t2 = battle.side(.P2).active.volatiles.Thrashing;
289
+ // If *both* sides are thrashing it really should be another speed tie, but we've patched
290
+ // that out and enforce host ordering of events, so P1 just goes first regardless of who
291
+ // won the original coin flip
292
+ if (t1 and t2) return .P1;
293
+ return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
294
+ }
295
+
296
+ return if (spe1 > spe2) .P1 else .P2;
297
+ }
298
+
299
+ fn hasCallback(m: Move) bool {
300
+ return switch (m) {
301
+ .Counter, .MirrorCoat, .Pursuit => true,
302
+ else => false,
303
+ };
304
+ }
305
+
306
+ fn doTurn(
307
+ battle: anytype,
308
+ player: Player,
309
+ player_choice: Choice,
310
+ foe_player: Player,
311
+ foe_choice: Choice,
312
+ options: anytype,
313
+ ) !?Result {
314
+ assert(player_choice.type != .Pass);
315
+
316
+ const volatiles = &battle.side(player).active.volatiles;
317
+ const foe_volatiles = &battle.foe(player).active.volatiles;
318
+
319
+ volatiles.DestinyBond = false;
320
+ if (try executeMove(battle, player, player_choice, options)) |r| return r;
321
+ foe_volatiles.Protect = false;
322
+ foe_volatiles.Endure = false;
323
+ foe_volatiles.DestinyBond = false;
324
+
325
+ // foe_volatiles.DestinyBond = false;
326
+ if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
327
+ volatiles.Protect = false;
328
+ volatiles.Endure = false;
329
+ volatiles.DestinyBond = false;
330
+
331
+ return null;
332
+ }
333
+
334
+ fn executeMove(battle: anytype, player: Player, choice: Choice, options: anytype) !?Result {
335
+ if (choice.type == .Switch) {
336
+ try switchIn(battle, player, choice.data, false, options);
337
+ return null;
338
+ }
339
+
340
+ assert(choice.type == .Move);
341
+ var mslot: u4 = @intCast(choice.data);
342
+
343
+ // const move = Move.get(side.last_selected_move);
344
+
345
+ // CheckTurn
346
+
347
+ return doMove(battle, player, options, mslot);
348
+ }
349
+
350
+ fn beforeMove(battle: anytype, player: Player, options: anytype) !bool {
351
+ var log = options.log;
352
+ var side = battle.side(player);
353
+ // const foe = battle.foe(player);
354
+ var active = &side.active;
355
+ var stored = side.stored();
356
+ const ident = battle.active(player);
357
+ var volatiles = &active.volatiles;
358
+
359
+ const move = Move.Pound; // TODO
360
+
361
+ if (volatiles.Recharging) {
362
+ volatiles.Recharging = false;
363
+ cantMove(volatiles);
364
+ try log.cant(ident, .Recharge);
365
+ return false;
366
+ }
367
+
368
+ if (Status.is(stored.status, .SLP)) slp: {
369
+ const before = stored.status;
370
+ // Even if the EXT bit is set this will still correctly modify the sleep duration
371
+ // if (options.calc.modify(player, .sleep)) |extend| {
372
+ // if (!extend) stored.status = 0;
373
+ // } else {
374
+ stored.status -= 1;
375
+ // }
376
+
377
+ const duration = Status.duration(stored.status);
378
+ if (!Status.is(stored.status, .EXT)) {
379
+ try options.chance.sleep(player, duration);
380
+ }
381
+
382
+ if (duration == 0) {
383
+ try log.curestatus(ident, before, .Message);
384
+ stored.status = 0; // clears EXT if present
385
+ cantMove(volatiles);
386
+ volatiles.Nightmare = false;
387
+ } else {
388
+ try log.cant(ident, .Sleep);
389
+ if (move == .Snore or move == .SleepTalk) break :slp;
390
+ cantMove(volatiles);
391
+ return false;
392
+ }
393
+ }
394
+
395
+ if (Status.is(stored.status, .FRZ) and !(move == .FlameWheel or move == .SacredFire)) {
396
+ cantMove(volatiles);
397
+ try log.cant(ident, .Freeze);
398
+ return false;
399
+ }
400
+
401
+ if (volatiles.Flinch) {
402
+ // Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
403
+ // Pokémon can sometimes flinch multiple times from the same original hit
404
+ // if (!showdown) volatiles.Flinch = false;
405
+ volatiles.Flinch = false;
406
+ cantMove(volatiles);
407
+ try log.cant(ident, .Flinch);
408
+ return false;
409
+ }
410
+
411
+ if (volatiles.disabled_duration > 0) {
412
+ // if (options.calc.modify(player, .disable)) |extend| {
413
+ // if (!extend) volatiles.disabled_duration = 0;
414
+ // } else {
415
+ volatiles.disabled_duration -= 1;
416
+ // }
417
+ try options.chance.disable(player, volatiles.disabled_duration);
418
+
419
+ if (volatiles.disabled_duration == 0) {
420
+ volatiles.disabled_move = 0;
421
+ try log.end(ident, .Disable);
422
+ }
423
+ }
424
+
425
+ if (volatiles.Confusion) {
426
+ assert(volatiles.confusion > 0);
427
+
428
+ // if (options.calc.modify(player, .confusion)) |extend| {
429
+ // if (!extend) volatiles.confusion = 0;
430
+ // } else {
431
+ volatiles.confusion -= 1;
432
+ // }
433
+ try options.chance.confusion(player, volatiles.confusion);
434
+
435
+ if (volatiles.confusion == 0) {
436
+ volatiles.Confusion = false;
437
+ try log.end(ident, .Confusion);
438
+ } else {
439
+ try log.activate(ident, .Confusion);
440
+
441
+ if (try Rolls.confused(battle, player, options)) {
442
+ volatiles.BeatUp = false;
443
+ volatiles.Flinch = false;
444
+ cantMove(volatiles);
445
+
446
+ // TODO HitConfusion
447
+
448
+ return false;
449
+ }
450
+ }
451
+ }
452
+
453
+ if (volatiles.Attract) {
454
+ try log.atrract(ident, .Attract);
455
+
456
+ if (try Rolls.attract(battle, player, options)) {
457
+ cantMove(volatiles);
458
+ try log.cant(ident, .Attract);
459
+ return false;
460
+ }
461
+ }
462
+
463
+ if (side.active.volatiles.disabled_move != 0) {
464
+ // A Pokémon that transforms after being disabled may end up with less move slots
465
+ const m = side.active.moves[side.active.volatiles.disabled_move - 1].id;
466
+ if (m != .None and m == move) {
467
+ side.active.volatiles.Charging = false;
468
+ cantMove(volatiles);
469
+ try options.log.disabled(ident, move);
470
+ return false;
471
+ }
472
+ }
473
+
474
+ if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
475
+ cantMove(volatiles);
476
+ try log.cant(ident, .Paralysis);
477
+ return false;
478
+ }
479
+
480
+ return true;
481
+ }
482
+
483
+ fn cantMove(volatiles: *Volatiles) void {
484
+ volatiles.Bide = false;
485
+ volatiles.Thrashing = false;
486
+ volatiles.Charging = false;
487
+ volatiles.Underground = false;
488
+ volatiles.Flying = false;
489
+ volatiles.Rollout = false;
490
+
491
+ volatiles.fury_cutter = 0;
492
+ }
493
+
494
+ fn canMove(battle: anytype, player: Player, options: anytype) !bool {
47
495
  _ = battle;
48
496
  _ = player;
49
- _ = request;
50
- _ = out;
497
+ _ = options;
498
+ return false;
499
+ }
500
+
501
+ fn decrementPP(side: *Side, mslot: u4) void {
502
+ var active = &side.active;
503
+ const volatiles = &active.volatiles;
504
+
505
+ // TODO assert(side.last_selected_move != .Struggle);
506
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
507
+
508
+ assert(active.move(mslot).pp > 0);
509
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
510
+ if (volatiles.Transform) return;
511
+
512
+ // FIXME mimic
513
+
514
+ assert(side.stored().move(mslot).pp > 0);
515
+ side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
516
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
517
+ }
518
+
519
+ fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
520
+ _ = options;
521
+ var side = battle.side(player);
522
+ const move = Move.get(.Teleport); // side.last_selected_move
523
+ switch (move.effect) {
524
+ .Teleport => {
525
+ // side.useMove();
526
+ decrementPP(side, mslot);
527
+ },
528
+ else => @panic("TODO"),
529
+ }
530
+ return null;
531
+ }
532
+
533
+ fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
534
+ if (move.bp == 0) return false;
535
+
536
+ const side = battle.side(player);
537
+ const pokemon = side.stored();
51
538
 
539
+ var stage: u8 =
540
+ if ((pokemon.species == .Chansey and pokemon.item == .LuckyPunch) or
541
+ (pokemon.species == .Farfetchd and pokemon.item == .Stick)) 2 else 0;
542
+ if (stage == 0) {
543
+ if (side.active.volatiles.FocusEnergy) stage += 1;
544
+ if (move.effect.isHighCritical()) stage += 2;
545
+ if (pokemon.item == .ScopeLens) stage += 1;
546
+ }
547
+ assert(stage <= 4);
548
+
549
+ return Rolls.criticalHit(battle, player, CRITICAL_HITS[stage], options);
550
+ }
551
+
552
+ fn calcDamage(
553
+ battle: anytype,
554
+ player: Player,
555
+ target_player: Player,
556
+ m: ?Move.Data,
557
+ crit: bool,
558
+ ) u16 {
559
+ _ = battle;
560
+ _ = player;
561
+ _ = target_player;
562
+ _ = m;
563
+ _ = crit;
52
564
  return 0;
53
565
  }
566
+
567
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
568
+
569
+ fn adjustDamage(battle: anytype, player: Player, m: Move, damage: u16, effectiveness: *u16) u16 {
570
+ if (m == .Struggle) return;
571
+
572
+ const side = battle.side(player);
573
+ const foe = battle.foe(player);
574
+ const types = foe.active.types;
575
+ const move = Move.get(side.m);
576
+
577
+ var d = damage;
578
+ if ((move.type == .Water and battle.field.weather == .Rain) or
579
+ (move.type == .Fire and battle.field.weather == .Sun))
580
+ {
581
+ d = d *% @intFromEnum(Effectiveness.Super) / 10;
582
+ } else if ((move.type == .Water and battle.field.weather == .Sun) or
583
+ ((move.type == .Fire or m == .SolarBeam) and battle.field.weather == .Rain))
584
+ {
585
+ d = d *% @intFromEnum(Effectiveness.Resisted) / 10;
586
+ }
587
+
588
+ if (side.active.types.includes(move.type)) d +%= d / 2;
589
+
590
+ const neutral = @intFromEnum(Effectiveness.Neutral);
591
+ const foresight = foe.active.volatiles.Foresight and FORESIGHT.includes(move.type);
592
+ const eff1: u16 = if (foresight and types.type1 == .Ghost)
593
+ 10
594
+ else
595
+ @intFromEnum(move.type.effectiveness(types.type1));
596
+ const eff2: u16 = if (foresight and types.type2 == .Ghost)
597
+ 10
598
+ else
599
+ @intFromEnum(move.type.effectiveness(types.type2));
600
+
601
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
602
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
603
+ Type.precedence(move.type, types.type1) > Type.precedence(move.type, types.type2))
604
+ {
605
+ assert(eff2 != neutral);
606
+ d = d *% eff2 / 10;
607
+ assert(types.type1 != types.type2);
608
+ assert(eff1 != neutral);
609
+ d = d *% eff1 / 10;
610
+ } else {
611
+ if (eff1 != neutral) d = d *% eff1 / 10;
612
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
613
+ }
614
+
615
+ effectiveness.* = if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
616
+ return d;
617
+ }
618
+
619
+ fn randomizeDamage(battle: anytype, player: Player, damage: u16, options: anytype) !u16 {
620
+ if (damage <= 1) return;
621
+ const random = try Rolls.damage(battle, player, options);
622
+ options.calc.base(player.foe(), damage);
623
+ damage = @intCast(@as(u32, damage) *% random / 255);
624
+ options.calc.final(player.foe(), damage);
625
+ return damage;
626
+ }
627
+
628
+ fn applyDamage(
629
+ battle: anytype,
630
+ player: Player,
631
+ options: anytype,
632
+ ) !bool {
633
+ _ = battle;
634
+ _ = player;
635
+ _ = options;
636
+ return false;
637
+ }
638
+
639
+ fn checkHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
640
+ if (moveHit(battle, player, move, options)) return true;
641
+
642
+ // try options.chance.commit(player, .miss);
643
+ try options.log.lastmiss();
644
+ try options.log.miss(battle.active(player));
645
+
646
+ return false;
647
+ }
648
+
649
+ // TODO: set damage = 0 if missed and not (High) Jump Kick
650
+ fn moveHit(
651
+ battle: anytype,
652
+ player: Player,
653
+ move: Move.Data,
654
+ options: anytype,
655
+ ) !bool {
656
+ const side = battle.side(player);
657
+ const foe = battle.foe(player);
658
+
659
+ if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) return false;
660
+ if (foe.active.volatiles.Protect) return false;
661
+ const drain = move.effect == .DrainHP or move.effect == .DreamEater;
662
+ if (drain and foe.active.volatiles.Substitute) return false;
663
+ if (side.active.volatiles.LockOn) {
664
+ return !(foe.active.volatiles.Flying and move.extra.undeground);
665
+ }
666
+ assert(!(foe.active.volatiles.Flying and foe.active.volatiles.Underground));
667
+ if (foe.active.volatiles.Flying) {
668
+ if (!move.extra.flying) return false;
669
+ } else if (foe.active.volatiles.Underground) {
670
+ if (!move.extra.underground) return false;
671
+ }
672
+ if (move.effect == .Thunder and battle.field.weather == .Rain) return true;
673
+ if (move.effect == .AlwaysHit) return true;
674
+
675
+ var accuracy: u16 = move.accuracy;
676
+ if (foe.active.boosts.evasion <= side.active.boosts.accuracy or
677
+ !foe.active.volatiles.Foresight)
678
+ {
679
+ var boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
680
+ accuracy = accuracy * boost[0] / boost[1];
681
+ boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
682
+ accuracy = accuracy * boost[0] / boost[1];
683
+ accuracy = @min(255, @max(1, accuracy));
684
+ }
685
+
686
+ if (foe.stored().item == .BrightPowder) {
687
+ accuracy -|= 20;
688
+ }
689
+
690
+ // The accuracy roll is skipped entirely if maxed
691
+ if (accuracy == 255) return true;
692
+ return !try Rolls.hit(battle, player, @intCast(accuracy), options);
693
+ }
694
+
695
+ fn checkFaint(
696
+ battle: anytype,
697
+ player: Player,
698
+ options: anytype,
699
+ ) @TypeOf(options.log).Error!?Result {
700
+ _ = battle;
701
+ _ = player;
702
+ return null;
703
+ }
704
+
705
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !?Result {
706
+ _ = battle;
707
+ _ = player;
708
+ _ = done;
709
+ _ = options;
710
+ return null;
711
+ }
712
+
713
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !void {
714
+ var side = battle.side(player);
715
+ var stored = side.stored();
716
+ const ident = battle.active(player);
717
+ var volatiles = &side.active.volatiles;
718
+
719
+ // TODO if (stored.hp == 0) return;
720
+ assert(stored.hp > 0);
721
+
722
+ const brn = Status.is(stored.status, .BRN);
723
+ if (brn or Status.is(stored.status, .PSN)) {
724
+ var damage: u16 = undefined;
725
+ if (volatiles.Toxic) {
726
+ volatiles.toxic += 1;
727
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
728
+ } else {
729
+ damage = @max(stored.stats.hp / 8, 1);
730
+ }
731
+
732
+ stored.hp -|= damage;
733
+ // Pokémon Showdown uses damageOf here but its not relevant in Generation II
734
+ try options.log.damage(ident, stored, if (brn) Damage.Burn else Damage.Poison);
735
+ if (stored.hp == 0) return;
736
+ }
737
+
738
+ if (volatiles.LeechSeed) {
739
+ var foe = battle.foe(player);
740
+ var foe_stored = foe.stored();
741
+ const foe_ident = battle.active(player.foe());
742
+
743
+ // if (foe_stored.hp == 0) {
744
+ // assert(showdown);
745
+ // return;
746
+ // }
747
+
748
+ const damage = @max(stored.stats.hp / 8, 1);
749
+ stored.hp -|= damage;
750
+ // As above, Pokémon Showdown uses damageOf but its not relevant
751
+ try options.log.damage(ident, stored, .LeechSeed);
752
+
753
+ const before = foe_stored.hp;
754
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
755
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
756
+ if (foe_stored.hp > before) try options.log.heal(foe_ident, foe_stored, .Silent);
757
+ if (stored.hp == 0) return;
758
+ }
759
+
760
+ if (volatiles.Nightmare) {
761
+ stored.hp -= @max(stored.stats.hp / 4, 1);
762
+ // ibid
763
+ try options.log.damage(ident, stored, Damage.Nightmare);
764
+ if (stored.hp == 0) return;
765
+ }
766
+
767
+ if (volatiles.Curse) {
768
+ stored.hp -= @max(stored.stats.hp / 4, 1);
769
+ // ibid
770
+ try options.log.damage(ident, stored, Damage.Curse);
771
+ if (stored.hp == 0) return;
772
+ }
773
+ }
774
+
775
+ fn betweenTurns(battle: anytype, mslot: u4, options: anytype) !void {
776
+ const players = std.enums.values(Player);
777
+
778
+ // TODO checkFaintThen(p1, p2);
779
+
780
+ // Future Sight
781
+ inline for (players) |player| {
782
+ var side = battle.side(player);
783
+ var future_sight = &side.conditions.future_sight;
784
+
785
+ if (future_sight.count > 0) {
786
+ future_sight.count -= 1;
787
+ assert(future_sight.count != 0);
788
+ if (future_sight.count == 1) {
789
+ try options.log.end(battle.active(player), .FutureSight);
790
+ // TODO doMove
791
+ }
792
+ }
793
+ }
794
+ // TODO checkFaintThen(p1, p2);
795
+
796
+ // Weather
797
+ if (battle.field.weather != .None) {
798
+ assert(battle.field.weather_duration > 0);
799
+ battle.field.weather_duration -= 1;
800
+
801
+ if (battle.field.weather_duration == 0) {
802
+ battle.field.weather = .None;
803
+ try options.log.weather(battle.field.weather, .None);
804
+ } else {
805
+ try options.log.weather(battle.field.weather, .Upkeep);
806
+ if (battle.field.weather == .Sandstorm) {
807
+ inline for (players) |player| {
808
+ var side = battle.side(player);
809
+ const active = side.active;
810
+ if (!(active.volatiles.underground or active.types.sandstormImmune())) {
811
+ side.stored().hp -|= @max(side.stored().stats.hp / 8, 1);
812
+ try options.log.damage(battle.active(player), side.stored(), .Sandstorm);
813
+ }
814
+ }
815
+ // TODO checkFaintThen(p1, p2);
816
+ }
817
+ }
818
+ }
819
+
820
+ // Binding
821
+ inline for (players) |player| {
822
+ var side = battle.side(player);
823
+ var volatiles = &side.active.volatiles;
824
+
825
+ if (volatiles.bind > 0 and !volatiles.Substitute) {
826
+ volatiles.bind -= 1;
827
+ if (volatiles.bind == 0) {
828
+ const reason = @intFromEnum(End.Bind) + volatiles.bind_reason - 1;
829
+ try options.log.end(battle.active(player), @enumFromInt(reason));
830
+ } else {
831
+ var reason = @intFromEnum(Activate.Bind) + volatiles.bind_reason - 1;
832
+ try options.log.activate(battle.active(player), @enumFromInt(reason));
833
+
834
+ reason = @intFromEnum(Activate.Damage) + volatiles.bind_reason - 1;
835
+ side.stored().hp -|= @max(side.stored().stats.hp / 16, 1);
836
+ try options.log.damage(battle.active(player), side.stored(), reason);
837
+ }
838
+ }
839
+ }
840
+ // TODO checkFaintThen(p1, p2);
841
+
842
+ // Perish Song
843
+ inline for (players) |player| {
844
+ var side = battle.side(player);
845
+ var volatiles = &side.active.volatiles;
846
+
847
+ if (volatiles.PerishSong) {
848
+ assert(volatiles.perish_song > 0);
849
+ volatiles.perish_song -= 1;
850
+
851
+ assert(volatiles.perish_song < 3);
852
+ const reason = @intFromEnum(Start.PerishSong0) + volatiles.perish_song;
853
+ try options.log.start(battle.active(player), reason);
854
+
855
+ if (volatiles.perish_song == 0) {
856
+ volatiles.PerishSong = false;
857
+ side.stored().hp = 0;
858
+ }
859
+ }
860
+ }
861
+ // TODO checkFaintThen(p1, p2);
862
+
863
+ // Leftovers
864
+ inline for (players) |player| {
865
+ var stored = battle.side(player).stored();
866
+
867
+ if (stored.item == .Leftovers) {
868
+ const before = stored.hp;
869
+ stored.hp = @min(stored.hp + @max(stored.stats.hp / 16, 1), stored.stats.hp);
870
+ if (stored.hp > before) try options.log.heal(battle.active(player), stored, .Leftovers);
871
+ }
872
+ }
873
+
874
+ // Mystery Berry
875
+ inline for (players) |player| {
876
+ var stored = battle.side(player).stored();
877
+
878
+ if (stored.item == .MysteryBerry) {
879
+ // TODO stored and active moves, transform, etc
880
+ }
881
+ }
882
+
883
+ // Defrost
884
+ inline for (players) |player| {
885
+ var side = battle.side(player);
886
+
887
+ if (Status.is(side.stored().status, .FRZ) and
888
+ !side.active.volatiles.frozen and
889
+ try Rolls.defrost(battle, player, options))
890
+ {
891
+ try options.log.curestatus(battle.active(player), side.stored().status, .Message);
892
+ side.stored().status = 0;
893
+ }
894
+ }
895
+
896
+ // Side Conditions
897
+ if (showdown) {
898
+ inline for (players) |player| {
899
+ updateSideCondition(battle, player, "Reflect", "reflect");
900
+ }
901
+ inline for (players) |player| {
902
+ updateSideCondition(battle, player, "LightScreen", "light_screen");
903
+ }
904
+ inline for (players) |player| {
905
+ updateSideCondition(battle, player, "Safeguard", "safeguard");
906
+ }
907
+ } else {
908
+ inline for (players) |player| {
909
+ updateSideCondition(battle, player, "Safeguard", "safeguard");
910
+ }
911
+
912
+ inline for (players) |player| {
913
+ updateSideCondition(battle, player, "LightScreen", "light_screen");
914
+ updateSideCondition(battle, player, "Reflect", "reflect");
915
+ }
916
+ }
917
+
918
+ // Healing items
919
+ inline for (players) |player| {
920
+ var side = battle.side(player);
921
+ var stored = side.stored();
922
+ const ident = battle.active(player);
923
+
924
+ const num = @intFromEnum(stored.item);
925
+ if (num > @intFromEnum(Item.Berry)) {
926
+ if (num <= @intFromEnum(Item.GoldBerry)) {
927
+ const proc = if (showdown)
928
+ stored.hp <= stored.stats.hp
929
+ else
930
+ stored.hp < stored.stats.hp;
931
+ if (proc) {
932
+ assert(stored.hp != 0);
933
+ try options.log.enditem(ident, stored.item, .Eat);
934
+ stored.item = .None;
935
+
936
+ const offset = num - @intFromEnum(Item.Berry);
937
+ assert(offset < 3);
938
+ stored.hp = @min(stored.hp + ((offset + 1) * 10), stored.stats.hp);
939
+ const reason: Heal = @enumFromInt(@intFromEnum(Heal.Berry) + offset);
940
+ try options.log.heal(ident, stored, reason);
941
+ }
942
+ } else if (num < @intFromEnum(Item.BitterBerry)) {
943
+ const proc = if (stored.item == .MiracleBerry)
944
+ Status.any(stored.status)
945
+ else
946
+ Status.is(stored.status, @enumFromInt(num - @intFromEnum(Item.MintBerry) + 2));
947
+
948
+ if (proc) {
949
+ assert(Status.any(stored.status));
950
+ try options.log.enditem(ident, stored.item, .Eat);
951
+ stored.item = .None;
952
+
953
+ // FIXME wtf?
954
+ // side.active.volatiles.Toxic = false;
955
+ // side.active.volatiles.NightMare = false;
956
+ if (stored.item == .MiracleBerry) {
957
+ side.active.volatiles.Confusion = false;
958
+ try options.log.end(ident, .Confusion);
959
+ }
960
+ stored.status = 0;
961
+
962
+ // FIXME recalc stats
963
+
964
+ try options.log.curestatus(ident, stored.status, .Message);
965
+ }
966
+ } else if (num == @intFromEnum(Item.BitterBerry)) {
967
+ if (side.active.volatiles.Confusion) {
968
+ try options.log.enditem(ident, stored.item, .Eat);
969
+ stored.item = .None;
970
+
971
+ side.active.volatiles.Confusion = false;
972
+ try options.log.end(ident, .Confusion);
973
+ }
974
+ }
975
+ }
976
+ }
977
+
978
+ // Encore
979
+ inline for (players) |player| {
980
+ var side = battle.side(player);
981
+ var volatiles = &side.active.volatiles;
982
+
983
+ if (volatiles.Encore) {
984
+ assert(volatiles.encore > 0);
985
+ volatiles.encore -= 1;
986
+
987
+ if (volatiles.encore == 0 or side.active.moves(mslot).pp == 0) {
988
+ volatiles.Encore = false;
989
+ try options.log.end(battle.active(player), .Encore);
990
+ }
991
+ }
992
+ }
993
+ }
994
+
995
+ inline fn updateSideCondition(
996
+ battle: anytype,
997
+ player: Player,
998
+ comptime key: []const u8,
999
+ comptime value: []const u8,
1000
+ options: anytype,
1001
+ ) !void {
1002
+ var side = battle.side(player);
1003
+ if (@field(side.conditions, key)) {
1004
+ assert(@field(side.conditions, value) > 0);
1005
+ @field(side.conditions, value) -= 1;
1006
+
1007
+ if (@field(side.conditions, value) == 0) {
1008
+ @field(side.conditions, key) = false;
1009
+ try options.log.sideend(battle.active(player), @field(protocol.Side, key));
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
1015
+ battle.turn += 1;
1016
+
1017
+ if (showdown and battle.turn >= 1000) {
1018
+ try options.log.tie();
1019
+ return Result.Tie;
1020
+ } else if (battle.turn >= 65535) {
1021
+ return Result.Error;
1022
+ }
1023
+
1024
+ try options.log.turn(battle.turn);
1025
+
1026
+ return Result.Default;
1027
+ }
1028
+
1029
+ pub const Effects = struct {
1030
+ fn protect(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1031
+ var side = battle.side(player);
1032
+ var volatiles = &side.active.volatiles;
1033
+
1034
+ // TODO or if we didn't go first
1035
+ if (volatiles.Substitute) return try options.log.fail(battle.active(player), .None);
1036
+
1037
+ // TODO
1038
+
1039
+ if (move.effect == .Endure) {
1040
+ volatiles.Endure = true;
1041
+ } else {
1042
+ volatiles.Protect = true;
1043
+ }
1044
+ try options.log.singleturn(battle.active(player), move.id);
1045
+ }
1046
+
1047
+ const MAGNITUDE_POWER = [_]u8{ 10, 30, 50, 70, 90, 110, 150 };
1048
+ };
1049
+
1050
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
1051
+ if (Status.is(status, .PAR)) {
1052
+ stats.spe = @max(stats.spe / 4, 1);
1053
+ } else if (Status.is(status, .BRN)) {
1054
+ stats.atk = @max(stats.atk / 2, 1);
1055
+ }
1056
+ }
1057
+
1058
+ inline fn isForced(active: anytype) bool {
1059
+ return active.volatiles.Recharging or active.volatiles.Rage or
1060
+ active.volatiles.Thrashing or active.volatiles.Charging or
1061
+ active.volatiles.Rollout;
1062
+ }
1063
+
1064
+ pub const Rolls = struct {
1065
+ inline fn speedTie(battle: anytype, options: anytype) !bool {
1066
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
1067
+ player == .P1
1068
+ else if (showdown)
1069
+ battle.rng.range(u8, 0, 2) == 0
1070
+ else
1071
+ battle.rng.next() < Gen12.percent(50) + 1;
1072
+
1073
+ try options.chance.speedTie(p1);
1074
+ return p1;
1075
+ }
1076
+
1077
+ inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
1078
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
1079
+ val == .true
1080
+ else if (showdown)
1081
+ battle.rng.chance(u8, 60, 256)
1082
+ else
1083
+ battle.rng.next() < 60;
1084
+
1085
+ try options.chance.quickClaw(player, qkc);
1086
+ return qkc;
1087
+ }
1088
+
1089
+ inline fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
1090
+ const ok = if (options.calc.overridden(player, .hit)) |val|
1091
+ val == .true
1092
+ else if (showdown)
1093
+ battle.rng.chance(u8, accuracy, 256)
1094
+ else
1095
+ battle.rng.next() < accuracy;
1096
+
1097
+ try options.chance.hit(player, ok, accuracy);
1098
+ return ok;
1099
+ }
1100
+
1101
+ inline fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
1102
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
1103
+ val == .true
1104
+ else if (showdown)
1105
+ battle.rng.chance(u8, rate, 256)
1106
+ else
1107
+ battle.rng.next() < rate;
1108
+
1109
+ try options.chance.criticalHit(player, crit, rate);
1110
+ return crit;
1111
+ }
1112
+
1113
+ inline fn damage(battle: anytype, player: anytype, options: anytype) !u8 {
1114
+ const roll = if (options.calc.overridden(player, .damage)) |val|
1115
+ val
1116
+ else roll: {
1117
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
1118
+ while (true) {
1119
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
1120
+ if (r >= 217) break :roll r;
1121
+ }
1122
+ };
1123
+
1124
+ assert(roll >= 217 and roll <= 255);
1125
+ try options.chance.damage(player, roll);
1126
+ return roll;
1127
+ }
1128
+
1129
+ inline fn confused(battle: anytype, player: Player, options: anytype) !bool {
1130
+ const cfz = if (options.calc.overridden(player, .confused)) |val|
1131
+ val == .true
1132
+ else if (showdown)
1133
+ !battle.rng.chance(u8, 128, 256)
1134
+ else
1135
+ battle.rng.next() >= Gen12.percent(50) + 1;
1136
+
1137
+ try options.chance.confused(player, cfz);
1138
+ return cfz;
1139
+ }
1140
+
1141
+ inline fn attract(battle: anytype, player: Player, options: anytype) !bool {
1142
+ const cant = if (options.calc.overridden(player, .attract)) |val|
1143
+ val == .true
1144
+ else if (showdown)
1145
+ battle.rng.chance(u8, 1, 2)
1146
+ else
1147
+ battle.rng.next() > Gen12.percent(50) + 1;
1148
+
1149
+ try options.chance.attract(player, cant);
1150
+ return cant;
1151
+ }
1152
+
1153
+ inline fn paralyzed(battle: anytype, player: Player, options: anytype) !bool {
1154
+ const par = if (options.calc.overridden(player, .paralyzed)) |val|
1155
+ val == .true
1156
+ else if (showdown)
1157
+ battle.rng.chance(u8, 63, 256)
1158
+ else
1159
+ battle.rng.next() < Gen12.percent(25);
1160
+
1161
+ try options.chance.paralyzed(player, par);
1162
+ return par;
1163
+ }
1164
+
1165
+ inline fn defrost(battle: anytype, player: Player, options: anytype) !bool {
1166
+ const thaw = if (options.calc.overridden(player, .defrost)) |val|
1167
+ val == .true
1168
+ else if (showdown)
1169
+ battle.rng.chance(u8, 25, 256)
1170
+ else
1171
+ battle.rng.next() < Gen12.percent(10);
1172
+
1173
+ try options.chance.defrost(player, thaw);
1174
+ return thaw;
1175
+ }
1176
+
1177
+ inline fn secondaryChance(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
1178
+ // GLITCH: 100% secondary chance will still fail 1/256 of the time
1179
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
1180
+ val == .true
1181
+ else if (showdown)
1182
+ battle.rng.chance(u8, rate, 256)
1183
+ else
1184
+ battle.rng.next() < rate;
1185
+
1186
+ try options.chance.secondaryChance(player, proc, rate);
1187
+ return proc;
1188
+ }
1189
+
1190
+ inline fn focusBand(battle: anytype, player: Player, options: anytype) !bool {
1191
+ const proc = if (options.calc.overridden(player, .focus_band)) |val|
1192
+ val == .true
1193
+ else if (showdown)
1194
+ battle.rng.chance(u8, 30, 256)
1195
+ else
1196
+ battle.rng.next() < 30;
1197
+
1198
+ try options.chance.focusBand(player, proc);
1199
+ return proc;
1200
+ }
1201
+
1202
+ inline fn kingsRock(battle: anytype, player: Player, options: anytype) !bool {
1203
+ const proc = if (options.calc.overridden(player, .kings_rock)) |val|
1204
+ val == .true
1205
+ else if (showdown)
1206
+ battle.rng.chance(u8, 30, 256)
1207
+ else
1208
+ battle.rng.next() < 30;
1209
+
1210
+ try options.chance.kingsRock(player, proc);
1211
+ return proc;
1212
+ }
1213
+
1214
+ inline fn sleepDuration(battle: anytype, player: Player, options: anytype) u3 {
1215
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
1216
+ @intCast(val)
1217
+ else if (showdown)
1218
+ @intCast(battle.rng.range(u8, 1, 7))
1219
+ else duration: {
1220
+ while (true) {
1221
+ const r = battle.rng.next() & 7;
1222
+ if (r != 0 and r != 7) break :duration @intCast(r);
1223
+ }
1224
+ };
1225
+
1226
+ assert(duration >= 1 and duration <= 6);
1227
+ options.chance.duration(.sleep, player, player.foe(), duration);
1228
+ return duration + 1;
1229
+ }
1230
+
1231
+ inline fn triAttack(battle: anytype, player: Player, options: anytype) !u8 {
1232
+ const status: TriAttack = if (options.calc.overridden(player, .tri_attack)) |val|
1233
+ val
1234
+ else if (showdown)
1235
+ @enumFromInt(battle.rng.range(u8, 0, 2))
1236
+ else loop: {
1237
+ while (true) {
1238
+ const r = std.math.rotr(u8, std.battle.rng.next(), 4) & 3;
1239
+ if (r != 0) break :loop @intCast(r - 1);
1240
+ }
1241
+ };
1242
+
1243
+ try options.chance.triAttack(player, status);
1244
+ return status.status();
1245
+ }
1246
+
1247
+ inline fn present(battle: anytype, player: Player, options: anytype) !u8 {
1248
+ const power = if (options.calc.overridden(player, .present)) |val|
1249
+ (val - 1) * 40
1250
+ else if (showdown) power: {
1251
+ const r = battle.rng.range(u8, 0, 10);
1252
+ if (r < 2) break :power 0;
1253
+ if (r < 6) break :power 40;
1254
+ if (r < 9) break :power 80;
1255
+ break :power 120;
1256
+ } else power: {
1257
+ const r = battle.rng.next();
1258
+ if (r <= Gen12.percent(40)) break :power 40;
1259
+ if (r <= Gen12.percent(70) + 1) break :power 80;
1260
+ if (r <= Gen12.percent(80)) break :power 120;
1261
+ break :power 0;
1262
+ };
1263
+
1264
+ assert(power <= 120);
1265
+ try options.chance.present(player, power);
1266
+ return power;
1267
+ }
1268
+
1269
+ inline fn magnitude(battle: anytype, player: Player, options: anytype) !u8 {
1270
+ const num = if (options.calc.overridden(player, .magnitude)) |val|
1271
+ val + 3
1272
+ else if (showdown) num: {
1273
+ const r = battle.rng.range(u8, 0, 100);
1274
+ if (r < 5) break :num 4;
1275
+ if (r < 15) break :num 5;
1276
+ if (r < 35) break :num 6;
1277
+ if (r < 65) break :num 7;
1278
+ if (r < 85) break :num 8;
1279
+ if (r < 95) break :num 9;
1280
+ break :num 10;
1281
+ } else num: {
1282
+ const r = battle.rng.next();
1283
+ if (r <= Gen12.percent(5) + 1) break :num 4;
1284
+ if (r <= Gen12.percent(15)) break :num 5;
1285
+ if (r <= Gen12.percent(35)) break :num 6;
1286
+ if (r <= Gen12.percent(65) + 1) break :num 7;
1287
+ if (r <= Gen12.percent(85) + 1) break :num 8;
1288
+ if (r <= Gen12.percent(95)) break :num 9;
1289
+ break :num 10;
1290
+ };
1291
+
1292
+ assert(num >= 4 and num <= 10);
1293
+ try options.chance.magnitude(player, num);
1294
+ return num;
1295
+ }
1296
+
1297
+ inline fn tripleKick(battle: anytype, player: Player, options: anytype) !u8 {
1298
+ const hits = if (options.calc.overridden(player, .triple_kick)) |val|
1299
+ val
1300
+ else if (showdown)
1301
+ battle.rng.range(u8, 1, 4)
1302
+ else power: {
1303
+ while (true) {
1304
+ const r = battle.rng.next() & 3;
1305
+ if (r != 0) break :power r - 1;
1306
+ }
1307
+ };
1308
+
1309
+ assert(hits >= 1 and hits <= 3);
1310
+ try options.chance.tripleKick(player, hits);
1311
+ return hits;
1312
+ }
1313
+
1314
+ inline fn spite(battle: anytype, player: Player, options: anytype) !u8 {
1315
+ const pp = if (options.calc.overridden(player, .spite)) |val|
1316
+ val + 1
1317
+ else if (showdown)
1318
+ battle.rng.range(u8, 2, 6)
1319
+ else
1320
+ (battle.rng.next() & 3) + 2;
1321
+
1322
+ assert(pp >= 2 and pp <= 5);
1323
+ try options.chance.spite(player, pp);
1324
+ return pp;
1325
+ }
1326
+
1327
+ // Conversion 2 can at most choose between 7 types (vs. a Grass-type attack)
1328
+ const CONVERSION_2: [7]Type = [_]Type{.{}} ** 7;
1329
+
1330
+ inline fn conversion2(battle: anytype, player: Player, mtype: Type, options: anytype) !Type {
1331
+ var i: u8 = 0;
1332
+ const neutral = @intFromEnum(Effectiveness.Neutral);
1333
+ assert(mtype != .@"???");
1334
+ const ty: Type = if (options.calc.overridden(player, .conversion_2)) |val|
1335
+ @enumFromInt(@intFromEnum(val) - 1)
1336
+ else if (showdown) ty: {
1337
+ for (Type.SHOWDOWN) |t| {
1338
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
1339
+ CONVERSION_2[i] = t;
1340
+ i += 1;
1341
+ }
1342
+ }
1343
+ assert(i > 0 and i <= 7);
1344
+ break :ty CONVERSION_2[battle.rng.range(u8, 0, i)];
1345
+ } else ty: {
1346
+ while (true) {
1347
+ const r = battle.rng.next() & 0b11111;
1348
+ if (r == 6) continue; // BIRD
1349
+ if (r > 9 and r < 20) continue; // UNUSED_TYPES
1350
+ if (r > 27) continue; // TYPES_END
1351
+
1352
+ const t = Types.conversion2(r);
1353
+ if (@intFromEnum(mtype.effectiveness(t)) < neutral) {
1354
+ break :ty t;
1355
+ }
1356
+ }
1357
+ };
1358
+
1359
+ assert(ty != .@"???");
1360
+ try options.chance.conversion2(player, ty, mtype, i);
1361
+ return ty;
1362
+ }
1363
+
1364
+ // TODO thrashingDuration
1365
+ // TODO confusionDuraiton (from thrash vs. from move)
1366
+ // TODO forceSwitch
1367
+ // TODO bindingDuration
1368
+ // TODO bideDuration
1369
+ // TODO conversion moveSlot
1370
+ // TODO disable duration
1371
+ // TODO encore duration
1372
+ // TODO metronome
1373
+ // TODO protect
1374
+ // TODO sleeptalk move slot
1375
+
1376
+ inline fn psywave(battle: anytype, player: Player, max: u8, options: anytype) !u8 {
1377
+ const power = if (options.calc.overridden(player, .psywave)) |val|
1378
+ val - 1
1379
+ else if (showdown)
1380
+ battle.rng.range(u8, 0, max)
1381
+ else power: {
1382
+ while (true) {
1383
+ const r = battle.rng.next();
1384
+ if (r < max) break :power r;
1385
+ }
1386
+ };
1387
+
1388
+ assert(power < max);
1389
+ try options.chance.psywave(player, power, max);
1390
+ return power;
1391
+ }
1392
+
1393
+ const METRONOME = init: {
1394
+ var num = 0;
1395
+ var moves: [238]Move = undefined;
1396
+ for (1..Move.size) |i| {
1397
+ if (Move.get(@enumFromInt(i)).extra.metronome) {
1398
+ moves[num] = @enumFromInt(i);
1399
+ num += 1;
1400
+ }
1401
+ }
1402
+ assert(num == moves.len);
1403
+ break :init moves;
1404
+ };
1405
+ };
1406
+
1407
+ test "RNG agreement" {
1408
+ if (!showdown) return;
1409
+ var expected: [256]u32 = undefined;
1410
+ for (0..expected.len) |i| {
1411
+ expected[i] = @intCast(i * 0x1000000);
1412
+ }
1413
+
1414
+ var spe: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1415
+ var qkc: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1416
+ var cfz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1417
+ var atr: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1418
+ var frz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1419
+ var fcb: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1420
+
1421
+ for (0..expected.len) |i| {
1422
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
1423
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
1424
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
1425
+ try expectEqual(atr.chance(u8, 1, 2), i < Gen12.percent(50) + 1);
1426
+ try expectEqual(frz.chance(u8, 25, 256), i < Gen12.percent(10));
1427
+ try expectEqual(fcb.chance(u8, 30, 256), !(30 <= i));
1428
+ }
1429
+ }
1430
+
1431
+ test "Roll probabilities" {
1432
+ if (showdown) return;
1433
+
1434
+ var present = [4]u8{ 0, 0, 0, 0 };
1435
+ var magnitude = [7]u8{ 0, 0, 0, 0, 0, 0, 0 };
1436
+ for (0..256) |i| {
1437
+ present[
1438
+ if (i <= Gen12.percent(40))
1439
+ 1
1440
+ else if (i <= Gen12.percent(70) + 1)
1441
+ 2
1442
+ else if (i <= Gen12.percent(80))
1443
+ 3
1444
+ else
1445
+ 0
1446
+ ] += 1;
1447
+ magnitude[
1448
+ if (i <= Gen12.percent(5) + 1)
1449
+ 0
1450
+ else if (i <= Gen12.percent(15) + 1)
1451
+ 1
1452
+ else if (i <= Gen12.percent(35))
1453
+ 2
1454
+ else if (i <= Gen12.percent(65) + 1)
1455
+ 3
1456
+ else if (i <= Gen12.percent(85) + 1)
1457
+ 4
1458
+ else if (i <= Gen12.percent(95))
1459
+ 5
1460
+ else
1461
+ 6
1462
+ ] += 1;
1463
+ }
1464
+
1465
+ try expectEqualSlices(u8, &.{ 51, 103, 77, 25 }, &present);
1466
+ try expectEqualSlices(u8, &.{ 14, 26, 50, 77, 51, 25, 13 }, &magnitude);
1467
+ }
1468
+
1469
+ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
1470
+ var n: u8 = 0;
1471
+ switch (request) {
1472
+ .Pass => {
1473
+ out[n] = .{};
1474
+ n += 1;
1475
+ },
1476
+ .Switch => {
1477
+ const side = battle.side(player);
1478
+ var slot: u4 = 2;
1479
+ while (slot <= 6) : (slot += 1) {
1480
+ const id = side.order[slot - 1];
1481
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1482
+ out[n] = .{ .type = .Switch, .data = slot };
1483
+ n += 1;
1484
+ }
1485
+ if (n == 0) {
1486
+ out[n] = .{};
1487
+ n += 1;
1488
+ }
1489
+ },
1490
+ .Move => {
1491
+ const side = battle.side(player);
1492
+
1493
+ var active = &side.active;
1494
+ const stored = side.stored();
1495
+
1496
+ // While players are not given any input options on the cartridge in these cases,
1497
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
1498
+ //
1499
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
1500
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
1501
+ // between passing while waiting for an opponent's forced switch after fainting and
1502
+ // passing due to being forced into using a move. Instead of introducing another option
1503
+ // we simply repurpose Move with no move slot, even though pedantically this is not
1504
+ // strictly correct as the player would not have been presented the option to move or
1505
+ // switch at all.
1506
+ if (isForced(active)) {
1507
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
1508
+ n += 1;
1509
+ return n;
1510
+ }
1511
+
1512
+ var slot: u4 = 2;
1513
+ while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
1514
+ const id = side.order[slot - 1];
1515
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1516
+ out[n] = .{ .type = .Switch, .data = slot };
1517
+ n += 1;
1518
+ }
1519
+
1520
+ const limited = active.volatiles.Bide or active.volatiles.bind > 0;
1521
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
1522
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
1523
+ // either disables all other moves in the case of limited or requires you to select a
1524
+ // move normally if sleeping/frozen/bound.
1525
+ if (!showdown and (limited or
1526
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
1527
+ {
1528
+ out[n] = .{ .type = .Move, .data = 0 };
1529
+ n += 1;
1530
+ return n;
1531
+ }
1532
+
1533
+ slot = 1;
1534
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
1535
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
1536
+ // Move will not result in forcing the subsequent use unless the user also had the
1537
+ // proc-ed move in their moveset) and disabling all other moves.
1538
+ if (limited) {
1539
+ assert(showdown);
1540
+ assert(side.last_selected_move != .None);
1541
+ while (slot <= 4) : (slot += 1) {
1542
+ const m = active.moves[slot - 1];
1543
+ if (m.id == .None) break;
1544
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
1545
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
1546
+ const struggle =
1547
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
1548
+ const s = if (struggle) 0 else slot;
1549
+ out[n] = .{ .type = .Move, .data = s };
1550
+ n += 1;
1551
+ return n;
1552
+ }
1553
+ }
1554
+ }
1555
+
1556
+ const before = n;
1557
+ slot = 1;
1558
+ while (slot <= 4) : (slot += 1) {
1559
+ const m = active.moves[slot - 1];
1560
+ if (m.id == .None) break;
1561
+ if (m.pp == 0) continue;
1562
+ if (active.volatiles.disabled_move == slot) continue;
1563
+ out[n] = .{ .type = .Move, .data = slot };
1564
+ n += 1;
1565
+ }
1566
+ // Struggle (Pokémon Showdown would use 'move 1' here)
1567
+ if (n == before) {
1568
+ out[n] = .{ .type = .Move, .data = 0 };
1569
+ n += 1;
1570
+ }
1571
+ },
1572
+ }
1573
+ return n;
1574
+ }