forked from smogon/pokemon-showdown-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient-battle.js
1330 lines (1224 loc) · 52.7 KB
/
client-battle.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
(function ($) {
var BattleRoom = this.BattleRoom = ConsoleRoom.extend({
type: 'battle',
title: '',
minWidth: 320,
minMainWidth: 956,
maxWidth: 1180,
initialize: function (data) {
this.me = {};
this.$el.addClass('ps-room-opaque').html('<div class="battle">Battle is here</div><div class="foehint"></div><div class="battle-log"></div><div class="battle-log-add">Connecting...</div><div class="battle-controls"></div><button class="battle-chat-toggle button" name="showChat"><i class="fa fa-caret-left"></i> Chat</button>');
this.$battle = this.$el.find('.battle');
this.$controls = this.$el.find('.battle-controls');
this.$chatFrame = this.$el.find('.battle-log');
this.$chatAdd = this.$el.find('.battle-log-add');
this.$join = null;
this.$foeHint = this.$el.find('.foehint');
BattleSound.setMute(Tools.prefs('mute'));
this.battle = new Battle(this.$battle, this.$chatFrame);
this.tooltips = new BattleTooltips(this.battle, this);
this.battle.roomid = this.id;
this.users = {};
this.$chat = this.$chatFrame.find('.inner');
this.$options = this.battle.optionsElem.html('<div style="padding-top: 3px; padding-right: 3px; text-align: right"><button class="icon button" name="openBattleOptions" title="Options">Battle Options</button></div>');
var self = this;
this.battle.customCallback = function () { self.updateControls(); };
this.battle.endCallback = function () { self.updateControls(); };
this.battle.startCallback = function () { self.updateControls(); };
this.battle.stagnateCallback = function () { self.updateControls(); };
this.battle.play();
},
events: {
'click .replayDownloadButton': 'clickReplayDownloadButton',
'change input[name=zmove]': 'updateZMove'
},
battleEnded: false,
join: function () {
app.send('/join ' + this.id);
},
showChat: function () {
this.$('.battle-chat-toggle').attr('name', 'hideChat').html('Battle <i class="fa fa-caret-right"></i>');
this.$el.addClass('showing-chat');
},
hideChat: function () {
this.$('.battle-chat-toggle').attr('name', 'showChat').html('<i class="fa fa-caret-left"></i> Chat');
this.$el.removeClass('showing-chat');
},
leave: function () {
if (!this.expired) app.send('/leave ' + this.id);
if (this.battle) this.battle.destroy();
},
requestLeave: function (e) {
if (this.side && this.battle && !this.battleEnded && !this.expired && !this.battle.forfeitPending) {
app.addPopup(ForfeitPopup, {room: this, sourceEl: e && e.currentTarget});
return false;
}
return true;
},
updateLayout: function () {
var width = this.$el.width();
if (width < 950) {
this.battle.messageDelay = 800;
} else {
this.battle.messageDelay = 8;
}
if (width && width < 640) {
var scale = (width / 640);
this.$battle.css('transform', 'scale(' + scale + ')');
this.$foeHint.css('transform', 'scale(' + scale + ')');
this.$controls.css('top', 360 * scale + 10);
} else {
this.$battle.css('transform', 'none');
this.$foeHint.css('transform', 'none');
this.$controls.css('top', 370);
}
this.$el.toggleClass('small-layout', width < 830);
this.$el.toggleClass('tiny-layout', width < 640);
if (this.$chat) this.$chatFrame.scrollTop(this.$chat.height());
},
show: function () {
Room.prototype.show.apply(this, arguments);
this.updateLayout();
},
receive: function (data) {
this.add(data);
},
focus: function () {
this.tooltips.hideTooltip();
if (this.battle.playbackState === 3) {
this.battle.play();
if (Tools.prefs('noanim')) this.battle.fastForwardTo(-1);
}
ConsoleRoom.prototype.focus.call(this);
},
blur: function () {
this.battle.pause();
},
init: function (data) {
var log = data.split('\n');
if (data.substr(0, 6) === '|init|') log.shift();
if (log.length && log[0].substr(0, 7) === '|title|') {
this.title = log[0].substr(7);
log.shift();
app.roomTitleChanged(this);
}
if (this.battle.activityQueue.length) return;
this.battle.activityQueue = log;
this.battle.fastForwardTo(-1);
if (this.battle.ended) this.battleEnded = true;
this.updateLayout();
this.updateControls();
},
add: function (data) {
if (!data) return;
if (data.substr(0, 6) === '|init|') {
return this.init(data);
}
if (data.substr(0, 9) === '|request|') {
var choiceData = {offset: 0};
var requestData = null;
data = data.slice(9);
if (!isNaN(data.charAt(0)) && data.charAt(1) === '|') {
var nlIndex = data.indexOf('\n');
if (nlIndex >= 0) {
choiceData.offset = +data.charAt(0);
try {
$.extend(choiceData, $.parseJSON(data.slice(2, nlIndex)));
} catch (err) {}
data = data.slice(nlIndex + 1);
}
}
try {
requestData = $.parseJSON(data);
} catch (err) {}
return this.receiveRequest(requestData, choiceData);
}
var log = data.split('\n');
for (var i = 0; i < log.length; i++) {
var logLine = log[i];
if (logLine === '|') {
this.callbackWaiting = false;
this.controlsShown = false;
this.$controls.html('');
}
if (logLine.substr(0, 10) === '|callback|') {
// TODO: Maybe a more sophisticated UI for this.
// In singles, this isn't really necessary because some elements of the UI will be
// immediately disabled. However, in doubles/triples it might not be obvious why
// the player is being asked to make a new decision without the following messages.
var args = logLine.substr(10).split('|');
var pokemon = isNaN(Number(args[1])) ? this.battle.getPokemon(args[1]) : this.battle.mySide.active[args[1]];
var requestData = this.request.active[pokemon ? pokemon.slot : 0];
delete this.choice;
switch (args[0]) {
case 'trapped':
requestData.trapped = true;
var pokeName = pokemon.side.n === 0 ? Tools.escapeHTML(pokemon.name) : "The opposing " + (this.battle.ignoreOpponent || this.battle.ignoreNicks ? pokemon.species : Tools.escapeHTML(pokemon.name));
this.battle.activityQueue.push('|message|' + pokeName + ' is trapped and cannot switch!');
break;
case 'cant':
for (var i = 0; i < requestData.moves.length; i++) {
if (requestData.moves[i].id === args[3]) {
requestData.moves[i].disabled = true;
}
}
args.splice(1, 1, pokemon.getIdent());
this.battle.activityQueue.push('|' + args.join('|'));
break;
}
} else if (logLine.substr(0, 7) === '|title|') { // eslint-disable-line no-empty
} else if (logLine.substr(0, 5) === '|win|') {
this.battleEnded = true;
this.battle.activityQueue.push(logLine);
} else if (logLine.substr(0, 6) === '|chat|' || logLine.substr(0, 3) === '|c|' || logLine.substr(0, 9) === '|chatmsg|' || logLine.substr(0, 10) === '|inactive|') {
this.battle.instantAdd(logLine);
} else {
this.battle.activityQueue.push(logLine);
}
}
this.battle.add('', Tools.prefs('noanim'));
this.updateControls();
},
toggleMessages: function (user) {
var $messages = $('.chatmessage-' + user + '.revealed');
var $button = $messages.find('button');
if (!$messages.is(':hidden')) {
$messages.hide();
$button.html('<small>(' + ($messages.length) + ' line' + ($messages.length > 1 ? 's' : '') + 'from ' + user + ')</small>');
$button.parent().show();
} else {
$button.html('<small>(Hide ' + ($messages.length) + ' line' + ($messages.length > 1 ? 's' : '') + ' from ' + user + ')</small>');
$button.parent().removeClass('revealed');
$messages.show();
}
},
/*********************************************************
* Battle stuff
*********************************************************/
updateControls: function (force) {
if (this.$join) {
this.$join.remove();
this.$join = null;
}
var controlsShown = this.controlsShown;
this.controlsShown = false;
if (this.battle.playbackState === 5) {
// battle is seeking
this.$controls.html('');
return;
} else if (this.battle.playbackState === 2 || this.battle.playbackState === 3) {
// battle is playing or paused
if (!this.side) {
// spectator
this.$controls.html('<p><button class="button" name="instantReplay"><i class="fa fa-undo"></i><br />First turn</button> <button class="button" name="rewindTurn"><i class="fa fa-step-backward"></i><br />Last turn</button><button class="button" name="skipTurn"><i class="fa fa-step-forward"></i><br />Skip turn</button> <button class="button" name="goToEnd"><i class="fa fa-fast-forward"></i><br />Skip to end</button></p><p><button name="switchSides"><i class="fa fa-random"></i> Switch sides</button></p>');
} else if (this.battleEnded) {
this.$controls.html('<p><button class="button" name="instantReplay"><i class="fa fa-undo"></i><br />First turn</button> <button class="button" name="rewindTurn"><i class="fa fa-step-backward"></i><br />Last turn</button><button class="button" name="skipTurn"><i class="fa fa-step-forward"></i><br />Skip turn</button> <button class="button" name="goToEnd"><i class="fa fa-fast-forward"></i><br />Skip to end</button></p>');
} else {
// is a player
this.$controls.html('<p>' + this.getTimerHTML() + '<button class="button" name="skipTurn"><i class="fa fa-step-forward"></i><br />Skip turn</button> <button class="button" name="goToEnd"><i class="fa fa-fast-forward"></i><br />Skip to end</button></p>');
}
return;
}
if (this.battle.ended) {
var replayDownloadButton = '<span style="float:right;"><a href="//replay.pokemonshowdown.com/" class="button replayDownloadButton" style="padding:2px 6px"><i class="fa fa-download"></i> Download replay</a><br /><br /><button name="saveReplay"><i class="fa fa-upload"></i> Upload and share replay</button></span>';
// battle has ended
if (this.side) {
// was a player
this.closeNotification('choice');
this.$controls.html('<div class="controls"><p>' + replayDownloadButton + '<button class="button" name="instantReplay"><i class="fa fa-undo"></i><br />Instant replay</button></p><p><button class="button" name="closeAndMainMenu"><strong>Main menu</strong><br /><small>(closes this battle)</small></button> <button class="button" name="closeAndRematch"><strong>Rematch</strong><br /><small>(closes this battle)</small></button></p></div>');
} else {
this.$controls.html('<div class="controls"><p>' + replayDownloadButton + '<button class="button" name="instantReplay"><i class="fa fa-undo"></i><br />Instant replay</button></p><p><button name="switchSides"><i class="fa fa-random"></i> Switch sides</button></p></div>');
}
} else if (this.side) {
// player
this.controlsShown = true;
if (force || !controlsShown || this.choice === undefined || this.choice && this.choice.waiting) {
// don't update controls (and, therefore, side) if `this.choice === null`: causes damage miscalculations
this.updateControlsForPlayer();
} else {
this.updateTimer();
}
} else if (!this.battle.mySide.initialized || !this.battle.yourSide.initialized) {
// empty battle
this.$controls.html('<p><em>Waiting for players...</em></p>');
this.$join = $('<div class="playbutton"><button name="joinBattle">Join Battle</button></div>');
this.$battle.append(this.$join);
} else {
// full battle
this.$controls.html('<p><button class="button" name="instantReplay"><i class="fa fa-undo"></i><br />First turn</button> <button class="button" name="rewindTurn"><i class="fa fa-step-backward"></i><br />Last turn</button><button class="button disabled" disabled><i class="fa fa-step-forward"></i><br />Skip turn</button> <button class="button disabled" disabled><i class="fa fa-fast-forward"></i><br />Skip to end</button></p><p><button name="switchSides"><i class="fa fa-random"></i> Switch sides</button></p><p><em>Waiting for players...</em></p>');
}
// This intentionally doesn't happen if the battle is still playing,
// since those early-return.
app.topbar.updateTabbar();
},
controlsShown: false,
updateControlsForPlayer: function () {
var battle = this.battle;
this.callbackWaiting = true;
var active = this.battle.mySide.active[0];
if (!active) active = {};
var act = '';
var switchables = [];
if (this.request) {
// TODO: investigate when to do this
this.updateSide(this.request.side);
act = this.request.requestType;
if (this.request.side) {
switchables = this.myPokemon;
}
if (!this.finalDecision) this.finalDecision = !!this.request.noCancel;
}
var choiceOffset = this.choiceData.offset && this.choiceData.offset <= 3 ? this.choiceData.offset : 0;
var preDecided = _.map(getString(this.choiceData.done).split(''), Number);
var preSwitchFlags = _.map(getString(this.choiceData.enter).split(''), Number);
var preSwitchOutFlags = _.map(getString(this.choiceData.leave).split(''), Number);
var preTeamOrder = _.map(getString(this.choiceData.team).split(''), Number);
if (this.choice && this.choice.waiting) {
act = '';
}
var type = this.choice ? this.choice.type : '';
// The choice object:
// !this.choice = nothing has been chosen
// this.choice.choices = array of choice strings
// this.choice.switchFlags = dict of pokemon indexes that have a switch pending
switch (act) {
case 'move':
if (!this.choice) {
this.choice = {
preDecided: preDecided,
choices: new Array(choiceOffset),
switchFlags: {},
switchOutFlags: {}
};
for (var i = 0; i < preSwitchFlags.length; i++) this.choice.switchFlags[preSwitchFlags[i]] = 1;
for (var i = 0; i < preSwitchOutFlags.length; i++) this.choice.switchOutFlags[preSwitchOutFlags[i]] = 1;
}
if (choiceOffset < this.battle.mySide.active.length) {
this.updateMoveControls(type);
} else {
this.updateWaitControls();
}
break;
case 'switch':
if (!this.choice) {
this.choice = {
preDecided: preDecided,
choices: new Array(choiceOffset),
switchFlags: {},
switchOutFlags: {},
freedomDegrees: 0, // Fancy term for the amount of Pokémon that won't be able to switch out.
canSwitch: 0
};
for (var i = 0; i < preSwitchFlags.length; i++) this.choice.switchFlags[preSwitchFlags[i]] = 1;
for (var i = 0; i < preSwitchOutFlags.length; i++) this.choice.switchOutFlags[preSwitchOutFlags[i]] = 1;
if (this.request.forceSwitch !== true) {
var faintedLength = _.filter(this.request.forceSwitch.slice(choiceOffset), function (fainted) {return fainted;}).length;
var freedomDegrees = faintedLength - _.filter(switchables.slice(this.battle.mySide.active.length), function (mon) {return !mon.zerohp;}).length;
this.choice.freedomDegrees = Math.max(freedomDegrees, 0);
this.choice.canSwitch = faintedLength - this.choice.freedomDegrees;
}
}
if (choiceOffset < this.battle.mySide.active.length) {
this.updateSwitchControls(type);
} else {
this.updateWaitControls();
}
break;
case 'team':
if (this.battle.mySide.pokemon && !this.battle.mySide.pokemon.length) {
// too early, we can't determine `this.choice.count` yet
// TODO: send teamPreviewCount in the request object
return;
}
if (!this.choice) {
this.choice = {
preDecided: preDecided,
choices: null,
preTeamOrder: preTeamOrder,
teamPreview: [1, 2, 3, 4, 5, 6].slice(0, switchables.length),
done: 0,
count: 1
};
if (this.battle.gameType === 'doubles') {
this.choice.count = 2;
}
if (this.battle.gameType === 'triples' || this.battle.gameType === 'rotation') {
this.choice.count = 3;
}
// Request full team order if one of our Pokémon has Illusion
for (var i = 0; i < switchables.length && i < 6; i++) {
if (toId(switchables[i].baseAbility) === 'illusion') {
this.choice.count = 6;
}
}
if (this.battle.teamPreviewCount) {
var requestCount = parseInt(this.battle.teamPreviewCount, 10);
if (requestCount > 0 && requestCount <= switchables.length) {
this.choice.count = requestCount;
}
}
this.choice.choices = new Array(this.choice.count);
}
if (choiceOffset < this.choice.count) {
this.updateTeamControls(type);
} else {
this.updateWaitControls(type);
}
break;
default:
this.updateWaitControls();
break;
}
},
timerInterval: 0,
getTimerHTML: function (nextTick) {
var time = 'Timer';
var timerTicking = (this.battle.kickingInactive && this.request && !this.request.wait && !(this.choice && this.choice.waiting)) ? ' timerbutton-on' : '';
if (!nextTick) {
var self = this;
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = 0;
}
if (timerTicking) this.timerInterval = setInterval(function () {
var $timerButton = self.$('.timerbutton');
if ($timerButton.length) {
$timerButton.replaceWith(self.getTimerHTML(true));
} else {
clearInterval(self.timerInterval);
self.timerInterval = 0;
}
}, 1000);
} else if (this.battle.kickingInactive > 1) {
this.battle.kickingInactive--;
}
if (this.battle.kickingInactive) {
var secondsLeft = this.battle.kickingInactive;
if (secondsLeft !== true) {
if (secondsLeft <= 10 && timerTicking) {
timerTicking = ' timerbutton-critical';
}
var minutesLeft = Math.floor(secondsLeft / 60);
secondsLeft -= minutesLeft * 60;
time = '' + minutesLeft + ':' + (secondsLeft < 10 ? '0' : '') + secondsLeft;
} else {
time = '-:--';
}
}
return '<button name="openTimer" class="button timerbutton' + timerTicking + '"><i class="fa fa-hourglass-start"></i> ' + time + '</button>';
},
updateZMove: function () {
var zChecked = this.$('input[name=zmove]')[0].checked;
if (zChecked) {
this.$('.movebuttons-noz').hide();
this.$('.movebuttons-z').show();
} else {
this.$('.movebuttons-noz').show();
this.$('.movebuttons-z').hide();
}
},
updateTimer: function () {
this.$('.timerbutton').replaceWith(this.getTimerHTML());
},
openTimer: function () {
app.addPopup(TimerPopup, {room: this});
},
updateMoveControls: function (type) {
var preDecided = this.choice.preDecided;
var switchables = this.request && this.request.side ? this.myPokemon : [];
if (type !== 'movetarget') {
while (preDecided.indexOf(this.choice.choices.length) >= 0 || switchables[this.choice.choices.length] && switchables[this.choice.choices.length].fainted && this.choice.choices.length + 1 < this.battle.mySide.active.length) {
this.choice.choices.push(preDecided.indexOf(this.choice.choices.length) >= 0 ? 'skip' : 'pass');
}
}
var moveTarget = this.choice ? this.choice.moveTarget : '';
var pos = this.choice.choices.length - (type === 'movetarget' ? 1 : 0);
var hpRatio = switchables[pos].hp / switchables[pos].maxhp;
var curActive = this.request && this.request.active && this.request.active[pos];
if (!curActive) return;
var trapped = curActive.trapped;
var canMegaEvo = curActive.canMegaEvo || switchables[pos].canMegaEvo;
var canZMove = curActive.canZMove || switchables[pos].canZMove;
if (canZMove && typeof canZMove[0] === 'string') {
canZMove = _.map(canZMove, function (move) {
return {move: move, target: Tools.getMove(move).target};
});
}
this.finalDecisionMove = curActive.maybeDisabled || false;
this.finalDecisionSwitch = curActive.maybeTrapped || false;
for (var i = pos + 1; i < this.battle.mySide.active.length; ++i) {
var p = this.battle.mySide.active[i];
if (p && !p.fainted) {
this.finalDecisionMove = this.finalDecisionSwitch = false;
break;
}
}
var requestTitle = '';
if (type === 'move2' || type === 'movetarget') {
requestTitle += '<button name="clearChoice">Back</button> ';
}
// Target selector
if (type === 'movetarget') {
requestTitle += 'At who? ';
var targetMenus = ['', ''];
var myActive = this.battle.mySide.active;
var yourActive = this.battle.yourSide.active;
var yourSlot = yourActive.length - 1 - pos;
for (var i = yourActive.length - 1; i >= 0; i--) {
var pokemon = yourActive[i];
var disabled = false;
if (moveTarget === 'adjacentAlly' || moveTarget === 'adjacentAllyOrSelf') {
disabled = true;
} else if (moveTarget === 'normal' || moveTarget === 'adjacentFoe') {
if (Math.abs(yourSlot - i) > 1) disabled = true;
}
if (disabled) {
targetMenus[0] += '<button disabled="disabled"></button> ';
} else if (!pokemon || pokemon.zerohp) {
targetMenus[0] += '<button class="disabled" name="chooseMoveTarget" value="' + (i + 1) + '"><span class="picon" style="' + Tools.getPokemonIcon('missingno') + '"></span></button> ';
} else {
targetMenus[0] += '<button name="chooseMoveTarget" value="' + (i + 1) + '"' + this.tooltips.tooltipAttrs("your" + i, 'pokemon', true) + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') + '</button> ';
}
}
for (var i = 0; i < myActive.length; i++) {
var pokemon = myActive[i];
var disabled = false;
if (moveTarget === 'adjacentFoe') {
disabled = true;
} else if (moveTarget === 'normal' || moveTarget === 'adjacentAlly' || moveTarget === 'adjacentAllyOrSelf') {
if (Math.abs(pos - i) > 1) disabled = true;
}
if (moveTarget !== 'adjacentAllyOrSelf' && pos == i) disabled = true;
if (disabled) {
targetMenus[1] += '<button disabled="disabled" style="visibility:hidden"></button> ';
} else if (!pokemon || pokemon.zerohp) {
targetMenus[1] += '<button class="disabled" name="chooseMoveTarget" value="' + (-(i + 1)) + '"><span class="picon" style="' + Tools.getPokemonIcon('missingno') + '"></span></button> ';
} else {
targetMenus[1] += '<button name="chooseMoveTarget" value="' + (-(i + 1)) + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') + '</button> ';
}
}
this.$controls.html(
'<div class="controls">' +
'<div class="whatdo">' + requestTitle + this.getTimerHTML() + '</div>' +
'<div class="switchmenu" style="display:block">' + targetMenus[0] + '<div style="clear:both"></div> </div>' +
'<div class="switchmenu" style="display:block">' + targetMenus[1] + '</div>' +
'</div>'
);
} else {
// Move chooser
var hpBar = '<small class="' + (hpRatio < 0.2 ? 'critical' : hpRatio < 0.5 ? 'weak' : 'healthy') + '">HP ' + switchables[pos].hp + '/' + switchables[pos].maxhp + '</small>';
requestTitle += ' What will <strong>' + Tools.escapeHTML(switchables[pos].name) + '</strong> do? ' + hpBar;
var hasMoves = false;
var moveMenu = '';
var movebuttons = '';
for (var i = 0; i < curActive.moves.length; i++) {
var moveData = curActive.moves[i];
var move = Tools.getMove(moveData.move);
var name = move.name;
var pp = moveData.pp + '/' + moveData.maxpp;
if (!moveData.maxpp) pp = '–';
if (move.id === 'Struggle' || move.id === 'Recharge') pp = '–';
if (move.id === 'Recharge') move.type = '–';
if (name.substr(0, 12) === 'Hidden Power') name = 'Hidden Power';
var moveType = this.tooltips.getMoveType(move, this.battle.mySide.active[pos] || this.myPokemon[pos]);
if (moveData.disabled) {
movebuttons += '<button disabled="disabled"' + this.tooltips.tooltipAttrs(moveData.move, 'move') + '>';
} else {
movebuttons += '<button class="type-' + moveType + '" name="chooseMove" value="' + (i + 1) + '" data-move="' + Tools.escapeHTML(moveData.move) + '" data-target="' + Tools.escapeHTML(moveData.target) + '"' + this.tooltips.tooltipAttrs(moveData.move, 'move') + '>';
hasMoves = true;
}
movebuttons += name + '<br /><small class="type">' + (moveType ? Tools.getType(moveType).name : "Unknown") + '</small> <small class="pp">' + pp + '</small> </button> ';
}
if (!hasMoves) {
moveMenu += '<button class="movebutton" name="chooseMove" value="0" data-move="Struggle" data-target="randomNormal">Struggle<br /><small class="type">Normal</small> <small class="pp">–</small> </button> ';
} else {
if (canZMove) {
movebuttons = '<div class="movebuttons-noz">' + movebuttons + '</div><div class="movebuttons-z" style="display:none">';
for (var i = 0; i < curActive.moves.length; i++) {
var moveData = curActive.moves[i];
var move = Tools.getMove(moveData.move);
var moveType = this.tooltips.getMoveType(move, this.battle.mySide.active[pos] || this.myPokemon[pos]);
if (canZMove[i]) {
movebuttons += '<button class="type-' + moveType + '" name="chooseMove" value="' + (i + 1) + '" data-move="' + Tools.escapeHTML(canZMove[i].move) + '" data-target="' + Tools.escapeHTML(canZMove[i].target) + '"' + this.tooltips.tooltipAttrs(canZMove[i].move, 'move') + '>';
movebuttons += canZMove[i].move + '<br /><small class="type">' + (moveType ? Tools.getType(moveType).name : "Unknown") + '</small> <small class="pp">1/1</small> </button> ';
} else {
movebuttons += '<button disabled="disabled"> </button>';
}
}
movebuttons += '</div>';
}
moveMenu += movebuttons;
}
if (canMegaEvo) {
moveMenu += '<br /><label class="megaevo"><input type="checkbox" name="megaevo" /> Mega Evolution</label>';
} else if (canZMove) {
moveMenu += '<br /><label class="megaevo"><input type="checkbox" name="zmove" /> Use Z Move</label>';
}
if (this.finalDecisionMove) {
moveMenu += '<em style="display:block;clear:both">You <strong>might</strong> have some moves disabled, so you won\'t be able to cancel an attack!</em><br/>';
}
moveMenu += '<div style="clear:left"></div>';
var moveControls = (
'<div class="movecontrols">' +
'<div class="moveselect"><button name="selectMove">Attack</button></div>' +
'<div class="movemenu">' + moveMenu + '</div>' +
'</div>'
);
var shiftControls = '';
if (this.battle.gameType === 'triples' && pos !== 1) {
shiftControls += '<div class="shiftselect"><button name="chooseShift">Shift</button></div>';
}
var switchMenu = '';
if (trapped) {
switchMenu += '<em>You are trapped and cannot switch!</em>';
} else {
for (var i = 0; i < switchables.length; i++) {
var pokemon = switchables[i];
pokemon.name = pokemon.ident.substr(4);
if (pokemon.zerohp || i < this.battle.mySide.active.length || this.choice.switchFlags[i]) {
switchMenu += '<button class="disabled" name="chooseDisabled" value="' + Tools.escapeHTML(pokemon.name) + (pokemon.zerohp ? ',fainted' : i < this.battle.mySide.active.length ? ',active' : '') + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + (!pokemon.zerohp ? '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') : '') + '</button> ';
} else {
switchMenu += '<button name="chooseSwitch" value="' + i + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') + '</button> ';
}
}
if (this.finalDecisionSwitch && this.battle.gen > 2) {
switchMenu += '<em style="display:block;clear:both">You <strong>might</strong> be trapped, so you won\'t be able to cancel a switch!</em><br/>';
}
}
var switchControls = (
'<div class="switchcontrols">' +
'<div class="switchselect"><button name="selectSwitch">Switch</button></div>' +
'<div class="switchmenu">' + switchMenu + '</div>' +
'</div>'
);
this.$controls.html(
'<div class="controls">' +
'<div class="whatdo">' + requestTitle + this.getTimerHTML() + '</div>' +
moveControls + shiftControls + switchControls +
'</div>'
);
}
},
updateSwitchControls: function (type) {
var preDecided = this.choice.preDecided;
var pos = this.choice.choices.length;
if (type !== 'switchposition' && this.request.forceSwitch !== true && !this.choice.freedomDegrees) {
while (preDecided.indexOf(pos) >= 0 || !this.request.forceSwitch[pos] && pos < 6) {
pos = this.choice.choices.push(preDecided.indexOf(pos) >= 0 ? 'skip' : 'pass');
}
}
var switchables = this.request && this.request.side ? this.myPokemon : [];
var myActive = this.battle.mySide.active;
var requestTitle = '';
if (type === 'switch2' || type === 'switchposition') {
requestTitle += '<button name="clearChoice">Back</button> ';
}
// Place selector
if (type === 'switchposition') {
// TODO? hpbar
requestTitle += "Which Pokémon will it switch in for?";
var controls = '<div class="switchmenu" style="display:block">';
for (var i = 0; i < myActive.length; i++) {
var pokemon = this.myPokemon[i];
if (pokemon && !pokemon.zerohp || this.choice.switchOutFlags[i]) {
controls += '<button disabled' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + (!pokemon.zerohp ? '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') : '') + '</button> ';
} else if (!pokemon) {
controls += '<button disabled></button> ';
} else {
controls += '<button name="chooseSwitchTarget" value="' + i + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') + '</button> ';
}
}
controls += '</div>';
this.$controls.html(
'<div class="controls">' +
'<div class="whatdo">' + requestTitle + this.getTimerHTML() + '</div>' +
controls +
'</div>'
);
} else {
if (this.choice.freedomDegrees >= 1) {
requestTitle += "Choose a Pokémon to send to battle!";
} else {
requestTitle += "Switch <strong>" + Tools.escapeHTML(switchables[pos].name) + "</strong> to:";
}
var switchMenu = '';
for (var i = 0; i < switchables.length; i++) {
var pokemon = switchables[i];
if (pokemon.zerohp || i < this.battle.mySide.active.length || this.choice.switchFlags[i]) {
switchMenu += '<button class="disabled" name="chooseDisabled" value="' + Tools.escapeHTML(pokemon.name) + (pokemon.zerohp ? ',fainted' : i < this.battle.mySide.active.length ? ',active' : '') + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '>';
} else {
switchMenu += '<button name="chooseSwitch" value="' + i + '"' + this.tooltips.tooltipAttrs(i, 'sidepokemon') + '>';
}
switchMenu += '<span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + (!pokemon.zerohp ? '<span class="hpbar' + pokemon.getHPColorClass() + '"><span style="width:' + (Math.round(pokemon.hp * 92 / pokemon.maxhp) || 1) + 'px"></span></span>' + (pokemon.status ? '<span class="status ' + pokemon.status + '"></span>' : '') : '') + '</button> ';
}
var controls = (
'<div class="switchcontrols">' +
'<div class="switchselect"><button name="selectSwitch">Switch</button></div>' +
'<div class="switchmenu">' + switchMenu + '</div>' +
'</div>'
);
this.$controls.html(
'<div class="controls">' +
'<div class="whatdo">' + requestTitle + this.getTimerHTML() + '</div>' +
controls +
'</div>'
);
this.selectSwitch();
}
},
updateTeamControls: function (type) {
var switchables = this.request && this.request.side ? this.myPokemon : [];
var maxIndex = Math.min(switchables.length, 6);
var requestTitle = "";
if (this.choice.done) {
requestTitle = '<button name="clearChoice">Back</button> ' + "What about the rest of your team?";
} else {
requestTitle = "How will you start the battle?";
}
var switchMenu = '';
for (var i = 0; i < maxIndex; i++) {
var oIndex = this.choice.teamPreview[i] - 1;
var pokemon = switchables[oIndex];
if (i < this.choice.done) {
switchMenu += '<button disabled="disabled"' + this.tooltips.tooltipAttrs(oIndex, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '</button> ';
} else {
switchMenu += '<button name="chooseTeamPreview" value="' + i + '"' + this.tooltips.tooltipAttrs(oIndex, 'sidepokemon') + '><span class="picon" style="' + Tools.getPokemonIcon(pokemon) + '"></span>' + Tools.escapeHTML(pokemon.name) + '</button> ';
}
}
var controls = (
'<div class="switchcontrols">' +
'<div class="switchselect"><button name="selectSwitch">' + (this.choice.done ? '' + "Choose a Pokémon for slot " + (this.choice.done + 1) : "Choose Lead") + '</button></div>' +
'<div class="switchmenu">' + switchMenu + '</div>' +
'</div>'
);
this.$controls.html(
'<div class="controls">' +
'<div class="whatdo">' + requestTitle + this.getTimerHTML() + '</div>' +
controls +
'</div>'
);
this.selectSwitch();
},
updateWaitControls: function () {
var buf = '<div class="controls">';
buf += this.getPlayerChoicesHTML();
if (!this.battle.mySide.initialized || !this.battle.yourSide.initialized || !this.request) {
if (this.battle.kickingInactive) {
buf += '<p><button class="button" name="setTimer" value="off">Stop timer</button> <small>← Your opponent has disconnected. This will give them more time to reconnect.</small></p>';
} else {
buf += '<p><button class="button" name="setTimer" value="on">Claim victory</button> <small>← Your opponent has disconnected. Click this if they don\'t reconnect.</small></p>';
}
}
this.$controls.html(buf + '</div>');
},
getPlayerChoicesHTML: function () {
var buf = '<p>' + this.getTimerHTML();
if (!this.choice || !this.choice.waiting) {
return buf + '<em>Waiting for opponent...</em></p>';
}
buf += '<small>';
if (this.choice.teamPreview) {
var myPokemon = this.battle.mySide.pokemon;
var leads = [];
for (var i = 0; i < this.choice.count; i++) {
leads.push(myPokemon[this.choice.teamPreview[i] - 1].species);
}
buf += leads.join(', ') + ' will be sent out first.<br />';
} else if (this.choice.choices) {
var myActive = this.battle.mySide.active;
for (var i = 0; i < this.choice.choices.length; i++) {
var parts = this.choice.choices[i].split(' ');
switch (parts[0]) {
case 'move':
var move = this.request.active[i].moves[parts[1] - 1].move;
var target = '';
buf += myActive[i].species + ' will ';
if (parts.length > 2) {
var targetPos = parts[2];
if (targetPos === 'mega') {
buf += 'mega evolve, then ';
targetPos = parts[3];
}
if (targetPos === 'zmove') {
move = this.request.active[i].canZMove[parts[1] - 1].move;
targetPos = parts[3];
}
if (targetPos) {
var targetActive = this.battle.yourSide.active;
// Targeting your own side in doubles / triples
if (targetPos < 0) {
targetActive = myActive;
targetPos = -targetPos;
target += 'your ';
}
target += targetActive[targetPos - 1].species;
}
}
buf += 'use ' + Tools.getMove(move).name + (target ? ' against ' + target : '') + '.<br />';
break;
case 'switch':
buf += '' + this.myPokemon[parts[1] - 1].species + ' will switch in';
if (myActive[i]) {
buf += ', replacing ' + myActive[i].species;
}
buf += '.<br />';
break;
case 'shift':
buf += myActive[i].species + ' will shift position.<br />';
break;
}
}
}
buf += '</small></p>';
if (!this.finalDecision) {
buf += '<p><small><em>Waiting for opponent...</em></small> <button class="button" name="undoChoice">Cancel</button></p>';
}
return buf;
},
// Appends the rqid to the message so that the server can
// verify that the decision is sent in response to the correct request.
sendDecision: function (message) {
if (!$.isArray(message)) return this.send('/' + message + '|' + this.request.rqid);
var buf = '/choose ';
for (var i = 0; i < message.length; i++) {
if (message[i]) buf += message[i] + ',';
}
this.send(buf.substr(0, buf.length - 1) + '|' + this.request.rqid);
},
request: null,
receiveRequest: function (request, choiceData) {
if (!request) {
this.side = '';
return;
}
request.requestType = 'move';
var notifyObject = null;
if (request.forceSwitch) {
request.requestType = 'switch';
} else if (request.teamPreview) {
request.requestType = 'team';
} else if (request.wait) {
request.requestType = 'wait';
}
this.choice = (choiceData && choiceData.offset ? {waiting: true} : null);
this.choiceData = choiceData;
this.finalDecision = this.finalDecisionMove = this.finalDecisionSwitch = false;
this.request = request;
if (request.side) {
this.updateSideLocation(request.side, true);
}
this.notifyRequest();
this.updateControls(true);
},
notifyRequest: function () {
var oName = this.battle.yourSide.name;
if (oName) oName = " against " + oName;
switch (this.request.requestType) {
case 'move':
this.notify("Your move!", "Move in your battle" + oName, 'choice');
break;
case 'switch':
this.notify("Your switch!", "Switch in your battle" + oName, 'choice');
break;
case 'team':
this.notify("Team preview!", "Choose your team order in your battle" + oName, 'choice');
break;
}
},
updateSideLocation: function (sideData, midBattle) {
if (!sideData.id) return;
this.side = sideData.id;
if (this.battle.sidesSwitched !== !!(this.side === 'p2')) {
this.battle.switchSides(!midBattle);
this.$chat = this.$chatFrame.find('.inner');
}
},
updateSide: function (sideData) {
this.myPokemon = sideData.pokemon;
for (var i = 0; i < sideData.pokemon.length; i++) {
var pokemonData = sideData.pokemon[i];
this.battle.parseDetails(pokemonData.ident.substr(4), pokemonData.ident, pokemonData.details, pokemonData);
this.battle.parseHealth(pokemonData.condition, pokemonData);
pokemonData.hpDisplay = Pokemon.prototype.hpDisplay;
pokemonData.getPixelRange = Pokemon.prototype.getPixelRange;
pokemonData.getFormattedRange = Pokemon.prototype.getFormattedRange;
pokemonData.getHPColorClass = Pokemon.prototype.getHPColorClass;
pokemonData.getHPColor = Pokemon.prototype.getHPColor;
pokemonData.getFullName = Pokemon.prototype.getFullName;
}
},
// buttons
joinBattle: function () {
this.send('/joinbattle');
},
setTimer: function (setting) {
this.send('/timer ' + setting);
},
forfeit: function () {
this.send('/forfeit');
},
saveReplay: function () {
this.send('/savereplay');
},
openBattleOptions: function () {
app.addPopup(BattleOptionsPopup, {battle: this.battle});
},
clickReplayDownloadButton: function (e) {
var filename = (this.battle.tier || 'Battle').replace(/[^A-Za-z0-9]/g, '');
// ladies and gentlemen, JavaScript dates
var date = new Date();
filename += '-' + date.getFullYear();
filename += (date.getMonth() >= 9 ? '-' : '-0') + (date.getMonth() + 1);
filename += (date.getDate() >= 10 ? '-' : '-0') + date.getDate();
filename += '-' + toId(this.battle.p1.name);
filename += '-' + toId(this.battle.p2.name);
e.currentTarget.href = Tools.createReplayFileHref(this);
e.currentTarget.download = filename + '.html';
e.stopPropagation();
},
switchSides: function () {
this.battle.switchSides();
},
instantReplay: function () {
this.tooltips.hideTooltip();
this.request = null;
this.battle.reset();
this.battle.play();
},
skipTurn: function () {
this.battle.skipTurn();
},
rewindTurn: function () {
if (this.battle.turn) {
this.battle.fastForwardTo(this.battle.turn - 1);
this.battle.play();
}
},
goToEnd: function () {
this.battle.fastForwardTo(-1);
},
register: function (userid) {
var registered = app.user.get('registered');
if (registered && registered.userid !== userid) registered = false;
if (!registered && userid === app.user.get('userid')) {
app.addPopup(RegisterPopup);
}
},
closeAndMainMenu: function () {
this.close();
app.focusRoom('');
},
closeAndRematch: function () {
app.rooms[''].requestNotifications();
app.rooms[''].challenge(this.battle.yourSide.name, this.battle.tier);
this.close();
app.focusRoom('');
},
// choice buttons