forked from FreezingMoon/AncientBeast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
1573 lines (1361 loc) · 40.4 KB
/
game.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
import * as $j from 'jquery';
import { Animations } from './animations';
import { CreatureQueue } from './creature_queue';
import { GameLog } from './utility/gamelog';
import { SoundSys } from './sound/soundsys';
import { MusicPlayer } from './sound/musicplayer';
import { Hex } from './utility/hex';
import { HexGrid } from './utility/hexgrid';
import { getUrl } from './assetLoader';
import { Player } from './player';
import { UI } from './ui/interface';
import { Creature } from './creature';
import dataJson from './data/units.json';
import 'pixi';
import 'p2';
import Phaser, { Signal } from 'phaser';
import MatchI from './multiplayer/match';
import Gameplay from './multiplayer/gameplay';
import { sleep } from './utility/time';
/* Game Class
*
* Game contains all Game elements and functions.
* It's the root element and defined only one time through the G variable.
*
* NOTE: Constructor does nothing because the G object must be defined
* before creating other class instances. The game setup is triggered
* to really start the game.
*/
export default class Game {
/* Attributes
*
* NOTE : attributes and variables starting with $ are jQuery elements
* and jQuery functions can be called directly from them.
*
* // jQuery attributes
* $combatFrame : Combat element containing all graphics except the UI
*
* // Game elements
* players : Array : Contains Player objects ordered by player ID (0 to 3)
* creatures : Array : Contains Creature objects (creatures[creature.id]) start at index 1
*
* grid : Grid : Grid object
* UI : UI : UI object
*
* queue : CreatureQueue : queue of creatures to manage phase order
*
* turn : Integer : Current's turn number
*
* // Normal attributes
* playerMode : Integer : Number of players in the game
* activeCreature : Creature : Current active creature object reference
* creatureIdCounter : Integer : Creature ID counter used for creature creation
* creatureData : Array : Array containing all data for the creatures
*
*/
constructor(version) {
this.version = version || 'dev';
this.abilities = [];
this.players = [];
this.creatures = [];
this.effects = [];
this.activeCreature = {
id: 0,
};
this.matchid = null;
this.playersReady = false;
this.preventSetup = false;
this.animations = new Animations(this);
this.queue = new CreatureQueue(this);
this.creatureIdCounter = 1;
this.creatureData = [];
this.pause = false;
this.gameState = 'initialized';
this.pauseTime = 0;
this.minimumTurnBeforeFleeing = 12;
this.availableCreatures = [];
this.animationQueue = [];
this.checkTimeFrequency = 1000;
this.gamelog = new GameLog(null, this);
this.configData = {};
this.match = {};
this.gameplay = {};
this.session = null;
this.client = null;
this.connect = null;
this.debugMode = process.env.DEBUG_MODE;
this.multiplayer = false;
this.matchInitialized = false;
this.realms = ['A', 'E', 'G', 'L', 'P', 'S', 'W'];
this.availableMusic = [];
this.soundEffects = [
'sounds/step',
'sounds/swing',
'sounds/swing2',
'sounds/swing3',
'sounds/heartbeat',
'sounds/drums',
'sounds/upgrade',
];
this.inputMethod = 'Mouse';
// Gameplay properties
this.firstKill = false;
this.freezedInput = false;
this.turnThrottle = false;
this.turn = 0;
// Phaser
this.Phaser = new Phaser.Game(1920, 1080, Phaser.AUTO, 'combatwrapper', {
update: this.phaserUpdate.bind(this),
render: this.phaserRender.bind(this),
});
// Messages
// TODO: Move strings to external file in order to be able to support translations
// https://github.com/FreezingMoon/AncientBeast/issues/923
this.msg = {
abilities: {
noTarget: 'No targets available.',
noPlasma: 'Not enough plasma.',
noPsy: 'Psyhelm overload: too many units!',
alreadyUsed: 'This ability has already been used.',
tooMuch: 'Too much %stat%.',
notEnough: 'Not enough %stat%.',
notMoveable: 'This creature cannot be moved.',
passiveCycle: 'Switches between any usable abilities.',
passiveUnavailable: 'No usable abilities to switch to.',
},
ui: {
dash: {
materializeOverload: 'Overload! Maximum number of units controlled',
selectUnit: 'Please select an available unit from the left grid',
lowPlasma: 'Low Plasma! Cannot materialize the selected unit',
// plasmaCost : String : plasma cost of the unit to materialize
materializeUnit: (plasmaCost) => {
return 'Materialize unit at target location for ' + plasmaCost + ' plasma';
},
materializeUsed: 'Materialization has already been used this round',
heavyDev: 'This unit is currently under heavy development',
},
},
};
/* Regex Test for triggers */
this.triggers = {
onStepIn: /\bonStepIn\b/,
onStepOut: /\bonStepOut\b/,
onReset: /\bonReset\b/,
onStartPhase: /\bonStartPhase\b/,
onEndPhase: /\bonEndPhase\b/,
onMovement: /\bonMovement\b/,
onUnderAttack: /\bonUnderAttack\b/,
onDamage: /\bonDamage\b/,
onHeal: /\bonHeal\b/,
onAttack: /\bonAttack\b/,
onCreatureMove: /\bonCreatureMove\b/,
onCreatureDeath: /\bonCreatureDeath\b/,
onCreatureSummon: /\bonCreatureSummon\b/,
onStepIn_other: /\bonOtherStepIn\b/,
onStepOut_other: /\bonOtherStepOut\b/,
onReset_other: /\bonOtherReset\b/,
onStartPhase_other: /\bonOtherStartPhase\b/,
onEndPhase_other: /\bonOtherEndPhase\b/,
onMovement_other: /\bonOtherMovement\b/,
onAttack_other: /\bonOtherAttack\b/,
onDamage_other: /\bonOtherDamage\b/,
onHeal_other: /\bonOtherHeal\b/,
onUnderAttack_other: /\bonOtherUnderAttack\b/,
onCreatureMove_other: /\bonOtherCreatureMove\b/,
onCreatureDeath_other: /\bonOtherCreatureDeath\b/,
onCreatureSummon_other: /\bonOtherCreatureSummon\b/,
onEffectAttach: /\bonEffectAttach\b/,
onEffectAttach_other: /\bonOtherEffectAttach\b/,
onStartOfRound: /\bonStartOfRound\b/,
onQuery: /\bonQuery\b/,
oncePerDamageChain: /\boncePerDamageChain\b/,
};
const signalChannels = ['ui', 'metaPowers', 'creature'];
this.signals = this.setupSignalChannels(signalChannels);
}
dataLoaded(data) {
let dpcolor = ['blue', 'orange', 'green', 'red'];
this.creatureData = data;
data.forEach((creature) => {
if (!creature.playable) {
return;
}
let creatureId = creature.id,
realm = creature.realm,
level = creature.level,
type = realm.toUpperCase() + level,
name = creature.name,
count,
i;
creature.type = type;
// Load unit shouts
this.soundsys.getSound(getUrl('units/shouts/' + name), 1000 + creatureId);
// Load artwork
this.getImage(getUrl('units/artwork/' + name));
if (name == 'Dark Priest') {
for (i = 0, count = dpcolor.length; i < count; i++) {
this.Phaser.load.image(
name + dpcolor[i] + '_cardboard',
getUrl('units/cardboards/' + name + ' ' + dpcolor[i]),
);
this.getImage(getUrl('units/avatars/' + name + ' ' + dpcolor[i]));
}
} else {
if (creature.drop) {
this.Phaser.load.image(
'drop_' + creature.drop.name,
getUrl('drops/' + creature.drop.name),
);
}
this.Phaser.load.image(name + '_cardboard', getUrl('units/cardboards/' + name));
this.getImage(getUrl('units/avatars/' + name));
}
// For code compatibility
this.availableCreatures[creatureId] = type;
});
this.Phaser.load.start();
}
/* loadGame(setupOpt) preload
*
* setupOpt : Object : Setup options from matchmaking menu
*
* Load all required game files
*/
loadGame(setupOpt, matchInitialized, matchid) {
// Need to remove keydown listener before new game start
// to prevent memory leak and mixing hotkeys between start screen and game
$j(document).off('keydown');
if (this.multiplayer && !matchid) {
this.matchInitialized = matchInitialized;
}
if (matchid) {
this.matchid = matchid;
}
let totalSoundEffects = this.soundEffects.length,
i;
this.gameState = 'loading';
if (setupOpt) {
this.gamelog.gameConfig = setupOpt;
this.configData = setupOpt;
$j.extend(this, setupOpt);
}
// console.log(this);
this.startLoading();
// Sounds
this.musicPlayer = new MusicPlayer();
this.soundLoaded = {};
this.soundsys = new SoundSys({}, this);
for (i = 0; i < totalSoundEffects; i++) {
this.soundsys.getSound(getUrl(this.soundEffects[i]), this.availableMusic.length + i);
}
this.Phaser.load.onFileComplete.add(this.loadFinish, this);
// Health
let playerColors = ['red', 'blue', 'orange', 'green'];
for (i = 0; i < 4; i++) {
this.Phaser.load.image('p' + i + '_health', getUrl('interface/rectangle_' + playerColors[i]));
this.Phaser.load.image('p' + i + '_plasma', getUrl('interface/capsule_' + playerColors[i]));
this.Phaser.load.image(
'p' + i + '_frozen',
getUrl('interface/rectangle_frozen_' + playerColors[i]),
);
}
// Ability SFX
this.Phaser.load.audio('MagmaSpawn0', getUrl('units/sfx/Infernal 0'));
// Grid
this.Phaser.load.image('hex', getUrl('interface/hex'));
this.Phaser.load.image('hex_dashed', getUrl('interface/hex_dashed'));
this.Phaser.load.image('hex_path', getUrl('interface/hex_path'));
this.Phaser.load.image('cancel', getUrl('interface/cancel'));
this.Phaser.load.image('input', getUrl('interface/hex_input'));
for (i = 0; i < 4; i++) {
this.Phaser.load.image('hex_p' + i, getUrl('interface/hex_glowing_' + playerColors[i]));
this.Phaser.load.image('hex_hover_p' + i, getUrl('interface/hex_outline_' + playerColors[i]));
}
// Traps
this.Phaser.load.image('trap_royal-seal', getUrl('units/sprites/Gumble - Royal Seal'));
this.Phaser.load.image('trap_mud-bath', getUrl('units/sprites/Swine Thug - Mud Bath'));
this.Phaser.load.image(
'trap_scorched-ground',
getUrl('units/sprites/Infernal - Scorched Ground'),
);
this.Phaser.load.image('trap_firewall', getUrl('units/sprites/Infernal - Scorched Ground'));
this.Phaser.load.image('trap_poisonous-vine', getUrl('units/sprites/Impaler - Poisonous Vine'));
// Effects
this.Phaser.load.image('effects_fiery-touch', getUrl('units/sprites/Abolished - Fiery Touch'));
this.Phaser.load.image(
'effects_fissure-vent',
getUrl('units/sprites/Infernal - Scorched Ground'),
);
this.Phaser.load.image(
'effects_freezing-spit',
getUrl('units/sprites/Snow Bunny - Freezing Spit'),
);
// Background
this.Phaser.load.image('background', getUrl('locations/' + this.background_image + '/bg'));
// Get JSON files
this.dataLoaded(dataJson);
}
startLoading() {
$j('#gameSetupContainer').hide();
$j('#loader').removeClass('hide');
$j('body').css('cursor', 'wait');
}
loadFinish() {
let progress = this.Phaser.load.progress,
progressWidth = progress + '%';
$j('#barLoader .progress').css('width', progressWidth);
if (progress == 100) {
setTimeout(() => {
this.gameState = 'loaded';
$j('#combatwrapper').show();
$j('body').css('cursor', 'default');
// Do not call setup if we are not active.
if (!this.preventSetup) {
this.setup(this.playerMode);
}
}, 100);
}
}
phaserUpdate() {
if (this.gameState != 'playing') {
return;
}
}
phaserRender() {
let count = this.creatures.length,
i;
for (i = 1; i < count; i++) {
//G.Phaser.debug.renderSpriteBounds(G.creatures[i].sprite);
}
}
// Catch the browser being made inactive to prevent initial rendering bugs.
onBlur() {
this.preventSetup = true;
}
// Catch the browser coming back into focus so we can render the game board.
onFocus() {
this.preventSetup = false;
// If loaded, call maybeSetup with a tiny delay to prevent rendering issues.
if (this.gameState == 'loaded') {
setTimeout(() => {
this.maybeSetup();
}, 100);
}
}
// If no red flags, remove the loading bar and begin rendering the game.
maybeSetup() {
if (this.preventSetup) {
return;
}
$j('#loader').addClass('hide');
$j('body').css('cursor', 'default');
this.setup(this.playerMode);
}
/* Setup(playerMode)
*
* playerMode : Integer : Ideally 2 or 4, number of players to configure
*
* Launch the game with the given number of player.
*
*/
setup(playerMode) {
let bg, i;
// Phaser
this.Phaser.scale.parentIsWindow = true;
this.Phaser.scale.pageAlignHorizontally = true;
this.Phaser.scale.pageAlignVertically = true;
this.Phaser.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.Phaser.scale.fullScreenScaleMode = Phaser.ScaleManager.SHOW_ALL;
this.Phaser.scale.refresh();
this.Phaser.stage.disableVisibilityChange = true;
if (!this.Phaser.device.desktop) {
this.Phaser.stage.forcePortrait = true;
}
bg = this.Phaser.add.sprite(0, 0, 'background');
bg.inputEnabled = true;
bg.events.onInputUp.add((Sprite, Pointer) => {
if (this.freezedInput || this.UI.dashopen) {
return;
}
switch (Pointer.button) {
case 0:
// Left mouse button pressed
break;
case 1:
// Middle mouse button pressed
break;
case 2:
// Right mouse button pressed
this.UI.showCreature(this.activeCreature.type, this.activeCreature.player.id);
break;
}
}, this);
// Reset global counters
this.trapId = 0;
this.effectId = 0;
this.dropId = 0;
this.creatureIdCounter = 1;
this.grid = new HexGrid({}, this); // Create Hexgrid
this.startMatchTime = new Date();
this.$combatFrame = $j('#combatframe');
this.$combatFrame.show();
// Remove loading screen
$j('#matchMaking').hide();
for (i = 0; i < playerMode; i++) {
let player = new Player(i, this);
this.players.push(player);
// Initialize players' starting positions
let pos = {};
if (playerMode > 2) {
// If 4 players
switch (player.id) {
case 0:
pos = {
x: 0,
y: 1,
};
break;
case 1:
pos = {
x: 15,
y: 1,
};
break;
case 2:
pos = {
x: 0,
y: 7,
};
break;
case 3:
pos = {
x: 15,
y: 7,
};
break;
}
} else {
// If 2 players
switch (player.id) {
case 0:
pos = {
x: 0,
y: 4,
};
break;
case 1:
pos = {
x: 14,
y: 4,
};
break;
}
}
player.summon('--', pos); // Summon Dark Priest
}
this.activeCreature = this.players[0].creatures[0]; // Prevent errors
this.UI = new UI(this); // Create UI (not before because some functions require creatures to already exist)
// DO NOT CALL LOG BEFORE UI CREATION
this.gameState = 'playing';
this.log('Welcome to Ancient Beast pre-Alpha');
this.log('Setting up a ' + playerMode + ' player match');
this.timeInterval = setInterval(() => {
this.checkTime();
}, this.checkTimeFrequency);
this.nextCreature();
this.resizeCombatFrame(); // Resize while the game is starting
this.UI.resizeDash();
var resizeGame = function () {
clearTimeout(this.windowResizeTimeout);
this.windowResizeTimeout = setTimeout(() => {
this.resizeCombatFrame();
this.UI.resizeDash();
}, 100);
}.bind(this);
// Handle resize events
$j(window).resize(() => {
// Throttle down to 1 event every 100ms of inactivity
resizeGame();
});
this.soundsys.playMusic();
if (this.gamelog.data) {
// TODO: Remove the need for a timeout here by having a proper
// "game is ready to play" event that can trigger log replays if
// they are queued. -- ktiedt
setTimeout(() => {
this.gamelog.play.apply(this.gamelog);
}, 1000);
}
this.matchInit();
}
async matchInit() {
if (this.multiplayer) {
if (Object.keys(this.match).length === 0) {
await this.connect.serverConnect(this.session);
let match = new MatchI(this.connect, this, this.session);
let gameplay = new Gameplay(this, match);
match.gameplay = gameplay;
this.gameplay = gameplay;
this.match = match;
// Only host
if (this.matchInitialized) {
let n = await this.match.matchCreate();
console.log('created match', n);
await match.matchMaker(n, this.configData);
}
}
// Non-host
if (this.matchid) {
let n = await this.match.matchJoin(this.matchid);
console.log('joined match', n);
}
}
}
async matchJoin() {
await this.matchInit();
await this.match.matchMaker();
}
async updateLobby() {
if (this.matchInitialized) return;
let self = this;
$j('.lobby-match-list').html('').addClass('refreshing');
$j('#refreshMatchButton').addClass('disabled');
$j('.lobby-loader').removeClass('hide');
$j('.lobby-no-matches').addClass('hide');
// Short delay to let the user know something has happened.
await sleep(Phaser.Timer.SECOND * 2);
$j('.lobby-match-list').removeClass('refreshing');
$j('#refreshMatchButton').removeClass('disabled');
$j('.lobby-loader').addClass('hide');
if (!this.match.matchUsers.length) {
$j('.lobby-no-matches').removeClass('hide');
return;
}
this.match.matchUsers.forEach((v) => {
const isAvailableMatch = v.string_properties && v.string_properties.match_id;
if (!isAvailableMatch) {
return;
}
let gameConfig = {
background_image: v.string_properties.background_image,
abilityUpgrades: v.numeric_properties.abilityUpgrades,
creaLimitNbr: v.numeric_properties.creaLimitNbr,
plasma_amount: v.numeric_properties.plasma_amount,
playerMode: v.numeric_properties.playerMode,
timePool: v.numeric_properties.timePool,
turnTimePool: v.numeric_properties.turnTimePool,
unitDrops: v.numeric_properties.unitDrops,
};
let turntimepool =
v.numeric_properties.turnTimePool < 0 ? '∞' : v.numeric_properties.timePool;
let timepool = v.numeric_properties.timePool < 0 ? '∞' : v.numeric_properties.timePool;
let unitdrops = v.numeric_properties.unitDrops < 0 ? 'off' : 'on';
let _matchBtn =
$j(`<a class="user-match"><div class="avatar"></div><div class="user-match__col">
Host: ${v.presence.username}<br />
Player Mode: ${v.numeric_properties.playerMode}<br />
Active Units: ${v.numeric_properties.creaLimitNbr}<br />
Ability Upgrades: ${v.numeric_properties.abilityUpgrades}<br />
</div><div class="user-match__col">
Plasma Points: ${v.numeric_properties.plasma_amount}<br />
Turn Time(seconds): ${turntimepool}<br />
Turn Pools(minutes): ${timepool}<br />
Unit Drops: ${unitdrops}<br /></div></a>
`);
_matchBtn.on('click', () => {
$j('.lobby').hide();
this.loadGame(gameConfig, false, v.string_properties.match_id);
});
$j('.lobby-match-list').append(_matchBtn);
});
}
/* resizeCombatFrame()
*
* Resize the combat frame
*/
resizeCombatFrame() {
if ($j('#cardwrapper').width() < $j('#card').width()) {
$j('#cardwrapper_inner').width();
}
}
/* nextRound()
*
* Replace the current queue with the next queue
*/
nextRound() {
let totalCreatures = this.creatures.length,
i;
this.turn++;
this.log('Round ' + this.turn, 'roundmarker', true);
this.queue.nextRound();
// Resets values
for (i = 0; i < totalCreatures; i++) {
if (this.creatures[i] instanceof Creature) {
this.creatures[i].delayable = true;
this.creatures[i].delayed = false;
}
}
this.onStartOfRound();
this.nextCreature();
}
/* nextCreature()
*
* Activate the next creature in queue
*/
nextCreature() {
this.UI.closeDash();
this.UI.btnToggleDash.changeState('normal');
this.grid.xray(new Hex(-1, -1, null, this)); // Clear Xray
if (this.gameState == 'ended') {
return;
}
this.stopTimer();
// Delay
setTimeout(() => {
let interval = setInterval(() => {
clearInterval(interval);
let differentPlayer = false;
if (this.queue.isCurrentEmpty()) {
this.nextRound(); // Switch to the next Round
return;
} else {
let next = this.queue.dequeue();
if (this.activeCreature) {
differentPlayer = this.activeCreature.player != next.player;
} else {
differentPlayer = true;
}
let last = this.activeCreature;
this.activeCreature = next; // Set new activeCreature
if (!last.dead) {
last.updateHealth(); // Update health display due to active creature change
}
}
if (this.activeCreature.player.hasLost) {
this.nextCreature();
return;
}
// Play heartbeat sound on other player's turn
if (differentPlayer) {
this.soundsys.playSound(this.soundLoaded[4], this.soundsys.heartbeatGainNode);
}
this.log('Active Creature : %CreatureName' + this.activeCreature.id + '%');
this.activeCreature.activate();
// console.log(this.activeCreature);
// Show mini tutorial in the first round for each player
if (this.turn == 1) {
this.log('The active unit has a flashing hexagon');
this.log('It uses a plasma field to protect itself');
this.log('Its portrait is displayed in the upper left');
this.log("Under the portrait are the unit's abilities");
this.log('The ones with revealed icons are usable');
this.log('Use the last one to materialize a creature');
this.log('Making units drains your plasma points');
this.log('Press the hourglass icon to skip the turn');
this.log('%CreatureName' + this.activeCreature.id + '%, press here to toggle tutorial!');
}
// Updates UI to match new creature
this.UI.updateActivebox();
this.updateQueueDisplay();
if (this.multiplayer && this.playersReady) {
this.gameplay.updateTurn();
} else {
this.playersReady = true;
}
}, 50);
}, 300);
}
updateQueueDisplay(excludeActiveCreature) {
if (this.UI) {
this.UI.updateQueueDisplay(excludeActiveCreature);
}
}
/* log(obj)
*
* obj : Any : Any variable to display in console and game log
*
* Display obj in the console log and in the game log
*/
log(obj, htmlclass, ifNoTimestamp = false) {
// Formating
let stringConsole = obj,
stringLog = obj,
totalCreatures = this.creatures.length,
creature,
i;
for (i = 0; i < totalCreatures; i++) {
creature = this.creatures[i];
if (creature instanceof Creature) {
stringConsole = stringConsole.replace(
'%CreatureName' + i + '%',
creature.player.name + "'s " + creature.name,
);
stringLog = stringLog.replace(
'%CreatureName' + i + '%',
"<span class='" + creature.player.color + "'>" + creature.name + '</span>',
);
}
}
console.log(stringConsole);
this.UI.chat.addMsg(stringLog, htmlclass, ifNoTimestamp);
}
togglePause() {
if (this.freezedInput && this.pause) {
this.pause = false;
this.freezedInput = false;
this.pauseTime += new Date() - this.pauseStartTime;
$j('#pause').remove();
this.startTimer();
} else if (!this.pause && !this.freezedInput) {
this.pause = true;
this.freezedInput = true;
this.pauseStartTime = new Date();
this.stopTimer();
$j('#ui').append('<div id="pause">Pause</div>');
}
}
/* skipTurn()
*
* End turn for the current unit
*/
skipTurn(o) {
// Removes temporary Creature from queue when Player skips turn
// while choosing materialize location for Creature
this.queue.removeTempCreature();
// Send skip turn to server
if (this.turnThrottle) {
return;
}
o = $j.extend(
{
callback: function () {},
noTooltip: false,
tooltip: 'Skipped',
},
o,
);
this.turnThrottle = true;
this.UI.btnSkipTurn.changeState('disabled');
this.UI.btnDelay.changeState('disabled');
this.UI.btnAudio.changeState('disabled');
if (!o.noTooltip) {
this.activeCreature.hint(o.tooltip, 'msg_effects');
}
setTimeout(() => {
this.turnThrottle = false;
this.UI.btnSkipTurn.changeState('normal');
if (
!this.activeCreature.hasWait &&
this.activeCreature.delayable &&
!this.queue.isCurrentEmpty()
) {
this.UI.btnDelay.changeState('normal');
}
o.callback.apply();
}, 1000);
this.activeCreature.facePlayerDefault();
let skipTurn = new Date();
let p = this.activeCreature.player;
p.totalTimePool = p.totalTimePool - (skipTurn - p.startTime);
this.pauseTime = 0;
this.activeCreature.deactivate(false);
this.nextCreature();
// Reset temporary Creature
this.queue.tempCreature = {};
}
/* delayCreature()
*
* Delay the action turn of the current creature
*/
delayCreature(o) {
// Send skip turn to server
if (this.multiplayer) {
this.gameplay.delay();
}
if (this.turnThrottle) {
return;
}
if (
this.activeCreature.hasWait ||
!this.activeCreature.delayable ||
this.queue.isCurrentEmpty()
) {
return;
}
o = $j.extend(
{
callback: function () {},
},
o,
);
this.turnThrottle = true;
this.UI.btnSkipTurn.changeState('disabled');
this.UI.btnDelay.changeState('disabled');
setTimeout(() => {
this.turnThrottle = false;
this.UI.btnSkipTurn.changeState('normal');
if (
!this.activeCreature.hasWait &&
this.activeCreature.delayable &&
!this.queue.isCurrentEmpty()
) {
this.UI.btnDelay.changeState('slideIn');
}
o.callback.apply();
}, 1000);
let skipTurn = new Date(),
p = this.activeCreature.player;
p.totalTimePool = p.totalTimePool - (skipTurn - p.startTime);
this.activeCreature.wait();
this.nextCreature();
}
startTimer() {
clearInterval(this.timeInterval);
this.activeCreature.player.startTime = new Date() - this.pauseTime;
this.checkTime();
this.timeInterval = setInterval(() => {
this.checkTime();
}, this.checkTimeFrequency);
}
stopTimer() {
clearInterval(this.timeInterval);
}
/* checkTime()
*/
checkTime() {
let date = new Date() - this.pauseTime,
p = this.activeCreature.player,
alertTime = 5, // In seconds
msgStyle = 'msg_effects',
totalPlayers = this.playerMode,
i;
p.totalTimePool = Math.max(p.totalTimePool, 0); // Clamp
// Check all timepools
// Check is always true for infinite time
let playerStillHaveTime = this.timePool > 0 ? false : true;
for (i = 0; i < totalPlayers; i++) {
// Each player
playerStillHaveTime = this.players[i].totalTimePool > 0 || playerStillHaveTime;
}
// Check Match Time
if (!playerStillHaveTime) {
this.endGame();
return;
}
this.UI.updateTimer();
// Turn time and timepool not infinite
if (this.timePool > 0 && this.turnTimePool > 0) {
if (
(date - p.startTime) / 1000 > this.turnTimePool ||
p.totalTimePool - (date - p.startTime) < 0
) {
if (p.totalTimePool - (date - p.startTime) < 0) {
p.deactivate(); // Only if timepool is empty
}
this.skipTurn();
return;
} else {
if ((p.totalTimePool - (date - p.startTime)) / 1000 < alertTime) {
msgStyle = 'damage';
}
if (this.turnTimePool - (date - p.startTime) / 1000 < alertTime && this.UI.dashopen) {
// Alert