forked from AllenDBB/infinite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
battle-engine.js
4143 lines (3840 loc) · 132 KB
/
battle-engine.js
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 process
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This file is where the battle simulation itself happens.
*
* The most important part of the simulation happens in runEvent -
* see that function's definition for details.
*
* @license MIT license
*/
require('sugar');
global.Config = require('./config/config.js');
/* if (Config.crashguard) {
// graceful crash - allow current battles to finish before restarting
process.on('uncaughtException', function (err) {
require('./crashlogger.js')(err, 'A simulator process');
var stack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />");
if (Rooms.lobby) {
Rooms.lobby.addRaw('<div><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>');
Rooms.lobby.addRaw('<div>You will not be able to talk in the lobby or start new battles until the server restarts.</div>');
}
Config.modchat = 'crash';
Rooms.global.lockdown = true;
});
} */
/**
* Converts anything to an ID. An ID must have only lowercase alphanumeric
* characters.
* If a string is passed, it will be converted to lowercase and
* non-alphanumeric characters will be stripped.
* If an object with an ID is passed, its ID will be returned.
* Otherwise, an empty string will be returned.
*/
global.toId = function (text) {
if (text && text.id) text = text.id;
else if (text && text.userid) text = text.userid;
return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
/**
* Validates a username or Pokemon nickname
*/
global.toName = function (name) {
name = string(name);
name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim();
if (name.length > 18) name = name.substr(0, 18).trim();
return name;
};
/**
* Safely ensures the passed variable is a string
* Simply doing '' + str can crash if str.toString crashes or isn't a function
* If we're expecting a string and being given anything that isn't a string
* or a number, it's safe to assume it's an error, and return ''
*/
global.string = function (str) {
if (typeof str === 'string' || typeof str === 'number') return '' + str;
return '';
};
global.Tools = require('./tools.js');
var Battle, BattleSide, BattlePokemon;
var Battles = {};
require('./repl.js').start('battle-engine-', process.pid, function (cmd) { return eval(cmd); });
// Receive and process a message sent using Simulator.prototype.send in
// another process.
battleEngineFakeProcess.client.on('message', function (message) {
//console.log('CHILD MESSAGE RECV: "' + message + '"');
var nlIndex = message.indexOf("\n");
var more = '';
if (nlIndex > 0) {
more = message.substr(nlIndex + 1);
message = message.substr(0, nlIndex);
}
var data = message.split('|');
if (data[1] === 'init') {
if (!Battles[data[0]]) {
try {
Battles[data[0]] = Battle.construct(data[0], data[2], data[3]);
} catch (err) {
var stack = err.stack + '\n\n' +
'Additional information:\n' +
'message = ' + message;
var fakeErr = {stack: stack};
if (!require('./crashlogger.js')(fakeErr, 'A battle')) {
var ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />");
battleEngineFakeProcess.client.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>A BATTLE PROCESS HAS CRASHED:</b> ' + ministack + '</div>');
} else {
battleEngineFakeProcess.client.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>The battle crashed!</b><br />Don\'t worry, we\'re working on fixing it.</div>');
}
}
}
} else if (data[1] === 'dealloc') {
if (Battles[data[0]]) Battles[data[0]].destroy();
delete Battles[data[0]];
} else {
var battle = Battles[data[0]];
if (battle) {
var prevRequest = battle.currentRequest;
var prevRequestDetails = battle.currentRequestDetails || '';
try {
battle.receive(data, more);
} catch (err) {
var stack = err.stack + '\n\n' +
'Additional information:\n' +
'message = ' + message + '\n' +
'currentRequest = ' + prevRequest + '\n\n' +
'Log:\n' + battle.log.join('\n').replace(/\n\|split\n[^\n]*\n[^\n]*\n[^\n]*\n/g, '\n');
var fakeErr = {stack: stack};
require('./crashlogger.js')(fakeErr, 'A battle');
var logPos = battle.log.length;
battle.add('html', '<div class="broadcast-red"><b>The battle crashed</b><br />You can keep playing but it might crash again.</div>');
var nestedError;
try {
battle.makeRequest(prevRequest, prevRequestDetails);
} catch (e) {
nestedError = e;
}
battle.sendUpdates(logPos);
if (nestedError) {
throw nestedError;
}
}
} else if (data[1] === 'eval') {
try {
eval(data[2]);
} catch (e) {}
}
}
});
BattlePokemon = (function () {
function BattlePokemon(set, side) {
this.side = side;
this.battle = side.battle;
var pokemonScripts = this.battle.data.Scripts.pokemon;
if (pokemonScripts) Object.merge(this, pokemonScripts);
if (typeof set === 'string') set = {name: set};
// "pre-bound" functions for nicer syntax (avoids repeated use of `bind`)
this.getHealth = this.getHealth || BattlePokemon.getHealth.bind(this);
this.getDetails = this.getDetails || BattlePokemon.getDetails.bind(this);
this.set = set;
this.baseTemplate = this.battle.getTemplate(set.species || set.name);
if (!this.baseTemplate.exists) {
this.battle.debug('Unidentified species: ' + this.species);
this.baseTemplate = this.battle.getTemplate('Unown');
}
this.species = this.baseTemplate.species;
if (set.name === set.species || !set.name || !set.species) {
set.name = this.species;
}
this.name = (set.name || set.species || 'Bulbasaur').substr(0, 20);
this.speciesid = toId(this.species);
this.template = this.baseTemplate;
this.moves = [];
this.baseMoves = this.moves;
this.movepp = {};
this.moveset = [];
this.baseMoveset = [];
this.level = this.battle.clampIntRange(set.forcedLevel || set.level || 100, 1, 1000);
var genders = {M:'M', F:'F'};
this.gender = this.template.gender || genders[set.gender] || (Math.random() * 2 < 1 ? 'M' : 'F');
if (this.gender === 'N') this.gender = '';
this.happiness = typeof set.happiness === 'number' ? this.battle.clampIntRange(set.happiness, 0, 255) : 255;
this.pokeball = this.set.pokeball || 'pokeball';
this.fullname = this.side.id + ': ' + this.name;
this.details = this.species + (this.level === 100 ? '' : ', L' + this.level) + (this.gender === '' ? '' : ', ' + this.gender) + (this.set.shiny ? ', shiny' : '');
this.id = this.fullname; // shouldn't really be used anywhere
this.statusData = {};
this.volatiles = {};
this.negateImmunity = {};
this.height = this.template.height;
this.heightm = this.template.heightm;
this.weight = this.template.weight;
this.weightkg = this.template.weightkg;
this.ignore = {};
this.baseAbility = toId(set.ability);
this.ability = this.baseAbility;
this.item = toId(set.item);
var forme;
if (this.baseTemplate.otherFormes) forme = this.battle.getTemplate(this.baseTemplate.otherFormes[0]);
this.canMegaEvo = ((this.battle.getItem(this.item).megaEvolves === this.baseTemplate.baseSpecies) || (forme && forme.isMega && forme.requiredMove && this.set.moves.indexOf(toId(forme.requiredMove)) > -1));
this.abilityData = {id: this.ability};
this.itemData = {id: this.item};
this.speciesData = {id: this.speciesid};
this.types = this.baseTemplate.types;
this.typesData = [];
for (var i = 0, l = this.types.length; i < l; i++) {
this.typesData.push({
type: this.types[i],
suppressed: false,
isAdded: false
});
}
if (this.set.moves) {
for (var i = 0; i < this.set.moves.length; i++) {
var move = this.battle.getMove(this.set.moves[i]);
if (!move.id) continue;
if (move.id === 'hiddenpower') {
if (!this.set.ivs || Object.values(this.set.ivs).every(31)) {
this.set.ivs = this.battle.getType(move.type).HPivs;
}
move = this.battle.getMove('hiddenpower');
}
this.baseMoveset.push({
move: move.name,
id: move.id,
pp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5),
maxpp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5),
target: (move.nonGhostTarget && !this.hasType('Ghost') ? move.nonGhostTarget : move.target),
disabled: false,
used: false
});
this.moves.push(move.id);
}
}
if (!this.set.evs) {
this.set.evs = {hp: 84, atk: 84, def: 84, spa: 84, spd: 84, spe: 84};
}
if (!this.set.ivs) {
this.set.ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31};
}
var stats = {hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31};
for (var i in stats) {
if (!this.set.evs[i]) this.set.evs[i] = 0;
if (!this.set.ivs[i] && this.set.ivs[i] !== 0) this.set.ivs[i] = 31;
}
for (var i in this.set.evs) {
this.set.evs[i] = this.battle.clampIntRange(this.set.evs[i], 0, 255);
}
for (var i in this.set.ivs) {
this.set.ivs[i] = this.battle.clampIntRange(this.set.ivs[i], 0, 31);
}
var hpTypes = ['Fighting', 'Flying', 'Poison', 'Ground', 'Rock', 'Bug', 'Ghost', 'Steel', 'Fire', 'Water', 'Grass', 'Electric', 'Psychic', 'Ice', 'Dragon', 'Dark'];
if (this.battle.gen && this.battle.gen === 2) {
// Gen 2 specific Hidden Power check. IVs are still treated 0-31 so we get them 0-15
var atkDV = Math.floor(this.set.ivs.atk / 2);
var defDV = Math.floor(this.set.ivs.def / 2);
var speDV = Math.floor(this.set.ivs.spe / 2);
var spcDV = Math.floor(this.set.ivs.spa / 2);
this.hpType = hpTypes[4 * (atkDV % 4) + (defDV % 4)];
this.hpPower = Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV > 2 ? 3 : spcDV)) / 2 + 31);
} else {
// Hidden Power check for gen 3 onwards
var hpTypeX = 0, hpPowerX = 0;
var i = 1;
for (var s in stats) {
hpTypeX += i * (this.set.ivs[s] % 2);
hpPowerX += i * (Math.floor(this.set.ivs[s] / 2) % 2);
i *= 2;
}
this.hpType = hpTypes[Math.floor(hpTypeX * 15 / 63)];
// In Gen 6, Hidden Power is always 60 base power
this.hpPower = (this.battle.gen && this.battle.gen < 6) ? Math.floor(hpPowerX * 40 / 63) + 30 : 60;
}
this.boosts = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0};
this.stats = {atk:0, def:0, spa:0, spd:0, spe:0};
this.baseStats = {atk:10, def:10, spa:10, spd:10, spe:10};
for (var statName in this.baseStats) {
var stat = this.template.baseStats[statName];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5);
var nature = this.battle.getNature(this.set.nature);
if (statName === nature.plus) stat *= 1.1;
if (statName === nature.minus) stat *= 0.9;
this.baseStats[statName] = Math.floor(stat);
}
this.maxhp = Math.floor(Math.floor(2 * this.template.baseStats['hp'] + this.set.ivs['hp'] + Math.floor(this.set.evs['hp'] / 4) + 100) * this.level / 100 + 10);
if (this.template.baseStats['hp'] === 1) this.maxhp = 1; // shedinja
this.hp = this.hp || this.maxhp;
this.baseIvs = this.set.ivs;
this.baseHpType = this.hpType;
this.baseHpPower = this.hpPower;
this.clearVolatile(true);
}
BattlePokemon.prototype.trapped = false;
BattlePokemon.prototype.maybeTrapped = false;
BattlePokemon.prototype.maybeDisabled = false;
BattlePokemon.prototype.hp = 0;
BattlePokemon.prototype.maxhp = 100;
BattlePokemon.prototype.illusion = null;
BattlePokemon.prototype.fainted = false;
BattlePokemon.prototype.faintQueued = false;
BattlePokemon.prototype.lastItem = '';
BattlePokemon.prototype.ateBerry = false;
BattlePokemon.prototype.status = '';
BattlePokemon.prototype.position = 0;
BattlePokemon.prototype.lastMove = '';
BattlePokemon.prototype.moveThisTurn = '';
BattlePokemon.prototype.lastDamage = 0;
BattlePokemon.prototype.lastAttackedBy = null;
BattlePokemon.prototype.usedItemThisTurn = false;
BattlePokemon.prototype.newlySwitched = false;
BattlePokemon.prototype.beingCalledBack = false;
BattlePokemon.prototype.isActive = false;
BattlePokemon.prototype.isStarted = false; // has this pokemon's Start events run yet?
BattlePokemon.prototype.transformed = false;
BattlePokemon.prototype.duringMove = false;
BattlePokemon.prototype.hpType = 'Dark';
BattlePokemon.prototype.hpPower = 60;
BattlePokemon.prototype.speed = 0;
BattlePokemon.prototype.toString = function () {
var fullname = this.fullname;
if (this.illusion) fullname = this.illusion.fullname;
var positionList = 'abcdef';
if (this.isActive) return fullname.substr(0, 2) + positionList[this.position] + fullname.substr(2);
return fullname;
};
// "static" function
BattlePokemon.getDetails = function (side) {
if (this.illusion) return this.illusion.details + '|' + this.getHealth(side);
return this.details + '|' + this.getHealth(side);
};
BattlePokemon.prototype.update = function (init) {
// reset for Light Metal etc
this.weightkg = this.template.weightkg;
// reset for diabled moves
this.disabledMoves = {};
this.negateImmunity = {};
this.trapped = this.maybeTrapped = false;
this.maybeDisabled = false;
// reset for ignore settings
this.ignore = {};
for (var i in this.moveset) {
if (this.moveset[i]) this.moveset[i].disabled = false;
}
if (init) return;
if (this.runImmunity('trapped')) this.battle.runEvent('MaybeTrapPokemon', this);
// Disable the faculty to cancel switches if a foe may have a trapping ability
for (var i = 0; i < this.battle.sides.length; ++i) {
var side = this.battle.sides[i];
if (side === this.side) continue;
for (var j = 0; j < side.active.length; ++j) {
var pokemon = side.active[j];
if (!pokemon || pokemon.fainted) continue;
var template = (pokemon.illusion || pokemon).template;
if (!template.abilities) continue;
for (var k in template.abilities) {
var ability = template.abilities[k];
if (ability === pokemon.ability) {
// This event was already run above so we don't need
// to run it again.
continue;
}
if ((k === 'H') && template.unreleasedHidden) {
// unreleased hidden ability
continue;
}
if (this.runImmunity('trapped')) {
this.battle.singleEvent('FoeMaybeTrapPokemon',
this.battle.getAbility(ability), {}, this, pokemon);
}
}
}
}
this.battle.runEvent('ModifyPokemon', this);
this.speed = this.getStat('spe');
};
BattlePokemon.prototype.calculateStat = function (statName, boost, modifier) {
statName = toId(statName);
if (statName === 'hp') return this.maxhp; // please just read .maxhp directly
// base stat
var stat = this.stats[statName];
// stat boosts
// boost = this.boosts[statName];
var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
stat = Math.floor(stat * boostTable[boost]);
} else {
stat = Math.floor(stat / boostTable[-boost]);
}
// stat modifier
stat = this.battle.modify(stat, (modifier || 1));
if (this.battle.getStatCallback) {
stat = this.battle.getStatCallback(stat, statName, this);
}
return stat;
};
BattlePokemon.prototype.getStat = function (statName, unboosted, unmodified) {
statName = toId(statName);
if (statName === 'hp') return this.maxhp; // please just read .maxhp directly
// base stat
var stat = this.stats[statName];
// stat boosts
if (!unboosted) {
var boost = this.boosts[statName];
var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
stat = Math.floor(stat * boostTable[boost]);
} else {
stat = Math.floor(stat / boostTable[-boost]);
}
}
// stat modifier effects
if (!unmodified) {
var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'};
var statMod = 1;
statMod = this.battle.runEvent('Modify' + statTable[statName], this, null, null, statMod);
stat = this.battle.modify(stat, statMod);
}
if (this.battle.getStatCallback) {
stat = this.battle.getStatCallback(stat, statName, this, unboosted);
}
return stat;
};
BattlePokemon.prototype.getMoveData = function (move) {
move = this.battle.getMove(move);
for (var i = 0; i < this.moveset.length; i++) {
var moveData = this.moveset[i];
if (moveData.id === move.id) {
return moveData;
}
}
return null;
};
BattlePokemon.prototype.deductPP = function (move, amount, source) {
move = this.battle.getMove(move);
var ppData = this.getMoveData(move);
var success = false;
if (ppData) {
ppData.used = true;
}
if (ppData && ppData.pp) {
ppData.pp -= this.battle.runEvent('DeductPP', this, source || this, move, amount || 1);
if (ppData.pp <= 0) {
ppData.pp = 0;
}
success = true;
}
return success;
};
BattlePokemon.prototype.moveUsed = function (move) {
this.lastMove = this.battle.getMove(move).id;
this.moveThisTurn = this.lastMove;
};
BattlePokemon.prototype.gotAttacked = function (move, damage, source) {
if (!damage) damage = 0;
move = this.battle.getMove(move);
this.lastAttackedBy = {
pokemon: source,
damage: damage,
move: move.id,
thisTurn: true
};
};
BattlePokemon.prototype.getLockedMove = function () {
var lockedMove = this.battle.runEvent('LockMove', this);
if (lockedMove === true) lockedMove = false;
return lockedMove;
};
BattlePokemon.prototype.getMoves = function (lockedMove, restrictData) {
if (lockedMove) {
lockedMove = toId(lockedMove);
this.trapped = true;
}
if (lockedMove === 'recharge') {
return [{
move: 'Recharge',
id: 'recharge'
}];
}
var moves = [];
var hasValidMove = false;
for (var i = 0; i < this.moveset.length; i++) {
var move = this.moveset[i];
if (lockedMove) {
if (lockedMove === move.id) {
return [{
move: move.move,
id: move.id
}];
}
continue;
}
if (this.disabledMoves[move.id] && (!restrictData || !this.disabledMoves[move.id].isHidden) || !move.pp && (this.battle.gen !== 1 || !this.volatiles['partialtrappinglock'])) {
move.disabled = !restrictData && this.disabledMoves[move.id] && this.disabledMoves[move.id].isHidden ? 'hidden' : true;
} else if (!move.disabled || move.disabled === 'hidden' && restrictData) {
hasValidMove = true;
}
var moveName = move.move;
if (move.id === 'hiddenpower') {
moveName = 'Hidden Power ' + this.hpType;
if (this.battle.gen < 6) moveName += ' ' + this.hpPower;
}
moves.push({
move: moveName,
id: move.id,
pp: move.pp,
maxpp: move.maxpp,
target: move.target,
disabled: move.disabled
});
}
if (lockedMove) {
return [{
move: this.battle.getMove(lockedMove).name,
id: lockedMove
}];
}
if (hasValidMove) return moves;
return [{
move: 'Struggle',
id: 'struggle'
}];
};
BattlePokemon.prototype.getRequestData = function () {
var lockedMove = this.getLockedMove();
// Information should be restricted for the last active Pokémon
var isLastActive = this.isLastActive();
var data = {moves: this.getMoves(lockedMove, isLastActive)};
if (isLastActive) {
if (this.maybeDisabled) {
data.maybeDisabled = true;
}
if (this.trapped === true) {
data.trapped = true;
} else if (this.maybeTrapped) {
data.maybeTrapped = true;
}
} else {
if (this.trapped) data.trapped = true;
}
return data;
};
BattlePokemon.prototype.isLastActive = function () {
if (!this.isActive) return false;
var allyActive = this.side.active;
for (var i = this.position + 1; i < allyActive.length; i++) {
if (allyActive[i] && !allyActive.fainted) return false;
}
return true;
};
BattlePokemon.prototype.positiveBoosts = function () {
var boosts = 0;
for (var i in this.boosts) {
if (this.boosts[i] > 0) boosts += this.boosts[i];
}
return boosts;
};
BattlePokemon.prototype.boostBy = function (boost) {
var changed = false;
for (var i in boost) {
var delta = boost[i];
this.boosts[i] += delta;
if (this.boosts[i] > 6) {
delta -= this.boosts[i] - 6;
this.boosts[i] = 6;
}
if (this.boosts[i] < -6) {
delta -= this.boosts[i] - (-6);
this.boosts[i] = -6;
}
if (delta) changed = true;
}
this.update();
return changed;
};
BattlePokemon.prototype.clearBoosts = function () {
for (var i in this.boosts) {
this.boosts[i] = 0;
}
this.update();
};
BattlePokemon.prototype.setBoost = function (boost) {
for (var i in boost) {
this.boosts[i] = boost[i];
}
this.update();
};
BattlePokemon.prototype.copyVolatileFrom = function (pokemon) {
this.clearVolatile();
this.boosts = pokemon.boosts;
for (var i in pokemon.volatiles) {
if (this.battle.getEffect(i).noCopy) continue;
// shallow clones
this.volatiles[i] = Object.clone(pokemon.volatiles[i]);
if (this.volatiles[i].linkedPokemon) {
delete pokemon.volatiles[i].linkedPokemon;
delete pokemon.volatiles[i].linkedStatus;
this.volatiles[i].linkedPokemon.volatiles[this.volatiles[i].linkedStatus].linkedPokemon = this;
}
}
pokemon.clearVolatile();
this.update();
for (var i in this.volatiles) {
this.battle.singleEvent('Copy', this.getVolatile(i), this.volatiles[i], this);
}
};
BattlePokemon.prototype.transformInto = function (pokemon, user) {
var template = pokemon.template;
if (pokemon.fainted || pokemon.illusion || (pokemon.volatiles['substitute'] && this.battle.gen >= 5)) {
return false;
}
if (!template.abilities || (pokemon && pokemon.transformed && this.battle.gen >= 2) || (user && user.transformed && this.battle.gen >= 5)) {
return false;
}
if (!this.formeChange(template, true)) {
return false;
}
this.transformed = true;
this.typesData = [];
for (var i = 0, l = pokemon.typesData.length; i < l; i++) {
this.typesData.push({
type: pokemon.typesData[i].type,
suppressed: false,
isAdded: pokemon.typesData[i].isAdded
});
}
for (var statName in this.stats) {
this.stats[statName] = pokemon.stats[statName];
}
this.moveset = [];
this.moves = [];
this.set.ivs = (this.battle.gen >= 5 ? this.set.ivs : pokemon.set.ivs);
this.hpType = (this.battle.gen >= 5 ? this.hpType : pokemon.hpType);
this.hpPower = (this.battle.gen >= 5 ? this.hpPower : pokemon.hpPower);
for (var i = 0; i < pokemon.moveset.length; i++) {
var move = this.battle.getMove(this.set.moves[i]);
var moveData = pokemon.moveset[i];
var moveName = moveData.move;
if (moveData.id === 'hiddenpower') {
moveName = 'Hidden Power ' + this.hpType;
}
this.moveset.push({
move: moveName,
id: moveData.id,
pp: move.noPPBoosts ? moveData.maxpp : 5,
maxpp: this.battle.gen >= 5 ? (move.noPPBoosts ? moveData.maxpp : 5) : (this.battle.gen <= 2 ? move.pp : moveData.maxpp),
target: moveData.target,
disabled: false
});
this.moves.push(toId(moveName));
}
for (var j in pokemon.boosts) {
this.boosts[j] = pokemon.boosts[j];
}
this.battle.add('-transform', this, pokemon);
this.setAbility(pokemon.ability);
this.update();
return true;
};
BattlePokemon.prototype.formeChange = function (template, dontRecalculateStats) {
template = this.battle.getTemplate(template);
if (!template.abilities) return false;
this.illusion = null;
this.template = template;
this.types = template.types;
this.typesData = [];
this.types = template.types;
for (var i = 0, l = this.types.length; i < l; i++) {
this.typesData.push({
type: this.types[i],
suppressed: false,
isAdded: false
});
}
if (!dontRecalculateStats) {
for (var statName in this.stats) {
var stat = this.template.baseStats[statName];
stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5);
// nature
var nature = this.battle.getNature(this.set.nature);
if (statName === nature.plus) stat *= 1.1;
if (statName === nature.minus) stat *= 0.9;
this.baseStats[statName] = this.stats[statName] = Math.floor(stat);
}
this.speed = this.stats.spe;
}
return true;
};
BattlePokemon.prototype.clearVolatile = function (init) {
this.boosts = {
atk: 0,
def: 0,
spa: 0,
spd: 0,
spe: 0,
accuracy: 0,
evasion: 0
};
this.moveset = this.baseMoveset.slice();
this.moves = this.moveset.map(function (move) {
return toId(move.move);
});
this.transformed = false;
this.ability = this.baseAbility;
this.set.ivs = this.baseIvs;
this.hpType = this.baseHpType;
this.hpPower = this.baseHpPower;
for (var i in this.volatiles) {
if (this.volatiles[i].linkedStatus) {
this.volatiles[i].linkedPokemon.removeVolatile(this.volatiles[i].linkedStatus);
}
}
this.volatiles = {};
this.switchFlag = false;
this.lastMove = '';
this.moveThisTurn = '';
this.lastDamage = 0;
this.lastAttackedBy = null;
this.newlySwitched = true;
this.beingCalledBack = false;
this.formeChange(this.baseTemplate);
this.update(init);
};
BattlePokemon.prototype.hasType = function (type) {
if (!type) return false;
if (Array.isArray(type)) {
for (var i = 0; i < type.length; i++) {
if (this.hasType(type[i])) return true;
}
} else {
if (this.getTypes().indexOf(type) > -1) return true;
}
return false;
};
// returns the amount of damage actually dealt
BattlePokemon.prototype.faint = function (source, effect) {
// This function only puts the pokemon in the faint queue;
// actually setting of this.fainted comes later when the
// faint queue is resolved.
if (this.fainted || this.faintQueued) return 0;
var d = this.hp;
this.hp = 0;
this.switchFlag = false;
this.faintQueued = true;
this.battle.faintQueue.push({
target: this,
source: source,
effect: effect
});
return d;
};
BattlePokemon.prototype.damage = function (d, source, effect) {
if (!this.hp) return 0;
if (d < 1 && d > 0) d = 1;
d = Math.floor(d);
if (isNaN(d)) return 0;
if (d <= 0) return 0;
this.hp -= d;
if (this.hp <= 0) {
d += this.hp;
this.faint(source, effect);
}
return d;
};
BattlePokemon.prototype.tryTrap = function (isHidden) {
if (this.runImmunity('trapped')) {
if (this.trapped && isHidden) return true;
this.trapped = isHidden ? 'hidden' : true;
return true;
}
return false;
};
BattlePokemon.prototype.hasMove = function (moveid) {
moveid = toId(moveid);
if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower';
for (var i = 0; i < this.moveset.length; i++) {
if (moveid === this.battle.getMove(this.moveset[i].move).id) {
return moveid;
}
}
return false;
};
BattlePokemon.prototype.getValidMoves = function (lockedMove) {
var pMoves = this.getMoves(lockedMove);
var moves = [];
for (var i = 0; i < pMoves.length; i++) {
if (!pMoves[i].disabled) {
moves.push(pMoves[i].id);
}
}
if (!moves.length) return ['struggle'];
return moves;
};
BattlePokemon.prototype.disableMove = function (moveid, isHidden, sourceEffect) {
if (!sourceEffect && this.battle.event) {
sourceEffect = this.battle.effect;
}
moveid = toId(moveid);
if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower';
if (this.disabledMoves[moveid] && !this.disabledMoves[moveid].isHidden) return;
this.disabledMoves[moveid] = {
isHidden: !!isHidden,
sourceEffect: sourceEffect
};
};
// returns the amount of damage actually healed
BattlePokemon.prototype.heal = function (d) {
if (!this.hp) return false;
d = Math.floor(d);
if (isNaN(d)) return false;
if (d <= 0) return false;
if (this.hp >= this.maxhp) return false;
this.hp += d;
if (this.hp > this.maxhp) {
d -= this.hp - this.maxhp;
this.hp = this.maxhp;
}
return d;
};
// sets HP, returns delta
BattlePokemon.prototype.sethp = function (d) {
if (!this.hp) return 0;
d = Math.floor(d);
if (isNaN(d)) return;
if (d < 1) d = 1;
d = d - this.hp;
this.hp += d;
if (this.hp > this.maxhp) {
d -= this.hp - this.maxhp;
this.hp = this.maxhp;
}
return d;
};
BattlePokemon.prototype.trySetStatus = function (status, source, sourceEffect) {
if (!this.hp) return false;
if (this.status) return false;
return this.setStatus(status, source, sourceEffect);
};
BattlePokemon.prototype.cureStatus = function () {
if (!this.hp) return false;
// unlike clearStatus, gives cure message
if (this.status) {
this.battle.add('-curestatus', this, this.status);
this.setStatus('');
}
};
BattlePokemon.prototype.setStatus = function (status, source, sourceEffect, ignoreImmunities) {
if (!this.hp) return false;
status = this.battle.getEffect(status);
if (this.battle.event) {
if (!source) source = this.battle.event.source;
if (!sourceEffect) sourceEffect = this.battle.effect;
}
if (!ignoreImmunities && status.id) {
// the game currently never ignores immunities
if (!this.runImmunity(status.id === 'tox' ? 'psn' : status.id)) {
this.battle.debug('immune to status');
return false;
}
}
if (this.status === status.id) return false;
var prevStatus = this.status;
var prevStatusData = this.statusData;
if (status.id && !this.battle.runEvent('SetStatus', this, source, sourceEffect, status)) {
this.battle.debug('set status [' + status.id + '] interrupted');
return false;
}
this.status = status.id;
this.statusData = {id: status.id, target: this};
if (source) this.statusData.source = source;
if (status.duration) {
this.statusData.duration = status.duration;
}
if (status.durationCallback) {
this.statusData.duration = status.durationCallback.call(this.battle, this, source, sourceEffect);
}
if (status.id && !this.battle.singleEvent('Start', status, this.statusData, this, source, sourceEffect)) {
this.battle.debug('status start [' + status.id + '] interrupted');
// cancel the setstatus
this.status = prevStatus;
this.statusData = prevStatusData;
return false;
}
this.update();
if (status.id && !this.battle.runEvent('AfterSetStatus', this, source, sourceEffect, status)) {
return false;
}
return true;
};
BattlePokemon.prototype.clearStatus = function () {
// unlike cureStatus, does not give cure message
return this.setStatus('');
};
BattlePokemon.prototype.getStatus = function () {
return this.battle.getEffect(this.status);
};
BattlePokemon.prototype.eatItem = function (item, source, sourceEffect) {
if (!this.hp || !this.isActive) return false;
if (!this.item) return false;
var id = toId(item);
if (id && this.item !== id) return false;
if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect;
if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target;
item = this.getItem();
if (this.battle.runEvent('UseItem', this, null, null, item) && this.battle.runEvent('EatItem', this, null, null, item)) {
this.battle.add('-enditem', this, item, '[eat]');
this.battle.singleEvent('Eat', item, this.itemData, this, source, sourceEffect);
this.lastItem = this.item;
this.item = '';
this.itemData = {id: '', target: this};
this.usedItemThisTurn = true;
this.ateBerry = true;
this.battle.runEvent('AfterUseItem', this, null, null, item);
return true;
}
return false;
};
BattlePokemon.prototype.useItem = function (item, source, sourceEffect) {
if (!this.isActive) return false;
if (!this.item) return false;
var id = toId(item);
if (id && this.item !== id) return false;
if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect;
if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target;
item = this.getItem();
if (this.battle.runEvent('UseItem', this, null, null, item)) {
switch (item.id) {
case 'redcard':
this.battle.add('-enditem', this, item, '[of] ' + source);
break;
default:
if (!item.isGem) {
this.battle.add('-enditem', this, item);