forked from smogon/pokemon-showdown-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattle-dex.ts
1380 lines (1272 loc) · 42.5 KB
/
battle-dex.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
/**
* Pokemon Showdown Dex
*
* Roughly equivalent to sim/dex.js in a Pokemon Showdown server, but
* designed for use in browsers rather than in Node.
*
* This is a generic utility library for Pokemon Showdown code: any
* code shared between the replay viewer and the client usually ends up
* here.
*
* Licensing note: PS's client has complicated licensing:
* - The client as a whole is AGPLv3
* - The battle replay/animation engine (battle-*.ts) by itself is MIT
*
* Compiled into battledata.js which includes all dependencies
*
* @author Guangcong Luo <[email protected]>
* @license MIT
*/
import { Pokemon, type ServerPokemon } from "./battle";
import {
BattleAvatarNumbers, BattleBaseSpeciesChart, BattlePokemonIconIndexes, BattlePokemonIconIndexesLeft, BattleStatNames,
Ability, Item, Move, Species, PureEffect, type ID, type Type,
} from "./battle-dex-data";
import type * as DexData from "./battle-dex-data";
export declare namespace Dex {
/* eslint-disable @typescript-eslint/no-shadow */
export type Ability = DexData.Ability;
export type Item = DexData.Item;
export type Move = DexData.Move;
export type Species = DexData.Species;
export type Type = DexData.Type;
export type Nature = DexData.Nature;
export type PureEffect = DexData.PureEffect;
export type Effect = DexData.Effect;
export type ID = DexData.ID;
/* eslint-enable @typescript-eslint/no-shadow */
export type StatName = DexData.StatName;
export type StatNameExceptHP = DexData.StatNameExceptHP;
export type BoostStatName = DexData.BoostStatName;
export type TypeName = DexData.TypeName;
export type StatusName = DexData.StatusName;
export type GenderName = DexData.GenderName;
export type NatureName = DexData.NatureName;
export type MoveTarget = DexData.MoveTarget;
export type StatsTable = { hp: number, atk: number, def: number, spa: number, spd: number, spe: number };
/**
* Dex.PokemonSet can be sparse, in which case that entry should be
* inferred from the rest of the set, according to sensible
* defaults.
*/
export interface PokemonSet {
/** Defaults to species name (not including forme), like in games */
name?: string;
species: string;
/** Defaults to no item */
item?: string;
/** Defaults to no ability (error in Gen 3+) */
ability?: string;
moves: string[];
/** Defaults to no nature (error in Gen 3+) */
nature?: NatureName;
/** Defaults to random legal gender, NOT subject to gender ratios */
gender?: string;
/** Defaults to flat 252's (200's/0's in Let's Go) (error in gen 3+) */
evs?: Partial<Dex.StatsTable>;
/** Defaults to whatever makes sense - flat 31's unless you have Gyro Ball etc */
ivs?: Dex.StatsTable;
/** Defaults as you'd expect (100 normally, 50 in VGC-likes, 5 in LC) */
level?: number;
/** Defaults to no (error if shiny event) */
shiny?: boolean;
/** Defaults to 255 unless you have Frustration, in which case 0 */
happiness?: number;
/** Defaults to event required ball, otherwise Poké Ball */
pokeball?: string;
/** Defaults to the type of your Hidden Power in Moves, otherwise Dark */
hpType?: string;
/** Defaults to 10 */
dynamaxLevel?: number;
/** Defaults to no (can only be yes for certain Pokemon) */
gigantamax?: boolean;
/** Defaults to the primary type */
teraType?: string;
}
}
export type { ID };
declare const require: any;
declare const global: any;
declare const process: any;
if (typeof window === 'undefined') {
// Node
global.window = global;
} else {
// browser (possibly NW.js!)
window.exports = window;
}
window.nodewebkit = !!(typeof process !== 'undefined' && process.versions?.['node-webkit']);
export function toID(text: any) {
if (text?.id) {
text = text.id;
} else if (text?.userid) {
text = text.userid;
}
if (typeof text !== 'string' && typeof text !== 'number') return '' as ID;
return `${text}`.toLowerCase().replace(/[^a-z0-9]+/g, '') as ID;
}
export function toUserid(text: any) {
return toID(text);
}
type Comparable = number | string | boolean | Comparable[] | { reverse: Comparable };
export const PSUtils = new class {
/**
* Like string.split(delimiter), but only recognizes the first `limit`
* delimiters (default 1).
*
* `"1 2 3 4".split(" ", 2) => ["1", "2"]`
*
* `splitFirst("1 2 3 4", " ", 1) => ["1", "2 3 4"]`
*
* Returns an array of length exactly limit + 1.
*/
splitFirst(str: string, delimiter: string, limit = 1) {
let splitStr: string[] = [];
while (splitStr.length < limit) {
let delimiterIndex = str.indexOf(delimiter);
if (delimiterIndex >= 0) {
splitStr.push(str.slice(0, delimiterIndex));
str = str.slice(delimiterIndex + delimiter.length);
} else {
splitStr.push(str);
str = '';
}
}
splitStr.push(str);
return splitStr;
}
/**
* Compares two variables; intended to be used as a smarter comparator.
* The two variables must be the same type (TypeScript will not check this).
*
* - Numbers are sorted low-to-high, use `-val` to reverse
* - Strings are sorted A to Z case-semi-insensitively, use `{reverse: val}` to reverse
* - Booleans are sorted true-first (REVERSE of casting to numbers), use `!val` to reverse
* - Arrays are sorted lexically in the order of their elements
*
* In other words: `[num, str]` will be sorted A to Z, `[num, {reverse: str}]` will be sorted Z to A.
*/
compare(a: Comparable, b: Comparable): number {
if (typeof a === 'number') {
return a - (b as number);
}
if (typeof a === 'string') {
return a.localeCompare(b as string);
}
if (typeof a === 'boolean') {
return (a ? 1 : 2) - (b ? 1 : 2);
}
if (Array.isArray(a)) {
for (let i = 0; i < a.length; i++) {
const comparison = PSUtils.compare(a[i], (b as Comparable[])[i]);
if (comparison) return comparison;
}
return 0;
}
if (a.reverse) {
return PSUtils.compare((b as { reverse: string }).reverse, a.reverse);
}
throw new Error(`Passed value ${a as any} is not comparable`);
}
/**
* Sorts an array according to the callback's output on its elements.
*
* The callback's output is compared according to `PSUtils.compare` (in
* particular, it supports arrays so you can sort by multiple things).
*/
sortBy<T>(array: T[], callback: (a: T) => Comparable): T[];
/**
* Sorts an array according to `PSUtils.compare`. (Correctly sorts numbers,
* unlike `array.sort`)
*/
sortBy<T extends Comparable>(array: T[]): T[];
sortBy<T>(array: T[], callback?: (a: T) => Comparable) {
if (!callback) return (array as any[]).sort(PSUtils.compare);
return array.sort((a, b) => PSUtils.compare(callback(a), callback(b)));
}
};
/**
* Sanitize a room ID by removing anything that isn't alphanumeric or `-`.
* Shouldn't actually do anything except against malicious input.
*/
export function toRoomid(roomid: string) {
return roomid.replace(/[^a-zA-Z0-9-]+/g, '').toLowerCase();
}
export function toName(name: any) {
if (typeof name !== 'string' && typeof name !== 'number') return '';
name = `${name}`.replace(/[|\s[\],\u202e]+/g, ' ').trim();
if (name.length > 18) name = name.substr(0, 18).trim();
// remove zalgo
name = name.replace(
/[\u0300-\u036f\u0483-\u0489\u0610-\u0615\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06ED\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g,
''
);
name = name.replace(/[\u239b-\u23b9]/g, '');
return name;
}
export interface SpriteData {
w: number;
h: number;
y?: number;
gen?: number;
url?: string;
rawHTML?: string;
pixelated?: boolean;
isFrontSprite?: boolean;
cryurl?: string;
shiny?: boolean;
}
export interface TeambuilderSpriteData {
x: number;
y: number;
spriteDir: string;
spriteid: string;
shiny?: boolean;
}
export const Dex = new class implements ModdedDex {
readonly Ability = Ability;
readonly Item = Item;
readonly Move = Move;
readonly Species = Species;
readonly gen = 9;
readonly modid = 'gen9' as ID;
readonly cache = null!;
readonly statNames: readonly Dex.StatName[] = ['hp', 'atk', 'def', 'spa', 'spd', 'spe'];
readonly statNamesExceptHP: readonly Dex.StatNameExceptHP[] = ['atk', 'def', 'spa', 'spd', 'spe'];
pokeballs: string[] | null = null;
resourcePrefix = (() => {
let prefix = '';
if (window.document?.location?.protocol !== 'http:') prefix = 'https:';
return `${prefix}//${window.Config ? Config.routes.client : 'play.pokemonshowdown.com'}/`;
})();
fxPrefix = (() => {
const protocol = (window.document?.location?.protocol !== 'http:') ? 'https:' : '';
return `${protocol}//${window.Config ? Config.routes.client : 'play.pokemonshowdown.com'}/fx/`;
})();
loadedSpriteData = { xy: 1, bw: 0 };
moddedDexes: { [mod: string]: ModdedDex } = {};
mod(modid: ID): ModdedDex {
if (modid === 'gen9') return this;
if (!window.BattleTeambuilderTable) return this;
if (modid in this.moddedDexes) {
return this.moddedDexes[modid];
}
this.moddedDexes[modid] = new ModdedDex(modid);
return this.moddedDexes[modid];
}
forGen(gen: number) {
if (!gen) return this;
return this.mod(`gen${gen}` as ID);
}
resolveAvatar(avatar: string): string {
if (window.BattleAvatarNumbers && avatar in BattleAvatarNumbers) {
avatar = BattleAvatarNumbers[avatar];
}
if (avatar.startsWith('#')) {
return Dex.resourcePrefix + 'sprites/trainers-custom/' + toID(avatar.substr(1)) + '.png';
}
if (avatar.includes('.') && window.Config?.server?.registered) {
// custom avatar served by the server
let protocol = (Config.server.port === 443) ? 'https' : 'http';
return protocol + '://' + Config.server.host + ':' + Config.server.port +
'/avatars/' + encodeURIComponent(avatar).replace(/%3F/g, '?');
}
return Dex.resourcePrefix + 'sprites/trainers/' + Dex.sanitizeName(avatar || 'unknown') + '.png';
}
/**
* This is used to sanitize strings from data files like `moves.js` and
* `teambuilder-tables.js`.
*
* This makes sure untrusted strings can't wreak havoc if someone forgets to
* escape it before putting it in HTML.
*
* None of these characters belong in these files, anyway. (They can be used
* in move descriptions, but those are served from `text.js`, which are
* definitely always treated as unsanitized.)
*/
sanitizeName(name: any) {
if (!name) return '';
return ('' + name)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
.slice(0, 50);
}
prefs(prop: string) {
// @ts-expect-error this is what I get for calling it Storage...
return window.Storage?.prefs?.(prop);
}
getShortName(name: string) {
let shortName = name.replace(/[^A-Za-z0-9]+$/, '');
if (shortName.includes('(')) {
shortName += name.slice(shortName.length).replace(/[^()]+/g, '').replace(/\(\)/g, '');
}
return shortName;
}
getEffect(name: string | null | undefined): PureEffect | Item | Ability | Move {
name = (name || '').trim();
if (name.substr(0, 5) === 'item:') {
return Dex.items.get(name.substr(5).trim());
} else if (name.substr(0, 8) === 'ability:') {
return Dex.abilities.get(name.substr(8).trim());
} else if (name.substr(0, 5) === 'move:') {
return Dex.moves.get(name.substr(5).trim());
}
let id = toID(name);
return new PureEffect(id, name);
}
moves = {
get: (nameOrMove: string | Move | null | undefined): Move => {
if (nameOrMove && typeof nameOrMove !== 'string') {
// TODO: don't accept Moves here
return nameOrMove;
}
let name = nameOrMove || '';
let id = toID(nameOrMove);
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
}
if (!window.BattleMovedex) window.BattleMovedex = {};
let data = window.BattleMovedex[id];
if (data && typeof data.exists === 'boolean') return data;
if (!data && id.substr(0, 11) === 'hiddenpower' && id.length > 11) {
let [, hpWithType, hpPower] = /([a-z]*)([0-9]*)/.exec(id)!;
data = {
...(window.BattleMovedex[hpWithType] || {}),
basePower: Number(hpPower) || 60,
};
}
if (!data && id.substr(0, 6) === 'return' && id.length > 6) {
data = {
...(window.BattleMovedex['return'] || {}),
basePower: Number(id.slice(6)),
};
}
if (!data && id.substr(0, 11) === 'frustration' && id.length > 11) {
data = {
...(window.BattleMovedex['frustration'] || {}),
basePower: Number(id.slice(11)),
};
}
if (!data) data = { exists: false };
let move = new Move(id, name, data);
window.BattleMovedex[id] = move;
return move;
},
};
getGen3Category(type: string) {
return [
'Fire', 'Water', 'Grass', 'Electric', 'Ice', 'Psychic', 'Dark', 'Dragon',
].includes(type) ? 'Special' : 'Physical';
}
items = {
get: (nameOrItem: string | Item | null | undefined): Item => {
if (nameOrItem && typeof nameOrItem !== 'string') {
// TODO: don't accept Items here
return nameOrItem;
}
let name = nameOrItem || '';
let id = toID(nameOrItem);
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
}
if (!window.BattleItems) window.BattleItems = {};
let data = window.BattleItems[id];
if (data && typeof data.exists === 'boolean') return data;
if (!data) data = { exists: false };
let item = new Item(id, name, data);
window.BattleItems[id] = item;
return item;
},
};
abilities = {
get: (nameOrAbility: string | Ability | null | undefined): Ability => {
if (nameOrAbility && typeof nameOrAbility !== 'string') {
// TODO: don't accept Abilities here
return nameOrAbility;
}
let name = nameOrAbility || '';
let id = toID(nameOrAbility);
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
}
if (!window.BattleAbilities) window.BattleAbilities = {};
let data = window.BattleAbilities[id];
if (data && typeof data.exists === 'boolean') return data;
if (!data) data = { exists: false };
let ability = new Ability(id, name, data);
window.BattleAbilities[id] = ability;
return ability;
},
};
species = {
get: (nameOrSpecies: string | Species | null | undefined): Species => {
if (nameOrSpecies && typeof nameOrSpecies !== 'string') {
// TODO: don't accept Species' here
return nameOrSpecies;
}
let name = nameOrSpecies || '';
let id = toID(nameOrSpecies);
let formid = id;
if (!window.BattlePokedexAltForms) window.BattlePokedexAltForms = {};
if (formid in window.BattlePokedexAltForms) return window.BattlePokedexAltForms[formid];
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
} else if (window.BattlePokedex && !(id in BattlePokedex) && window.BattleBaseSpeciesChart) {
for (const baseSpeciesId of BattleBaseSpeciesChart) {
if (formid.startsWith(baseSpeciesId)) {
id = baseSpeciesId;
break;
}
}
}
if (!window.BattlePokedex) window.BattlePokedex = {};
let data = window.BattlePokedex[id];
let species: Species;
if (data && typeof data.exists === 'boolean') {
species = data;
} else {
if (!data) data = { exists: false };
if (!data.tier && id.endsWith('totem')) {
data.tier = this.species.get(id.slice(0, -5)).tier;
}
if (!data.tier && data.baseSpecies && toID(data.baseSpecies) !== id) {
data.tier = this.species.get(data.baseSpecies).tier;
}
data.nfe = data.id === 'dipplin' || !!(data as Species).evos?.some(evo => {
const evoSpecies = this.species.get(evo);
return !evoSpecies.isNonstandard || evoSpecies.isNonstandard === data.isNonstandard ||
// Pokemon with Hisui evolutions
evoSpecies.isNonstandard === "Unobtainable";
});
species = new Species(id, name, data);
window.BattlePokedex[id] = species;
}
if (species.cosmeticFormes) {
for (const forme of species.cosmeticFormes) {
if (toID(forme) === formid) {
species = new Species(formid, name, {
...species,
name: forme,
forme: forme.slice(species.name.length + 1),
baseForme: "",
baseSpecies: species.name,
otherFormes: null,
});
window.BattlePokedexAltForms[formid] = species;
break;
}
}
}
return species;
},
};
types = {
allCache: null as Type[] | null,
get: (type: any): Type => {
if (!type || typeof type === 'string') {
const id = toID(type) as string;
const name = id.substr(0, 1).toUpperCase() + id.substr(1);
type = window.BattleTypeChart?.[id] || {};
if (type.damageTaken) type.exists = true;
if (!type.id) type.id = id;
if (!type.name) type.name = name;
if (!type.effectType) {
type.effectType = 'Type';
}
}
return type;
},
all: (): readonly Type[] => {
if (this.types.allCache) return this.types.allCache;
const types = [];
for (const id in (window.BattleTypeChart || {})) {
types.push(Dex.types.get(id));
}
if (types.length) this.types.allCache = types;
return types;
},
isName: (name: string | null): boolean => {
const id = toID(name);
if (name !== id.substr(0, 1).toUpperCase() + id.substr(1)) return false;
return window.BattleTypeChart?.hasOwnProperty(id);
},
};
hasAbility(species: Species, ability: string) {
for (const i in species.abilities) {
if (ability === species.abilities[i as '0']) return true;
}
return false;
}
loadSpriteData(gen: 'xy' | 'bw') {
if (this.loadedSpriteData[gen]) return;
this.loadedSpriteData[gen] = 1;
let path = $('script[src*="pokedex-mini.js"]').attr('src') || '';
let qs = '?' + (path.split('?')[1] || '');
path = ((/.+?(?=data\/pokedex-mini\.js)/.exec(path)) || [])[0] || '';
let el = document.createElement('script');
el.src = path + 'data/pokedex-mini-bw.js' + qs;
document.getElementsByTagName('body')[0].appendChild(el);
}
getSpriteData(pokemon: Pokemon | Species | string, isFront: boolean, options: {
gen?: number,
shiny?: boolean,
gender?: Dex.GenderName,
afd?: boolean,
noScale?: boolean,
mod?: string,
dynamax?: boolean,
} = { gen: 6 }) {
const mechanicsGen = options.gen || 6;
let isDynamax = !!options.dynamax;
if (pokemon instanceof Pokemon) {
if (pokemon.volatiles.transform) {
options.shiny = pokemon.volatiles.transform[2];
options.gender = pokemon.volatiles.transform[3];
} else {
options.shiny = pokemon.shiny;
options.gender = pokemon.gender;
}
let isGigantamax = false;
if (pokemon.volatiles.dynamax) {
if (pokemon.volatiles.dynamax[1]) {
isGigantamax = true;
} else if (options.dynamax !== false) {
isDynamax = true;
}
}
pokemon = pokemon.getSpeciesForme() + (isGigantamax ? '-Gmax' : '');
}
const species = Dex.species.get(pokemon);
// Gmax sprites are already extremely large, so we don't need to double.
if (species.name.endsWith('-Gmax')) isDynamax = false;
let spriteData = {
gen: mechanicsGen,
w: 96,
h: 96,
y: 0,
url: Dex.resourcePrefix + 'sprites/',
pixelated: true,
isFrontSprite: false,
cryurl: '',
shiny: options.shiny,
};
let name = species.spriteid;
let dir;
let facing;
if (isFront) {
spriteData.isFrontSprite = true;
dir = '';
facing = 'front';
} else {
dir = '-back';
facing = 'back';
}
// Decide which gen sprites to use.
//
// There are several different generations we care about here:
//
// - mechanicsGen: the generation number of the mechanics and battle (options.gen)
// - graphicsGen: the generation number of sprite/field graphics the user has requested.
// This will default to mechanicsGen, but may be altered depending on user preferences.
// - spriteData.gen: the generation number of a the specific Pokemon sprite in question.
// This defaults to graphicsGen, but if the graphicsGen doesn't have a sprite for the Pokemon
// (eg. Darmanitan in graphicsGen 2) then we go up gens until it exists.
//
let graphicsGen = mechanicsGen;
if (Dex.prefs('nopastgens')) graphicsGen = 6;
if (Dex.prefs('bwgfx') && graphicsGen >= 6) graphicsGen = 5;
spriteData.gen = Math.max(graphicsGen, Math.min(species.gen, 5));
const baseDir = ['', 'gen1', 'gen2', 'gen3', 'gen4', 'gen5', '', '', '', ''][spriteData.gen];
let animationData = null;
let miscData = null;
let speciesid = species.id;
if (species.isTotem) speciesid = toID(name);
if (baseDir === '' && window.BattlePokemonSprites) {
animationData = BattlePokemonSprites[speciesid];
}
if (baseDir === 'gen5' && window.BattlePokemonSpritesBW) {
animationData = BattlePokemonSpritesBW[speciesid];
}
if (window.BattlePokemonSprites) miscData = BattlePokemonSprites[speciesid];
if (!miscData && window.BattlePokemonSpritesBW) miscData = BattlePokemonSpritesBW[speciesid];
if (!animationData) animationData = {};
if (!miscData) miscData = {};
if (miscData.num !== 0 && miscData.num > -5000) {
let baseSpeciesid = toID(species.baseSpecies);
spriteData.cryurl = 'audio/cries/' + baseSpeciesid;
let formeid = species.formeid;
if (species.isMega || formeid && (
formeid === '-crowned' ||
formeid === '-eternal' ||
formeid === '-eternamax' ||
formeid === '-four' ||
formeid === '-hangry' ||
formeid === '-hero' ||
formeid === '-lowkey' ||
formeid === '-noice' ||
formeid === '-primal' ||
formeid === '-rapidstrike' ||
formeid === '-roaming' ||
formeid === '-school' ||
formeid === '-sky' ||
formeid === '-starter' ||
formeid === '-super' ||
formeid === '-therian' ||
formeid === '-unbound' ||
baseSpeciesid === 'calyrex' ||
baseSpeciesid === 'kyurem' ||
baseSpeciesid === 'cramorant' ||
baseSpeciesid === 'indeedee' ||
baseSpeciesid === 'lycanroc' ||
baseSpeciesid === 'necrozma' ||
baseSpeciesid === 'oinkologne' ||
baseSpeciesid === 'oricorio' ||
baseSpeciesid === 'slowpoke' ||
baseSpeciesid === 'tatsugiri' ||
baseSpeciesid === 'zygarde'
)) {
spriteData.cryurl += formeid;
}
spriteData.cryurl += '.mp3';
}
if (options.shiny && mechanicsGen > 1) dir += '-shiny';
// April Fool's 2014
if (Dex.prefs('afd') !== false && (window.Config?.server?.afd || Dex.prefs('afd') || options.afd)) {
// Explicit false check above means AFD will be off if the user disables it - no matter what
dir = 'afd' + dir;
spriteData.url += dir + '/' + name + '.png';
// Duplicate code but needed to make AFD tinymax work
// April Fool's 2020
if (isDynamax && !options.noScale) {
spriteData.w *= 0.25;
spriteData.h *= 0.25;
spriteData.y += -22;
} else if (species.isTotem && !options.noScale) {
spriteData.w *= 0.5;
spriteData.h *= 0.5;
spriteData.y += -11;
}
return spriteData;
}
// Mod Cries
if (options.mod) {
spriteData.cryurl = `sprites/${options.mod}/audio/${toID(species.baseSpecies)}`;
spriteData.cryurl += '.mp3';
}
if (animationData[facing + 'f'] && options.gender === 'F') facing += 'f';
let allowAnim = !Dex.prefs('noanim') && !Dex.prefs('nogif');
if (allowAnim && spriteData.gen >= 6) spriteData.pixelated = false;
if (allowAnim && animationData[facing] && spriteData.gen >= 5) {
if (facing.endsWith('f')) name += '-f';
dir = baseDir + 'ani' + dir;
spriteData.w = animationData[facing].w;
spriteData.h = animationData[facing].h;
spriteData.url += dir + '/' + name + '.gif';
} else {
// There is no entry or enough data in pokedex-mini.js
// Handle these in case-by-case basis; either using BW sprites or matching the played gen.
dir = (baseDir || 'gen5') + dir;
// Gender differences don't exist prior to Gen 4,
// so there are no sprites for it
if (spriteData.gen >= 4 && miscData['frontf'] && options.gender === 'F') {
name += '-f';
}
spriteData.url += dir + '/' + name + '.png';
}
if (!options.noScale) {
if (graphicsGen > 4) {
// no scaling
} else if (spriteData.isFrontSprite) {
spriteData.w *= 2;
spriteData.h *= 2;
spriteData.y += -16;
} else {
// old gen backsprites are multiplied by 1.5x by the 3D engine
spriteData.w *= 2 / 1.5;
spriteData.h *= 2 / 1.5;
spriteData.y += -11;
}
if (spriteData.gen <= 2) spriteData.y += 2;
}
if (isDynamax && !options.noScale) {
spriteData.w *= 2;
spriteData.h *= 2;
spriteData.y += -22;
} else if (species.isTotem && !options.noScale) {
spriteData.w *= 1.5;
spriteData.h *= 1.5;
spriteData.y += -11;
}
return spriteData;
}
getPokemonIconNum(id: ID, isFemale?: boolean, facingLeft?: boolean) {
let num = 0;
if (window.BattlePokemonSprites?.[id]?.num) {
num = BattlePokemonSprites[id].num;
} else if (window.BattlePokedex?.[id]?.num) {
num = BattlePokedex[id].num;
}
if (num < 0) num = 0;
if (num > 1025) num = 0;
if (window.BattlePokemonIconIndexes?.[id]) {
num = BattlePokemonIconIndexes[id];
}
if (isFemale) {
if (['unfezant', 'frillish', 'jellicent', 'meowstic', 'pyroar'].includes(id)) {
num = BattlePokemonIconIndexes[id + 'f'];
}
}
if (facingLeft) {
if (BattlePokemonIconIndexesLeft[id]) {
num = BattlePokemonIconIndexesLeft[id];
}
}
return num;
}
getPokemonIcon(pokemon: string | Pokemon | ServerPokemon | Dex.PokemonSet | null, facingLeft?: boolean) {
if (pokemon === 'pokeball') {
return `background:transparent url(${Dex.resourcePrefix}sprites/pokemonicons-pokeball-sheet.png) no-repeat scroll -0px 4px`;
} else if (pokemon === 'pokeball-statused') {
return `background:transparent url(${Dex.resourcePrefix}sprites/pokemonicons-pokeball-sheet.png) no-repeat scroll -40px 4px`;
} else if (pokemon === 'pokeball-fainted') {
return `background:transparent url(${Dex.resourcePrefix}sprites/pokemonicons-pokeball-sheet.png) no-repeat scroll -80px 4px;opacity:.4;filter:contrast(0)`;
} else if (pokemon === 'pokeball-none') {
return `background:transparent url(${Dex.resourcePrefix}sprites/pokemonicons-pokeball-sheet.png) no-repeat scroll -80px 4px`;
}
let id = toID(pokemon);
if (!pokemon || typeof pokemon === 'string') pokemon = null;
// @ts-expect-error safe, but too lazy to cast
if (pokemon?.speciesForme) id = toID(pokemon.speciesForme);
// @ts-expect-error safe, but too lazy to cast
if (pokemon?.species) id = toID(pokemon.species);
// @ts-expect-error safe, but too lazy to cast
if (pokemon?.volatiles?.formechange && !pokemon.volatiles.transform) {
// @ts-expect-error safe, but too lazy to cast
id = toID(pokemon.volatiles.formechange[1]);
}
let num = this.getPokemonIconNum(id, pokemon?.gender === 'F', facingLeft);
let top = Math.floor(num / 12) * 30;
let left = (num % 12) * 40;
let fainted = ((pokemon as Pokemon | ServerPokemon)?.fainted ?
`;opacity:.3;filter:grayscale(100%) brightness(.5)` : ``);
return `background:transparent url(${Dex.resourcePrefix}sprites/pokemonicons-sheet.png?v18) no-repeat scroll -${left}px -${top}px${fainted}`;
}
getTeambuilderSpriteData(pokemon: any, gen = 0): TeambuilderSpriteData {
let id = toID(pokemon.species);
let spriteid = pokemon.spriteid;
let species = Dex.species.get(pokemon.species);
if (pokemon.species && !spriteid) {
spriteid = species.spriteid || toID(pokemon.species);
}
if (!species.exists) return { spriteDir: 'sprites/gen5', spriteid: '0', x: 10, y: 5 };
if (window.Config?.server?.afd || Dex.prefs('afd')) {
return {
spriteid,
spriteDir: 'sprites/afd',
shiny: !!pokemon.shiny,
x: 10,
y: 5,
};
}
const spriteData: TeambuilderSpriteData = {
spriteid,
spriteDir: 'sprites/dex',
x: -2,
y: -3,
};
if (pokemon.shiny) spriteData.shiny = true;
if (Dex.prefs('nopastgens')) gen = 6;
if (Dex.prefs('bwgfx') && gen > 5) gen = 5;
let xydexExists = (!species.isNonstandard || species.isNonstandard === 'Past' || species.isNonstandard === 'CAP') || [
"pikachustarter", "eeveestarter", "meltan", "melmetal", "pokestarufo", "pokestarufo2", "pokestarbrycenman", "pokestarmt", "pokestarmt2", "pokestargiant", "pokestarhumanoid", "pokestarmonster", "pokestarf00", "pokestarf002", "pokestarspirit",
].includes(species.id);
if (species.gen >= 8 && species.isNonstandard !== 'CAP') xydexExists = false;
if ((!gen || gen >= 6) && xydexExists) {
if (species.gen >= 7) {
spriteData.x = -6;
spriteData.y = -7;
} else if (id.substr(0, 6) === 'arceus') {
spriteData.x = -2;
spriteData.y = 7;
} else if (id === 'garchomp') {
spriteData.x = -2;
spriteData.y = 2;
} else if (id === 'garchompmega') {
spriteData.x = -2;
spriteData.y = 0;
}
return spriteData;
}
spriteData.spriteDir = 'sprites/gen5';
if (gen <= 1 && species.gen <= 1) spriteData.spriteDir = 'sprites/gen1';
else if (gen <= 2 && species.gen <= 2) spriteData.spriteDir = 'sprites/gen2';
else if (gen <= 3 && species.gen <= 3) spriteData.spriteDir = 'sprites/gen3';
else if (gen <= 4 && species.gen <= 4) spriteData.spriteDir = 'sprites/gen4';
spriteData.x = 10;
spriteData.y = 5;
return spriteData;
}
getTeambuilderSprite(pokemon: any, gen = 0) {
if (!pokemon) return '';
const data = this.getTeambuilderSpriteData(pokemon, gen);
const shiny = (data.shiny ? '-shiny' : '');
return `background-image:url(${Dex.resourcePrefix}${data.spriteDir}${shiny}/${data.spriteid}.png);background-position:${data.x}px ${data.y}px;background-repeat:no-repeat`;
}
getItemIcon(item: any) {
let num = 0;
if (typeof item === 'string' && exports.BattleItems) item = exports.BattleItems[toID(item)];
if (item?.spritenum) num = item.spritenum;
let top = Math.floor(num / 16) * 24;
let left = (num % 16) * 24;
return `background:transparent url(${Dex.resourcePrefix}sprites/itemicons-sheet.png?v1) no-repeat scroll -${left}px -${top}px`;
}
getTypeIcon(type: string | null, b?: boolean) { // b is just for utilichart.js
type = this.types.get(type).name;
if (!type) type = '???';
let sanitizedType = type.replace(/\?/g, '%3f');
return `<img src="${Dex.resourcePrefix}sprites/types/${sanitizedType}.png" alt="${type}" height="14" width="32" class="pixelated${b ? ' b' : ''}" />`;
}
getCategoryIcon(category: string | null) {
const categoryID = toID(category);
let sanitizedCategory = '';
switch (categoryID) {
case 'physical':
case 'special':
case 'status':
sanitizedCategory = categoryID.charAt(0).toUpperCase() + categoryID.slice(1);
break;
default:
sanitizedCategory = 'undefined';
break;
}
return `<img src="${Dex.resourcePrefix}sprites/categories/${sanitizedCategory}.png" alt="${sanitizedCategory}" height="14" width="32" class="pixelated" />`;
}
getPokeballs() {
if (this.pokeballs) return this.pokeballs;
this.pokeballs = [];
if (!window.BattleItems) window.BattleItems = {};
for (const data of Object.values<AnyObject>(window.BattleItems)) {
if (!data.isPokeball) continue;
this.pokeballs.push(data.name);
}
return this.pokeballs;
}
};
export class ModdedDex {
readonly gen: number;
readonly modid: ID;
readonly cache = {
Moves: {} as { [k: string]: Move },
Items: {} as { [k: string]: Item },
Abilities: {} as { [k: string]: Ability },
Species: {} as { [k: string]: Species },
Types: {} as { [k: string]: Dex.Effect },
};
pokeballs: string[] | null = null;
constructor(modid: ID) {
this.modid = modid;
const gen = parseInt(modid.substr(3, 1), 10);
if (!modid.startsWith('gen') || !gen) throw new Error("Unsupported modid");
this.gen = gen;
}
moves = {
get: (name: string): Move => {
let id = toID(name);
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
}
if (this.cache.Moves.hasOwnProperty(id)) return this.cache.Moves[id];
let data = { ...Dex.moves.get(name) };
for (let i = Dex.gen - 1; i >= this.gen; i--) {
const table = window.BattleTeambuilderTable[`gen${i}`];
if (id in table.overrideMoveData) {
Object.assign(data, table.overrideMoveData[id]);
}
}
if (this.modid !== `gen${this.gen}`) {
const table = window.BattleTeambuilderTable[this.modid];
if (id in table.overrideMoveData) {
Object.assign(data, table.overrideMoveData[id]);
}
}
if (this.gen <= 3 && data.category !== 'Status') {
data.category = Dex.getGen3Category(data.type);
}
const move = new Move(id, name, data);
this.cache.Moves[id] = move;
return move;
},
};
items = {
get: (name: string): Item => {
let id = toID(name);
if (window.BattleAliases && id in BattleAliases) {
name = BattleAliases[id];
id = toID(name);
}
if (this.cache.Items.hasOwnProperty(id)) return this.cache.Items[id];
let data = { ...Dex.items.get(name) };
for (let i = Dex.gen - 1; i >= this.gen; i--) {
const table = window.BattleTeambuilderTable[`gen${i}`];
if (id in table.overrideItemData) {
Object.assign(data, table.overrideItemData[id]);
}
}
if (this.modid !== `gen${this.gen}`) {
const table = window.BattleTeambuilderTable[this.modid];
if (id in table.overrideItemData) {
Object.assign(data, table.overrideItemData[id]);
}
}