forked from andreleblanc-wf/bcodeviewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.js
More file actions
1596 lines (1363 loc) · 55.9 KB
/
player.js
File metadata and controls
1596 lines (1363 loc) · 55.9 KB
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 MINE_NEUTRAL = 0x6c6c6c;
var MINE_A = 0xFF6666;
var MINE_B = 0x6666FF;
var FRAME_DURATION = 1000;
// Temporary variables to avoid
// constant allocation;
var bk, i, sprite, bot, sel, delta;
var mine, gx, gy, px, py;
var teamPowerMax, teamPower, teamPowerInner, teamPowerPct;
var ax, ay, av, ak;
var deltaEvent, stateCallback;
var statsCounts, statsTeam, statsPanelHQ;
var researchMax;
var projectileX, projectileY;
var fogBotIdx;
var val, color, wins;
var pos;
var panel;
var parts;
var hbs;
var selectedBotHPPct;
var lines, attackingStr;
var src, dest;
var applyIter, undoIter;
var currentRound, maxRound;
var visionTmpMinY, visionTmpMaxY;
var visionMinY, visionMaxY, visionMinX, visionMaxX;
var visX, visY;
var hat;
/**
* Creates the BattleCode Game Viewer.
*
* @param {Object} container - an element to serve as the container for the player
* @constructor
*/
var Player = function (container, options) {
console.log('pixelratio', window.devicePixelRatio);
/**
* The container for the entire player
* @member {jQuery} container
*/
this.container = $(container);
this.container.empty();
/**
* The team (a or b) whose vision is displayed.
*
* @member {String} visionTeam
*/
this.visionTeam = null;
/**
* have the textures loaded yet?
* @member {boolean} assetsLoaded
*/
this.assetsLoaded = false;
/**
* a Game object to play.
* @member {Game} game
*/
this.game = null;
/**
* Is playback paused?
* @member {boolean} paused
*/
this.paused = true;
/**
* time in MS that each round should last
* @member {Number} frameDuration
* */
this.frameDuration = FRAME_DURATION;
/**
* a div within container to hold the canvas.
* @member {jQuery} canvasContainer
*/
this.canvasContainer = $("<div id='canvasContainer'></div>");
/**
* the top level rendering container.
* @member {PIXI.Container} stage;
*/
this.stage = new PIXI.Container();
/**
* the layer which mines are drawn on.
* @member {PIXI.Graphics} field
*/
this.field = new PIXI.Graphics();
/**
* the layer which all robots are drawn on.
* @member {PIXI.Container} botLayer
*/
this.botLayer = new PIXI.Container();
/**
* the layer which artillery fire, explosions,
* and shield/medbay 'auras' are drawn on
* @member {PIXI.Graphics} effectsLayer
*/
this.effectsLayer = new PIXI.Graphics();
/**
* the layer which health and action bars are drawn on
*
* @member {PIXI.Graphics} statusLayer
*/
this.statusLayer = new PIXI.Graphics();
/**
* the fog layer.
* @member {PIXI.Grapics} fogLayer;
*/
this.fogLayer = new PIXI.Graphics();
/**
* the PIXI renderer
* @member {*|WebGLRenderer|CanvasRenderer} renderer
*/
this.renderer = PIXI.autoDetectRenderer(
$(this.canvasContainer).width(),
$(this.canvasContainer).height(),
{antialias: false, transparent: true, autoResize: true, resolution: window.devicePixelRatio});
/**
* the PIXI InteractionManager
* @member {PIXI.interaction.InteractionManager} renderer
*/
this.interactionManager = new PIXI.interaction.InteractionManager(
this.renderer, {autoPreventDefault: true});
/**
* a div created by the player to contain detail panels
* for each team and the selected robot.
* @type {jQuery} statsPanel
*/
this.statsPanel = null;
this.stage.addChild(this.field);
this.stage.addChild(this.botLayer);
this.stage.addChild(this.statusLayer);
this.stage.addChild(this.effectsLayer);
this.stage.addChild(this.fogLayer);
this.canvasContainer.append(this.renderer.view);
$(window).on('resize', '', this.onResize.bind(this));
this.loadAssets();
};
/**
* Called when assets are fully loaded
*
* @param {PIXI.Loader} loader - the PIXI Asset loader
* @param {Object} resources - the loaded resources
*/
Player.prototype.onAssetsLoaded = function (loader, resources) {
// setup the hat textures
this.hatTextures = [];
for (var i=0; i<=2; i++) {
this.hatTextures.push(new PIXI.Texture(resources['hat-' + i].texture));
}
// initialize the exposion animation texture-array;
this.boomFrames = [];
var texture = resources.boom.texture;
var frameWidth = 60, frameHeight = 60;
for(var i = 0; i < texture.width-frameWidth; i+=frameWidth) {
this.boomFrames.push({texture: new PIXI.Texture(texture.baseTexture, new PIXI.Rectangle(i, 0, frameWidth, frameHeight)), time: 1});
}
var rev = [];
for(var i = 0; i < texture.width-frameWidth; i+=frameWidth) {
rev.push({texture: new PIXI.Texture(texture.baseTexture, new PIXI.Rectangle(i, 0, frameWidth, frameHeight)), time: 1});
}
rev.reverse();
this.boomFrames = this.boomFrames.concat(rev);
// initialize this.textures with all bot textures.
for (var t in {a: true, b: true}) {
for (var rt in {soldier: true, hq: true, artillery: true, medbay: true, shields: true, supplier: true, generator: true}) {
this.textures[t][rt] = new PIXI.Texture(resources[rt + '-' + t].texture);
}
}
this.assetsLoaded = true;
this.container.append(this.buildHeader());
this.container.append(this.canvasContainer);
requestAnimationFrame( this.animate.bind(this) );
};
/**
* Pre-loads all textures needed by the viewer and calls
* onAssetsLoaded when complete
*/
Player.prototype.loadAssets = function () {
PIXI.loader
.add("boom", "img/boom.png")
.add("hq-a", "img/hq-a.png")
.add("hq-b", "img/hq-b.png")
.add("soldier-a", "img/soldier-a.png")
.add("soldier-b", "img/soldier-b.png")
.add("supplier-a", "img/supplier-a.png")
.add("supplier-b", "img/supplier-b.png")
.add("generator-a", "img/generator-a.png")
.add("generator-b", "img/generator-b.png")
.add("artillery-a", "img/artillery-a.png")
.add("artillery-b", "img/artillery-b.png")
.add("medbay-a", "img/medbay-a.png")
.add("medbay-b", "img/medbay-b.png")
.add("shields-a", "img/shields-a.png")
.add("shields-b", "img/shields-b.png")
.add("hat-0", "img/hats/0.png")
.add("hat-1", "img/hats/1.png")
.add("hat-2", "img/hats/2.png")
.load(this.onAssetsLoaded.bind(this));
};
/**
* called when the window is resized.
*/
Player.prototype.onResize = function () {
console.log("Container resized!");
var newW = $(this.canvasContainer).width();
var newH = $(this.canvasContainer).height() - 1;
if (this.renderer && this.renderer.view) {
console.log("Resizing renderer to " + newW + "x" + newH);
$(this.renderer.view).width(newW + "px");
$(this.renderer.view).height(newH + "px");
this.renderer.resize(newW, newH);
this.setDimensions();
}
};
/**
* called when a new match is selected from the dropdown
*
* @param {Object} ev - change event
*/
Player.prototype.onMatchSelectorChange = function (ev) {
var val = $(ev.currentTarget).val();
console.log("Match: val");
if (!this.paused) {
this.togglePlayback();
}
this.initMatch(this.game.matches[val]);
};
/**
* called when the 'Go to first round' button is clicked
*
* @param {Object} ev - click event
*/
Player.prototype.onGotoStartButton = function (ev) {
this.transitionToRound(0);
};
/**
* called when the 'Go to last round' button is clicked
*
* @param {Object} ev - click event
*/
Player.prototype.onGotoEndButton = function (ev) {
this.transitionToRound(this.match.states.length-1);
};
/**
* called when the 'Go to next round' button is clicked
*
* @param {Object} ev - click event
*/
Player.prototype.onGoForwardButton = function (ev) {
this.transitionToRound(Math.min(this.round + 1, this.match.states.length-1));
};
/**
* called when the 'Go to previous round' button is clicked
*
* @param {Object} ev - click event
*/
Player.prototype.onGoBackButton = function (ev) {
this.transitionToRound(Math.max(this.round - 1, 0));
};
/**
* called when the 'fullscreen' button is clicked
*
* @param {Object} ev - click event
*/
Player.prototype.onFullscreenButton = function (e) {
if (Util.isFullscreen()) {
Util.cancelFullscreen();
} else {
Util.makeFullscreen($('body'));
}
};
/**
* called when the round slider is moved.
*
* @param {Object} e - change event
*/
Player.prototype.onTimeSliderChange = function (e) {
this.transitionToRound($(e.currentTarget).val());
};
/**
* called when the pseed slider is moved.
*
* @param {Object} e - change event
*/
Player.prototype.onSpeedSliderChange = function (e) {
var pct = this.speedSlider.val();
this.frameDuration = (0.106122 * pct * pct) - (20.7184*pct) + 1020.61;
this.speedIndicator.text(this.speedSlider.val() + "%");
for (i=0; i<this.boomFrames.length; i++) {
this.boomFrames[i].time = this.frameDuration*2 / this.boomFrames.length;
}
};
/**
* Called when the 'vision' dropdown is changed.
* @param {Object} ev - Change Event
*/
Player.prototype.onVisionSelectorChange = function (ev) {
this.visionTeam = this.visionSelector.val();
this.renderFog();
};
/**
* called when the user clicks on a robot.
*
* @param {PIXI.interaction.InteractionData} ev - click data
*/
Player.prototype.onBotClick = function (ev) {
bot = ev.target;
if (bot.selectedBot != bot.id) {
this.selectBot(bot.id);
}
};
/**
* Set the selected bot by id
*
* @param {Number} botId - the bot id to select
*/
Player.prototype.selectBot = function (botId) {
bot = this.matchState.robots[botId];
this.selectedBot = bot.id;
$('.botIcon', this.selectedBotPanel)
.empty()
.append("<div class='energonOuter'><div class='energon'></div></div>");
$('.selectedBotStats').show();
this.updateSelectedBotPanel();
};
/**
* Position the stats panel over the unused area of the canvas.
*/
Player.prototype.positionStatsPanel = function () {
var bottomSpace = $(this.canvasContainer).height() - this.boardHeight;
var rightSpace = $(this.canvasContainer).width() - this.boardWidth;
if (bottomSpace > rightSpace) {
console.log("Stats At Bottom!");
this.statsHorizontal = true;
this.statsVertical = false;
this.statsPanel.removeClass("vertical").addClass("horizontal");
var top = this.canvasContainer.offset().top + this.boardHeight;
this.statsPanel.css({
'boxSizing': 'border-box',
left: 0 + "px",
top: top,
width: this.boardWidth,
height: this.canvasContainer.height() - this.boardHeight,
flexDirection: 'row'
});
} else {
this.statsHorizontal = false;
this.statsVertical = true;
this.statsPanel.removeClass("horizontal").addClass("vertical");
console.log("Stats At Side!");
this.statsPanel.css({
'boxSizing': 'border-box',
left: this.canvasContainer.offset().left + this.boardWidth,
top: this.canvasContainer.offset().top,
//width: this.canvasContainer.width() - this.boardWidth,
height: this.boardHeight,
flexDirection: 'column'
});
}
};
/**
* sets the size of game objects based on available screen size.
*/
Player.prototype.setDimensions = function () {
if (this.match) {
var wPix = (this.canvasContainer.width() / this.match.mapWidth);
var hPix = (this.canvasContainer.height() / this.match.mapHeight);
this.cellSize = Math.min(wPix, hPix);
this.boardWidth = (this.cellSize * this.match.mapWidth);
this.boardHeight = (this.cellSize * this.match.mapHeight);
var bottomSpace = $(this.canvasContainer).height() - this.boardHeight;
var rightSpace = $(this.canvasContainer).width() - this.boardWidth;
if (bottomSpace > rightSpace) {
while (bottomSpace < 160) {
this.cellSize -= 0.25;
this.boardWidth = (this.cellSize * this.match.mapWidth);
this.boardHeight = (this.cellSize * this.match.mapHeight);
bottomSpace = $(this.canvasContainer).height() - this.boardHeight;
}
} else {
while (rightSpace < 250) {
this.cellSize -= 0.25;
this.boardWidth = (this.cellSize * this.match.mapWidth);
this.boardHeight = (this.cellSize * this.match.mapHeight);
rightSpace = $(this.canvasContainer).width() - this.boardWidth;
}
}
this.botSize = this.cellSize;
this.halfBotSize = this.botSize / 2;
}
if (this.matchState) {
sprite, bot;
for (bk in this.matchState.robots) {
bot = this.matchState.robots[bk];
sprite = this.botSprites[bk];
if (bot.type == 'hq') {
sprite.width = this.botSize * 1.5;
sprite.height = this.botSize * 1.5;
} else {
sprite.width = this.botSize;
sprite.height = this.botSize;
}
TweenLite.killTweensOf(sprite.position);
pos = this.getCellCenter(bot.pos);
sprite.position.x = pos.x;
sprite.position.y = pos.y;
}
} if (this.statsPanel) {
this.positionStatsPanel();
}
this.renderMap();
this.renderFog();
console.log("Initialized " + this.boardWidth + "x" + this.boardHeight +
" canvas and " + this.cellSize + "px cell size");
};
/**
* Called when the Game fails to load
*
* Shows an error message in the loading dialog.
*/
Player.prototype.onGameLoadError = function (err) {
console.error(err.error);
$(".loadMessage", this.loadDialog).addClass("error").text("ERROR: " + err.message);
$('progress', this.loadDialog).remove();
var retryButton = $("<button class='reload'>Back</button>");
this.loadDialog.append(retryButton);
retryButton.on('click', function () { location.reload() }).focus();
};
/**
* Called when the Game begins loading.
*
* Shows a Loading dialog.
*/
Player.prototype.onGameLoadStart = function () {
this.loadDialog = $("<div id='loadDialog'><div class='logo'></div><div class='loadMessage'>Loading game...</div><progress></progress></div>");
$('progress', this.loadDialog).attr("max", 100);
$('progress', this.loadDialog).attr("value", 0);
this.loadDialog.css({
position: 'absolute',
top: '45%',
left: '30%',
width: '40%'
});
$('body').append(this.loadDialog);
};
/**
* Called throughout the Game loading process.
*
* @param {Number} progress - loading progress (0-100)
*/
Player.prototype.onGameLoadProgress = function (progress) {
setTimeout(function () {
$("progress", this.loadDialog).attr("value", Math.floor(progress));
}.bind(this), 1);
};
/**
* Finds all squares visible by the given team.
*
* @param {String} team
* @returns {Object} - keys are integer-locations, values are true.
*/
Player.prototype.calculateFog = function (team) {
if (this.matchState) {
var visibleCells = {};
var visionRadius = 3;
if (this.matchState.hasVision(team)) {
visionRadius = 5;
}
for (bk in this.matchState.robots) {
bot = this.matchState.robots[bk];
if (bot.team == team) {
fogBotIdx = (this.match.mapWidth * bot.pos.y) + bot.pos.x;
$.extend(visibleCells, this.getVisibleCells(bot.pos, visionRadius));
}
}
return visibleCells;
}
return {};
};
/**
* finds all squares visible from the given position
* within the given radius. (not squared.)
*
* @param pos
* @param {Number} radius - Only 3 and 5 are supported.
* @returns {Object} - keys are integer locations.
*/
Player.prototype.getVisibleCells = function (pos, radius) {
var results = {};
var visionMinX = Math.max(0, pos.x - radius);
var visionMaxX = Math.min(this.match.mapWidth-1, pos.x + radius);
var visionMinY = Math.max(0, pos.y - radius);
var visionMaxY = Math.min(this.match.mapHeight-1, pos.y + radius);
var visionTmpMinY, visionTmpMaxY;
if (radius == 3) {
for (visX = visionMinX; visX <= visionMaxX; visX++) {
if (visX == pos.x - radius || visX == pos.x + radius) {
visionTmpMinY = pos.y - radius + 1;
visionTmpMaxY = pos.y + radius - 1;
} else {
visionTmpMinY= visionMinY;
visionTmpMaxY = visionMaxY;
}
for (visY = visionTmpMinY; visY <= visionTmpMaxY; visY++) {
results[(visY * this.match.mapWidth) + visX] = true;
}
}
return results;
} else {
for (visX = visionMinX; visX <= visionMaxX; visX++) {
if (visX == pos.x - radius || visX == pos.x + radius) {
visionTmpMinY = pos.y - radius + 3;
visionTmpMaxY = pos.y + radius - 3;
} else if (visX < (pos.x - radius) + 3 || visX > pos.x + radius - 3) {
visionTmpMinY = pos.y - radius + 1;
visionTmpMaxY = pos.y + radius - 1;
} else {
visionTmpMinY = visionMinY;
visionTmpMaxY = visionMaxY;
}
for (visY = visionTmpMinY; visY <= visionTmpMaxY; visY++) {
results[(visY * this.match.mapWidth) + visX] = true;
}
}
return results;
}
};
/**
* Called when the Game is fully loaded and parsed.
*/
Player.prototype.onGameLoadComplete = function () {
if (this.loadDialog) {
this.loadDialog.remove();
}
this.matchSelector.empty();
for (i=0; i<this.game.matches.length; i++) {
var mapName = this.game.matches[i].mapName;
if (mapName.substring(mapName.length-4).toLowerCase() == '.xml') {
mapName = mapName.substring(0, mapName.length-4);
}
this.matchSelector.append("<option value='" + i + "'>" + i + ". " + mapName + "</option>");
}
this.visionSelector.empty();
this.visionSelector.append($("<option value=''>-Vision-</option>"));
this.visionSelector.append($("<option value='a'>" + this.game.teams.a.name + "</option>"));
this.visionSelector.append($("<option value='b'>" + this.game.teams.b.name + "</option>"));
this.initMatch(this.game.matches[0]);
};
/**
* sets the Game to be played.
*
* @param {Game} game - a Game
* @param {function} callback - a function to call when loading is complete.
*/
Player.prototype.loadGame = function (game, callback) {
if (!this.paused) {
console.log("Toggling");
this.togglePlayback();
this.transitionToRound(0);
}
if (typeof game == 'string') {
this.game = new Game();
this.game.load(game);
} else {
this.game = game;
}
if (!game.isLoaded) {
this.game.on('loadStart', this.onGameLoadStart.bind(this));
this.game.on('loadProgress', this.onGameLoadProgress.bind(this));
this.game.on('loadComplete', this.onGameLoadComplete.bind(this));
this.game.on('loadError', this.onGameLoadError.bind(this));
$('div.loadMessage', this.loadDialog).html("<span class='errorMessage'></span>");
} else {
this.onGameLoadComplete();
}
};
/**
* Intialize the player for the selected match
* (resizes the game board and stats panel)
*
* @param {Match} match - the match
*/
Player.prototype.initMatch = function (match) {
this.match = match;
this.reset();
$(window).resize();
this.renderMap();
this.timeSlider.val(0);
this.timeSlider.attr("max", this.match.states.length-1);
this.transitionToRound(0);
};
/**
* Renders a batch of mines using the current line/fill style.
*
* @param {Object} mines - keys are integers mapping to locations, values are 'true'
*/
Player.prototype.renderMineList = function (mines) {
for (mine in mines) {
gx = mine % this.match.mapWidth;
gy = Math.floor(mine / this.match.mapWidth);
px = 1+(this.cellSize * gx);
py = 1+(this.cellSize* gy);
this.field.drawRect(px, py, this.cellSize-2, this.cellSize-2);
}
};
/**
* Builds a 'Team Stats Panel' for the given team.
* this is a div containing power levels, bot counts and upgrade progress.
*
* @param {String} team - 'a' or 'b'
* @returns {jQuery}
*/
Player.prototype.buildTeamStatsPanel = function (team) {
var teamInfo = this.game.teams[team];
var $panel = $("<div class='teamStatsPanel' id='team-stats-"+team+"'></div>");
$panel.append($("<h1 class='team-" + team + "'>" + teamInfo.name + "</h1>"));
var tbl = $("<table class='teamStats'></table>");
var row1 = $('<tr>' +
'<td rowspan="3" class="hqCell"></td>' +
'<th class="soldier"></th>' +
'<td class="soldier">0</td>' +
'<th class="medbay"></th>' +
'<td class="medbay">0</td>' +
'<th class="shields"></th>' +
'<td class="shields">0</td>' +
'</tr>');
var row2 = $('<tr>' +
'<th class="supplier"></th>' +
'<td class="supplier">0</td>' +
'<th class="generator"></th>' +
'<td class="generator">0</td>' +
'<th class="artillery"></th>' +
'<td class="artillery">0</td>' +
'</tr>');
var row3 = $('<tr>' +
'<td colspan="6" class="teamPower"></td>' +
'</tr>');
var row4 = $('<tr class="upgradesRow" style="display: none">' +
'<td colspan="7" class="upgrades"></td>' +
'</tr>');
var row5 = $("<tr class='starsRow' style='display: none'><td colspan='7' class='stars'></td></tr>");
tbl.append(row1);
tbl.append(row2);
tbl.append(row3);
tbl.append(row4);
tbl.append(row5);
var hqIcon = $("<div class='hqIcon team-" + team + "'></div>");
var hqEnergon = $("<div class='energonOuter'><div class='energon'></div></div>");
hqIcon.append(hqEnergon);
$('td.hqCell', tbl).append(hqIcon);
var progressBar = $("<span class='power-value'>0</span><div class='teamPowerWrapper'><div class='teamPower'></div></div>");
$('td.teamPower', tbl).append(progressBar);
$panel.append(tbl);
for (var u in this.upgrades) {
$('td', row4).append($('<div title="' + u + '" style="display: none" class="upgrade '+ u + '">' +
'<progress value="0" max="' + this.upgrades[u] + '"></progress>' +
'</div>'));
}
return $panel;
};
/**
* Builds the 'Selected Bot Panel' where details on the
* selected bot are displayed.
*
* @returns {jQuery}
*/
Player.prototype.buildSelectedBotPanel = function () {
this.selectedBotPanel = $(
"<div id='selectedBotPanel'>" +
"<h1>no robot selected</h1>" +
"<table class='selectedBotStats' style='display:none;'>" +
"<tr><td rowspan='3'><div class='botIcon'></div></td><th title='Energon' class='energon'><i title='Energon' class='fa fa-heartbeat'></i></th><td title='Energon' class='energon'></td><th title='Shields' class='shields'><i title='Shields' class='fa fa-shield'></i></th><td title='Shields' class='shields'></td></tr>" +
"<tr><th class='position' title='Position' ><i title='position' class='fa fa-compass'></i></th><td title='position' class='position'></td><th title='Bytecodes Used' class='bytecodes'><i title='Bytecodes Used' class='fa fa-clock-o'></i></th><td title='Bytecodes Used' class='bytecodes'>0</td></tr>" +
"<tr><td colspan='4' class='action'><span class='action-text'>Idle</span><div class='actionProgressWrapper'><div class='actionProgress'></div></div></td></tr>" +
"</table>" +
"<div class='indicatorStrings'></div>" +
"</div>");
return this.selectedBotPanel;
};
/**
* Builds the Player's header where are all controls reside.
*
* @returns {jQuery}
*/
Player.prototype.buildHeader = function () {
this.header = $("<div id='header'></div>");
this.logo = $("<img id='logo' src='img/blitzcode.png' />");
this.matchSelector = $("<select id='matchSelector'></select>");
this.roundIndicator = $("<div id='roundIndicator'>0/0</div>");
this.timeSlider = $("<input id='timeSlider' type='range' max='1' value='0' />");
this.speedSlider = $("<input title='Playback Speed' id='speedSlider' type='range' min='1' max='99' value='70' />");
this.playPauseButton = $("<button title='Play/Pause' id='playPauseButton' class='paused'><i class='fa fa-play'></i></button>");
this.gotoEndButton = $("<button title='Go to last round' id='gotoEndButton'><i class='fa fa-fast-forward'></i></button>");
this.gotoStartButton = $("<button title='Go to first round' id='gotoStartButton'><i class='fa fa-fast-backward'></i></button>");
this.goForwardButton = $("<button title='Go to next round' id='goForwardButton'><i class='fa fa-forward'></i></button>");
this.goBackButton = $("<button title='Go to previous round' id='goBackButton'><i class='fa fa-backward'></i></button>");
this.speedIndicator= $("<div id='speedIndicator'>75%</div>");
this.fullscreenButton = $("<button title='Toggle Fullscreen' id='fullscreenButton'><i class='fa fa-arrows-alt'></i></button>");
this.visionSelector = $("<select id='visionSelector'>" +
"<option value=''>-Vision-</option>" +
"<option value='a' style='color: #FF0000'>Team A</option>" +
"<option value='b' style='color: #FF0000'>Team B</option>" +
"</select>");
this.timeSlider.on('change input', '', this.onTimeSliderChange.bind(this));
this.gotoStartButton.on('click', this.onGotoStartButton.bind(this));
this.gotoEndButton.on('click', this.onGotoEndButton.bind(this));
this.goBackButton.on('click', this.onGoBackButton.bind(this));
this.goForwardButton.on('click', this.onGoForwardButton.bind(this));
this.fullscreenButton.on('click', this.onFullscreenButton.bind(this));
this.visionSelector.on('change', this.onVisionSelectorChange.bind(this));
this.matchSelector.on('change', '', this.onMatchSelectorChange.bind(this));
this.speedSlider.on('change input', '', this.onSpeedSliderChange.bind(this));
this.playPauseButton.on('click', '', this.togglePlayback.bind(this));
this.header.append(this.logo);
this.header.append(this.matchSelector);
this.header.append(this.gotoStartButton);
this.header.append(this.goBackButton);
this.header.append(this.playPauseButton);
this.header.append(this.goForwardButton);
this.header.append(this.gotoEndButton);
this.header.append(this.timeSlider);
this.header.append(this.roundIndicator);
this.header.append(this.speedSlider);
this.header.append(this.speedIndicator);
this.header.append(this.visionSelector);
this.header.append(this.fullscreenButton);
this.speedSlider.change();
return this.header;
};
/**
* Builds the 'Stats Panel' - a container for the
* 'Selected Bot Panel' and 'Team Stats Panels'
*
* Unlike the build* functions this one appends it to the DOM as well.
*/
Player.prototype.initializeStatsPanel = function () {
$("#statsPanel").remove();
this.statsPanel = $("<div id='statsPanel'></div>");
this.statsPanel.css({position: 'absolute', display: 'flex'});
$('body').append(this.statsPanel);
this.statsPanel.append(this.buildTeamStatsPanel('a'));
this.statsPanel.append(this.buildTeamStatsPanel('b'));
this.statsPanel.append(this.buildSelectedBotPanel());
};
/**
* Reset the player
*
* ugh.
*/
Player.prototype.reset = function () {
this.initializeStatsPanel();
this.botSprites = {};
this.hatSprites = {};
this.selectedBot = null;
this.matchState = null;
this.frameTime = 0;
this.round = -1;
this.lastElapsed = 0;
this.playbackComplete = false;
this.paused = true;
this.botSprites = {};
this.botLayer.removeChildren();
};
/**
* toggle play/pause state.
*/
Player.prototype.togglePlayback = function () {
if (!this.assetsLoaded) {
// TODO: They pressed play before
// textures were loaded.
return;
}
this.paused = !this.paused;
$("i.fa", this.playPauseButton)
.removeClass('fa-play fa-pause')
.addClass(this.paused ? 'fa-play' : 'fa-pause');
};
/**
* Convert a string location of the format 'x,y' to an integer
* representing the index of that location in a 1-dimensional array.
*
* @param {String} locStr - a location (eg. 10,2)
* @returns {Number}
*/
Player.prototype.parseLoc = function (locStr) {
parts = locStr.split(",");
return (this.match.mapWidth * parts[0]) + parts[1];
};
/**
* Transition from the current round to the given round.
*
* This is called after a round has played
* for {@link Player#frameDuration} ms or when
* the round is changed manually.
*
* @param {Number} round - the desired round
*/
Player.prototype.transitionToRound = function (round) {
if (round > this.match.states.length-1) {
return;
}
this.effectsLayer.clear();
currentRound = this.round;
if (round == currentRound) {
//TODO: No-op?
} else if (round > currentRound) {
// Go Forward.
for (applyIter=currentRound+1; applyIter<=round; applyIter++) {
//console.log("Applying state " + this.round + " -> " + i);
this.round = applyIter;
this.matchState = this.match.states[this.round];
this.applyMatchState(this.matchState, round == applyIter);
}
} else {
// Go backwards.
for (undoIter=currentRound-1; undoIter>=round; undoIter--) {
//console.log("Undoing state " + this.round + " -> " + i);
this.undoMatchState(this.matchState, round == undoIter);
this.round = undoIter;
this.matchState = this.match.states[this.round];
}
}
$("#timeSlider").val(this.round);
maxRound = this.match.states.length-1;
this.roundIndicator.text(Util.zeroPad(this.round, ("" + maxRound).length) + "/" + maxRound);
this.updateStatsPanel();
this.renderMap();
this.renderFog();
};
Player.prototype.renderFog = function () {
this.fogLayer.clear();
if (this.visionTeam) {
this.fogLayer.beginFill(0x000000, 0.666);
var visibleCells = this.calculateFog(this.visionTeam);
var gx, gy;
for (i = 0; i < this.match.mapWidth * this.match.mapHeight; i++) {
if (!visibleCells[i]) {
gx = i % this.match.mapWidth;
gy = Math.floor(i / this.match.mapWidth);
this.fogLayer.drawRect(gx * this.cellSize, gy * this.cellSize, this.cellSize, this.cellSize);
}
}
this.fogLayer.endFill();
}
};
/**
* Updates all the values in the Stats Panels
*/
Player.prototype.updateStatsPanel = function () {
statsCounts = {a: {hq: 0, soldier: 0, artillery: 0, generator: 0, shields: 0, medbay: 0, supplier: 0},
b: {hq: 0, soldier: 0, artillery: 0, generator: 0, shields: 0, medbay: 0, supplier: 0}};
statsPanelHQ = {a: null, b: null};
for (bk in this.matchState.robots) {
bot = this.matchState.robots[bk];
statsCounts[bot.team][bot.type] ++;
if (bot.type == 'hq') {
statsPanelHQ[bot.team] = bot;
}
}
for (statsTeam in {a: true, b: true}) {
panel = $("#team-stats-" + statsTeam);
wins = this.match.wins[statsTeam];
if (this.round == this.match.states.length-1) {
if (this.match.winner == statsTeam) {
wins += 1;
} else {