-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathbattle-actions.ts
1970 lines (1791 loc) · 71.2 KB
/
battle-actions.ts
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
import {Dex, toID} from './dex';
const CHOOSABLE_TARGETS = new Set(['normal', 'any', 'adjacentAlly', 'adjacentAllyOrSelf', 'adjacentFoe']);
export class BattleActions {
battle: Battle;
dex: ModdedDex;
readonly MAX_MOVES: {readonly [k: string]: string} = {
Flying: 'Max Airstream',
Dark: 'Max Darkness',
Fire: 'Max Flare',
Bug: 'Max Flutterby',
Water: 'Max Geyser',
Status: 'Max Guard',
Ice: 'Max Hailstorm',
Fighting: 'Max Knuckle',
Electric: 'Max Lightning',
Psychic: 'Max Mindstorm',
Poison: 'Max Ooze',
Grass: 'Max Overgrowth',
Ghost: 'Max Phantasm',
Ground: 'Max Quake',
Rock: 'Max Rockfall',
Fairy: 'Max Starfall',
Steel: 'Max Steelspike',
Normal: 'Max Strike',
Dragon: 'Max Wyrmwind',
};
readonly Z_MOVES: {readonly [k: string]: string} = {
Poison: "Acid Downpour",
Fighting: "All-Out Pummeling",
Dark: "Black Hole Eclipse",
Grass: "Bloom Doom",
Normal: "Breakneck Blitz",
Rock: "Continental Crush",
Steel: "Corkscrew Crash",
Dragon: "Devastating Drake",
Electric: "Gigavolt Havoc",
Water: "Hydro Vortex",
Fire: "Inferno Overdrive",
Ghost: "Never-Ending Nightmare",
Bug: "Savage Spin-Out",
Psychic: "Shattered Psyche",
Ice: "Subzero Slammer",
Flying: "Supersonic Skystrike",
Ground: "Tectonic Rage",
Fairy: "Twinkle Tackle",
};
constructor(battle: Battle) {
this.battle = battle;
this.dex = battle.dex;
if (this.dex.data.Scripts.actions) Object.assign(this, this.dex.data.Scripts.actions);
if (battle.format.actions) Object.assign(this, battle.format.actions);
}
// #region SWITCH
// ==================================================================
switchIn(pokemon: Pokemon, pos: number, sourceEffect: Effect | null = null, isDrag?: boolean) {
if (!pokemon || pokemon.isActive) {
this.battle.hint("A switch failed because the Pokémon trying to switch in is already in.");
return false;
}
const side = pokemon.side;
if (pos >= side.active.length) {
throw new Error(`Invalid switch position ${pos} / ${side.active.length}`);
}
const oldActive = side.active[pos];
const unfaintedActive = oldActive?.hp ? oldActive : null;
if (unfaintedActive) {
oldActive.beingCalledBack = true;
let switchCopyFlag: 'copyvolatile' | 'shedtail' | boolean = false;
if (sourceEffect && typeof (sourceEffect as Move).selfSwitch === 'string') {
switchCopyFlag = (sourceEffect as Move).selfSwitch!;
}
if (!oldActive.skipBeforeSwitchOutEventFlag && !isDrag) {
this.battle.runEvent('BeforeSwitchOut', oldActive);
if (this.battle.gen >= 5) {
this.battle.eachEvent('Update');
}
}
oldActive.skipBeforeSwitchOutEventFlag = false;
if (!this.battle.runEvent('SwitchOut', oldActive)) {
// Warning: DO NOT interrupt a switch-out if you just want to trap a pokemon.
// To trap a pokemon and prevent it from switching out, (e.g. Mean Look, Magnet Pull)
// use the 'trapped' flag instead.
// Note: Nothing in the real games can interrupt a switch-out (except Pursuit KOing,
// which is handled elsewhere); this is just for custom formats.
return false;
}
if (!oldActive.hp) {
// a pokemon fainted from Pursuit before it could switch
return 'pursuitfaint';
}
// will definitely switch out at this point
oldActive.illusion = null;
this.battle.singleEvent('End', oldActive.getAbility(), oldActive.abilityState, oldActive);
// if a pokemon is forced out by Whirlwind/etc or Eject Button/Pack, it can't use its chosen move
this.battle.queue.cancelAction(oldActive);
let newMove = null;
if (this.battle.gen === 4 && sourceEffect) {
newMove = oldActive.lastMove;
}
if (switchCopyFlag) {
pokemon.copyVolatileFrom(oldActive, switchCopyFlag);
}
if (newMove) pokemon.lastMove = newMove;
oldActive.clearVolatile();
}
if (oldActive) {
oldActive.isActive = false;
oldActive.isStarted = false;
oldActive.usedItemThisTurn = false;
oldActive.statsRaisedThisTurn = false;
oldActive.statsLoweredThisTurn = false;
oldActive.position = pokemon.position;
pokemon.position = pos;
side.pokemon[pokemon.position] = pokemon;
side.pokemon[oldActive.position] = oldActive;
}
pokemon.isActive = true;
side.active[pos] = pokemon;
pokemon.activeTurns = 0;
pokemon.activeMoveActions = 0;
for (const moveSlot of pokemon.moveSlots) {
moveSlot.used = false;
}
this.battle.runEvent('BeforeSwitchIn', pokemon);
if (sourceEffect) {
this.battle.add(isDrag ? 'drag' : 'switch', pokemon, pokemon.getDetails, '[from] ' + sourceEffect);
} else {
this.battle.add(isDrag ? 'drag' : 'switch', pokemon, pokemon.getDetails);
}
pokemon.abilityOrder = this.battle.abilityOrder++;
if (isDrag && this.battle.gen === 2) pokemon.draggedIn = this.battle.turn;
pokemon.previouslySwitchedIn++;
if (isDrag && this.battle.gen >= 5) {
// runSwitch happens immediately so that Mold Breaker can make hazards bypass Clear Body and Levitate
this.battle.singleEvent('PreStart', pokemon.getAbility(), pokemon.abilityState, pokemon);
this.runSwitch(pokemon);
} else {
this.battle.queue.insertChoice({choice: 'runUnnerve', pokemon});
this.battle.queue.insertChoice({choice: 'runSwitch', pokemon});
}
return true;
}
dragIn(side: Side, pos: number) {
const pokemon = this.battle.getRandomSwitchable(side);
if (!pokemon || pokemon.isActive) return false;
const oldActive = side.active[pos];
if (!oldActive) throw new Error(`nothing to drag out`);
if (!oldActive.hp) return false;
if (!this.battle.runEvent('DragOut', oldActive)) {
return false;
}
if (!this.switchIn(pokemon, pos, null, true)) return false;
return true;
}
runSwitch(pokemon: Pokemon) {
this.battle.runEvent('Swap', pokemon);
if (this.battle.gen >= 5) {
this.battle.runEvent('SwitchIn', pokemon);
}
this.battle.runEvent('EntryHazard', pokemon);
if (this.battle.gen <= 4) {
this.battle.runEvent('SwitchIn', pokemon);
}
if (this.battle.gen <= 2) {
// pokemon.lastMove is reset for all Pokemon on the field after a switch. This affects Mirror Move.
for (const poke of this.battle.getAllActive()) poke.lastMove = null;
if (!pokemon.side.faintedThisTurn && pokemon.draggedIn !== this.battle.turn) {
this.battle.runEvent('AfterSwitchInSelf', pokemon);
}
}
if (!pokemon.hp) return false;
pokemon.isStarted = true;
if (!pokemon.fainted) {
this.battle.singleEvent('Start', pokemon.getAbility(), pokemon.abilityState, pokemon);
this.battle.singleEvent('Start', pokemon.getItem(), pokemon.itemState, pokemon);
}
if (this.battle.gen === 4) {
for (const foeActive of pokemon.foes()) {
foeActive.removeVolatile('substitutebroken');
}
}
pokemon.draggedIn = null;
return true;
}
// #endregion
// #region MOVES
// ==================================================================
/**
* runMove is the "outside" move caller. It handles deducting PP,
* flinching, full paralysis, etc. All the stuff up to and including
* the "POKEMON used MOVE" message.
*
* For details of the difference between runMove and useMove, see
* useMove's info.
*
* externalMove skips LockMove and PP deduction, mostly for use by
* Dancer.
*/
runMove(
moveOrMoveName: Move | string, pokemon: Pokemon, targetLoc: number,
options?: {
sourceEffect?: Effect | null, zMove?: string, externalMove?: boolean,
maxMove?: string, originalTarget?: Pokemon,
}
) {
pokemon.activeMoveActions++;
const zMove = options?.zMove;
const maxMove = options?.maxMove;
const externalMove = options?.externalMove;
const originalTarget = options?.originalTarget;
let sourceEffect = options?.sourceEffect;
let target = this.battle.getTarget(pokemon, maxMove || zMove || moveOrMoveName, targetLoc, originalTarget);
let baseMove = this.dex.getActiveMove(moveOrMoveName);
const priority = baseMove.priority;
const pranksterBoosted = baseMove.pranksterBoosted;
if (baseMove.id !== 'struggle' && !zMove && !maxMove && !externalMove) {
const changedMove = this.battle.runEvent('OverrideAction', pokemon, target, baseMove);
if (changedMove && changedMove !== true) {
baseMove = this.dex.getActiveMove(changedMove);
baseMove.priority = priority;
if (pranksterBoosted) baseMove.pranksterBoosted = pranksterBoosted;
target = this.battle.getRandomTarget(pokemon, baseMove);
}
}
let move = baseMove;
if (zMove) {
move = this.getActiveZMove(baseMove, pokemon);
} else if (maxMove) {
move = this.getActiveMaxMove(baseMove, pokemon);
}
move.isExternal = externalMove;
this.battle.setActiveMove(move, pokemon, target);
/* if (pokemon.moveThisTurn) {
// THIS IS PURELY A SANITY CHECK
// DO NOT TAKE ADVANTAGE OF THIS TO PREVENT A POKEMON FROM MOVING;
// USE this.queue.cancelMove INSTEAD
this.battle.debug('' + pokemon.id + ' INCONSISTENT STATE, ALREADY MOVED: ' + pokemon.moveThisTurn);
this.battle.clearActiveMove(true);
return;
} */
const willTryMove = this.battle.runEvent('BeforeMove', pokemon, target, move);
if (!willTryMove) {
this.battle.runEvent('MoveAborted', pokemon, target, move);
this.battle.clearActiveMove(true);
// The event 'BeforeMove' could have returned false or null
// false indicates that this counts as a move failing for the purpose of calculating Stomping Tantrum's base power
// null indicates the opposite, as the Pokemon didn't have an option to choose anything
pokemon.moveThisTurnResult = willTryMove;
return;
}
// Used exclusively for a hint later
if (move.flags['cantusetwice'] && pokemon.lastMove?.id === move.id) {
pokemon.addVolatile(move.id);
}
if (move.beforeMoveCallback) {
if (move.beforeMoveCallback.call(this.battle, pokemon, target, move)) {
this.battle.clearActiveMove(true);
pokemon.moveThisTurnResult = false;
return;
}
}
pokemon.lastDamage = 0;
let lockedMove;
if (!externalMove) {
lockedMove = this.battle.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove) {
if (!pokemon.deductPP(baseMove, null, target) && (move.id !== 'struggle')) {
this.battle.add('cant', pokemon, 'nopp', move);
this.battle.clearActiveMove(true);
pokemon.moveThisTurnResult = false;
return;
}
} else {
sourceEffect = this.dex.conditions.get('lockedmove');
}
pokemon.moveUsed(move, targetLoc);
}
// Dancer Petal Dance hack
// TODO: implement properly
const noLock = externalMove && !pokemon.volatiles['lockedmove'];
if (zMove) {
if (pokemon.illusion) {
this.battle.singleEvent('End', this.dex.abilities.get('Illusion'), pokemon.abilityState, pokemon);
}
this.battle.add('-zpower', pokemon);
pokemon.side.zMoveUsed = true;
}
const oldActiveMove = move;
const moveDidSomething = this.useMove(baseMove, pokemon, {target, sourceEffect, zMove, maxMove});
this.battle.lastSuccessfulMoveThisTurn = moveDidSomething ? this.battle.activeMove && this.battle.activeMove.id : null;
if (this.battle.activeMove) move = this.battle.activeMove;
this.battle.singleEvent('AfterMove', move, null, pokemon, target, move);
this.battle.runEvent('AfterMove', pokemon, target, move);
if (move.flags['cantusetwice'] && pokemon.removeVolatile(move.id)) {
this.battle.add('-hint', `Some effects can force a Pokemon to use ${move.name} again in a row.`);
}
// Dancer's activation order is completely different from any other event, so it's handled separately
if (move.flags['dance'] && moveDidSomething && !move.isExternal) {
const dancers = [];
for (const currentPoke of this.battle.getAllActive()) {
if (pokemon === currentPoke) continue;
if (currentPoke.hasAbility('dancer') && !currentPoke.isSemiInvulnerable()) {
dancers.push(currentPoke);
}
}
// Dancer activates in order of lowest speed stat to highest
// Note that the speed stat used is after any volatile replacements like Speed Swap,
// but before any multipliers like Agility or Choice Scarf
// Ties go to whichever Pokemon has had the ability for the least amount of time
dancers.sort(
(a, b) => -(b.storedStats['spe'] - a.storedStats['spe']) || b.abilityOrder - a.abilityOrder
);
const targetOf1stDance = this.battle.activeTarget!;
for (const dancer of dancers) {
if (this.battle.faintMessages()) break;
if (dancer.fainted) continue;
this.battle.add('-activate', dancer, 'ability: Dancer');
const dancersTarget = !targetOf1stDance.isAlly(dancer) && pokemon.isAlly(dancer) ?
targetOf1stDance :
pokemon;
const dancersTargetLoc = dancer.getLocOf(dancersTarget);
this.runMove(move.id, dancer, dancersTargetLoc, {sourceEffect: this.dex.abilities.get('dancer'), externalMove: true});
}
}
if (noLock && pokemon.volatiles['lockedmove']) delete pokemon.volatiles['lockedmove'];
this.battle.faintMessages();
this.battle.checkWin();
if (this.battle.gen <= 4) {
// In gen 4, the outermost move is considered the last move for Copycat
this.battle.activeMove = oldActiveMove;
}
}
/**
* useMove is the "inside" move caller. It handles effects of the
* move itself, but not the idea of using the move.
*
* Most caller effects, like Sleep Talk, Nature Power, Magic Bounce,
* etc use useMove.
*
* The only ones that use runMove are Instruct, Pursuit, and
* Dancer.
*/
useMove(
move: Move | string, pokemon: Pokemon, options?: {
target?: Pokemon | null, sourceEffect?: Effect | null,
zMove?: string, maxMove?: string,
}
) {
pokemon.moveThisTurnResult = undefined;
const oldMoveResult: boolean | null | undefined = pokemon.moveThisTurnResult;
const moveResult = this.useMoveInner(move, pokemon, options);
if (oldMoveResult === pokemon.moveThisTurnResult) pokemon.moveThisTurnResult = moveResult;
return moveResult;
}
useMoveInner(
moveOrMoveName: Move | string, pokemon: Pokemon, options?: {
target?: Pokemon | null, sourceEffect?: Effect | null,
zMove?: string, maxMove?: string,
},
) {
let target = options?.target;
let sourceEffect = options?.sourceEffect;
const zMove = options?.zMove;
const maxMove = options?.maxMove;
if (!sourceEffect && this.battle.effect.id) sourceEffect = this.battle.effect;
if (sourceEffect && ['instruct', 'custapberry'].includes(sourceEffect.id)) sourceEffect = null;
let move = this.dex.getActiveMove(moveOrMoveName);
pokemon.lastMoveUsed = move;
if (move.id === 'weatherball' && zMove) {
// Z-Weather Ball only changes types if it's used directly,
// not if it's called by Z-Sleep Talk or something.
this.battle.singleEvent('ModifyType', move, null, pokemon, target, move, move);
if (move.type !== 'Normal') sourceEffect = move;
}
if (zMove || (move.category !== 'Status' && sourceEffect && (sourceEffect as ActiveMove).isZ)) {
move = this.getActiveZMove(move, pokemon);
}
if (maxMove && move.category !== 'Status') {
// Max move outcome is dependent on the move type after type modifications from ability and the move itself
this.battle.singleEvent('ModifyType', move, null, pokemon, target, move, move);
this.battle.runEvent('ModifyType', pokemon, target, move, move);
}
if (maxMove || (move.category !== 'Status' && sourceEffect && (sourceEffect as ActiveMove).isMax)) {
move = this.getActiveMaxMove(move, pokemon);
}
if (this.battle.activeMove) {
move.priority = this.battle.activeMove.priority;
if (!move.hasBounced) move.pranksterBoosted = this.battle.activeMove.pranksterBoosted;
}
const baseTarget = move.target;
let targetRelayVar = {target};
targetRelayVar = this.battle.runEvent('ModifyTarget', pokemon, target, move, targetRelayVar, true);
if (targetRelayVar.target !== undefined) target = targetRelayVar.target;
if (target === undefined) target = this.battle.getRandomTarget(pokemon, move);
if (move.target === 'self' || move.target === 'allies') {
target = pokemon;
}
if (sourceEffect) {
move.sourceEffect = sourceEffect.id;
move.ignoreAbility = (sourceEffect as ActiveMove).ignoreAbility;
}
let moveResult = false;
this.battle.setActiveMove(move, pokemon, target);
this.battle.singleEvent('ModifyType', move, null, pokemon, target, move, move);
this.battle.singleEvent('ModifyMove', move, null, pokemon, target, move, move);
if (baseTarget !== move.target) {
// Target changed in ModifyMove, so we must adjust it here
// Adjust before the next event so the correct target is passed to the
// event
target = this.battle.getRandomTarget(pokemon, move);
}
move = this.battle.runEvent('ModifyType', pokemon, target, move, move);
move = this.battle.runEvent('ModifyMove', pokemon, target, move, move);
if (baseTarget !== move.target) {
// Adjust again
target = this.battle.getRandomTarget(pokemon, move);
}
if (!move || pokemon.fainted) {
return false;
}
let attrs = '';
let movename = move.name;
if (move.id === 'hiddenpower') movename = 'Hidden Power';
if (sourceEffect) attrs += `|[from] ${sourceEffect.fullname}`;
if (zMove && move.isZ === true) {
attrs = '|[anim]' + movename + attrs;
movename = 'Z-' + movename;
}
this.battle.addMove('move', pokemon, movename, target + attrs);
if (zMove) this.runZPower(move, pokemon);
if (!target) {
this.battle.attrLastMove('[notarget]');
this.battle.add(this.battle.gen >= 5 ? '-fail' : '-notarget', pokemon);
return false;
}
const {targets, pressureTargets} = pokemon.getMoveTargets(move, target);
if (targets.length) {
target = targets[targets.length - 1]; // in case of redirection
}
const callerMoveForPressure = sourceEffect && (sourceEffect as ActiveMove).pp ? sourceEffect as ActiveMove : null;
if (!sourceEffect || callerMoveForPressure || sourceEffect.id === 'pursuit') {
let extraPP = 0;
for (const source of pressureTargets) {
const ppDrop = this.battle.runEvent('DeductPP', source, pokemon, move);
if (ppDrop !== true) {
extraPP += ppDrop || 0;
}
}
if (extraPP > 0) {
pokemon.deductPP(callerMoveForPressure || moveOrMoveName, extraPP);
}
}
if (!this.battle.singleEvent('TryMove', move, null, pokemon, target, move) ||
!this.battle.runEvent('TryMove', pokemon, target, move)) {
move.mindBlownRecoil = false;
return false;
}
this.battle.singleEvent('UseMoveMessage', move, null, pokemon, target, move);
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
if (this.battle.gen !== 4 && move.selfdestruct === 'always') {
this.battle.faint(pokemon, pokemon, move);
}
let damage: number | false | undefined | '' = false;
if (move.target === 'all' || move.target === 'foeSide' || move.target === 'allySide' || move.target === 'allyTeam') {
damage = this.tryMoveHit(targets, pokemon, move);
if (damage === this.battle.NOT_FAIL) pokemon.moveThisTurnResult = null;
if (damage || damage === 0 || damage === undefined) moveResult = true;
} else {
if (!targets.length) {
this.battle.attrLastMove('[notarget]');
this.battle.add(this.battle.gen >= 5 ? '-fail' : '-notarget', pokemon);
return false;
}
if (this.battle.gen === 4 && move.selfdestruct === 'always') {
this.battle.faint(pokemon, pokemon, move);
}
moveResult = this.trySpreadMoveHit(targets, pokemon, move);
}
if (move.selfBoost && moveResult) this.moveHit(pokemon, pokemon, move, move.selfBoost, false, true);
if (!pokemon.hp) {
this.battle.faint(pokemon, pokemon, move);
}
if (!moveResult) {
this.battle.singleEvent('MoveFail', move, null, target, pokemon, move);
return false;
}
if (
!move.negateSecondary &&
!(move.hasSheerForce && pokemon.hasAbility('sheerforce')) &&
!move.flags['futuremove']
) {
const originalHp = pokemon.hp;
this.battle.singleEvent('AfterMoveSecondarySelf', move, null, pokemon, target, move);
this.battle.runEvent('AfterMoveSecondarySelf', pokemon, target, move);
if (pokemon && pokemon !== target && move.category !== 'Status') {
if (pokemon.hp <= pokemon.maxhp / 2 && originalHp > pokemon.maxhp / 2) {
this.battle.runEvent('EmergencyExit', pokemon, pokemon);
}
}
}
return true;
}
/** NOTE: includes single-target moves */
trySpreadMoveHit(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove, notActive?: boolean) {
if (targets.length > 1 && !move.smartTarget) move.spreadHit = true;
const moveSteps: ((targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) =>
(number | boolean | "" | undefined)[] | undefined)[] = [
// 0. check for semi invulnerability
this.hitStepInvulnerabilityEvent,
// 1. run the 'TryHit' event (Protect, Magic Bounce, Volt Absorb, etc.) (this is step 2 in gens 5 & 6, and step 4 in gen 4)
this.hitStepTryHitEvent,
// 2. check for type immunity (this is step 1 in gens 4-6)
this.hitStepTypeImmunity,
// 3. check for various move-specific immunities
this.hitStepTryImmunity,
// 4. check accuracy
this.hitStepAccuracy,
// 5. break protection effects
this.hitStepBreakProtect,
// 6. steal positive boosts (Spectral Thief)
this.hitStepStealBoosts,
// 7. loop that processes each hit of the move (has its own steps per iteration)
this.hitStepMoveHitLoop,
];
if (this.battle.gen <= 6) {
// Swap step 1 with step 2
[moveSteps[1], moveSteps[2]] = [moveSteps[2], moveSteps[1]];
}
if (this.battle.gen === 4) {
// Swap step 4 with new step 2 (old step 1)
[moveSteps[2], moveSteps[4]] = [moveSteps[4], moveSteps[2]];
}
if (notActive) this.battle.setActiveMove(move, pokemon, targets[0]);
const hitResult = this.battle.singleEvent('Try', move, null, pokemon, targets[0], move) &&
this.battle.singleEvent('PrepareHit', move, {}, targets[0], pokemon, move) &&
this.battle.runEvent('PrepareHit', pokemon, targets[0], move);
if (!hitResult) {
if (hitResult === false) {
this.battle.add('-fail', pokemon);
this.battle.attrLastMove('[still]');
}
return hitResult === this.battle.NOT_FAIL;
}
let atLeastOneFailure = false;
for (const step of moveSteps) {
const hitResults: (number | boolean | "" | undefined)[] | undefined = step.call(this, targets, pokemon, move);
if (!hitResults) continue;
targets = targets.filter((val, i) => hitResults[i] || hitResults[i] === 0);
atLeastOneFailure = atLeastOneFailure || hitResults.some(val => val === false);
if (move.smartTarget && atLeastOneFailure) move.smartTarget = false;
if (!targets.length) {
// console.log(step.name);
break;
}
}
const moveResult = !!targets.length;
if (!moveResult && !atLeastOneFailure) pokemon.moveThisTurnResult = null;
const hitSlot = targets.map(p => p.getSlot());
if (move.spreadHit) this.battle.attrLastMove('[spread] ' + hitSlot.join(','));
return moveResult;
}
hitStepInvulnerabilityEvent(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
if (move.id === 'helpinghand') return new Array(targets.length).fill(true);
const hitResults: boolean[] = [];
for (const [i, target] of targets.entries()) {
if (target.volatiles['commanding']) {
hitResults[i] = false;
} else if (this.battle.gen >= 8 && move.id === 'toxic' && pokemon.hasType('Poison')) {
hitResults[i] = true;
} else {
hitResults[i] = this.battle.runEvent('Invulnerability', target, pokemon, move);
}
if (hitResults[i] === false) {
if (move.smartTarget) {
move.smartTarget = false;
} else {
if (!move.spreadHit) this.battle.attrLastMove('[miss]');
this.battle.add('-miss', pokemon, target);
}
}
}
return hitResults;
}
hitStepTryHitEvent(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
const hitResults = this.battle.runEvent('TryHit', targets, pokemon, move);
if (!hitResults.includes(true) && hitResults.includes(false)) {
this.battle.add('-fail', pokemon);
this.battle.attrLastMove('[still]');
}
for (const i of targets.keys()) {
if (hitResults[i] !== this.battle.NOT_FAIL) hitResults[i] = hitResults[i] || false;
}
return hitResults;
}
hitStepTypeImmunity(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
if (move.ignoreImmunity === undefined) {
move.ignoreImmunity = (move.category === 'Status');
}
const hitResults = [];
for (const i of targets.keys()) {
hitResults[i] = (move.ignoreImmunity && (move.ignoreImmunity === true || move.ignoreImmunity[move.type])) ||
targets[i].runImmunity(move.type, !move.smartTarget);
}
return hitResults;
}
hitStepTryImmunity(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
const hitResults = [];
for (const [i, target] of targets.entries()) {
if (this.battle.gen >= 6 && move.flags['powder'] && target !== pokemon && !this.dex.getImmunity('powder', target)) {
this.battle.debug('natural powder immunity');
this.battle.add('-immune', target);
hitResults[i] = false;
} else if (!this.battle.singleEvent('TryImmunity', move, {}, target, pokemon, move)) {
this.battle.add('-immune', target);
hitResults[i] = false;
} else if (this.battle.gen >= 7 && move.pranksterBoosted && pokemon.hasAbility('prankster') &&
!targets[i].isAlly(pokemon) && !this.dex.getImmunity('prankster', target)) {
this.battle.debug('natural prankster immunity');
if (target.illusion || !(move.status && !this.dex.getImmunity(move.status, target))) {
this.battle.hint("Since gen 7, Dark is immune to Prankster moves.");
}
this.battle.add('-immune', target);
hitResults[i] = false;
} else {
hitResults[i] = true;
}
}
return hitResults;
}
hitStepAccuracy(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
const hitResults = [];
for (const [i, target] of targets.entries()) {
this.battle.activeTarget = target;
// calculate true accuracy
let accuracy = move.accuracy;
if (move.ohko) { // bypasses accuracy modifiers
if (!target.isSemiInvulnerable()) {
accuracy = 30;
if (move.ohko === 'Ice' && this.battle.gen >= 7 && !pokemon.hasType('Ice')) {
accuracy = 20;
}
if (!target.volatiles['dynamax'] && pokemon.level >= target.level &&
(move.ohko === true || !target.hasType(move.ohko))) {
accuracy += (pokemon.level - target.level);
} else {
this.battle.add('-immune', target, '[ohko]');
hitResults[i] = false;
continue;
}
}
} else {
accuracy = this.battle.runEvent('ModifyAccuracy', target, pokemon, move, accuracy);
if (accuracy !== true) {
let boost = 0;
if (!move.ignoreAccuracy) {
const boosts = this.battle.runEvent('ModifyBoost', pokemon, null, null, {...pokemon.boosts});
boost = this.battle.clampIntRange(boosts['accuracy'], -6, 6);
}
if (!move.ignoreEvasion) {
const boosts = this.battle.runEvent('ModifyBoost', target, null, null, {...target.boosts});
boost = this.battle.clampIntRange(boost - boosts['evasion'], -6, 6);
}
if (boost > 0) {
accuracy = this.battle.trunc(accuracy * (3 + boost) / 3);
} else if (boost < 0) {
accuracy = this.battle.trunc(accuracy * 3 / (3 - boost));
}
}
}
if (move.alwaysHit || (move.id === 'toxic' && this.battle.gen >= 8 && pokemon.hasType('Poison')) ||
(move.target === 'self' && move.category === 'Status' && !target.isSemiInvulnerable())) {
accuracy = true; // bypasses ohko accuracy modifiers
} else {
accuracy = this.battle.runEvent('Accuracy', target, pokemon, move, accuracy);
}
if (accuracy !== true && !this.battle.randomChance(accuracy, 100)) {
if (move.smartTarget) {
move.smartTarget = false;
} else {
if (!move.spreadHit) this.battle.attrLastMove('[miss]');
this.battle.add('-miss', pokemon, target);
}
if (!move.ohko && pokemon.hasItem('blunderpolicy') && pokemon.useItem()) {
this.battle.boost({spe: 2}, pokemon);
}
hitResults[i] = false;
continue;
}
hitResults[i] = true;
}
return hitResults;
}
hitStepBreakProtect(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
if (move.breaksProtect) {
for (const target of targets) {
let broke = false;
for (const effectid of [
'banefulbunker', 'burningbulwark', 'kingsshield', 'obstruct', 'protect', 'silktrap', 'spikyshield',
]) {
if (target.removeVolatile(effectid)) broke = true;
}
if (this.battle.gen >= 6 || !target.isAlly(pokemon)) {
for (const effectid of ['craftyshield', 'matblock', 'quickguard', 'wideguard']) {
if (target.side.removeSideCondition(effectid)) broke = true;
}
}
if (broke) {
if (move.id === 'feint') {
this.battle.add('-activate', target, 'move: Feint');
} else {
this.battle.add('-activate', target, 'move: ' + move.name, '[broken]');
}
if (this.battle.gen >= 6) delete target.volatiles['stall'];
}
}
}
return undefined;
}
hitStepStealBoosts(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
const target = targets[0]; // hardcoded
if (move.stealsBoosts) {
const boosts: SparseBoostsTable = {};
let stolen = false;
let statName: BoostID;
for (statName in target.boosts) {
const stage = target.boosts[statName];
if (stage > 0) {
boosts[statName] = stage;
stolen = true;
}
}
if (stolen) {
this.battle.attrLastMove('[still]');
this.battle.add('-clearpositiveboost', target, pokemon, 'move: ' + move.name);
this.battle.boost(boosts, pokemon, pokemon);
let statName2: BoostID;
for (statName2 in boosts) {
boosts[statName2] = 0;
}
target.setBoost(boosts);
if (move.id === "spectralthief") {
this.battle.addMove('-anim', pokemon, "Spectral Thief", target);
}
}
}
return undefined;
}
afterMoveSecondaryEvent(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) {
// console.log(`${targets}, ${pokemon}, ${move}`)
if (!move.negateSecondary && !(move.hasSheerForce && pokemon.hasAbility('sheerforce'))) {
this.battle.singleEvent('AfterMoveSecondary', move, null, targets[0], pokemon, move);
this.battle.runEvent('AfterMoveSecondary', targets, pokemon, move);
}
return undefined;
}
/** NOTE: used only for moves that target sides/fields rather than pokemon */
tryMoveHit(targetOrTargets: Pokemon | Pokemon[], pokemon: Pokemon, move: ActiveMove): number | undefined | false | '' {
const target = Array.isArray(targetOrTargets) ? targetOrTargets[0] : targetOrTargets;
const targets = Array.isArray(targetOrTargets) ? targetOrTargets : [target];
this.battle.setActiveMove(move, pokemon, targets[0]);
let hitResult = this.battle.singleEvent('Try', move, null, pokemon, target, move) &&
this.battle.singleEvent('PrepareHit', move, {}, target, pokemon, move) &&
this.battle.runEvent('PrepareHit', pokemon, target, move);
if (!hitResult) {
if (hitResult === false) {
this.battle.add('-fail', pokemon);
this.battle.attrLastMove('[still]');
}
return false;
}
const isFFAHazard = move.target === 'foeSide' && this.battle.gameType === 'freeforall';
if (move.target === 'all') {
hitResult = this.battle.runEvent('TryHitField', target, pokemon, move);
} else if (isFFAHazard) {
const hitResults: any[] = this.battle.runEvent('TryHitSide', targets, pokemon, move);
// if some side blocked the move, prevent the move from executing against any other sides
if (hitResults.some(result => !result)) return false;
hitResult = true;
} else {
hitResult = this.battle.runEvent('TryHitSide', target, pokemon, move);
}
if (!hitResult) {
if (hitResult === false) {
this.battle.add('-fail', pokemon);
this.battle.attrLastMove('[still]');
}
return false;
}
return this.moveHit(isFFAHazard ? targets : target, pokemon, move);
}
hitStepMoveHitLoop(targets: Pokemon[], pokemon: Pokemon, move: ActiveMove) { // Temporary name
let damage: (number | boolean | undefined)[] = [];
for (const i of targets.keys()) {
damage[i] = 0;
}
move.totalDamage = 0;
pokemon.lastDamage = 0;
let targetHits = move.multihit || 1;
if (Array.isArray(targetHits)) {
// yes, it's hardcoded... meh
if (targetHits[0] === 2 && targetHits[1] === 5) {
if (this.battle.gen >= 5) {
// 35-35-15-15 out of 100 for 2-3-4-5 hits
targetHits = this.battle.sample([2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5]);
if (targetHits < 4 && pokemon.hasItem('loadeddice')) {
targetHits = 5 - this.battle.random(2);
}
} else {
targetHits = this.battle.sample([2, 2, 2, 3, 3, 3, 4, 5]);
}
} else {
targetHits = this.battle.random(targetHits[0], targetHits[1] + 1);
}
}
if (targetHits === 10 && pokemon.hasItem('loadeddice')) targetHits -= this.battle.random(7);
targetHits = Math.floor(targetHits);
let nullDamage = true;
let moveDamage: (number | boolean | undefined)[] = [];
// There is no need to recursively check the ´sleepUsable´ flag as Sleep Talk can only be used while asleep.
const isSleepUsable = move.sleepUsable || this.dex.moves.get(move.sourceEffect).sleepUsable;
let targetsCopy: (Pokemon | false | null)[] = targets.slice(0);
let hit: number;
for (hit = 1; hit <= targetHits; hit++) {
if (damage.includes(false)) break;
if (hit > 1 && pokemon.status === 'slp' && (!isSleepUsable || this.battle.gen === 4)) break;
if (targets.every(target => !target?.hp)) break;
move.hit = hit;
if (move.smartTarget && targets.length > 1) {
targetsCopy = [targets[hit - 1]];
damage = [damage[hit - 1]];
} else {
targetsCopy = targets.slice(0);
}
const target = targetsCopy[0]; // some relevant-to-single-target-moves-only things are hardcoded
if (target && typeof move.smartTarget === 'boolean') {
if (hit > 1) {
this.battle.addMove('-anim', pokemon, move.name, target);
} else {
this.battle.retargetLastMove(target);
}
}
// like this (Triple Kick)
if (target && move.multiaccuracy && hit > 1) {
let accuracy = move.accuracy;
const boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
if (accuracy !== true) {
if (!move.ignoreAccuracy) {
const boosts = this.battle.runEvent('ModifyBoost', pokemon, null, null, {...pokemon.boosts});
const boost = this.battle.clampIntRange(boosts['accuracy'], -6, 6);
if (boost > 0) {
accuracy *= boostTable[boost];
} else {
accuracy /= boostTable[-boost];
}
}
if (!move.ignoreEvasion) {
const boosts = this.battle.runEvent('ModifyBoost', target, null, null, {...target.boosts});
const boost = this.battle.clampIntRange(boosts['evasion'], -6, 6);
if (boost > 0) {
accuracy /= boostTable[boost];
} else if (boost < 0) {
accuracy *= boostTable[-boost];
}
}
}
accuracy = this.battle.runEvent('ModifyAccuracy', target, pokemon, move, accuracy);
if (!move.alwaysHit) {
accuracy = this.battle.runEvent('Accuracy', target, pokemon, move, accuracy);
if (accuracy !== true && !this.battle.randomChance(accuracy, 100)) break;
}
}
const moveData = move;
if (!moveData.flags) moveData.flags = {};
let moveDamageThisHit;
// Modifies targetsCopy (which is why it's a copy)
[moveDamageThisHit, targetsCopy] = this.spreadMoveHit(targetsCopy, pokemon, move, moveData);
// When Dragon Darts targets two different pokemon, targetsCopy is a length 1 array each hit
// so spreadMoveHit returns a length 1 damage array
if (move.smartTarget) {
moveDamage.push(...moveDamageThisHit);
} else {
moveDamage = moveDamageThisHit;
}
if (!moveDamage.some(val => val !== false)) break;
nullDamage = false;
for (const [i, md] of moveDamage.entries()) {
if (move.smartTarget && i !== hit - 1) continue;
// Damage from each hit is individually counted for the
// purposes of Counter, Metal Burst, and Mirror Coat.
damage[i] = md === true || !md ? 0 : md;
// Total damage dealt is accumulated for the purposes of recoil (Parental Bond).
move.totalDamage += damage[i] as number;
}
if (move.mindBlownRecoil) {
const hpBeforeRecoil = pokemon.hp;
this.battle.damage(Math.round(pokemon.maxhp / 2), pokemon, pokemon, this.dex.conditions.get(move.id), true);
move.mindBlownRecoil = false;
if (pokemon.hp <= pokemon.maxhp / 2 && hpBeforeRecoil > pokemon.maxhp / 2) {
this.battle.runEvent('EmergencyExit', pokemon, pokemon);
}
}
this.battle.eachEvent('Update');
if (!pokemon.hp && targets.length === 1) {
hit++; // report the correct number of hits for multihit moves
break;
}
}
// hit is 1 higher than the actual hit count
if (hit === 1) return damage.fill(false);
if (nullDamage) damage.fill(false);
this.battle.faintMessages(false, false, !pokemon.hp);
if (move.multihit && typeof move.smartTarget !== 'boolean') {
this.battle.add('-hitcount', targets[0], hit - 1);
}
if ((move.recoil || move.id === 'chloroblast') && move.totalDamage) {
const hpBeforeRecoil = pokemon.hp;
this.battle.damage(this.calcRecoilDamage(move.totalDamage, move, pokemon), pokemon, pokemon, 'recoil');
if (pokemon.hp <= pokemon.maxhp / 2 && hpBeforeRecoil > pokemon.maxhp / 2) {
this.battle.runEvent('EmergencyExit', pokemon, pokemon);
}