-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmechanics.zig
More file actions
3251 lines (2808 loc) · 127 KB
/
Copy pathmechanics.zig
File metadata and controls
3251 lines (2808 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const DEBUG = @import("../common/debug.zig").print;
const builtin = @import("builtin");
const chance = @import("chance.zig");
const common = @import("../common/data.zig");
const data = @import("data.zig");
const pkmn = @import("../pkmn.zig");
const protocol = @import("../common/protocol.zig");
const rng = @import("../common/rng.zig");
const std = @import("std");
const assert = std.debug.assert;
const Boost = protocol.Boost;
const Choice = common.Choice;
const Damage = protocol.Damage;
const Effectiveness = data.Effectiveness;
const expectEqual = std.testing.expectEqual;
const Fail = protocol.Fail;
const Gen12 = rng.Gen12;
const Heal = protocol.Heal;
const ID = common.ID;
const Move = data.Move;
const MoveSlot = data.MoveSlot;
const Player = common.Player;
const Result = common.Result;
const showdown = pkmn.options.showdown;
const Side = data.Side;
const Species = data.Species;
const Stats = data.Stats;
const Status = data.Status;
const Type = data.Type;
// zig fmt: off
const BOOSTS = &[_][2]u8{
.{ 25, 100 }, // -6
.{ 28, 100 }, // -5
.{ 33, 100 }, // -4
.{ 40, 100 }, // -3
.{ 50, 100 }, // -2
.{ 66, 100 }, // -1
.{ 1, 1 }, // 0
.{ 15, 10 }, // +1
.{ 2, 1 }, // +2
.{ 25, 10 }, // +3
.{ 3, 1 }, // +4
.{ 35, 10 }, // +5
.{ 4, 1 }, // +6
};
// zig fmt: on
const MAX_STAT_VALUE = 999;
pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
if (battle.turn == 0) return start(battle, options);
var s1 = false;
var s2 = false;
if (selectMove(battle, .P1, c1, c2, &s1)) |r| return r;
if (selectMove(battle, .P2, c2, c1, &s2)) |r| return r;
var p1 = battle.side(.P1);
var p2 = battle.side(.P2);
const r1 = showdown and p1.active.volatiles.Binding and c2.type == .Switch;
const r2 = showdown and p2.active.volatiles.Binding and c1.type == .Switch;
if (try turnOrder(battle, c1, c2, options) == .P1) {
if (try doTurn(battle, .P1, c1, r1, s1, .P2, c2, r2, s2, options)) |r| return r;
} else {
if (try doTurn(battle, .P2, c2, r2, s2, .P1, c1, r1, s1, options)) |r| return r;
}
if (p1.active.volatiles.attacks == 0) p1.active.volatiles.Binding = false;
if (p2.active.volatiles.attacks == 0) p2.active.volatiles.Binding = false;
return endTurn(battle, options);
}
fn start(battle: anytype, options: anytype) !Result {
const p1 = battle.side(.P1);
const p2 = battle.side(.P2);
const p1_slot = findFirstAlive(p1);
assert(!showdown or p1_slot == 1);
if (p1_slot == 0) return if (findFirstAlive(p2) == 0) .Tie else .Lose;
const p2_slot = findFirstAlive(p2);
assert(!showdown or p2_slot == 1);
if (p2_slot == 0) return .Win;
try switchIn(battle, .P1, p1_slot, true, options);
try switchIn(battle, .P2, p2_slot, true, options);
return endTurn(battle, options);
}
fn findFirstAlive(side: *const Side) u8 {
for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.order[i];
return 0;
}
fn selectMove(
battle: anytype,
player: Player,
choice: Choice,
foe_choice: Choice,
skip_turn: *bool,
) ?Result {
if (choice.type == .Pass) return null;
var side = battle.side(player);
var volatiles = &side.active.volatiles;
const stored = side.stored();
assert(!isForced(side.active) or
(choice.type == .Move and choice.data == @intFromBool(showdown)));
// pre-battle menu
if (volatiles.Recharging) {
if (showdown and battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
return null;
}
if (volatiles.Rage) {
if (showdown) {
if (battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
saveMove(battle, player, null);
}
return null;
}
// Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
if (!showdown) volatiles.Flinch = false;
if (volatiles.Thrashing or volatiles.Charging) {
if (showdown) {
if (battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
saveMove(battle, player, null);
}
return null;
}
// battle menu
if (choice.type == .Switch) return null;
// pre-move select
if (Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP) or volatiles.Bide) {
assert(showdown or choice.data == 0);
if (showdown) {
if (volatiles.Bide and battle.foe(player).active.volatiles.Binding) skip_turn.* = true;
saveMove(battle, player, choice);
}
return null;
}
if (volatiles.Binding) {
if (showdown) {
// Pokémon Showdown overwrites Mirror Move with whatever was selected - really this
// should set side.last_selected_move = last.id to reuse Mirror Move and fail in order
// to satisfy the conditions of the Desync Clause Mod. However, because Binding is still
// set the selected move will not actually be used, it will just be reported as having
// been used (this differs from how Pokémon Showdown works, but its impossible to
// replicate the incorrect behavior with the correct mechanisms)
saveMove(battle, player, choice);
} else {
assert(choice.data == 0);
// GLITCH: https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch
if (foe_choice.type == .Switch) {
const last = side.active.move(battle.lastMove(player).index);
if (last.id == .Metronome) side.last_selected_move = last.id;
if (last.id == .MirrorMove) {
if (!pkmn.options.mod) return .Error;
side.last_selected_move = last.id;
}
}
}
return null;
}
if (battle.foe(player).active.volatiles.Binding) {
skip_turn.* = true;
if (showdown) {
saveMove(battle, player, choice);
} else {
assert(choice.data == 0);
side.last_selected_move = .SKIP_TURN;
}
return null;
}
// move select
volatiles.state = 0;
if (choice.data == 0) {
const struggle = ok: {
for (side.active.moves, 0..) |move, i| {
if (move.pp > 0 and volatiles.disable_move != i + 1) break :ok false;
}
break :ok true;
};
assert(struggle);
}
saveMove(battle, player, choice);
return null;
}
fn saveMove(battle: anytype, player: Player, choice: ?Choice) void {
var side = battle.side(player);
if (choice) |c| {
assert(c.type == .Move);
if (c.data == 0) {
side.last_selected_move = .Struggle;
} else {
assert(showdown or side.active.volatiles.disable_move != c.data);
const move = side.active.move(c.data);
// You cannot *select* a move with 0 PP (except on Pokémon Showdown where that is
// sometimes required...), but a 0 PP move can be used automatically
assert(showdown or move.pp != 0);
side.last_selected_move = move.id;
battle.lastMove(player).index = @intCast(c.data);
}
}
}
fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
var side = battle.side(player);
var foe = battle.foe(player);
var active = &side.active;
const incoming = side.get(slot);
assert(incoming.hp != 0);
assert(slot != 1 or initial);
const out = side.order[0];
side.order[0] = side.order[slot - 1];
side.order[slot - 1] = out;
battle.lastMove(player).index = 1;
side.last_used_move = .None;
foe.last_used_move = .None;
active.stats = incoming.stats;
active.species = incoming.species;
active.types = incoming.types;
active.boosts = .{};
active.volatiles = .{};
active.moves = incoming.moves;
statusModify(incoming.status, &active.stats);
options.chance.switched(player, slot);
foe.active.volatiles.Binding = false;
try options.log.switched(.{ battle.active(player), incoming });
if (showdown and incoming.status == Status.TOX) {
incoming.status = Status.init(.PSN);
// Technically, Pokémon Showdown adds these after *both* Pokémon have switched, but we'd
// rather not clutter up turnOrder just for this (incorrect) log message
try options.log.status(.{ battle.active(player), incoming.status, .Silent });
}
}
fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
assert(c1.type != .Pass or c2.type != .Pass);
if (c1.type == .Pass) return .P2;
if (c2.type == .Pass) return .P1;
if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
// https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
// > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
// > your own screen without waiting for the other player's choice (and their choice will appear
// > to happen first for them too, unless they attacked in which case your switch happens first)
// A cartridge-compatible implemention must not advance the RNG so we simply default to P1
const double_switch = c1.type == .Switch and c2.type == .Switch;
if (!showdown and double_switch) return .P1;
const m1 = battle.side(.P1).last_selected_move;
const m2 = battle.side(.P2).last_selected_move;
if (!showdown or !double_switch) {
if ((m1 == .QuickAttack) != (m2 == .QuickAttack)) {
return if (m1 == .QuickAttack) .P1 else .P2;
} else if ((m1 == .Counter) != (m2 == .Counter)) {
return if (m1 == .Counter) .P2 else .P1;
}
}
const spe1 = battle.side(.P1).active.stats.spe;
const spe2 = battle.side(.P2).active.stats.spe;
if (spe1 == spe2) {
// Pokémon Showdown's beforeTurnCallback shenanigans
if (showdown and !double_switch and m1 == .Counter and m2 == .Counter) {
battle.rng.advance(1);
}
const p1 = try Rolls.speedTie(battle, options);
if (!showdown) return if (p1) .P1 else .P2;
// Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
// meaning that if a side is locked into a thrashing move and wins the speed tie, it
// actually uses its priority to simply insert its actual changed action into the queue,
// causing it to then execute *after* the side which should go second...
const t1 = battle.side(.P1).active.volatiles.Thrashing;
const t2 = battle.side(.P2).active.volatiles.Thrashing;
// If *both* sides are thrashing it really should be another speed tie, but we've patched
// that out and enforce host ordering of events, so P1 just goes first regardless of who
// won the original coin flip
if (t1 and t2) return .P1;
return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
}
return if (spe1 > spe2) .P1 else .P2;
}
fn doTurn(
battle: anytype,
player: Player,
player_choice: Choice,
player_rewrap: bool,
player_skip: bool,
foe_player: Player,
foe_choice: Choice,
foe_rewrap: bool,
foe_skip: bool,
options: anytype,
) !?Result {
assert(player_choice.type != .Pass);
var residual = true;
var replace = battle.side(player).stored().hp == 0;
if (try executeMove(
battle,
player,
player_choice,
player_rewrap,
player_skip,
&residual,
options,
)) |r| return r;
if (!replace) {
if (player_choice.type != .Switch) {
if (try checkFaint(battle, foe_player, true, options)) |r| return r;
}
if (residual) try handleResidual(battle, player, options);
if (try checkFaint(battle, player, false, options)) |r| return r;
} else if (foe_choice.type == .Pass) return null;
if (!showdown) options.chance.clearPending();
residual = true;
replace = battle.side(foe_player).stored().hp == 0;
const calc = pkmn.options.calc and foe_choice.type == .Pass;
if (if (calc) null else try executeMove(
battle,
foe_player,
foe_choice,
foe_rewrap,
foe_skip,
&residual,
options,
)) |r| return r;
if (!replace) {
if (!calc and foe_choice.type != .Switch) {
if (try checkFaint(battle, player, true, options)) |r| return r;
}
if (residual) try handleResidual(battle, foe_player, options);
if (try checkFaint(battle, foe_player, false, options)) |r| return r;
}
// Flinch is bugged on Pokémon Showdown because it gets implemented with a duration which causes
// it to get removed in the non-existent "residual" phase instead of during move selection
if (showdown) {
battle.side(.P1).active.volatiles.Flinch = false;
battle.side(.P2).active.volatiles.Flinch = false;
}
return null;
}
fn executeMove(
battle: anytype,
player: Player,
choice: Choice,
rewrap: bool,
skip: bool,
residual: *bool,
options: anytype,
) !?Result {
var side = battle.side(player);
if (choice.type == .Switch) {
try switchIn(battle, player, choice.data, false, options);
return null;
}
// This is the correct place to check for SKIP_TURN and abort early, however since Pokémon
// Showdown overwrites the SKIP_TURN sentinel with its botched move select we need to add an
// additional skip boolean to accomplish the same thing in the Binding check of BeforeMove
if (side.last_selected_move == .SKIP_TURN) {
assert(!showdown);
if (battle.foe(player).active.volatiles.Binding) {
try options.log.cant(.{ battle.active(player), .Bound });
}
return null;
}
assert(choice.type == .Move);
var mslot: u4 = @intCast(choice.data);
// Sadly, we can't even check `Move.get(side.last_selected_move).effect == .Binding` here
// because Pokémon Showdown's Mirror Move implementation clobbers side.last_selected_move
var auto = showdown and side.last_selected_move != .None;
// GLITCH: Freeze top move selection desync & PP underflow shenanigans
if (mslot == 0 and side.last_selected_move != .None and side.last_selected_move != .Struggle) {
// choice.data == 0 only happens with Struggle on Pokémon Showdown
assert(!showdown);
mslot = @intCast(battle.lastMove(player).index);
const stored = side.stored();
// GLITCH: Struggle bypass PP underflow via Hyper Beam / Trapping-switch auto selection
auto = pkmn.options.mod or isForced(&side.active) or
side.active.volatiles.Binding or side.active.volatiles.Bide or
side.last_selected_move == .HyperBeam or
Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP);
// If it wasn't Hyper Beam or the continuation of a move effect then we must have just
// thawed, in which case we will desync unless the last_selected_move happened to be at
// index 1 and the current Pokémon has the same move in its first slot
if (!auto) {
// side.active.moves(slot) is safe to check even though the slot in question might not
// technically be from this Pokémon because it must be exactly 1 to not desync and
// every Pokémon must have at least one move
if (mslot != 1 or side.active.move(mslot).id != side.last_selected_move) {
return .Error;
} else {
auto = true;
}
}
} else if (showdown and side.active.volatiles.Charging) {
// Incorrect mslot with Pokémon Showdown choice semantics so we need to recover from index
assert(mslot == 1);
mslot = @intCast(battle.lastMove(player).index);
}
var skip_can = false;
var skip_pp = false;
switch (try beforeMove(battle, player, skip, residual, options)) {
.done => return null,
.skip_can => skip_can = true,
.skip_pp => skip_pp = true,
.ok => {},
.err => return .Error,
}
// Pokémon Showdown incorrectly implements PP deduction when handling the Hyper Beam automatic
// selection glitch - if the move was proced due to Metronome / Mirror Move it either subtracts
// from the Hyper Beam slot if present or skips PP deduction entirely...
if (showdown and !skip_pp and side.last_selected_move == .HyperBeam and
side.last_selected_move != side.active.move(mslot).id)
{
assert(mslot == 1);
const has_beam = has_beam: {
for (side.active.moves, 0..) |m, i| {
if (m.id == .HyperBeam) {
mslot = @intCast(i + 1);
break :has_beam true;
}
}
break :has_beam false;
};
if (!has_beam) skip_pp = true;
}
const can = skip_can or
try canMove(battle, player, mslot, auto, skip_pp, .None, residual, options);
if (!can) return null;
return doMove(battle, player, mslot, rewrap, auto, residual, options);
}
const BeforeMove = enum { done, skip_can, skip_pp, ok, err };
fn beforeMove(
battle: anytype,
player: Player,
skip: bool,
residual: *bool,
options: anytype,
) !BeforeMove {
var log = options.log;
var side = battle.side(player);
const foe = battle.foe(player);
var active = &side.active;
var stored = side.stored();
const ident = battle.active(player);
var volatiles = &active.volatiles;
if (Status.is(stored.status, .SLP)) {
const before = stored.status;
const slf = Status.is(stored.status, .EXT);
// Even if the EXT bit is set this will still correctly modify the sleep duration
if (options.calc.overridden(player, .sleep)) |obs| switch (obs) {
.started, .ended => stored.status = 0,
.continuing => if (Status.duration(stored.status) > 1) {
stored.status -= 1;
},
else => unreachable,
} else {
stored.status -= 1;
}
const duration = Status.duration(stored.status);
try options.chance.sleep(player, if (slf)
.None
else if (duration == 0) .ended else .continuing);
if (duration == 0) {
try log.curestatus(.{ ident, before, .Message });
stored.status = 0; // clears EXT if present
} else {
try log.cant(.{ ident, .Sleep });
}
side.last_used_move = .None;
return .done;
}
if (Status.is(stored.status, .FRZ)) {
try log.cant(.{ ident, .Freeze });
side.last_used_move = .None;
return .done;
}
if (skip or foe.active.volatiles.Binding) {
try log.cant(.{ ident, .Bound });
return .done;
}
if (volatiles.Flinch) {
// Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
// Pokémon can sometimes flinch multiple times from the same original hit
if (!showdown) volatiles.Flinch = false;
try log.cant(.{ ident, .Flinch });
return .done;
}
if (volatiles.Recharging) {
volatiles.Recharging = false;
try log.cant(.{ ident, .Recharge });
return .done;
}
if (volatiles.disable_duration > 0) {
volatiles.disable_duration =
decrement(.disable, player, options, volatiles.disable_duration);
try options.chance.disable(
player,
if (volatiles.disable_duration == 0) .ended else .continuing,
);
if (volatiles.disable_duration == 0) {
volatiles.disable_move = 0;
try log.end(.{ ident, .Disable });
}
}
// Pokémon Showdown's disable condition has a single onBeforeMove handler
if (showdown and try disabled(side, ident, options)) return .done;
// This can only happen if a Pokémon started the battle frozen/sleeping and was thawed/woken
// before the side had a selected a move - we simply need to assume this leads to a desync
if (side.last_selected_move == .None) {
assert(!pkmn.options.mod);
return .err;
}
if (volatiles.Confusion) {
assert(volatiles.confusion > 0);
if (options.calc.overridden(player, .confusion)) |obs| switch (obs) {
.started, .ended => volatiles.confusion = 0,
.continuing => if (volatiles.confusion > 1) {
volatiles.confusion -= 1;
},
.overwritten => {},
else => unreachable,
} else {
volatiles.confusion -= 1;
}
try options.chance.confusion(player, if (volatiles.confusion == 0) .ended else .continuing);
if (volatiles.confusion == 0) {
volatiles.Confusion = false;
try log.end(.{ ident, .Confusion });
} else {
try log.activate(.{ ident, .Confusion });
if (try Rolls.confused(battle, player, options)) {
assert(!volatiles.MultiHit);
if (!volatiles.Rage) volatiles.state = 0;
volatiles.Bide = false;
volatiles.Thrashing = false;
volatiles.MultiHit = false;
volatiles.Flinch = false;
volatiles.Charging = false;
volatiles.Binding = false;
volatiles.Invulnerable = false;
options.chance.observe(.attacking, player, .None);
options.chance.observe(.binding, player, .None);
{
// This feels (and is) disgusting but the cartridge literally just overwrites
// the opponent's defense with the user's defense and resets it after. As a
// result of this the *opponent's* Reflect impacts confusion self-hit damage
const def = foe.active.stats.def;
foe.active.stats.def = active.stats.def;
defer foe.active.stats.def = def;
if (!calcDamage(battle, player, player.foe(), null, false, options)) {
return .err;
}
}
const uncapped = battle.last_damage;
// Skipping adjustDamage / randomizeDamage / checkHit
_ = try applyDamage(battle, player, player.foe(), .Confusion, options);
// Pokémon Showdown thinks that confusion damage is uncapped ¯\_(ツ)_/¯
if (showdown) battle.last_damage = uncapped;
return .done;
}
}
}
if (!showdown and try disabled(side, ident, options)) return .done;
if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
if (!volatiles.Rage) volatiles.state = 0;
volatiles.Bide = false;
volatiles.Thrashing = false;
volatiles.Charging = false;
volatiles.Binding = false;
options.chance.observe(.attacking, player, .None);
options.chance.observe(.binding, player, .None);
// GLITCH: Invulnerable is not cleared, resulting in permanent Fly/Dig invulnerability
try log.cant(.{ ident, .Paralysis });
return .done;
}
if (volatiles.Bide) {
assert(!volatiles.Thrashing and !volatiles.Rage);
if (showdown) {
// Pokémon Showdown doesn't implement Bide potentially overflowing in the event of
// OHKO-move damage, but we can fake this incorrect behavior by simply saturating the
// addition because 65535 is sufficient to faint any Pokémon anyway
volatiles.state +|= battle.last_damage;
} else {
volatiles.state +%= battle.last_damage;
}
volatiles.attacks = decrement(.attacking, player, options, volatiles.attacks);
try options.chance.attacking(player, if (volatiles.attacks == 0) .ended else .continuing);
if (volatiles.attacks != 0) {
try log.activate(.{ ident, .Bide });
return .done;
}
volatiles.Bide = false;
try log.end(.{ ident, .Bide });
battle.last_damage = volatiles.state *% 2;
volatiles.state = 0;
if (battle.last_damage == 0) {
try log.fail(.{ ident, .None });
return .done;
}
const sub = showdown and foe.active.volatiles.Substitute;
_ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
if (foe.stored().hp > 0 and !sub) try buildRage(battle, player.foe(), options);
// For reasons passing understanding, Pokémon Showdown still inflicts residual damage to
// Bide's user even if the above damage has caused the foe to faint. It's simpler to always
// run residual here regardless of whether the foe fainted and opt-out of the default flow
if (showdown) {
residual.* = false;
try handleResidual(battle, player, options);
}
return .done;
}
if (volatiles.Thrashing) {
try log.move(.{ ident, side.last_selected_move, battle.active(player.foe()) });
volatiles.attacks = decrement(.attacking, player, options, volatiles.attacks);
try options.chance.attacking(player, if (volatiles.attacks == 0) .ended else .continuing);
if (volatiles.attacks == 0) {
const overwritten = volatiles.Confusion;
volatiles.Thrashing = false;
volatiles.Confusion = true;
volatiles.confusion = Rolls.confusionDuration(battle, player, options);
// On Pokémon Showdown this could leak information to the opponent that thrashing has
// ended (the engine's protocol is always from the omniscient perspective and clients
// can be expected to recognize this pattern and pass the information only to the
// correct player)
try log.start(.{ battle.active(player), .ConfusionSilent });
options.chance.observe(.confusion, player, if (overwritten)
if (pkmn.options.overwrite) .overwritten else .continuing
else
.started);
if (!overwritten) options.calc.confusion(player);
}
// This shouldn't actually set last_used_move, but Pokémon Showdown sets last
// used in useMove and doesn't have the notion of skipping canMove semantics
if (showdown) side.last_used_move = side.last_selected_move;
return .skip_can;
}
if (volatiles.Binding) {
volatiles.attacks = decrement(.binding, player, options, volatiles.attacks);
try options.chance.binding(player, if (volatiles.attacks == 0) .ended else .continuing);
try log.move(.{ ident, side.last_selected_move, battle.active(player.foe()) });
if (showdown or battle.last_damage != 0) {
const sub = showdown and foe.active.volatiles.Substitute;
_ = try applyDamage(battle, player.foe(), player.foe(), .None, options);
if (battle.foe(player).stored().hp > 0 and !sub) {
try buildRage(battle, player.foe(), options);
}
}
return .done;
}
return if (volatiles.Rage) .skip_pp else .ok;
}
fn canMove(
battle: anytype,
player: Player,
mslot: u4,
auto: bool,
skip_pp: bool,
from: Move,
residual: *bool,
options: anytype,
) !bool {
var side = battle.side(player);
const player_ident = battle.active(player);
const move = Move.get(side.last_selected_move);
if (side.active.volatiles.Charging) {
side.active.volatiles.Charging = false;
side.active.volatiles.Invulnerable = false;
} else if (move.effect == .Charge) {
try options.log.move(.{ player_ident, side.last_selected_move, ID{}, from });
setCounterable(battle, player, side, move);
try Effects.charge(battle, player, options);
return false;
}
side.last_used_move = side.last_selected_move;
if (!skip_pp) decrementPP(side, mslot, auto);
const target = if (move.target == .Self) player else player.foe();
try options.log.move(.{ player_ident, side.last_selected_move, battle.active(target), from });
setCounterable(battle, player, side, move);
if (move.effect.onBegin()) {
try onBegin(battle, player, move, mslot, residual, options);
return false;
}
if (move.effect == .Thrashing) {
Effects.thrashing(battle, player, options);
} else if (move.effect == .Binding) {
// Pokémon Showdown handles this after hit/miss checks and damage calculation, though clears
// Recharging in onTryMove (required for the Hyper Beam automatic selection glitch)
if (showdown) {
battle.foe(player).active.volatiles.Recharging = false;
} else {
try Effects.binding(battle, player, false, options);
}
}
return true;
}
fn setCounterable(battle: anytype, player: Player, side: *Side, move: Move.Data) void {
// The Counter desync is caused by the cartridge not calling GetCurrentMove until now, meaning
// in cases where an early return happens the data for a players last selected move does not get
// reloaded and HandleCounterMove actually bases its success/failure off of stale information.
// This boolean state we track here doesn't exist on the cartridge because it instead manifests
// as the desync results from actually having two separate battle states that subtly disagree
const counterable = side.last_selected_move != .Counter and move.bp > 0 and
(move.type == .Normal or move.type == .Fighting);
battle.lastMove(player).counterable = @intFromBool(counterable);
}
fn decrementPP(side: *Side, mslot: u4, auto: bool) void {
if (side.last_selected_move == .Struggle) return;
var active = &side.active;
const volatiles = &active.volatiles;
assert(!volatiles.Rage and !volatiles.Thrashing and !volatiles.MultiHit);
if (volatiles.Bide) return;
var move_slot = active.move(mslot);
assert(move_slot.pp > 0 or auto);
move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
if (volatiles.Transform) return;
move_slot = side.stored().move(mslot);
assert(move_slot.pp > 0 or auto);
move_slot.pp = @as(u6, @intCast(move_slot.pp)) -% 1;
assert(active.move(mslot).pp == side.stored().move(mslot).pp);
}
fn incrementPP(side: *Side, player: Player, mslot: u4, options: anytype) void {
var active = &side.active;
const volatiles = &active.volatiles;
active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) +% 1;
// GLITCH: No check for Transform means an empty/incorrect stored slot can get incremented
if (showdown and volatiles.Transform) return;
const n = options.calc.overridden(player, .pp) orelse 1;
if (volatiles.Transform and !options.chance.pp(player, n)) return;
assert(mslot > 0 and mslot <= 4);
side.stored().moves[mslot - 1].pp = @as(u6, @intCast(side.stored().moves[mslot - 1].pp)) +% n;
}
// Pokémon Showdown does hit/multi/crit/damage instead of crit/damage/hit/multi
fn doMove(
battle: anytype,
player: Player,
mslot: u4,
rewrap: bool,
auto: bool,
residual: *bool,
options: anytype,
) !?Result {
var log = options.log;
var side = battle.side(player);
const foe = battle.foe(player);
var move = Move.get(side.last_selected_move);
const counter = side.last_selected_move == .Counter;
const status = move.bp == 0 and move.effect != .OHKO;
var crit = false;
var ohko = false;
var immune = false;
var mist = false;
var hits: u4 = 1;
var effectiveness = Effectiveness.neutral;
// Due to control flow shenanigans we need to clear last_damage for Pokémon Showdown
if (showdown and !counter) battle.last_damage = 0;
// The cartridge handles set damage moves in applyDamage but we short circuit to simplify things
if (move.effect == .SuperFang or move.effect == .SpecialDamage) {
return specialDamage(battle, player, move, options);
}
// Pokémon Showdown runs invulnerability / immunity checks before checking accuracy - simply
// calling moveHit early covers most of that but we also need to check type immunity first
var miss = showdown and miss: {
immune = move.target != .Self and !status and !counter and
(@intFromEnum(move.type.effectiveness(foe.active.types.type1)) == 0 or
@intFromEnum(move.type.effectiveness(foe.active.types.type2)) == 0);
if (immune and move.effect != .Binding) break :miss true;
if (move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe) {
battle.last_damage = 0;
break :miss true;
}
break :miss (move.target != .Self and
!try moveHit(battle, player, move, &immune, &mist, options));
};
assert(!immune or miss or (showdown and move.effect == .Binding));
var late = showdown and move.effect != .Explode;
const skip = status or immune;
if ((!showdown or (!skip or counter)) and !miss) damage: {
if (showdown and move.effect.isMulti()) {
try Effects.multiHit(battle, player, move, options);
hits = side.active.volatiles.attacks;
late = false;
}
// Cartridge rolls for crit even for moves that can't crit (Counter/Metronome/status/OHKO)
const check = !showdown or (!counter and move.effect != .OHKO);
if (check) crit = try checkCriticalHit(battle, player, move, options);
if (counter) return counterDamage(battle, player, move, options);
battle.last_damage = 0;
// Disassembly does a check to allow 0 BP MultiHit moves but this isn't possible in practice
assert(move.effect != .MultiHit or move.bp > 0);
if (!skip) {
if (move.effect == .OHKO) {
ohko = if (!showdown) side.active.stats.spe >= foe.active.stats.spe else true;
// This can overflow after adjustDamage, but will still be sufficient to OHKO
battle.last_damage = if (ohko) 65535 else 0;
if (showdown) break :damage; // skip adjustDamage / randomizeDamage
} else if (!calcDamage(battle, player, player.foe(), move, crit, options)) {
if (!showdown) try options.chance.commit(player, .err);
return .Error;
}
if (battle.last_damage == 0) {
immune = true;
effectiveness = 0;
} else {
effectiveness = adjustDamage(battle, player);
immune = effectiveness == 0;
}
try randomizeDamage(battle, player, options);
}
}
var missed: bool = undefined;
const zero = battle.last_damage == 0;
if (!showdown and !skip) {
missed = !try moveHit(battle, player, move, &immune, &mist, options);
miss = missed or zero;
}
assert(showdown or miss or battle.last_damage > 0 or skip);
assert((!showdown and miss) or !(ohko and immune));
assert(!immune or miss or move.effect == .Binding);
if (!showdown or !miss) {
if (move.effect == .MirrorMove) {
return mirrorMove(battle, player, mslot, rewrap, auto, residual, options);
} else if (move.effect == .Metronome) {
return metronome(battle, player, mslot, rewrap, auto, residual, options);
} else if (move.effect.onEnd()) {
try onEnd(battle, player, move, options);
return null;
}
}
if (miss) {
const foe_ident = battle.active(player.foe());
const invulnerable =
showdown and foe.active.volatiles.Invulnerable and move.effect != .Swift;
ohko = (!showdown or (!immune and !invulnerable)) and
move.effect == .OHKO and side.active.stats.spe < foe.active.stats.spe;
if (ohko) {
try log.immune(.{ foe_ident, .OHKO });
} else if (immune and !invulnerable and (!showdown or move.effect != .Binding)) {
try log.immune(.{ foe_ident, .None });
if (!showdown) {
if (move.effect == .Binding) {
// Rather obnoxiously, the cartridge sets the Binding volatile in canMove and
// then simply clears it later on if the move happens to miss in moveHit.
// However, moveHit can return true and we'll still end up in the outer miss
// handling block because attacking into an immune Pokemon does zero damage
// (considered missing)
assert(zero);
// Thus we still need to actually save the hit result (but not the crit roll).
// Using .miss for this commit would accomplish what we want, but is somewhat
// misleading as its entirely possible the move actually did hit (and the target
// is now trapped) so we use the .binding value instead which is effectively
// identical, just doesn't claim to know about the actual results of the hit
// roll)
try options.chance.commit(player, .binding);
} else {
// The .glitch option allows for conditionally committing if we are in a
// division-by-zero freeze alternative timeline scenario
try options.chance.commit(player, .glitch);
}
}
} else if (mist) {
if (!foe.active.volatiles.Substitute) try log.activate(.{ foe_ident, .Mist });
try log.fail(.{ foe_ident, .None });
} else {
if (!showdown) try options.chance.commit(player, if (zero and !missed) .hit else .miss);
try log.lastmiss(.{});
try log.miss(.{battle.active(player)});
}
if (move.effect == .JumpKick) {
// Recoil is supposed to be damage/8 but damage will always be 0 here
assert(showdown or battle.last_damage == 0);
battle.last_damage = 1;
_ = try applyDamage(battle, player, player.foe(), .None, options);
if (showdown and side.stored().hp == 0) residual.* = false;
} else if (move.effect == .Explode) {
try Effects.explode(battle, player);