forked from smogon/pokemon-showdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattle.ts
3178 lines (2880 loc) · 105 KB
/
battle.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 Battle
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This file is where the battle simulation itself happens.
*
* The most important part of the simulation is the event system:
* see the `runEvent` function definition for details.
*
* General battle mechanics are in `battle-actions`; move-specific,
* item-specific, etc mechanics are in the corresponding file in
* `data`.
*
* @license MIT
*/
import {Dex, toID} from './dex';
import {Teams} from './teams';
import {Field} from './field';
import {Pokemon, EffectState, RESTORATIVE_BERRIES} from './pokemon';
import {PRNG, PRNGSeed} from './prng';
import {Side} from './side';
import {State} from './state';
import {BattleQueue, Action} from './battle-queue';
import {BattleActions} from './battle-actions';
import {Utils} from '../lib/utils';
declare const __version: any;
export type ChannelID = 0 | 1 | 2 | 3 | 4;
export type ChannelMessages<T extends ChannelID | -1> = Record<T, string[]>;
const splitRegex = /^\|split\|p([1234])\n(.*)\n(.*)|.+/gm;
export function extractChannelMessages<T extends ChannelID | -1>(message: string, channelIds: T[]): ChannelMessages<T> {
const channelIdSet = new Set(channelIds);
const channelMessages: ChannelMessages<ChannelID | -1> = {
[-1]: [],
0: [],
1: [],
2: [],
3: [],
4: [],
};
for (const [lineMatch, playerMatch, secretMessage, sharedMessage] of message.matchAll(splitRegex)) {
const player = playerMatch ? parseInt(playerMatch) : 0;
for (const channelId of channelIdSet) {
let line = lineMatch;
if (player) {
line = channelId === -1 || player === channelId ? secretMessage : sharedMessage;
if (!line) continue;
}
channelMessages[channelId].push(line);
}
}
return channelMessages;
}
interface BattleOptions {
format?: Format;
formatid: ID;
/** Output callback */
send?: (type: string, data: string | string[]) => void;
prng?: PRNG; // PRNG override (you usually don't need this, just pass a seed)
seed?: PRNGSeed; // PRNG seed
rated?: boolean | string; // Rated string
p1?: PlayerOptions; // Player 1 data
p2?: PlayerOptions; // Player 2 data
p3?: PlayerOptions; // Player 3 data
p4?: PlayerOptions; // Player 4 data
debug?: boolean; // show debug mode option
forceRandomChance?: boolean; // force Battle#randomChance to always return true or false (used in some tests)
deserialized?: boolean;
strictChoices?: boolean; // whether invalid choices should throw
}
interface EventListenerWithoutPriority {
effect: Effect;
target?: Pokemon;
index?: number;
// eslint-disable-next-line @typescript-eslint/ban-types
callback?: Function;
state: EffectState | null;
// eslint-disable-next-line @typescript-eslint/ban-types
end: Function | null;
endCallArgs?: any[];
effectHolder: Pokemon | Side | Field | Battle;
}
interface EventListener extends EventListenerWithoutPriority {
order: number | false;
priority: number;
subOrder: number;
speed?: number;
}
type Part = string | number | boolean | Pokemon | Side | Effect | Move | null | undefined;
// The current request state of the Battle:
//
// - 'teampreview': beginning of BW/XY/SM battle (Team Preview)
// - 'move': beginning of each turn
// - 'switch': end of turn if fainted (or mid turn with switching effects)
// - '': no request. Used between turns, or when the battle is over.
//
// An individual Side's request state is encapsulated in its `activeRequest` field.
export type RequestState = 'teampreview' | 'move' | 'switch' | '';
export class Battle {
readonly id: ID;
readonly debugMode: boolean;
readonly forceRandomChance: boolean | null;
readonly deserialized: boolean;
readonly strictChoices: boolean;
readonly format: Format;
readonly formatData: EffectState;
readonly gameType: GameType;
/**
* The number of active pokemon per half-field.
* See header comment in side.ts for details.
*/
readonly activePerHalf: 1 | 2 | 3;
readonly field: Field;
readonly sides: [Side, Side] | [Side, Side, Side, Side];
readonly prngSeed: PRNGSeed;
dex: ModdedDex;
gen: number;
ruleTable: Dex.RuleTable;
prng: PRNG;
rated: boolean | string;
reportExactHP: boolean;
reportPercentages: boolean;
supportCancel: boolean;
actions: BattleActions;
queue: BattleQueue;
readonly faintQueue: {
target: Pokemon,
source: Pokemon | null,
effect: Effect | null,
}[];
readonly log: string[];
readonly inputLog: string[];
readonly messageLog: string[];
sentLogPos: number;
sentEnd: boolean;
requestState: RequestState;
turn: number;
midTurn: boolean;
started: boolean;
ended: boolean;
winner?: string;
effect: Effect;
effectState: EffectState;
event: AnyObject;
events: AnyObject | null;
eventDepth: number;
activeMove: ActiveMove | null;
activePokemon: Pokemon | null;
activeTarget: Pokemon | null;
lastMove: ActiveMove | null;
lastSuccessfulMoveThisTurn: ID | null;
lastMoveLine: number;
/** The last damage dealt by a move in the battle - only used by Gen 1 Counter. */
lastDamage: number;
abilityOrder: number;
quickClawRoll: boolean;
teamGenerator: ReturnType<typeof Teams.getGenerator> | null;
readonly hints: Set<string>;
readonly NOT_FAIL: '';
readonly HIT_SUBSTITUTE: 0;
readonly FAIL: false;
readonly SILENT_FAIL: null;
readonly send: (type: string, data: string | string[]) => void;
trunc: (num: number, bits?: number) => number;
clampIntRange: (num: any, min?: number, max?: number) => number;
toID = toID;
constructor(options: BattleOptions) {
this.log = [];
this.add('t:', Math.floor(Date.now() / 1000));
const format = options.format || Dex.formats.get(options.formatid, true);
this.format = format;
this.dex = Dex.forFormat(format);
this.gen = this.dex.gen;
this.ruleTable = this.dex.formats.getRuleTable(format);
this.trunc = this.dex.trunc;
this.clampIntRange = Utils.clampIntRange;
// Object.assign(this, this.dex.data.Scripts);
for (const i in this.dex.data.Scripts) {
const entry = this.dex.data.Scripts[i];
if (typeof entry === 'function') (this as any)[i] = entry;
}
if (format.battle) Object.assign(this, format.battle);
this.id = '';
this.debugMode = format.debug || !!options.debug;
// Require debug mode and explicitly passed true/false
this.forceRandomChance = (this.debugMode && typeof options.forceRandomChance === 'boolean') ?
options.forceRandomChance : null;
this.deserialized = !!options.deserialized;
this.strictChoices = !!options.strictChoices;
this.formatData = {id: format.id};
this.gameType = (format.gameType || 'singles');
this.field = new Field(this);
this.sides = Array(format.playerCount).fill(null) as any;
this.activePerHalf = this.gameType === 'triples' ? 3 :
(format.playerCount > 2 || this.gameType === 'doubles') ? 2 :
1;
this.prng = options.prng || new PRNG(options.seed || undefined);
this.prngSeed = this.prng.startingSeed;
this.rated = options.rated || !!options.rated;
this.reportExactHP = !!format.debug;
this.reportPercentages = false;
this.supportCancel = false;
this.queue = new BattleQueue(this);
this.actions = new BattleActions(this);
this.faintQueue = [];
this.inputLog = [];
this.messageLog = [];
this.sentLogPos = 0;
this.sentEnd = false;
this.requestState = '';
this.turn = 0;
this.midTurn = false;
this.started = false;
this.ended = false;
this.effect = {id: ''} as Effect;
this.effectState = {id: ''};
this.event = {id: ''};
this.events = null;
this.eventDepth = 0;
this.activeMove = null;
this.activePokemon = null;
this.activeTarget = null;
this.lastMove = null;
this.lastMoveLine = -1;
this.lastSuccessfulMoveThisTurn = null;
this.lastDamage = 0;
this.abilityOrder = 0;
this.quickClawRoll = false;
this.teamGenerator = null;
this.hints = new Set();
this.NOT_FAIL = '';
this.HIT_SUBSTITUTE = 0;
this.FAIL = false;
this.SILENT_FAIL = null;
this.send = options.send || (() => {});
const inputOptions: {formatid: ID, seed: PRNGSeed, rated?: string | true} = {
formatid: options.formatid, seed: this.prngSeed,
};
if (this.rated) inputOptions.rated = this.rated;
if (typeof __version !== 'undefined') {
if (__version.head) {
this.inputLog.push(`>version ${__version.head}`);
}
if (__version.origin) {
this.inputLog.push(`>version-origin ${__version.origin}`);
}
}
this.inputLog.push(`>start ` + JSON.stringify(inputOptions));
this.add('gametype', this.gameType);
// timing is early enough to hook into ModifySpecies event
for (const rule of this.ruleTable.keys()) {
if ('+*-!'.includes(rule.charAt(0))) continue;
const subFormat = this.dex.formats.get(rule);
if (subFormat.exists) {
const hasEventHandler = Object.keys(subFormat).some(
// skip event handlers that are handled elsewhere
val => val.startsWith('on') && ![
'onBegin', 'onTeamPreview', 'onBattleStart', 'onValidateRule', 'onValidateTeam', 'onChangeSet', 'onValidateSet',
].includes(val)
);
if (hasEventHandler) this.field.addPseudoWeather(rule);
}
}
const sides: SideID[] = ['p1', 'p2', 'p3', 'p4'];
for (const side of sides) {
if (options[side]) {
this.setPlayer(side, options[side]!);
}
}
}
toJSON(): AnyObject {
return State.serializeBattle(this);
}
static fromJSON(serialized: string | AnyObject): Battle {
return State.deserializeBattle(serialized);
}
get p1() {
return this.sides[0];
}
get p2() {
return this.sides[1];
}
get p3() {
return this.sides[2];
}
get p4() {
return this.sides[3];
}
toString() {
return `Battle: ${this.format}`;
}
random(m?: number, n?: number) {
return this.prng.random(m, n);
}
randomChance(numerator: number, denominator: number) {
if (this.forceRandomChance !== null) return this.forceRandomChance;
return this.prng.randomChance(numerator, denominator);
}
sample<T>(items: readonly T[]): T {
return this.prng.sample(items);
}
/** Note that passing `undefined` resets to the starting seed, but `null` will roll a new seed */
resetRNG(seed: PRNGSeed | null = this.prngSeed) {
this.prng = new PRNG(seed);
this.add('message', "The battle's RNG was reset.");
}
suppressingAbility(target?: Pokemon) {
return this.activePokemon && this.activePokemon.isActive && (this.activePokemon !== target || this.gen < 8) &&
this.activeMove && this.activeMove.ignoreAbility && !target?.hasItem('Ability Shield');
}
setActiveMove(move?: ActiveMove | null, pokemon?: Pokemon | null, target?: Pokemon | null) {
this.activeMove = move || null;
this.activePokemon = pokemon || null;
this.activeTarget = target || pokemon || null;
}
clearActiveMove(failed?: boolean) {
if (this.activeMove) {
if (!failed) {
this.lastMove = this.activeMove;
}
this.activeMove = null;
this.activePokemon = null;
this.activeTarget = null;
}
}
updateSpeed() {
for (const pokemon of this.getAllActive()) {
pokemon.updateSpeed();
}
}
/**
* The default sort order for actions, but also event listeners.
*
* 1. Order, low to high (default last)
* 2. Priority, high to low (default 0)
* 3. Speed, high to low (default 0)
* 4. SubOrder, low to high (default 0)
*
* Doesn't reference `this` so doesn't need to be bound.
*/
comparePriority(a: AnyObject, b: AnyObject) {
return -((b.order || 4294967296) - (a.order || 4294967296)) ||
((b.priority || 0) - (a.priority || 0)) ||
((b.speed || 0) - (a.speed || 0)) ||
-((b.subOrder || 0) - (a.subOrder || 0)) ||
0;
}
static compareRedirectOrder(a: AnyObject, b: AnyObject) {
return ((b.priority || 0) - (a.priority || 0)) ||
((b.speed || 0) - (a.speed || 0)) ||
((a.effectHolder && b.effectHolder) ? -(b.effectHolder.abilityOrder - a.effectHolder.abilityOrder) : 0) ||
0;
}
static compareLeftToRightOrder(a: AnyObject, b: AnyObject) {
return -((b.order || 4294967296) - (a.order || 4294967296)) ||
((b.priority || 0) - (a.priority || 0)) ||
-((b.index || 0) - (a.index || 0)) ||
0;
}
/** Sort a list, resolving speed ties the way the games do. */
speedSort<T extends AnyObject>(list: T[], comparator: (a: T, b: T) => number = this.comparePriority) {
if (list.length < 2) return;
let sorted = 0;
// This is a Selection Sort - not the fastest sort in general, but
// actually faster than QuickSort for small arrays like the ones
// `speedSort` is used for.
// More importantly, it makes it easiest to resolve speed ties
// properly.
while (sorted + 1 < list.length) {
let nextIndexes = [sorted];
// grab list of next indexes
for (let i = sorted + 1; i < list.length; i++) {
const delta = comparator(list[nextIndexes[0]], list[i]);
if (delta < 0) continue;
if (delta > 0) nextIndexes = [i];
if (delta === 0) nextIndexes.push(i);
}
// put list of next indexes where they belong
for (let i = 0; i < nextIndexes.length; i++) {
const index = nextIndexes[i];
if (index !== sorted + i) {
// nextIndexes is guaranteed to be in order, so it will never have
// been disturbed by an earlier swap
[list[sorted + i], list[index]] = [list[index], list[sorted + i]];
}
}
if (nextIndexes.length > 1) {
this.prng.shuffle(list, sorted, sorted + nextIndexes.length);
}
sorted += nextIndexes.length;
}
}
/**
* Runs an event with no source on each Pokémon on the field, in Speed order.
*/
eachEvent(eventid: string, effect?: Effect | null, relayVar?: boolean) {
const actives = this.getAllActive();
if (!effect && this.effect) effect = this.effect;
this.speedSort(actives, (a, b) => b.speed - a.speed);
for (const pokemon of actives) {
this.runEvent(eventid, pokemon, null, effect, relayVar);
}
if (eventid === 'Weather' && this.gen >= 7) {
// TODO: further research when updates happen
this.eachEvent('Update');
}
}
/**
* Runs an event with no source on each effect on the field, in Speed order.
*
* Unlike `eachEvent`, this contains a lot of other handling and is intended only for the residual step.
*/
residualEvent(eventid: string, relayVar?: any) {
const callbackName = `on${eventid}`;
let handlers = this.findBattleEventHandlers(callbackName, 'duration');
handlers = handlers.concat(this.findFieldEventHandlers(this.field, `onField${eventid}`, 'duration'));
for (const side of this.sides) {
if (side.n < 2 || !side.allySide) {
handlers = handlers.concat(this.findSideEventHandlers(side, `onSide${eventid}`, 'duration'));
}
for (const active of side.active) {
if (!active) continue;
handlers = handlers.concat(this.findPokemonEventHandlers(active, callbackName, 'duration'));
handlers = handlers.concat(this.findSideEventHandlers(side, callbackName, undefined, active));
handlers = handlers.concat(this.findFieldEventHandlers(this.field, callbackName, undefined, active));
}
}
this.speedSort(handlers);
while (handlers.length) {
const handler = handlers[0];
handlers.shift();
const effect = handler.effect;
if ((handler.effectHolder as Pokemon).fainted) continue;
if (handler.end && handler.state && handler.state.duration) {
handler.state.duration--;
if (!handler.state.duration) {
const endCallArgs = handler.endCallArgs || [handler.effectHolder, effect.id];
handler.end.call(...endCallArgs as [any, ...any[]]);
if (this.ended) return;
continue;
}
}
let handlerEventid = eventid;
if ((handler.effectHolder as Side).sideConditions) handlerEventid = `Side${eventid}`;
if ((handler.effectHolder as Field).pseudoWeather) handlerEventid = `Field${eventid}`;
if (handler.callback) {
this.singleEvent(handlerEventid, effect, handler.state, handler.effectHolder, null, null, relayVar, handler.callback);
}
this.faintMessages();
if (this.ended) return;
}
}
/** The entire event system revolves around this function and runEvent. */
singleEvent(
eventid: string, effect: Effect, state: AnyObject | null,
target: string | Pokemon | Side | Field | Battle | null, source?: string | Pokemon | Effect | false | null,
sourceEffect?: Effect | string | null, relayVar?: any, customCallback?: unknown
) {
if (this.eventDepth >= 8) {
// oh fuck
this.add('message', 'STACK LIMIT EXCEEDED');
this.add('message', 'PLEASE REPORT IN BUG THREAD');
this.add('message', 'Event: ' + eventid);
this.add('message', 'Parent event: ' + this.event.id);
throw new Error("Stack overflow");
}
if (this.log.length - this.sentLogPos > 1000) {
this.add('message', 'LINE LIMIT EXCEEDED');
this.add('message', 'PLEASE REPORT IN BUG THREAD');
this.add('message', 'Event: ' + eventid);
this.add('message', 'Parent event: ' + this.event.id);
throw new Error("Infinite loop");
}
// this.add('Event: ' + eventid + ' (depth ' + this.eventDepth + ')');
let hasRelayVar = true;
if (relayVar === undefined) {
relayVar = true;
hasRelayVar = false;
}
if (effect.effectType === 'Status' && (target instanceof Pokemon) && target.status !== effect.id) {
// it's changed; call it off
return relayVar;
}
if (eventid !== 'Start' && eventid !== 'TakeItem' && eventid !== 'Primal' &&
effect.effectType === 'Item' && (target instanceof Pokemon) && target.ignoringItem()) {
this.debug(eventid + ' handler suppressed by Embargo, Klutz or Magic Room');
return relayVar;
}
if (eventid !== 'End' && effect.effectType === 'Ability' && (target instanceof Pokemon) && target.ignoringAbility()) {
this.debug(eventid + ' handler suppressed by Gastro Acid or Neutralizing Gas');
return relayVar;
}
if (
effect.effectType === 'Weather' && eventid !== 'FieldStart' && eventid !== 'FieldResidual' &&
eventid !== 'FieldEnd' && this.field.suppressingWeather()
) {
this.debug(eventid + ' handler suppressed by Air Lock');
return relayVar;
}
const callback = customCallback || (effect as any)[`on${eventid}`];
if (callback === undefined) return relayVar;
const parentEffect = this.effect;
const parentEffectState = this.effectState;
const parentEvent = this.event;
this.effect = effect;
this.effectState = state || {};
this.event = {id: eventid, target, source, effect: sourceEffect};
this.eventDepth++;
const args = [target, source, sourceEffect];
if (hasRelayVar) args.unshift(relayVar);
let returnVal;
if (typeof callback === 'function') {
returnVal = callback.apply(this, args);
} else {
returnVal = callback;
}
this.eventDepth--;
this.effect = parentEffect;
this.effectState = parentEffectState;
this.event = parentEvent;
return returnVal === undefined ? relayVar : returnVal;
}
/**
* runEvent is the core of Pokemon Showdown's event system.
*
* Basic usage
* ===========
*
* this.runEvent('Blah')
* will trigger any onBlah global event handlers.
*
* this.runEvent('Blah', target)
* will additionally trigger any onBlah handlers on the target, onAllyBlah
* handlers on any active pokemon on the target's team, and onFoeBlah
* handlers on any active pokemon on the target's foe's team
*
* this.runEvent('Blah', target, source)
* will additionally trigger any onSourceBlah handlers on the source
*
* this.runEvent('Blah', target, source, effect)
* will additionally pass the effect onto all event handlers triggered
*
* this.runEvent('Blah', target, source, effect, relayVar)
* will additionally pass the relayVar as the first argument along all event
* handlers
*
* You may leave any of these null. For instance, if you have a relayVar but
* no source or effect:
* this.runEvent('Damage', target, null, null, 50)
*
* Event handlers
* ==============
*
* Items, abilities, statuses, and other effects like SR, confusion, weather,
* or Trick Room can have event handlers. Event handlers are functions that
* can modify what happens during an event.
*
* event handlers are passed:
* function (target, source, effect)
* although some of these can be blank.
*
* certain events have a relay variable, in which case they're passed:
* function (relayVar, target, source, effect)
*
* Relay variables are variables that give additional information about the
* event. For instance, the damage event has a relayVar which is the amount
* of damage dealt.
*
* If a relay variable isn't passed to runEvent, there will still be a secret
* relayVar defaulting to `true`, but it won't get passed to any event
* handlers.
*
* After an event handler is run, its return value helps determine what
* happens next:
* 1. If the return value isn't `undefined`, relayVar is set to the return
* value
* 2. If relayVar is falsy, no more event handlers are run
* 3. Otherwise, if there are more event handlers, the next one is run and
* we go back to step 1.
* 4. Once all event handlers are run (or one of them results in a falsy
* relayVar), relayVar is returned by runEvent
*
* As a shortcut, an event handler that isn't a function will be interpreted
* as a function that returns that value.
*
* You can have return values mean whatever you like, but in general, we
* follow the convention that returning `false` or `null` means
* stopping or interrupting the event.
*
* For instance, returning `false` from a TrySetStatus handler means that
* the pokemon doesn't get statused.
*
* If a failed event usually results in a message like "But it failed!"
* or "It had no effect!", returning `null` will suppress that message and
* returning `false` will display it. Returning `null` is useful if your
* event handler already gave its own custom failure message.
*
* Returning `undefined` means "don't change anything" or "keep going".
* A function that does nothing but return `undefined` is the equivalent
* of not having an event handler at all.
*
* Returning a value means that that value is the new `relayVar`. For
* instance, if a Damage event handler returns 50, the damage event
* will deal 50 damage instead of whatever it was going to deal before.
*
* Useful values
* =============
*
* In addition to all the methods and attributes of Dex, Battle, and
* Scripts, event handlers have some additional values they can access:
*
* this.effect:
* the Effect having the event handler
* this.effectState:
* the data store associated with the above Effect. This is a plain Object
* and you can use it to store data for later event handlers.
* this.effectState.target:
* the Pokemon, Side, or Battle that the event handler's effect was
* attached to.
* this.event.id:
* the event ID
* this.event.target, this.event.source, this.event.effect:
* the target, source, and effect of the event. These are the same
* variables that are passed as arguments to the event handler, but
* they're useful for functions called by the event handler.
*/
runEvent(
eventid: string, target?: Pokemon | Pokemon[] | Side | Battle | null, source?: string | Pokemon | false | null,
sourceEffect?: Effect | null, relayVar?: any, onEffect?: boolean, fastExit?: boolean
) {
// if (Battle.eventCounter) {
// if (!Battle.eventCounter[eventid]) Battle.eventCounter[eventid] = 0;
// Battle.eventCounter[eventid]++;
// }
if (this.eventDepth >= 8) {
// oh fuck
this.add('message', 'STACK LIMIT EXCEEDED');
this.add('message', 'PLEASE REPORT IN BUG THREAD');
this.add('message', 'Event: ' + eventid);
this.add('message', 'Parent event: ' + this.event.id);
throw new Error("Stack overflow");
}
if (!target) target = this;
let effectSource = null;
if (source instanceof Pokemon) effectSource = source;
const handlers = this.findEventHandlers(target, eventid, effectSource);
if (onEffect) {
if (!sourceEffect) throw new Error("onEffect passed without an effect");
// @ts-ignore - dynamic lookup
const callback = sourceEffect[`on${eventid}`];
if (callback !== undefined) {
if (Array.isArray(target)) throw new Error("");
handlers.unshift(this.resolvePriority({
effect: sourceEffect, callback, state: {}, end: null, effectHolder: target,
}, `on${eventid}`));
}
}
if (['Invulnerability', 'TryHit', 'DamagingHit', 'EntryHazard'].includes(eventid)) {
handlers.sort(Battle.compareLeftToRightOrder);
} else if (fastExit) {
handlers.sort(Battle.compareRedirectOrder);
} else {
this.speedSort(handlers);
}
let hasRelayVar = 1;
const args = [target, source, sourceEffect];
// console.log('Event: ' + eventid + ' (depth ' + this.eventDepth + ') t:' + target.id + ' s:' + (!source || source.id) + ' e:' + effect.id);
if (relayVar === undefined || relayVar === null) {
relayVar = true;
hasRelayVar = 0;
} else {
args.unshift(relayVar);
}
const parentEvent = this.event;
this.event = {id: eventid, target, source, effect: sourceEffect, modifier: 1};
this.eventDepth++;
let targetRelayVars = [];
if (Array.isArray(target)) {
if (Array.isArray(relayVar)) {
targetRelayVars = relayVar;
} else {
for (let i = 0; i < target.length; i++) targetRelayVars[i] = true;
}
}
for (const handler of handlers) {
if (handler.index !== undefined) {
// TODO: find a better way to do this
if (!targetRelayVars[handler.index] && !(targetRelayVars[handler.index] === 0 &&
eventid === 'DamagingHit')) continue;
if (handler.target) {
args[hasRelayVar] = handler.target;
this.event.target = handler.target;
}
if (hasRelayVar) args[0] = targetRelayVars[handler.index];
}
const effect = handler.effect;
const effectHolder = handler.effectHolder;
// this.debug('match ' + eventid + ': ' + status.id + ' ' + status.effectType);
if (effect.effectType === 'Status' && (effectHolder as Pokemon).status !== effect.id) {
// it's changed; call it off
continue;
}
if (effect.effectType === 'Ability' && effect.flags['breakable'] &&
this.suppressingAbility(effectHolder as Pokemon)) {
if (effect.flags['breakable']) {
this.debug(eventid + ' handler suppressed by Mold Breaker');
continue;
}
if (!effect.num) {
// ignore attacking events for custom abilities
const AttackingEvents = {
BeforeMove: 1,
BasePower: 1,
Immunity: 1,
RedirectTarget: 1,
Heal: 1,
SetStatus: 1,
CriticalHit: 1,
ModifyAtk: 1, ModifyDef: 1, ModifySpA: 1, ModifySpD: 1, ModifySpe: 1, ModifyAccuracy: 1,
ModifyBoost: 1,
ModifyDamage: 1,
ModifySecondaries: 1,
ModifyWeight: 1,
TryAddVolatile: 1,
TryHit: 1,
TryHitSide: 1,
TryMove: 1,
Boost: 1,
DragOut: 1,
Effectiveness: 1,
};
if (eventid in AttackingEvents) {
this.debug(eventid + ' handler suppressed by Mold Breaker');
continue;
} else if (eventid === 'Damage' && sourceEffect && sourceEffect.effectType === 'Move') {
this.debug(eventid + ' handler suppressed by Mold Breaker');
continue;
}
}
}
if (eventid !== 'Start' && eventid !== 'SwitchIn' && eventid !== 'TakeItem' &&
effect.effectType === 'Item' && (effectHolder instanceof Pokemon) && effectHolder.ignoringItem()) {
if (eventid !== 'Update') {
this.debug(eventid + ' handler suppressed by Embargo, Klutz or Magic Room');
}
continue;
} else if (eventid !== 'End' && effect.effectType === 'Ability' &&
(effectHolder instanceof Pokemon) && effectHolder.ignoringAbility()) {
if (eventid !== 'Update') {
this.debug(eventid + ' handler suppressed by Gastro Acid or Neutralizing Gas');
}
continue;
}
if ((effect.effectType === 'Weather' || eventid === 'Weather') &&
eventid !== 'Residual' && eventid !== 'End' && this.field.suppressingWeather()) {
this.debug(eventid + ' handler suppressed by Air Lock');
continue;
}
let returnVal;
if (typeof handler.callback === 'function') {
const parentEffect = this.effect;
const parentEffectState = this.effectState;
this.effect = handler.effect;
this.effectState = handler.state || {};
this.effectState.target = effectHolder;
returnVal = handler.callback.apply(this, args);
this.effect = parentEffect;
this.effectState = parentEffectState;
} else {
returnVal = handler.callback;
}
if (returnVal !== undefined) {
relayVar = returnVal;
if (!relayVar || fastExit) {
if (handler.index !== undefined) {
targetRelayVars[handler.index] = relayVar;
if (targetRelayVars.every(val => !val)) break;
} else {
break;
}
}
if (hasRelayVar) {
args[0] = relayVar;
}
}
}
this.eventDepth--;
if (typeof relayVar === 'number' && relayVar === Math.abs(Math.floor(relayVar))) {
// this.debug(eventid + ' modifier: 0x' +
// ('0000' + (this.event.modifier * 4096).toString(16)).slice(-4).toUpperCase());
relayVar = this.modify(relayVar, this.event.modifier);
}
this.event = parentEvent;
return Array.isArray(target) ? targetRelayVars : relayVar;
}
/**
* priorityEvent works just like runEvent, except it exits and returns
* on the first non-undefined value instead of only on null/false.
*/
priorityEvent(
eventid: string, target: Pokemon | Side | Battle, source?: Pokemon | null,
effect?: Effect, relayVar?: any, onEffect?: boolean
): any {
return this.runEvent(eventid, target, source, effect, relayVar, onEffect, true);
}
resolvePriority(handler: EventListenerWithoutPriority, callbackName: string) {
// @ts-ignore
handler.order = handler.effect[`${callbackName}Order`] || false;
// @ts-ignore
handler.priority = handler.effect[`${callbackName}Priority`] || 0;
// @ts-ignore
handler.subOrder = handler.effect[`${callbackName}SubOrder`] || 0;
if (handler.effectHolder && (handler.effectHolder as Pokemon).getStat) {
(handler as EventListener).speed = (handler.effectHolder as Pokemon).speed;
}
return handler as EventListener;
}
findEventHandlers(target: Pokemon | Pokemon[] | Side | Battle, eventName: string, source?: Pokemon | null) {
let handlers: EventListener[] = [];
if (Array.isArray(target)) {
for (const [i, pokemon] of target.entries()) {
// console.log(`Event: ${eventName}, Target: ${'' + pokemon}, ${i}`);
const curHandlers = this.findEventHandlers(pokemon, eventName, source);
for (const handler of curHandlers) {
handler.target = pokemon; // Original "effectHolder"
handler.index = i;
}
handlers = handlers.concat(curHandlers);
}
return handlers;
}
// events usually run through EachEvent should never have any handlers besides `on${eventName}` so don't check for them
const prefixedHandlers = !['BeforeTurn', 'Update', 'Weather', 'WeatherChange', 'TerrainChange'].includes(eventName);
if (target instanceof Pokemon && (target.isActive || source?.isActive)) {
handlers = this.findPokemonEventHandlers(target, `on${eventName}`);
if (prefixedHandlers) {
for (const allyActive of target.alliesAndSelf()) {
handlers.push(...this.findPokemonEventHandlers(allyActive, `onAlly${eventName}`));
handlers.push(...this.findPokemonEventHandlers(allyActive, `onAny${eventName}`));
}
for (const foeActive of target.foes()) {
handlers.push(...this.findPokemonEventHandlers(foeActive, `onFoe${eventName}`));
handlers.push(...this.findPokemonEventHandlers(foeActive, `onAny${eventName}`));
}
}
target = target.side;
}
if (source && prefixedHandlers) {
handlers.push(...this.findPokemonEventHandlers(source, `onSource${eventName}`));
}
if (target instanceof Side) {
for (const side of this.sides) {
if (side.n >= 2 && side.allySide) break;
if (side === target || side === target.allySide) {
handlers.push(...this.findSideEventHandlers(side, `on${eventName}`));
} else if (prefixedHandlers) {
handlers.push(...this.findSideEventHandlers(side, `onFoe${eventName}`));
}
if (prefixedHandlers) handlers.push(...this.findSideEventHandlers(side, `onAny${eventName}`));
}
}
handlers.push(...this.findFieldEventHandlers(this.field, `on${eventName}`));
handlers.push(...this.findBattleEventHandlers(`on${eventName}`));
return handlers;
}
findPokemonEventHandlers(pokemon: Pokemon, callbackName: string, getKey?: 'duration') {
const handlers: EventListener[] = [];
const status = pokemon.getStatus();
// @ts-ignore - dynamic lookup
let callback = status[callbackName];
if (callback !== undefined || (getKey && pokemon.statusState[getKey])) {
handlers.push(this.resolvePriority({
effect: status, callback, state: pokemon.statusState, end: pokemon.clearStatus, effectHolder: pokemon,
}, callbackName));
}
for (const id in pokemon.volatiles) {
const volatileState = pokemon.volatiles[id];
const volatile = this.dex.conditions.getByID(id as ID);
// @ts-ignore - dynamic lookup
callback = volatile[callbackName];
if (callback !== undefined || (getKey && volatileState[getKey])) {
handlers.push(this.resolvePriority({
effect: volatile, callback, state: volatileState, end: pokemon.removeVolatile, effectHolder: pokemon,
}, callbackName));
}
}
const ability = pokemon.getAbility();
// @ts-ignore - dynamic lookup
callback = ability[callbackName];
if (callback !== undefined || (getKey && pokemon.abilityState[getKey])) {
handlers.push(this.resolvePriority({
effect: ability, callback, state: pokemon.abilityState, end: pokemon.clearAbility, effectHolder: pokemon,
}, callbackName));
}
const item = pokemon.getItem();
// @ts-ignore - dynamic lookup
callback = item[callbackName];
if (callback !== undefined || (getKey && pokemon.itemState[getKey])) {
handlers.push(this.resolvePriority({
effect: item, callback, state: pokemon.itemState, end: pokemon.clearItem, effectHolder: pokemon,
}, callbackName));
}
const species = pokemon.baseSpecies;
// @ts-ignore - dynamic lookup
callback = species[callbackName];
if (callback !== undefined) {
handlers.push(this.resolvePriority({
effect: species, callback, state: pokemon.speciesState, end() {}, effectHolder: pokemon,
}, callbackName));
}
const side = pokemon.side;
for (const conditionid in side.slotConditions[pokemon.position]) {