-
Notifications
You must be signed in to change notification settings - Fork 0
/
pokemon.ts
2165 lines (1949 loc) · 69.6 KB
/
pokemon.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
/**
* Simulator Pokemon
* Pokemon Showdown - http://pokemonshowdown.com/
*
* @license MIT license
*/
import {State} from './state';
import {toID} from './dex';
/** A Pokemon's move slot. */
interface MoveSlot {
id: ID;
move: string;
pp: number;
maxpp: number;
target?: string;
disabled: boolean | string;
disabledSource?: string;
used: boolean;
virtual?: boolean;
}
interface Attacker {
source: Pokemon;
damage: number;
thisTurn: boolean;
move?: ID;
slot: PokemonSlot;
damageValue?: (number | boolean | undefined);
}
export interface EffectState {
// TODO: set this to be an actual number after converting data/ to .ts
duration?: number | any;
[k: string]: any;
}
// Berries which restore PP/HP and thus inflict external staleness when given to an opponent as
// there are very few non-malicious competitive reasons to do so
export const RESTORATIVE_BERRIES = new Set([
'leppaberry', 'aguavberry', 'enigmaberry', 'figyberry', 'iapapaberry', 'magoberry', 'sitrusberry', 'wikiberry', 'oranberry',
] as ID[]);
export class Pokemon {
readonly side: Side;
readonly battle: Battle;
readonly set: PokemonSet;
readonly name: string;
readonly fullname: string;
readonly level: number;
readonly gender: GenderName;
readonly happiness: number;
readonly pokeball: string;
readonly dynamaxLevel: number;
readonly gigantamax: boolean;
/** Transform keeps the original pre-transformed Hidden Power in Gen 2-4. */
readonly baseHpType: string;
readonly baseHpPower: number;
readonly baseMoveSlots: MoveSlot[];
moveSlots: MoveSlot[];
hpType: string;
hpPower: number;
/**
* Index of `pokemon.side.pokemon` and `pokemon.side.active`, which are
* guaranteed to be the same for active pokemon. Note that this isn't
* its field position in multi battles - use `getSlot()` for that.
*/
position: number;
details: string;
baseSpecies: Species;
species: Species;
speciesState: EffectState;
status: ID;
statusState: EffectState;
volatiles: {[id: string]: EffectState};
showCure?: boolean;
/**
* These are the basic stats that appear on the in-game stats screen:
* calculated purely from the species base stats, level, IVs, EVs,
* and Nature, before modifications from item, ability, etc.
*
* Forme changes affect these, but Transform doesn't.
*/
baseStoredStats: StatsTable;
/**
* These are pre-modification stored stats in-battle. At switch-in,
* they're identical to `baseStoredStats`, but can be temporarily changed
* until switch-out by effects such as Power Trick and Transform.
*
* Stat multipliers from abilities, items, and volatiles, such as
* Solar Power, Choice Band, or Swords Dance, are not stored in
* `storedStats`, but applied on top and accessed by `pokemon.getStat`.
*
* (Except in Gen 1, where stat multipliers are stored, leading
* to several famous glitches.)
*/
storedStats: StatsExceptHPTable;
boosts: BoostsTable;
baseAbility: ID;
ability: ID;
abilityState: EffectState;
item: ID;
itemState: EffectState;
lastItem: ID;
usedItemThisTurn: boolean;
ateBerry: boolean;
trapped: boolean | "hidden";
maybeTrapped: boolean;
maybeDisabled: boolean;
illusion: Pokemon | null;
transformed: boolean;
maxhp: number;
/** This is the max HP before Dynamaxing; it's updated for Power Construct etc */
baseMaxhp: number;
hp: number;
fainted: boolean;
faintQueued: boolean;
subFainted: boolean | null;
types: string[];
addedType: string;
knownType: boolean;
/** Keeps track of what type the client sees for this Pokemon. */
apparentType: string;
/**
* If the switch is called by an effect with a special switch
* message, like U-turn or Baton Pass, this will be the ID of
* the calling effect.
*/
switchFlag: ID | boolean;
forceSwitchFlag: boolean;
skipBeforeSwitchOutEventFlag: boolean;
draggedIn: number | null;
newlySwitched: boolean;
beingCalledBack: boolean;
lastMove: ActiveMove | null;
// Gen 2 only
lastMoveEncore?: ActiveMove | null;
lastMoveUsed: ActiveMove | null;
lastMoveTargetLoc?: number;
moveThisTurn: string | boolean;
statsRaisedThisTurn: boolean;
statsLoweredThisTurn: boolean;
/**
* The result of the last move used on the previous turn by this
* Pokemon. Stomping Tantrum checks this property for a value of false
* when determine whether to double its power, but it has four
* possible values:
*
* undefined indicates this Pokemon was not active last turn. It should
* not be used to indicate that a move was attempted and failed, either
* in a way that boosts Stomping Tantrum or not.
*
* null indicates that the Pokemon's move was skipped in such a way
* that does not boost Stomping Tantrum, either from having to recharge
* or spending a turn trapped by another Pokemon's Sky Drop.
*
* false indicates that the move completely failed to execute for any
* reason not mentioned above, including missing, the target being
* immune, the user being immobilized by an effect such as paralysis, etc.
*
* true indicates that the move successfully executed one or more of
* its effects on one or more targets, including hitting with an attack
* but dealing 0 damage to the target in cases such as Disguise, or that
* the move was blocked by one or more moves such as Protect.
*/
moveLastTurnResult: boolean | null | undefined;
/**
* The result of the most recent move used this turn by this Pokemon.
* At the start of each turn, the value stored here is moved to its
* counterpart, moveLastTurnResult, and this property is reinitialized
* to undefined. This property can have one of four possible values:
*
* undefined indicates that this Pokemon has not yet finished an
* attempt to use a move this turn. As this value is only overwritten
* after a move finishes execution, it is not sufficient for an event
* to examine only this property when checking if a Pokemon has not
* moved yet this turn if the event could take place during that
* Pokemon's move.
*
* null indicates that the Pokemon's move was skipped in such a way
* that does not boost Stomping Tantrum, either from having to recharge
* or spending a turn trapped by another Pokemon's Sky Drop.
*
* false indicates that the move completely failed to execute for any
* reason not mentioned above, including missing, the target being
* immune, the user being immobilized by an effect such as paralysis, etc.
*
* true indicates that the move successfully executed one or more of
* its effects on one or more targets, including hitting with an attack
* but dealing 0 damage to the target in cases such as Disguise. It can
* also mean that the move was blocked by one or more moves such as
* Protect. Uniquely, this value can also be true if this Pokemon mega
* evolved or ultra bursted this turn, but in that case the value should
* always be overwritten by a move action before the end of that turn.
*/
moveThisTurnResult: boolean | null | undefined;
/**
* The undynamaxed HP value this Pokemon was reduced to by damage this turn,
* or false if it hasn't taken damage yet this turn
*
* Used for Assurance, Emergency Exit, and Wimp Out
*/
hurtThisTurn: number | null;
lastDamage: number;
attackedBy: Attacker[];
timesAttacked: number;
isActive: boolean;
activeTurns: number;
/**
* This is for Fake-Out-likes specifically - it mostly counts how many move
* actions you've had since the last time you switched in, so 1/turn normally,
* +1 for Dancer/Instruct, -1 for shifting/Sky Drop.
*
* Incremented before the move is used, so the first move use has
* `activeMoveActions === 1`.
*
* Unfortunately, Truant counts Mega Evolution as an action and Fake
* Out doesn't, meaning that Truant can't use this number.
*/
activeMoveActions: number;
previouslySwitchedIn: number;
truantTurn: boolean;
// Gen 9 only
swordBoost: boolean;
shieldBoost: boolean;
syrupTriggered: boolean;
stellarBoostedTypes: string[];
/** Have this pokemon's Start events run yet? (Start events run every switch-in) */
isStarted: boolean;
duringMove: boolean;
weighthg: number;
speed: number;
abilityOrder: number;
canMegaEvo: string | null | undefined;
canMegaEvoX: string | null | undefined;
canMegaEvoY: string | null | undefined;
canUltraBurst: string | null | undefined;
readonly canGigantamax: string | null;
/**
* A Pokemon's Tera type if it can Terastallize, false if it is temporarily unable to tera and should have its
* ability restored upon switching out, or null if its inability to tera is permanent.
*/
canTerastallize: string | false | null;
teraType: string;
baseTypes: string[];
terastallized?: string;
/** A Pokemon's currently 'staleness' with respect to the Endless Battle Clause. */
staleness?: 'internal' | 'external';
/** Staleness that will be set once a future action occurs (eg. eating a berry). */
pendingStaleness?: 'internal' | 'external';
/** Temporary staleness that lasts only until the Pokemon switches. */
volatileStaleness?: 'external';
// Gen 1 only
modifiedStats?: StatsExceptHPTable;
modifyStat?: (this: Pokemon, statName: StatIDExceptHP, modifier: number) => void;
// Stadium only
recalculateStats?: (this: Pokemon) => void;
/**
* An object for storing untyped data, for mods to use.
*/
m: {
gluttonyFlag?: boolean, // Gen-NEXT
innate?: string, // Partners in Crime
originalSpecies?: string, // Mix and Mega
[key: string]: any,
};
constructor(set: string | AnyObject, side: Side) {
this.side = side;
this.battle = side.battle;
this.m = {};
const pokemonScripts = this.battle.format.pokemon || this.battle.dex.data.Scripts.pokemon;
if (pokemonScripts) Object.assign(this, pokemonScripts);
if (typeof set === 'string') set = {name: set};
this.baseSpecies = this.battle.dex.species.get(set.species || set.name);
if (!this.baseSpecies.exists) {
throw new Error(`Unidentified species: ${this.baseSpecies.name}`);
}
this.set = set as PokemonSet;
this.species = this.baseSpecies;
if (set.name === set.species || !set.name) {
set.name = this.baseSpecies.baseSpecies;
}
this.speciesState = {id: this.species.id};
this.name = set.name.substr(0, 20);
this.fullname = this.side.id + ': ' + this.name;
set.level = this.battle.clampIntRange(set.adjustLevel || set.level || 100, 1, 9999);
this.level = set.level;
const genders: {[key: string]: GenderName} = {M: 'M', F: 'F', N: 'N'};
this.gender = genders[set.gender] || this.species.gender || (this.battle.random() * 2 < 1 ? 'M' : 'F');
if (this.gender === 'N') this.gender = '';
this.happiness = typeof set.happiness === 'number' ? this.battle.clampIntRange(set.happiness, 0, 255) : 255;
this.pokeball = this.set.pokeball || 'pokeball';
this.dynamaxLevel = typeof set.dynamaxLevel === 'number' ? this.battle.clampIntRange(set.dynamaxLevel, 0, 10) : 10;
this.gigantamax = this.set.gigantamax || false;
this.baseMoveSlots = [];
this.moveSlots = [];
if (!this.set.moves?.length) {
throw new Error(`Set ${this.name} has no moves`);
}
for (const moveid of this.set.moves) {
let move = this.battle.dex.moves.get(moveid);
if (!move.id) continue;
if (move.id === 'hiddenpower' && move.type !== 'Normal') {
if (!set.hpType) set.hpType = move.type;
move = this.battle.dex.moves.get('hiddenpower');
}
let basepp = (move.noPPBoosts || move.isZ) ? move.pp : move.pp * 8 / 5;
if (this.battle.gen < 3) basepp = Math.min(61, basepp);
this.baseMoveSlots.push({
move: move.name,
id: move.id,
pp: basepp,
maxpp: basepp,
target: move.target,
disabled: false,
disabledSource: '',
used: false,
});
}
this.position = 0;
let displayedSpeciesName = this.species.name;
if (displayedSpeciesName === 'Greninja-Bond') displayedSpeciesName = 'Greninja';
this.details = displayedSpeciesName + (this.level === 100 ? '' : ', L' + this.level) +
(this.gender === '' ? '' : ', ' + this.gender) + (this.set.shiny ? ', shiny' : '');
this.status = '';
this.statusState = {};
this.volatiles = {};
this.showCure = undefined;
if (!this.set.evs) {
this.set.evs = {hp: 0, atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
}
if (!this.set.ivs) {
this.set.ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};
}
const stats: StatsTable = {hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31};
let stat: StatID;
for (stat in stats) {
if (!this.set.evs[stat]) this.set.evs[stat] = 0;
if (!this.set.ivs[stat] && this.set.ivs[stat] !== 0) this.set.ivs[stat] = 31;
}
for (stat in this.set.evs) {
this.set.evs[stat] = this.battle.clampIntRange(this.set.evs[stat], 0, 255);
}
for (stat in this.set.ivs) {
this.set.ivs[stat] = this.battle.clampIntRange(this.set.ivs[stat], 0, 31);
}
if (this.battle.gen && this.battle.gen <= 2) {
// We represent DVs using even IVs. Ensure they are in fact even.
for (stat in this.set.ivs) {
this.set.ivs[stat] &= 30;
}
}
const hpData = this.battle.dex.getHiddenPower(this.set.ivs);
this.hpType = set.hpType || hpData.type;
this.hpPower = hpData.power;
this.baseHpType = this.hpType;
this.baseHpPower = this.hpPower;
// initialized in this.setSpecies(this.baseSpecies)
this.baseStoredStats = null!;
this.storedStats = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
this.boosts = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0};
this.baseAbility = toID(set.ability);
this.ability = this.baseAbility;
this.abilityState = {id: this.ability};
this.item = toID(set.item);
this.itemState = {id: this.item};
this.lastItem = '';
this.usedItemThisTurn = false;
this.ateBerry = false;
this.trapped = false;
this.maybeTrapped = false;
this.maybeDisabled = false;
this.illusion = null;
this.transformed = false;
this.fainted = false;
this.faintQueued = false;
this.subFainted = null;
this.types = this.baseSpecies.types;
this.baseTypes = this.types;
this.addedType = '';
this.knownType = true;
this.apparentType = this.baseSpecies.types.join('/');
// Every Pokemon has a Terastal type
this.teraType = this.set.teraType || this.types[0];
this.switchFlag = false;
this.forceSwitchFlag = false;
this.skipBeforeSwitchOutEventFlag = false;
this.draggedIn = null;
this.newlySwitched = false;
this.beingCalledBack = false;
this.lastMove = null;
// This is used in gen 2 only, here to avoid code repetition.
// Only declared if gen 2 to avoid declaring an object we aren't going to need.
if (this.battle.gen === 2) this.lastMoveEncore = null;
this.lastMoveUsed = null;
this.moveThisTurn = '';
this.statsRaisedThisTurn = false;
this.statsLoweredThisTurn = false;
this.hurtThisTurn = null;
this.lastDamage = 0;
this.attackedBy = [];
this.timesAttacked = 0;
this.isActive = false;
this.activeTurns = 0;
this.activeMoveActions = 0;
this.previouslySwitchedIn = 0;
this.truantTurn = false;
this.swordBoost = false;
this.shieldBoost = false;
this.syrupTriggered = false;
this.stellarBoostedTypes = [];
this.isStarted = false;
this.duringMove = false;
this.weighthg = 1;
this.speed = 0;
/**
* Determines the order in which redirect abilities like Lightning Rod
* activate if speed tied. Surprisingly not random like every other speed
* tie, but based on who first switched in or acquired the ability!
*/
this.abilityOrder = 0;
this.canMegaEvo = this.battle.actions.canMegaEvo(this);
this.canMegaEvoX = this.battle.actions.canMegaEvoX?.(this);
this.canMegaEvoY = this.battle.actions.canMegaEvoY?.(this);
this.canUltraBurst = this.battle.actions.canUltraBurst(this);
this.canGigantamax = this.baseSpecies.canGigantamax || null;
this.canTerastallize = this.battle.actions.canTerastallize(this);
// This is used in gen 1 only, here to avoid code repetition.
// Only declared if gen 1 to avoid declaring an object we aren't going to need.
if (this.battle.gen === 1) this.modifiedStats = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0};
this.maxhp = 0;
this.baseMaxhp = 0;
this.hp = 0;
this.clearVolatile();
this.hp = this.maxhp;
}
toJSON(): AnyObject {
return State.serializePokemon(this);
}
get moves(): readonly string[] {
return this.moveSlots.map(moveSlot => moveSlot.id);
}
get baseMoves(): readonly string[] {
return this.baseMoveSlots.map(moveSlot => moveSlot.id);
}
getSlot(): PokemonSlot {
const positionOffset = Math.floor(this.side.n / 2) * this.side.active.length;
const positionLetter = 'abcdef'.charAt(this.position + positionOffset);
return (this.side.id + positionLetter) as PokemonSlot;
}
toString() {
const fullname = (this.illusion) ? this.illusion.fullname : this.fullname;
return this.isActive ? this.getSlot() + fullname.slice(2) : fullname;
}
getDetails = () => {
const health = this.getHealth();
let details = this.details;
if (this.illusion) {
const level = this.battle.ruleTable.has('illusionlevelmod') ? this.illusion.level : this.level;
let displayedSpeciesName = this.illusion.species.name;
if (displayedSpeciesName === 'Greninja-Bond') displayedSpeciesName = 'Greninja';
const illusionDetails = displayedSpeciesName + (level === 100 ? '' : ', L' + level) +
(this.illusion.gender === '' ? '' : ', ' + this.illusion.gender) + (this.illusion.set.shiny ? ', shiny' : '');
details = illusionDetails;
}
if (this.terastallized) details += `, tera:${this.terastallized}`;
return {side: health.side, secret: `${details}|${health.secret}`, shared: `${details}|${health.shared}`};
};
updateSpeed() {
this.speed = this.getActionSpeed();
}
calculateStat(statName: StatIDExceptHP, boost: number, modifier?: number, statUser?: Pokemon) {
statName = toID(statName) as StatIDExceptHP;
// @ts-ignore - type checking prevents 'hp' from being passed, but we're paranoid
if (statName === 'hp') throw new Error("Please read `maxhp` directly");
// base stat
let stat = this.storedStats[statName];
// Wonder Room swaps defenses before calculating anything else
if ('wonderroom' in this.battle.field.pseudoWeather) {
if (statName === 'def') {
stat = this.storedStats['spd'];
} else if (statName === 'spd') {
stat = this.storedStats['def'];
}
}
// stat boosts
let boosts: SparseBoostsTable = {};
const boostName = statName as BoostID;
boosts[boostName] = boost;
boosts = this.battle.runEvent('ModifyBoost', statUser || this, null, null, boosts);
boost = boosts[boostName]!;
const boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
stat = Math.floor(stat * boostTable[boost]);
} else {
stat = Math.floor(stat / boostTable[-boost]);
}
// stat modifier
return this.battle.modify(stat, (modifier || 1));
}
getStat(statName: StatIDExceptHP, unboosted?: boolean, unmodified?: boolean) {
statName = toID(statName) as StatIDExceptHP;
// @ts-ignore - type checking prevents 'hp' from being passed, but we're paranoid
if (statName === 'hp') throw new Error("Please read `maxhp` directly");
// base stat
let stat = this.storedStats[statName];
// Download ignores Wonder Room's effect, but this results in
// stat stages being calculated on the opposite defensive stat
if (unmodified && 'wonderroom' in this.battle.field.pseudoWeather) {
if (statName === 'def') {
statName = 'spd';
} else if (statName === 'spd') {
statName = 'def';
}
}
// stat boosts
if (!unboosted) {
const boosts = this.battle.runEvent('ModifyBoost', this, null, null, {...this.boosts});
let boost = boosts[statName];
const boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
stat = Math.floor(stat * boostTable[boost]);
} else {
stat = Math.floor(stat / boostTable[-boost]);
}
}
// stat modifier effects
if (!unmodified) {
const statTable: {[s in StatIDExceptHP]: string} = {atk: 'Atk', def: 'Def', spa: 'SpA', spd: 'SpD', spe: 'Spe'};
stat = this.battle.runEvent('Modify' + statTable[statName], this, null, null, stat);
}
if (statName === 'spe' && stat > 10000 && !this.battle.format.battle?.trunc) stat = 10000;
return stat;
}
getActionSpeed() {
let speed = this.getStat('spe', false, false);
if (this.battle.field.getPseudoWeather('trickroom')) {
speed = 10000 - speed;
}
return this.battle.trunc(speed, 13);
}
/**
* Gets the Pokemon's best stat.
* Moved to its own method due to frequent use of the same code.
* Used by Beast Boost, Quark Drive, and Protosynthesis.
*/
getBestStat(unboosted?: boolean, unmodified?: boolean): StatIDExceptHP {
let statName: StatIDExceptHP = 'atk';
let bestStat = 0;
const stats: StatIDExceptHP[] = ['atk', 'def', 'spa', 'spd', 'spe'];
for (const i of stats) {
if (this.getStat(i, unboosted, unmodified) > bestStat) {
statName = i;
bestStat = this.getStat(i, unboosted, unmodified);
}
}
return statName;
}
/* Commented out for now until a use for Combat Power is found in Let's Go
getCombatPower() {
let statSum = 0;
let awakeningSum = 0;
for (const stat in this.stats) {
statSum += this.calculateStat(stat, this.boosts[stat as BoostName]);
awakeningSum += this.calculateStat(
stat, this.boosts[stat as BoostName]) + this.set.evs[stat];
}
const combatPower = Math.floor(Math.floor(statSum * this.level * 6 / 100) +
(Math.floor(awakeningSum) * Math.floor((this.level * 4) / 100 + 2)));
return this.battle.clampIntRange(combatPower, 0, 10000);
}
*/
getWeight() {
const weighthg = this.battle.runEvent('ModifyWeight', this, null, null, this.weighthg);
return Math.max(1, weighthg);
}
getMoveData(move: string | Move) {
move = this.battle.dex.moves.get(move);
for (const moveSlot of this.moveSlots) {
if (moveSlot.id === move.id) {
return moveSlot;
}
}
return null;
}
getMoveHitData(move: ActiveMove) {
if (!move.moveHitData) move.moveHitData = {};
const slot = this.getSlot();
return move.moveHitData[slot] || (move.moveHitData[slot] = {
crit: false,
typeMod: 0,
zBrokeProtect: false,
});
}
alliesAndSelf(): Pokemon[] {
return this.side.allies();
}
allies(): Pokemon[] {
return this.side.allies().filter(ally => ally !== this);
}
adjacentAllies(): Pokemon[] {
return this.side.allies().filter(ally => this.isAdjacent(ally));
}
foes(all?: boolean): Pokemon[] {
return this.side.foes(all);
}
adjacentFoes(): Pokemon[] {
if (this.battle.activePerHalf <= 2) return this.side.foes();
return this.side.foes().filter(foe => this.isAdjacent(foe));
}
isAlly(pokemon: Pokemon | null) {
return !!pokemon && (this.side === pokemon.side || this.side.allySide === pokemon.side);
}
isAdjacent(pokemon2: Pokemon) {
if (this.fainted || pokemon2.fainted) return false;
if (this.battle.activePerHalf <= 2) return this !== pokemon2;
if (this.side === pokemon2.side) return Math.abs(this.position - pokemon2.position) === 1;
return Math.abs(this.position + pokemon2.position + 1 - this.side.active.length) <= 1;
}
getUndynamaxedHP(amount?: number) {
const hp = amount || this.hp;
if (this.volatiles['dynamax']) {
return Math.ceil(hp * this.baseMaxhp / this.maxhp);
}
return hp;
}
/** Get targets for Dragon Darts */
getSmartTargets(target: Pokemon, move: ActiveMove) {
const target2 = target.adjacentAllies()[0];
if (!target2 || target2 === this || !target2.hp) {
move.smartTarget = false;
return [target];
}
if (!target.hp) {
move.smartTarget = false;
return [target2];
}
return [target, target2];
}
getAtLoc(targetLoc: number) {
let side = this.battle.sides[targetLoc < 0 ? this.side.n % 2 : (this.side.n + 1) % 2];
targetLoc = Math.abs(targetLoc);
if (targetLoc > side.active.length) {
targetLoc -= side.active.length;
side = this.battle.sides[side.n + 2];
}
return side.active[targetLoc - 1];
}
/**
* Returns a relative location: 1-3, positive for foe, and negative for ally.
* Use `getAtLoc` to reverse.
*/
getLocOf(target: Pokemon) {
const positionOffset = Math.floor(target.side.n / 2) * target.side.active.length;
const position = target.position + positionOffset + 1;
const sameHalf = (this.side.n % 2) === (target.side.n % 2);
return sameHalf ? -position : position;
}
getMoveTargets(move: ActiveMove, target: Pokemon): {targets: Pokemon[], pressureTargets: Pokemon[]} {
let targets: Pokemon[] = [];
switch (move.target) {
case 'all':
case 'foeSide':
case 'allySide':
case 'allyTeam':
if (!move.target.startsWith('foe')) {
targets.push(...this.alliesAndSelf());
}
if (!move.target.startsWith('ally')) {
targets.push(...this.foes(true));
}
if (targets.length && !targets.includes(target)) {
this.battle.retargetLastMove(targets[targets.length - 1]);
}
break;
case 'allAdjacent':
targets.push(...this.adjacentAllies());
// falls through
case 'allAdjacentFoes':
targets.push(...this.adjacentFoes());
if (targets.length && !targets.includes(target)) {
this.battle.retargetLastMove(targets[targets.length - 1]);
}
break;
case 'allies':
targets = this.alliesAndSelf();
break;
default:
const selectedTarget = target;
if (!target || (target.fainted && !target.isAlly(this)) && this.battle.gameType !== 'freeforall') {
// If a targeted foe faints, the move is retargeted
const possibleTarget = this.battle.getRandomTarget(this, move);
if (!possibleTarget) return {targets: [], pressureTargets: []};
target = possibleTarget;
}
if (this.battle.activePerHalf > 1 && !move.tracksTarget) {
const isCharging = move.flags['charge'] && !this.volatiles['twoturnmove'] &&
!(move.id.startsWith('solarb') && ['sunnyday', 'desolateland'].includes(this.effectiveWeather())) &&
!(move.id === 'electroshot' && ['raindance', 'primordialsea'].includes(this.effectiveWeather())) &&
!(this.hasItem('powerherb') && move.id !== 'skydrop');
if (!isCharging) {
target = this.battle.priorityEvent('RedirectTarget', this, this, move, target);
}
}
if (move.smartTarget) {
targets = this.getSmartTargets(target, move);
target = targets[0];
} else {
targets.push(target);
}
if (target.fainted && !move.flags['futuremove']) {
return {targets: [], pressureTargets: []};
}
if (selectedTarget !== target) {
this.battle.retargetLastMove(target);
}
}
// Resolve apparent targets for Pressure.
let pressureTargets = targets;
if (move.target === 'foeSide') {
pressureTargets = [];
}
if (move.flags['mustpressure']) {
pressureTargets = this.foes();
}
return {targets, pressureTargets};
}
ignoringAbility() {
if (this.battle.gen >= 5 && !this.isActive) return true;
// Certain Abilities won't activate while Transformed, even if they ordinarily couldn't be suppressed (e.g. Disguise)
if (this.getAbility().flags['notransform'] && this.transformed) return true;
if (this.getAbility().flags['cantsuppress']) return false;
if (this.volatiles['gastroacid']) return true;
// Check if any active pokemon have the ability Neutralizing Gas
if (this.hasItem('Ability Shield') || this.ability === ('neutralizinggas' as ID)) return false;
for (const pokemon of this.battle.getAllActive()) {
// can't use hasAbility because it would lead to infinite recursion
if (pokemon.ability === ('neutralizinggas' as ID) && !pokemon.volatiles['gastroacid'] &&
!pokemon.transformed && !pokemon.abilityState.ending && !this.volatiles['commanding']) {
return true;
}
}
return false;
}
ignoringItem() {
return !!(
this.itemState.knockedOff || // Gen 3-4
(this.battle.gen >= 5 && !this.isActive) ||
(!this.getItem().ignoreKlutz && this.hasAbility('klutz')) ||
this.volatiles['embargo'] || this.battle.field.pseudoWeather['magicroom']
);
}
deductPP(move: string | Move, amount?: number | null, target?: Pokemon | null | false) {
const gen = this.battle.gen;
move = this.battle.dex.moves.get(move);
const ppData = this.getMoveData(move);
if (!ppData) return 0;
ppData.used = true;
if (!ppData.pp && gen > 1) return 0;
if (!amount) amount = 1;
ppData.pp -= amount;
if (ppData.pp < 0 && gen > 1) {
amount += ppData.pp;
ppData.pp = 0;
}
return amount;
}
moveUsed(move: ActiveMove, targetLoc?: number) {
this.lastMove = move;
if (this.battle.gen === 2) this.lastMoveEncore = move;
this.lastMoveTargetLoc = targetLoc;
this.moveThisTurn = move.id;
}
gotAttacked(move: string | Move, damage: number | false | undefined, source: Pokemon) {
const damageNumber = (typeof damage === 'number') ? damage : 0;
move = this.battle.dex.moves.get(move);
this.attackedBy.push({
source,
damage: damageNumber,
move: move.id,
thisTurn: true,
slot: source.getSlot(),
damageValue: damage,
});
}
getLastAttackedBy() {
if (this.attackedBy.length === 0) return undefined;
return this.attackedBy[this.attackedBy.length - 1];
}
getLastDamagedBy(filterOutSameSide: boolean) {
const damagedBy: Attacker[] = this.attackedBy.filter(attacker => (
typeof attacker.damageValue === 'number' &&
(filterOutSameSide === undefined || !this.isAlly(attacker.source))
));
if (damagedBy.length === 0) return undefined;
return damagedBy[damagedBy.length - 1];
}
/**
* This refers to multi-turn moves like SolarBeam and Outrage and
* Sky Drop, which remove all choice (no dynamax, switching, etc).
* Don't use it for "soft locks" like Choice Band.
*/
getLockedMove(): string | null {
const lockedMove = this.battle.runEvent('LockMove', this);
return (lockedMove === true) ? null : lockedMove;
}
getMoves(lockedMove?: string | null, restrictData?: boolean): {
move: string, id: string, disabled?: string | boolean, disabledSource?: string,
target?: string, pp?: number, maxpp?: number,
}[] {
if (lockedMove) {
lockedMove = toID(lockedMove);
this.trapped = true;
if (lockedMove === 'recharge') {
return [{
move: 'Recharge',
id: 'recharge',
}];
}
for (const moveSlot of this.moveSlots) {
if (moveSlot.id !== lockedMove) continue;
return [{
move: moveSlot.move,
id: moveSlot.id,
}];
}
// does this happen?
return [{
move: this.battle.dex.moves.get(lockedMove).name,
id: lockedMove,
}];
}
const moves = [];
let hasValidMove = false;
for (const moveSlot of this.moveSlots) {
let moveName = moveSlot.move;
if (moveSlot.id === 'hiddenpower') {
moveName = 'Hidden Power ' + this.hpType;
if (this.battle.gen < 6) moveName += ' ' + this.hpPower;
} else if (moveSlot.id === 'return' || moveSlot.id === 'frustration') {
const basePowerCallback = this.battle.dex.moves.get(moveSlot.id).basePowerCallback as (pokemon: Pokemon) => number;
moveName += ' ' + basePowerCallback(this);
}
let target = moveSlot.target;
switch (moveSlot.id) {
case 'curse':
if (!this.hasType('Ghost')) {
target = this.battle.dex.moves.get('curse').nonGhostTarget;
}
break;
case 'pollenpuff':
// Heal Block only prevents Pollen Puff from targeting an ally when the user has Heal Block
if (this.volatiles['healblock']) {
target = 'adjacentFoe';
}
break;
case 'terastarstorm':
if (this.species.name === 'Terapagos-Stellar') {
target = 'allAdjacentFoes';
}
break;
}
let disabled = moveSlot.disabled;
if (this.volatiles['dynamax']) {
// if each of a Pokemon's base moves are disabled by one of these effects, it will Struggle
const canCauseStruggle = ['Encore', 'Disable', 'Taunt', 'Assault Vest', 'Belch', 'Stuff Cheeks'];
disabled = this.maxMoveDisabled(moveSlot.id) || disabled && canCauseStruggle.includes(moveSlot.disabledSource!);
} else if (
(moveSlot.pp <= 0 && !this.volatiles['partialtrappinglock']) || disabled &&
this.side.active.length >= 2 && this.battle.actions.targetTypeChoices(target!)
) {
disabled = true;
}
if (!disabled) {
hasValidMove = true;
} else if (disabled === 'hidden' && restrictData) {
disabled = false;
}
moves.push({
move: moveName,
id: moveSlot.id,
pp: moveSlot.pp,
maxpp: moveSlot.maxpp,
target,
disabled,
});
}
return hasValidMove ? moves : [];
}