-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.ts
841 lines (728 loc) · 24.4 KB
/
index.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
import {
AbilityName,
Condition,
Data,
Dex,
Species as DexSpecies,
Type as DexType,
EggGroup,
EvoType,
FormeName,
GenderName,
GenerationNum,
ID,
ItemName,
Move,
MoveCategory,
MoveName,
MoveSource,
Nature,
Nonstandard,
SpeciesAbility,
SpeciesName,
SpeciesTag,
StatID,
StatsTable,
Tier,
TypeName,
} from '@pkmn/dex-types';
const DEFAULT_EXISTS = (d: Data) => {
if (!d.exists) return false;
if ('isNonstandard' in d && d.isNonstandard) return false;
if (d.kind === 'Ability' && d.id === 'noability') return false;
return !('tier' in d && ['Illegal', 'Unreleased'].includes(d.tier));
};
const tr = (num: number, bits = 0) => bits ? (num >>> 0) % (2 ** bits) : num >>> 0;
export type ExistsFn = (d: Data, g: GenerationNum) => boolean;
type BoundExistsFn = (d: Data) => boolean;
function assignWithout(a: {[key: string]: any}, b: {[key: string]: any}, exclude: Set<string>) {
for (const key in b) {
if (Object.prototype.hasOwnProperty.call(b, key) && !exclude.has(key)) {
a[key] = b[key];
}
}
return a;
}
export function toID(text: any): ID {
if (text?.id) text = text.id;
if (typeof text !== 'string' && typeof text !== 'number') return '';
return ('' + text).toLowerCase().replace(/[^a-z0-9]+/g, '') as ID;
}
export class Generations {
/* private */ readonly cache = Object.create(null) as {[num: number]: Generation};
/* private */ readonly dex: Dex;
/* private */ readonly exists: ExistsFn;
static DEFAULT_EXISTS = DEFAULT_EXISTS;
constructor(dex: Dex, exists = Generations.DEFAULT_EXISTS) {
this.dex = dex;
this.exists = exists;
}
get(g: string | number) {
// May not actually be a GenerationNum, but isNaN and Dex.forGen will validate the rest
const gen = (typeof g === 'string' ? parseInt(g.slice(g.search(/\d/))) : g) as GenerationNum;
if (isNaN(+gen)) throw new Error(`Invalid gen ${g}`);
if (this.cache[gen]) return this.cache[gen];
return (this.cache[gen] = new Generation(this.dex.forGen(gen), d => this.exists(d, gen)));
}
*[Symbol.iterator]() {
for (let gen = 1; gen <= 9; gen++) {
yield this.get(gen as GenerationNum);
}
}
}
export class Generation {
readonly abilities: Abilities;
readonly items: Items;
readonly moves: Moves;
readonly species: Species;
readonly types: Types;
readonly natures: Natures;
readonly learnsets: Learnsets;
readonly conditions: Conditions;
readonly stats: Stats;
readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
static get(dex: Dex, g: string | number, exists = DEFAULT_EXISTS) {
return new Generations(dex, exists).get(g);
}
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
this.abilities = new Abilities(this.dex, this.exists);
this.items = new Items(this.dex, this.exists);
this.moves = new Moves(this.dex, this.exists);
this.species = new Species(this.dex, this.exists);
this.natures = new Natures(this.dex, this.exists);
this.types = new Types(this.dex, this.exists);
this.learnsets = new Learnsets(this, this.dex, this.exists);
this.conditions = new Conditions(this.dex, this.exists);
this.stats = new Stats(this.dex);
}
get num() {
return this.dex.gen;
}
toString() {
return `[Generation:${this.num}]`;
}
toJSON() {
return this.toString();
}
}
export class Abilities {
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
const ability = this.dex.abilities.get(name);
return this.exists(ability) ? ability : undefined;
}
*[Symbol.iterator]() {
for (const ability in this.dex.data.Abilities) {
const a = this.get(ability);
if (a) yield a;
}
}
}
export class Items {
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
const item = this.dex.items.get(name);
return this.exists(item) ? item : undefined;
}
*[Symbol.iterator]() {
for (const item in this.dex.data.Items) {
const i = this.get(item);
if (i) yield i;
}
}
}
export class Moves {
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
const move = this.dex.moves.get(name);
return this.exists(move) ? move : undefined;
}
*[Symbol.iterator]() {
for (const move in this.dex.data.Moves) {
const m = this.get(move);
if (m) yield m;
}
}
}
export class Species {
/* private */ readonly cache = Object.create(null) as {[id: string]: Specie};
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
const species = this.dex.species.get(name);
if (!this.exists(species)) return undefined;
const id = (species as any).speciesid || species.id; // FIXME Event-only ability hack
const cached = this.cache[id];
if (cached) return cached;
return (this.cache[id] = new Specie(this.dex, this.exists, species));
}
*[Symbol.iterator]() {
for (const species in this.dex.data.Species) {
const s = this.get(species);
if (s) yield s;
}
}
}
export class Specie implements DexSpecies {
readonly id!: ID;
readonly name!: SpeciesName;
readonly fullname!: string;
readonly exists!: boolean;
readonly num!: number;
readonly gen!: GenerationNum;
readonly shortDesc!: string;
readonly desc!: string;
readonly isNonstandard!: Nonstandard | null;
readonly duration?: number;
readonly effectType!: 'Pokemon';
readonly kind!: 'Species';
readonly baseStats!: StatsTable;
readonly baseSpecies!: SpeciesName;
readonly baseForme!: FormeName | '';
readonly forme!: FormeName | '';
readonly abilities!: SpeciesAbility<AbilityName | ''>;
readonly types!: [TypeName] | [TypeName, TypeName];
readonly prevo?: SpeciesName | '';
readonly evos?: SpeciesName[];
readonly nfe: boolean;
readonly eggGroups!: EggGroup[];
readonly weightkg!: number;
readonly weighthg!: number;
readonly tags!: SpeciesTag[];
readonly unreleasedHidden!: boolean | 'Past';
readonly maleOnlyHidden!: boolean;
readonly inheritsFrom!: ID;
readonly tier!: Tier.Singles | Tier.Other;
readonly doublesTier!: Tier.Doubles | Tier.Other;
readonly natDexTier!: Tier.Singles | Tier.Other;
readonly changesFrom?: SpeciesName;
readonly cosmeticFormes?: SpeciesName[];
readonly otherFormes?: SpeciesName[];
readonly formeOrder?: SpeciesName[];
readonly formes?: SpeciesName[];
readonly genderRatio: {M: number; F: number};
readonly isMega?: boolean;
readonly isPrimal?: boolean;
readonly battleOnly?: SpeciesName | SpeciesName[];
readonly canGigantamax?: MoveName;
readonly gmaxUnreleased?: boolean;
readonly cannotDynamax?: boolean;
readonly requiredAbility?: AbilityName;
readonly requiredItem?: ItemName;
readonly requiredItems?: ItemName[];
readonly requiredMove?: MoveName;
readonly gender?: GenderName;
readonly maxHP?: number;
readonly evoMove?: MoveName;
readonly evoItem?: string;
readonly evoRegion?: 'Alola' | 'Galar';
readonly evoLevel?: number;
readonly evoCondition?: string;
readonly evoType?: EvoType;
readonly condition?: Partial<Condition>;
readonly canHatch!: boolean;
/* private */ readonly dex: Dex;
/* private */ static readonly EXCLUDE = new Set([
'abilities', 'cosmeticFormes', 'evos', 'formeOrder',
'gender', 'genderRatio', 'nfe', 'otherFormes', 'prevo',
]);
constructor(dex: Dex, exists: BoundExistsFn, species: DexSpecies) {
assignWithout(this, species, Specie.EXCLUDE);
this.dex = dex;
if (this.dex.gen >= 2) {
this.gender = species.gender;
this.genderRatio = species.genderRatio;
} else {
this.genderRatio = {M: 0, F: 0};
}
if (this.dex.gen >= 3) {
this.abilities = {0: species.abilities[0]};
// "because PS", Pokemon have the abilities that were added in Gen 4 in Gen 3 :bigthonk:
if (species.abilities[1] &&
this.dex.abilities.get(species.abilities[1]).gen <= this.dex.gen) {
this.abilities[1] = species.abilities[1];
}
if (this.dex.gen >= 5 && species.abilities.H) this.abilities.H = species.abilities.H;
if (this.dex.gen >= 7 && species.abilities.S) this.abilities.S = species.abilities.S;
} else {
this.abilities = {0: ''};
}
this.evos = species.evos?.filter(s => exists(this.dex.species.get(s)));
this.nfe = !!this.evos?.length;
if (!this.nfe) this.evos = undefined;
this.cosmeticFormes = species.cosmeticFormes?.filter(s => exists(this.dex.species.get(s)));
if (!this.cosmeticFormes?.length) this.cosmeticFormes = undefined;
this.otherFormes = species.otherFormes?.filter(s => exists(this.dex.species.get(s)));
if (!this.otherFormes?.length) this.otherFormes = undefined;
this.formeOrder = species.formeOrder?.filter(s => exists(this.dex.species.get(s)));
if (!this.formeOrder || this.formeOrder.length <= 1) this.formeOrder = undefined;
this.formes = this.formeOrder?.filter(s =>
this.dex.species.get(s).isNonstandard !== 'Gigantamax');
this.prevo =
species.prevo && exists(this.dex.species.get(species.prevo)) ? species.prevo : undefined;
}
get formeNum() {
return (this.baseSpecies === this.name
? this.formeOrder ? this.formeOrder.findIndex(name => name === this.name) : 0
: this.dex.species.get(this.baseSpecies).formeOrder!.findIndex(
name => name === (this.isNonstandard === 'Gigantamax' ? this.baseSpecies : this.name)
));
}
toString() {
return this.name;
}
toJSON() {
return assignWithout({}, this, new Set(['dex']));
}
}
export class Conditions {
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
const condition = this.dex.conditions.get(name);
return this.exists(condition) ? condition : undefined;
}
}
export class Natures {
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
}
get(name: string) {
if (this.dex.gen < 3) return undefined;
const nature = this.dex.natures.get(name);
return this.exists(nature) ? nature : undefined;
}
*[Symbol.iterator]() {
for (const nature in this.dex.data.Natures) {
const n = this.get(nature);
if (n) yield n;
}
}
}
const EFFECTIVENESS = {
'-3': 0.125,
'-2': 0.25,
'-1': 0.5,
'0': 1,
'1': 2,
'2': 4,
'3': 8,
};
type TypeTarget = {getTypes: () => TypeName[]} | {types: TypeName[]} | TypeName[] | TypeName;
export class Types {
/* private */ readonly cache = Object.create(null) as {[id: string]: Type};
/* private */ readonly unknown: Type;
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(dex: Dex, exists: BoundExistsFn) {
this.dex = dex;
this.exists = exists;
// PS doesn't contain data for the '???' type
this.unknown = new Type({
effectType: 'Type',
kind: 'Type',
// Regrettably PS ID's can't represent '???'
id: '',
name: '???',
// Technically this only exists as a true type in Gens 2-4, but there are moves dealing
// typeless damage in Gen 1 so we include it there.
exists: dex.gen <= 4,
gen: 1,
// This gets filled in for us by Type's constructor
damageTaken: {} as {[t in Exclude<TypeName, '???'>]: number},
HPivs: {},
HPdvs: {},
}, dex, this);
}
get(name: string) {
if (name === '???' && this.dex.gen >= 2 && this.dex.gen <= 4) return this.unknown;
const type = this.dex.types.get(name);
if (!this.exists(type)) return undefined;
const cached = this.cache[type.id];
if (cached) return cached;
return (this.cache[type.id] = new Type(type, this.dex, this));
}
*[Symbol.iterator]() {
for (const type in this.dex.data.Types) {
const t = this.get(type);
if (t) yield t;
}
if (this.dex.gen >= 2 && this.dex.gen <= 4) {
yield this.unknown;
}
}
getHiddenPower(ivs: StatsTable) {
return this.dex.getHiddenPower(ivs);
}
canDamage(source: {type: TypeName} | TypeName, target: TypeTarget) {
return this.dex.getImmunity(source, target);
}
totalEffectiveness(source: {type: TypeName} | TypeName, target: TypeTarget) {
if (!this.canDamage(source, target)) return 0;
const e = `${this.dex.getEffectiveness(source, target)}`;
// convert from PS's ridiculous encoding to something usable
return EFFECTIVENESS[e as keyof typeof EFFECTIVENESS];
}
}
export type TypeEffectiveness = 0 | 0.5 | 1 | 2;
const DAMAGE_TAKEN = [1, 2, 0.5, 0] as TypeEffectiveness[];
const SPECIAL = ['Fire', 'Water', 'Grass', 'Electric', 'Ice', 'Psychic', 'Dark', 'Dragon'];
export class Type {
readonly id!: ID;
readonly name!: TypeName;
readonly effectType!: 'Type';
readonly kind!: 'Type';
readonly exists!: boolean;
readonly gen!: GenerationNum;
readonly effectiveness: {[t in TypeName]: TypeEffectiveness};
readonly HPivs!: Partial<StatsTable>;
readonly HPdvs!: Partial<StatsTable>;
readonly category?: Exclude<MoveCategory, 'Status'>;
/* private */ readonly types: Types;
constructor(type: DexType, dex: Dex, types: Types) {
Object.assign(this, type);
this.types = types;
this.category = ['Fairy', 'Stellar'].includes(this.name)
? undefined : SPECIAL.includes(this.name) ? 'Special' : 'Physical';
// convert from PS's ridiculous encoding to something usable (plus damage taken -> dealt)
this.effectiveness = {'???': 1} as {[t in TypeName]: TypeEffectiveness};
for (const k in dex.data.Types) {
const t = k.charAt(0).toUpperCase() + k.slice(1) as Exclude<TypeName, '???'>;
const data = dex.data.Types[k as Lowercase<string>];
this.effectiveness[t] = DAMAGE_TAKEN[data.damageTaken[this.name] || 0];
}
}
canDamage(target: TypeTarget) {
return this.types.canDamage(this.name, target);
}
totalEffectiveness(target: TypeTarget) {
return this.types.totalEffectiveness(this.name, target);
}
toString() {
return this.name;
}
toJSON() {
return assignWithout({}, this, new Set(['types']));
}
}
const GEN3_HMS =
new Set(['cut', 'fly', 'surf', 'strength', 'flash', 'rocksmash', 'waterfall', 'dive'] as ID[]);
// NOTE: Whirlpool and Defog are Gen 4 HMs but the HMs differ in DPPt vs. HGSS
const GEN4_HMS =
new Set(['cut', 'fly', 'surf', 'strength', 'rocksmash', 'waterfall', 'rockclimb'] as ID[]);
type Restriction = 'Pentagon' | 'Plus' | 'Galar' | 'Paldea';
export class Learnsets {
/* private */ readonly cache = Object.create(null) as {
[speciesid: string]: {[moveid: string]: MoveSource[]};
};
/* private */ readonly gen: Generation;
/* private */ readonly dex: Dex;
/* private */ readonly exists: BoundExistsFn;
constructor(gen: Generation, dex: Dex, exists: BoundExistsFn) {
this.gen = gen;
this.dex = dex;
this.exists = exists;
}
async get(name: string) {
const learnset = await this.dex.learnsets.get(toID(name));
return this.exists(learnset) ? learnset : undefined;
}
async *[Symbol.iterator]() {
if (!this.dex.data.Learnsets) await this.dex.learnsets.get('LOAD' as ID);
for (const id in this.dex.data.Learnsets) {
const l = await this.get(id);
if (l) yield l;
}
}
async* all(species: Specie) {
let id = species.id;
let learnset = await this.get(id);
if (!learnset) {
id = typeof species.battleOnly === 'string' && species.battleOnly !== species.baseSpecies
? toID(species.battleOnly)
: toID(species.baseSpecies);
learnset = await this.get(id);
}
while (learnset) {
yield learnset;
if (id === 'lycanrocdusk' || (species.id === 'rockruff' && id === 'rockruff')) {
id = 'rockruffdusk' as ID;
} else if (species.id === 'gastrodoneast') {
id = 'gastrodon' as ID;
} else if (species.id === 'pumpkaboosuper') {
id = 'pumpkaboo' as ID;
} else {
id = toID(species.battleOnly || species.changesFrom || species.prevo);
}
if (!id) break;
const s = this.gen.species.get(id);
if (!s) break;
species = s;
learnset = await this.get(id);
}
}
// BUG: this only covers what Pokémon Showdown deems "teambuilder legality" - proper legality
// checks/restriction enforcement requires @pkmn/sim's TeamValidator.
async learnable(name: string, restriction?: Restriction) {
const species = this.gen.species.get(name);
if (!species) return undefined;
if (!restriction) {
const cached = this.cache[species.id];
if (cached) return cached;
}
const moves: {[moveid: string]: MoveSource[]} = {};
for await (const learnset of this.all(species)) {
if (learnset.learnset) {
for (const moveid in learnset.learnset) {
const move = this.gen.moves.get(moveid);
if (move) {
const sources = learnset.learnset[moveid];
if (this.isLegal(move, sources, restriction || this.gen)) {
const filtered = sources.filter(s => +s.charAt(0) <= this.gen.num);
if (!filtered.length) continue;
if (moves[move.id]) {
// If we simply add filtered to moves[move.id] we may end up with some duplicates or
// situations where we have mixed learnset information. We assume that while
// moves[move.id] and filtered are already deduped, their union might not be, and
// thus iterate through looking for unique prefixes. For efficiency, instead of
// appending each deduped source from filtered to moves[move.id] immediately and
// making each subsequent iteration longer we make a list of the unique sources to
// add at the end. This is only safe given our assumption that filtered is unique
// internally to begin with.
const unique = [];
// These lists are all expected to be short arrays so this O(n^2) linear searching
// is still expected to be faster runtime-wise than a more sophisticated approach
loop: for (const source of filtered) {
const prefix = source.slice(0, 2);
// sadly Babel chokes on using an .every(...) here due to throwIfClosureRequired
for (const s of moves[move.id]) if (s.startsWith(prefix)) continue loop;
unique.push(source);
}
moves[move.id].push(...unique);
} else {
moves[move.id] = filtered;
}
}
}
}
}
}
if (!restriction) this.cache[species.id] = moves;
return moves;
}
// BUG: this only covers what Pokémon Showdown deems "teambuilder legality" - proper legality
// checks/restriction enforcement requires @pkmn/sim's TeamValidator.
async canLearn(name: string, move: Move | string, restriction?: Restriction) {
const species = this.gen.species.get(name);
if (!species) return false;
move = typeof move === 'string' && this.gen.moves.get(move) || move;
if (typeof move === 'string') return false;
for await (const learnset of this.all(species)) {
if (this.isLegal(move, learnset.learnset?.[move.id], restriction || this.gen)) {
return true;
}
}
return false;
}
// BUG: this only covers what Pokémon Showdown deems "teambuilder legality" - proper legality
// checks/restriction enforcement requires @pkmn/sim's TeamValidator.
isLegal(move: Move, sources: MoveSource[] | undefined, gen: Generation | Restriction) {
if (!sources) return undefined;
const gens = sources.map(x => Number(x[0]));
const minGen = Math.min(...gens);
const vcOnly = (
minGen === 7 && sources.every(x => x[0] !== '7' || x === '7V') ||
minGen === 8 && sources.every(x => x[0] !== '8' || x === '8V')
);
if (gen === 'Pentagon') return gens.includes(6);
if (gen === 'Plus') return gens.includes(7) && !vcOnly;
if (gen === 'Galar') return gens.includes(8) && !vcOnly;
if (gen === 'Paldea') return gens.includes(9);
if (this.gen.num >= 3 && minGen <= 4 && (GEN3_HMS.has(move.id) || GEN4_HMS.has(move.id))) {
let legalGens = '';
let available = false;
if (minGen === 3) {
legalGens += '3';
available = true;
}
if (available) available = !GEN3_HMS.has(move.id);
if (available || gens.includes(4)) {
legalGens += '4';
available = true;
}
if (available) available = !GEN4_HMS.has(move.id);
const minUpperGen = available ? 5 : Math.min(...gens.filter(g => g > 4));
legalGens += '0123456789'.slice(minUpperGen);
return legalGens.includes(`${gen.num}`);
} else {
return '0123456789'.slice(minGen).includes(`${gen.num}`);
}
}
}
const STATS = ['hp', 'atk', 'def', 'spe', 'spa', 'spd'] as const;
const NAMES: Readonly<{[name: string]: StatID}> = {
HP: 'hp', hp: 'hp',
Attack: 'atk', Atk: 'atk', atk: 'atk',
Defense: 'def', Def: 'def', def: 'def',
'Special Attack': 'spa', SpA: 'spa', SAtk: 'spa', SpAtk: 'spa', spa: 'spa',
Special: 'spa', spc: 'spa', Spc: 'spa',
'Special Defense': 'spd', SpD: 'spd', SDef: 'spd', SpDef: 'spd', spd: 'spd',
Speed: 'spe', Spe: 'spe', Spd: 'spe', spe: 'spe',
};
const DISPLAY: Readonly<{[stat: string]: Readonly<[string, string]>}> = {
hp: ['HP', 'HP'],
atk: ['Atk', 'Attack'],
def: ['Def', 'Defense'],
spa: ['SpA', 'Special Attack'],
spd: ['SpD', 'Special Defense'],
spe: ['Spe', 'Speed'],
spc: ['Spc', 'Special'],
};
export class Stats {
/* private */ readonly dex: Dex;
constructor(dex: Dex) {
this.dex = dex;
}
calc(stat: StatID, base: number, iv = 31, ev?: number, level = 100, nature?: Nature) {
if (ev === undefined) ev = this.dex.gen < 3 ? 252 : 0;
if (this.dex.gen < 3) {
iv = this.toDV(iv) * 2;
nature = undefined;
}
if (stat === 'hp') {
return base === 1 ? base : tr(tr(2 * base + iv + tr(ev / 4) + 100) * level / 100 + 10);
} else {
const val = tr(tr(2 * base + iv + tr(ev / 4)) * level / 100 + 5);
if (nature !== undefined) {
if (nature.plus === stat) return tr(tr(val * 110, 16) / 100);
if (nature.minus === stat) return tr(tr(val * 90, 16) / 100);
}
return val;
}
}
get(s: string): StatID | undefined {
return NAMES[s];
}
display(str: string, full = false): string {
let s: StatID | 'spc' | undefined = NAMES[str];
if (s === undefined) return str;
if (this.dex.gen === 1 && s === 'spa') s = 'spc';
return DISPLAY[s][+full];
}
fill<T>(stats: Partial<StatsTable<T>>, val: T): StatsTable<T> {
for (const stat of STATS) {
if (!(stat in stats)) stats[stat] = val;
}
return stats as StatsTable<T>;
}
getHPDV(ivs: Partial<StatsTable>): number {
return (
(this.toDV(ivs.atk === undefined ? 31 : ivs.atk) % 2) * 8 +
(this.toDV(ivs.def === undefined ? 31 : ivs.def) % 2) * 4 +
(this.toDV(ivs.spe === undefined ? 31 : ivs.spe) % 2) * 2 +
(this.toDV(ivs.spa === undefined ? 31 : ivs.spa) % 2)
);
}
*[Symbol.iterator](): IterableIterator<StatID> {
for (const s of STATS) {
yield s;
}
}
toDV(iv: number): number {
return Math.floor(iv / 2);
}
toIV(dv: number): number {
return dv * 2 + 1;
}
}
export type {
ID,
As,
Weather,
FieldCondition,
SideCondition,
GenerationNum,
GenderName,
StatID,
StatsTable,
BoostID,
BoostsTable,
MoveCategory,
MoveTarget,
Nonstandard,
EvoType,
EggGroup,
SideID,
Player,
GameType,
HPColor,
StatusName,
NatureName,
TypeName,
HPTypeName,
Tier,
PokemonSet,
AbilityName,
ItemName,
MoveName,
SpeciesName,
FormeName,
EffectType,
Effect,
DataKind,
Data,
EffectData,
HitEffect,
SecondaryEffect,
ConditionData,
AbilityData,
ItemData,
MoveData,
SpeciesData,
MoveSource,
EventInfoData,
LearnsetData,
TypeData,
NatureData,
BasicEffect,
Condition,
Ability,
Item,
Move,
// Species,
EventInfo,
Learnset,
// Type,
Nature,
GenID,
Dex,
} from '@pkmn/dex-types';