-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
1719 lines (1516 loc) · 42.1 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
/**
* @file game.js
* @brief Represents the game world and all Entities within it
*/
/**
* Wrapper class for pausable timeouts associated with a Game
*/
const FINAL_LEVEL = 5;
const DIFFICULTY_LEVEL = {
baby: 0,
normal: 1,
hard: 2,
expert: 3,
rage: 4
};
function Timeout(name, onTimeout, wait, game)
{
if (game.timeouts[name])
{
game.timeouts[name].Pause();
delete game.timeouts[name];
}
this.name = name;
this.onTimeout = onTimeout;
this.id = setTimeout(function(game) {
this.onTimeout();
delete game.timeouts[this.name]}.bind(this,game), wait);
game.timeouts[this.name] = this;
this.wait = wait;
this.start = (new Date()).getTime();
this.running = true;
this.game = game;
}
/**
* Pause timeout
*/
Timeout.prototype.Pause = function()
{
if (!this.running)
return;
this.running = false;
this.wait -= (new Date()).getTime() - this.start;
clearTimeout(this.id);
//console.debug("Pause <" + this.name + "> timeout with " + String(this.wait) + "ms left");
this.wait = Math.max(this.wait, 0);
}
/**
* Resume timeout
*/
Timeout.prototype.Resume = function()
{
if (this.running)
return;
this.running = true;
//console.debug("Timeout <" + this.name + "> resumed with " + String(this.wait) + " ms remaining");
this.id = setTimeout(function(game) {
this.onTimeout();
delete game.timeouts[this.name]}.bind(this,this.game), this.wait);
}
Timeout.prototype.constructor = Timeout;
/**
* Game class
* @param canvas - HTML5 canvas element to render into
* @param audio - HTML5 audio element to use for sound
* @param document - The webpage DOM
*/
function Game(canvas, audio, document, multiplayer)
{
Debug("Construct Game");
this.document = document;
this.audio = audio;
this.level = -1;
// If true, "advertising" spash screens are shown every time a level starts/restarts
// Hacks to keep track of level durations
// Needed because some devices won't play audio so we have to check the time ourselves
// instead of using a "ended" event listener.
// Level 0 is the tutorial and doesn't end at a specified time depending on player speed
this.levelDurations = [null, 198000,150000,210000,165000,2480000];
this.backgrounds = ["data/backgrounds/forest1_cropped.jpg",
"data/backgrounds/flowers2.jpg",
"data/backgrounds/forest1_cropped.jpg",
"data/backgrounds/dark1.png",
"data/backgrounds/forest1_cropped.jpg",
"data/backgrounds/forest1_cropped.jpg"]
this.localTime = new Date();
this.canvas = new Canvas(canvas); // Construct Canvas class on the HTML5 canvas
if (this.spriteCollisions)
this.canvas.prepareSpriteCollisions = true; // unused will probably break things
this.gravity = [0, -1]; // gravity!
this.stepRate = 20; // Time we would ideally have between steps in ms (lol setTimeout)
this.timeouts = {}; // Timeouts
this.settingsElement = document.getElementById("settings");
this.statusBar = document.getElementById("statusBar");
this.canvasElement = canvas;
this.touchBarElement = document.getElementById("touchBar");
this.settings = {};
// Reference cookies from utils.js
this.cookies = cookies;
try {
this.settings = JSON.parse(window.localStorage.getItem("settings"));
if (Object.keys(this.settings).length > 0) {
console.debug("Loaded settings", this.settings);
} else {
console.debug("Applying default settings");
this.ApplySettingsForm();
}
} catch(err) {
console.debug("Error loading settings", err);
this.settings = {};
this.ApplySettingsForm();
}
this.SaveSettings();
statusBar.hidden = (this.settings.displayStatusBar === false);
// Apply the art style to touchbar buttons
if (this.settings.enableTouchBar) {
// Look it's 2021 and I learned arrow functions
["Left", "Right", "Up", "Down"].forEach(direction => {
button = document.getElementById("touch"+direction)
for (let i = 0; i < button.children.length; ++i) {
if (!button.children[i].src) {
continue;
}
newSource = button.children[0].src.replace("/humphrey/", "/"+this.settings.rabbitSprites+"/")
if (newSource != button.children[0].src) {
console.debug(`Set direction from ${button.children[0].src} to ${newSource}`);
button.children[0].src = newSource;
}
break;
}
});
}
this.running = false;
this.blockResume = false; // Used to prevent player interactions during level transition
this.runTime = 0;
this.entities = [];
this.unloadedEntities = [];
this.playedTutorial = false;
this.webSockets = [];
this.multiplayer = multiplayer;
if (this.multiplayer)
{
Debug("Open WebSocket Connection");
var con = new WebSocket("ws://localhost:7681", "ws");
con.onopen = function() {console.debug("Connected to WebSocket")}
con.onclose = function(e) {console.debug("Closed WebSocket sesame"); console.debug(e.reason); delete g_game.multiplayer;}
con.onerror = function(e) {console.debug("WebSocket Error"); console.debug(e); console.debug(String(e)); delete g_game.multiplayer;}
con.onmessage = function(e) {this.MultiplayerSync(e.data);}.bind(this); // didn't want to use a global here :(
this.webSockets.push(con);
}
this.playerCount = 1;
this.GetAdvertChoices();
}
Game.prototype.AddTimeout = function(name, onTimeout, wait)
{
if (!this.timeouts)
this.timeouts = {};
return new Timeout(name, onTimeout, wait, this);
}
Game.prototype.Pause = function(message,image , colour)
{
if (!this.running) {
console.debug('Pause requested but game not running...');
return;
}
console.debug(`Pause requested document focused: ${window.document.hasFocus()}`);
delete this.stepTime;
this.running = false;
for (var t in this.timeouts)
{
this.timeouts[t].Pause();
}
if (this.audio && typeof(this.audio.pause) === "function") {
if (!this.romanticMode) {
this.audio.pause();
}
}
this.Draw();
this.UpdateDOM(this.player);
if (message === null || image === null)
return;
if (typeof(image) === "undefined")
image = "data/rabbit/drawing2.svg";
if (typeof(colour) === "undefined")
colour = [1,1,1,1];
if (!this.romanticMode) {
console.debug("Show pause screen", message);
this.canvas.SplashScreen(image, message, colour);
} else {
this.canvas.Clear([1,0,0,1])
}
// We didn't have backticks in 2014
console.debug(`Pause completed. running=${this.running}`)
}
Game.prototype.Resume = function(forceUnblock)
{
console.debug(`Resume requested, document focused: ${window.document.hasFocus()}`);
if (forceUnblock) {
this.blockResume = false;
}
if (this.running || this.blockResume) {
console.debug("Resume was blocked. Remain paused")
return;
}
// Don't resume when settings are open
if (!this.settingsElement.hidden) {
console.debug("Resume blocked by settings panel.")
return;
}
this.canvas.cancelSplash = true;
this.UpdateDOM(this.player);
this.running = true;
for (var t in this.timeouts)
{
this.timeouts[t].Resume();
}
if (this.audio && this.settings.playMusic) {
this.audio.muted = false;
this.audio.play().catch(err => {});
}
if (typeof(this.timeouts["MainLoop"]) === "undefined")
this.MainLoop();
if (this.level > 0)
{
if (typeof(this.timeouts["AddEnemy"]) === "undefined")
this.AddTimeout("AddEnemy", function() {this.AddEnemy()}.bind(this), this.stepRate*600);
if (typeof(this.timeouts["AddCloud"]) === "undefined")
{
this.AddTimeout("AddCloud", function() {this.AddCloud()}.bind(this), this.stepRate*(1000 + Math.random()*2000));
}
}
if (!this.running) {
// Do we need this check?
this.PauseExceptMainLoop();
}
this.canvas.Clear(this.GetColour());
console.debug(`Resume completed. running=${this.running}`)
}
Game.prototype.PauseExceptMainLoop = function () {
Object.keys(this.timeouts).forEach(timeoutName => {
if (timeoutName != "MainLoop") {
this.timeouts[timeoutName].Pause();
}
})
}
Game.prototype.Start = function(level)
{
this.level = level-1;
this.NextLevel();
}
Game.prototype.SetLevel = function(level)
{
Debug("Set level " + String(level));
this.level = Math.min(level,5);
this.victoryBox = null;
this.message = ""
delete this.tutorial;
delete this.tutorialState;
for (var t in this.timeouts) {
this.timeouts[t].Pause();
delete this.timeouts[t];
}
this.Clear();
// hooray globals
if (typeof(this.settings.maxLevel) != "undefined") {
if (this.settings.maxLevel < this.level)
{
this.settings.maxLevel = this.level;
this.SaveSettings();
}
}
this.spawnedEnemies = 0;
if (this.audio)
{
if (this.romanticMode === true)
this.audio.src = "data/romanticmode.mp3";
else if (this.xmasMode === true && this.level === 1)
this.audio.src = "data/xmasmode.mp3";
else
this.audio.src = "data/theme"+this.level+".mp3";
this.audio.load();
this.audio.pause();
//this.levelDurations[this.level] = this.audio.duration*1000;
}
delete this.stepTime;
this.runTime = 0;
this.stepCount = 0;
this.keyState = [];
this.entities = [];
for (var t in this.timeouts)
{
this.timeouts[t].Pause();
delete this.timeouts[t];
}
this.timeouts = {};
this.entityCount = {};
this.deathCount = {};
// Add the walls
this.AddEntity(new Wall({min: [-Infinity,-Infinity], max:[Infinity, -1]}, "Floor")); // bottom
this.AddEntity(new Wall({min: [-Infinity,0.8], max:[Infinity,Infinity]}, "Roof")); // top
this.AddEntity(new Wall({min: [-Infinity,-Infinity], max:[-1, Infinity]})); // left
this.AddEntity(new Wall({min: [1,-Infinity], max:[Infinity, Infinity]})); // right
// Add the player
this.player = new Player([0,0],[0,0],this.gravity, this.canvas, "data/rabbit/"+this.settings.rabbitSprites);
this.AddEntity(this.player);
if (!this.romanticMode) {
this.AddEntity(this.player.wings);
}
this.player.lives += this.settings.startingLives;
if (this.multiplayer && this.playerCount && this.playerCount > 1)
{
this.multiplayer = []
this.multiplayer[this.playerID] = this.player;
this.player.playerID = this.playerID;
this.player.position[0] = -(this.player.Width()/2)*this.playerCount + this.player.Width()*this.playerID;
for (var i = 0; i < this.playerCount; ++i)
{
if (i == this.playerID) continue;
var x = -(this.player.Width()/2)*this.playerCount + this.player.Width()*i;
this.multiplayer[i] = new Player([x, 0], [0,0], this.gravity, this.canvas, "data/rabbit");
this.multiplayer[i].playerID = i;
this.AddEntity(this.multiplayer[i]);
}
}
// Add VictoryBox if the player already completed this level
// console.debug(`Current level: ${this.level}, vs maxLevel: ${this.settings.maxLevel}`)
if (this.level < this.settings.maxLevel && this.level < FINAL_LEVEL && this.level > 0) {
if (DIFFICULTY_LEVEL[this.settings.difficulty] > DIFFICULTY_LEVEL.hard) {
console.debug("Victory Box canceled by difficulty != normal", this.settings.difficulty);
} else {
this.AddVictoryBox();
}
}
/** level specific code goes below here **/
//TODO: Make NaN and Infinity levels
for (var i = 0; i < Math.min(this.level*2,6); ++i) {
this.AddHat();
}
if (this.level == 2)
{
this.AddEntity(new Ox([0,1],[0,0],this.gravity,this.canvas));
}
if (this.level == 3)
{
this.AddEntity(new Ox([-0.8,1],[0,0],this.gravity,this.canvas));
this.AddEntity(new Wolf([-0.8,1],[0,0],this.gravity,this.canvas));
}
if (this.level == 4)
{
this.AddEntity(new Ox([0,1],[0,0],this.gravity,this.canvas));
this.AddEntity(new Wolf([0.8,1],[0,0], this.gravity, this.canvas));
this.AddEntity(new Wolf([-0.8,1],[0,0],this.gravity,this.canvas));
}
if (this.level == 5)
{
this.AddEntity(new Rox([-0.8,0],[0,0],this.canvas));
}
if (this.level == 6)
{
this.AddEntity(new Rox([-0.8,0.7],[0,0],this.canvas));
this.AddEntity(new Rox([+0.8,-0.3],[0,0],this.canvas));
}
if (isNaN(this.level))
{
this.player.LoadSprites(this.canvas, "data/fox");
}
this.canvas.SetBackground(this.backgrounds[this.level]);
Debug("");
}
/** Get background draw colour (in OpenGL RGBA) **/
Game.prototype.GetColour = function()
{
if (this.romanticMode === true)
return [1,0.9,0.9,1];
else if (this.xmasMode === true && this.level === 1)
return [0.9,0.9,1,1];
else if (this.level == 0)
return [0.9,1,0.9,1];
else if (this.level == 1)
return [0.9,0.9,1,1];
else if (this.level == 2)
return [0.8,0.6,0.6,1];
else if (this.level == 3)
return [1.0,0.9,0.8,1];
else if (this.level == 4)
return [1.0,0.7,1.0,1];
else if (this.level == 5)
return [0.6,0.5,0.5,1];
return [1,1,1,1];
}
/**
* Populate list of advertisements
*/
Game.prototype.GetAdvertChoices = async function() {
return HttpGet("data/adverts/index.json").then(response => {
console.debug('Retrieved advertisements list');
try
{
sortedChoices = JSON.parse(response);
this.advertChoices = [];
while (sortedChoices.length > 0) {
const priorLength = sortedChoices.length;
var index = Math.floor(Math.slowRandom()*sortedChoices.length);
this.advertChoices.push(sortedChoices[index]);
var lhs = sortedChoices.slice(0,index);
var rhs = sortedChoices.slice(index+1);
sortedChoices = [...lhs,...rhs];
}
console.debug('advertChoices', this.advertChoices);
this.advertChoiceIndex = 0;
}
catch (err)
{
console.error('Error getting advertisment that was listed in the index.json:', err);
Promise.reject(err);
}
});
}
/**
* Pick an advert to show; on the first call it will HTTP GET the list of adverts
* @param trial - Used to stop recursion
*/
Game.prototype.ChooseAdvert = function()
{
if (g_usingAdblocker) {
return "br0whyuh8ad.svg";
}
if (!this.advertChoices) {
this.GetAdvertChoices();
}
if (this.advertChoices) {
console.debug('Choice index', this.advertChoiceIndex, ' of ', this.advertChoices.length);
// Go through the adverts in order
return "data/adverts/" + this.advertChoices[this.advertChoiceIndex++ % this.advertChoices.length];
}
}
/**
* Progress to the Next Level
* @param skipAd - Used to prevent recursion
*/
Game.prototype.NextLevel = function(skipAd, from)
{
this.blockResume = true;
if (!this.romanticMode) {
this.Pause("Loading...");
}
if (from) {
this.level = from;
}
const targetLevel = this.level + 1;
if (this.settings.showAdverts && !skipAd
// Always bypass ad when going to tutorial, since it could be confusing
&& targetLevel > 0
&& !this.romanticMode)
{
// Make the splash screen then call NextLevel (with the skipAd flag
// to prevent recursing infinitely)
const advertChoice = this.ChooseAdvert();
if (advertChoice) {
console.debug("Loading advert", advertChoice);
this.canvas.SplashScreen(advertChoice, "",[1,1,1,1], function() {
console.debug("Rendered advert", advertChoice);
this.AddTimeout("Advert", this.NextLevel.bind(this,true), 4000);
}.bind(this));
return;
} else {
console.debug('Curses you foiled my adblock detector');
g_usingAdblocker = true;
}
}
this.SetLevel(targetLevel);
this.Clear();
this.Draw();
var boss;
var taunt;
var colour;
var message;
// The tutorial is optional
if (false) //if (this.level == 0 && !confirm("Play the tutorial?\nIf you haven't before you really want to.\n\nTrust me."))
{
return this.NextLevel(true); // Skip to level 1
}
switch (this.level)
{
case 0:
boss = "data/rabbit/drawing3.svg";
taunt = "Tutorial Time!";
message = "Prepare to be amazed by the physics engine.";
colour = [0.5,0.5,0.9,1];
break;
case 1:
//this.Resume();
//return;
boss = "data/fox/drawing1.svg";
taunt = message = "Fox Time.";
message = "And so our dance begins..."
colour = [0.9,0.5,0.5,1];
break;
case 2:
boss = "data/ox/drawing1.svg";
taunt = message = "Ox Time.";
message = "The plot thickens...";
colour = [0.9,0.5,0.5,1];
break;
case 3:
boss = "data/wolf/drawing1.svg";
taunt = "Wolf Time.";
message = "Bad Wolf";
colour = [0.9,0.5,0.5,1];
break;
case 4:
boss = "data/wolf/drawing1.svg";
taunt = "More wol";
var choice = Math.round((new Date()).getTime()/1e3) % 6;
switch (choice)
{
case 0:
taunt += "fs";
break;
case 1:
taunt += "ves";
break;
case 2:
taunt += "fen";
break;
case 3:
taunt += "vies";
break;
case 4:
taunt += "fies";
break;
case 5:
taunt = "Wolf Brother Time!";
break;
}
if (choice != 5)
{
taunt += ". Because lazy developer.";
}
message = "Wolfs are pack animals FYI.";
colour = [0.9,0.5,0.5,1];
break;
case 5:
boss = "data/rox/drawing1.svg";
taunt = "It is time to Roc.";
message = "(With sincere apologies to Ronny James Dio)";
colour = [0.9,0.5,0.5,1];
break;
default:
if (isNaN(this.level))
{
boss = "data/rabbit/drawing2.svg";
taunt = "Role Reversal Time!";
colour = [0.9,0.5,0.5,1];
}
else
{
boss = "data/rabbit/drawing2.svg";
taunt = "Mystery Level?";
colour = [0.9,0.5,0.5,1];
}
break;
}
if (!this.romanticMode) {
// Show splash screen, then start level
this.canvas.SplashScreen(boss, taunt, colour, function() {
this.AddTimeout("Level"+String(this.level),
function() {
this.Resume(true);
//this.MultiplayerWait("level");
if (this.level == 0) // Hacky but more concise
this.Tutorial("start");
}.bind(this) ,2000);
this.Message(message, 2000);
}.bind(this));
} else {
this.canvas.Clear([0.8,0,0]);
this.AddTimeout("Level"+String(this.level),
function() {
this.Resume(true);
}.bind(this),
2000);
}
}
/**
* Add a Fox
*/
Game.prototype.AddFox = function() {
var targetPlayer = this.GetTargetPlayer();
var enemy = new Fox([targetPlayer.position[0], 1],[0,0], this.gravity, this.canvas)
this.AddEntity(enemy);
return enemy;
}
/**
* Add a Box
*/
Game.prototype.AddBox = function() {
var targetPlayer = this.GetTargetPlayer();
var enemy = new Box([targetPlayer.position[0], 1],[0,0], this.gravity, this.canvas)
enemy.angle = [0, Math.PI/2, Math.PI, 3*Math.PI/2][rand() % 4]
// hack for Christmas and Romantic Mode)
if (this.xmasMode === true)
{
enemy.frame = this.canvas.LoadTexture("data/box/box_xmas"+enemy.index+".gif");
enemy.damagedFrame = enemy.frame; // you can't hurt the merry
}
else if (this.romanticMode === true)
{
enemy.frame = this.canvas.LoadTexture("data/box/box_valentine.gif");
enemy.damagedFrame = enemy.frame; // you can't hurt the lovely
enemy.angle = [0, Math.PI/4, Math.PI/2, 3*Math.PI/4, Math.PI, 5*Math.PI/4, 3*Math.PI/2,7*Math.PI/4][rand() % 4]
}
this.AddEntity(enemy);
return enemy;
}
/**
* Add an Enemy and then set a timeout to call AddEnemy again
* This should only be called once at the start of a level
*/
Game.prototype.AddEnemy = function()
{
var enemy;
this.spawnedEnemies += 1;
if (this.level > 0 && this.level < 5 &&
(this.spawnedEnemies % (6-Math.min(4,this.level))) == 0 &&
(!this.entityCount["Fox"] || this.entityCount["Fox"] < 2+this.level))
{
enemy = this.AddFox();
}
else
{
enemy = this.AddBox();
}
if (this.spawnedEnemies % 10 == 0)
{
if (Math.random() >= 0.25) {
this.AddHat();
} else {
this.AddCarrot();
}
}
var enemyTimeout = this.stepRate*300/Math.min(Math.pow(this.level,0.5),1);
if (this.romanticMode) {
enemyTimeout -= (this.runTime / 100);
}
console.debug(`Created enemy type ${enemy.GetName()} - next AddEnemy in ${enemyTimeout}`)
// Timeout for next call to this function:
var timeoutInstance = this.AddTimeout("AddEnemy", function() {
this.AddEnemy()
}.bind(this), enemyTimeout);
// Pause the timeout if the global game state is paused
if (!this.running && timeoutInstance) {
console.debug("Game not running after AddEnemy; force pause the timeout");
timeoutInstance.Pause()
}
}
/**
* Add a Cloud and then set a timeout to call AddCloud again
* This should only be called once at the start of a level
*/
Game.prototype.AddCloud = function()
{
var x = Math.random() > 0.5 ? 1.1 : -1.1;
var y = 0.8*Math.random();
this.AddEntity(new Cloud([x, y],this.canvas));
this.AddTimeout("AddCloud", function() {this.AddCloud()}.bind(this), this.stepRate*(4000 + Math.random()*6000)/Math.min(Math.pow(this.level,0.5),1));
if (!this.running)
this.timeouts["AddCloud"].Pause();
}
/**
* Add a Hat and... don't set a timeout to add one again
* (Yeah I should have named those other functions better I guess)
*/
Game.prototype.AddHat = function()
{
if (this.romanticMode) {
return this.AddEnemy(); // why would anyone want this
}
var targetPlayer = this.GetTargetPlayer();
var hat = new Hat([targetPlayer.position[0], 1], [0,0], [0.8*this.gravity[0], 0.8*this.gravity[1]], this.canvas);
this.AddEntity(hat);
}
/**
* Add a Carrot
*/
Game.prototype.AddCarrot = function()
{
if (this.romanticMode) {
return this.AddEnemy();
}
var targetPlayer = this.GetTargetPlayer();
var carrot = new Carrot([targetPlayer.position[0], 1], [0,0], [0.8*this.gravity[0], 0.8*this.gravity[1]], this.canvas);
this.AddEntity(carrot);
}
/**
* Add an Entity; optimises use of this.entities array
*/
Game.prototype.AddEntity = function(entity)
{
if (this.canvas.AreImagesLoaded() !== true && entity.GetName() !== "SFX") {
console.debug(`${entity.GetName()} not yet loaded (probably)`);
this.PauseExceptMainLoop();
this.unloadedEntities.push(entity);
return;
}
for (var i = 0; i < this.entities.length; ++i)
{
if (!this.entities[i])
{
this.entities[i] = entity;
return;
}
}
if (!this.entityCount[entity.GetName()])
{
this.entityCount[entity.GetName()] = 1;
}
else
{
this.entityCount[entity.GetName()] += 1;
}
console.debug(`Adding new ${entity.GetName()}`);
this.entities.push(entity);
return entity;
}
/**
* Spawn new entity (given its constructor function) at another entity's position
*/
Game.prototype.SpawnEntity = function(constructor, other)
{
var entity = new constructor(other.position, other.velocity, other.acceleration, this.canvas, this);
this.AddEntity(entity);
}
/**
* Key was pressed
* Warning: Magic keycode numbers incoming
*/
Game.prototype.KeyDown = function(event)
{
this.userInteracted = true;
if (!this.keyState)
this.keyState = [];
if ([32,37,38,39,40].indexOf(event.keyCode) > -1 && event.preventDefault) {
event.preventDefault();
}
if (this.keyState[event.keyCode] === true)
return;
this.keyState[event.keyCode] = true;
if (event.keyCode == 192) {
this.ToggleSettings();
return;
}
if (event.keyCode == 32 || event.keyCode == 27) // space or escape
{
if (this.running && !this.player.hidden)
{
this.Pause("Paused");
this.playerPaused = this.playerID;
this.Message("Focus tab, press any key");
}
else if (this.player && this.player.alive && !this.player.hidden)
{
if (this.playerPaused == this.playerID)
{
this.Resume();
this.Message("");
}
}
}
if (event.keyCode >= 48 && event.keyCode <= 53 && devtools.open)
{
this.Pause();
this.SetLevel(event.keyCode-48);
if (this.level == 0) {
this.Tutorial("start");
}
this.Resume();
}
if (!this.webSockets)
return;
for (var i = 0; i < this.webSockets.length; ++i)
{
this.webSockets[i].send("+"+event.keyCode+"\n");
}
}
/**
* Key was released
*/
Game.prototype.KeyUp = function(event)
{
if (!this.keyState)
this.keyState = [];
if (this.keyState[event.keyCode] !== true)
return;
this.keyState[event.keyCode] = false;
if (!this.webSockets)
return;
for (var i = 0; i < this.webSockets.length; ++i)
{
this.webSockets[i].send("-"+event.keyCode+"\n");
}
}
Game.prototype.TouchDown = function(event)
{
if (event.preventDefault) {
event.preventDefault()
}
if (!this.running && this.player && this.player.alive && !this.player.hidden
&& (!this.multiplayer || this.multiplayer.length <= 1))
{
this.Resume();
}
this.keyState = [];
if (!this.player || !this.canvas)
return;
//alert("TouchDown at "+String(event.clientX) +","+String(event.clientY));
var delx = ((2*event.clientX/this.canvas.width)-1) - this.player.position[0];
var dely = (1-2*(event.clientY/this.canvas.height)) - this.player.position[1];
// note y coordinate positive direction is reversed in GL (game) coords vs canvas coords
//this.Message("TouchDown "+String(delx)+","+String(dely));
if (delx >= this.player.Width())// || event.clientX > 0.8*this.canvas.width)
{
this.KeyDown({keyCode : 39});
}
else if (delx <= -0*this.player.Width())// || event.clientX < 0.2*this.canvas.width)
{
this.KeyDown({keyCode : 37});
}
if (dely >= 3*this.player.Height())// || event.clientY < 0.2*this.canvas.height)
{
this.KeyDown({keyCode : 38});
}
else if (dely <= -3*this.player.Height())// || event.clientY > 0.8*this.canvas.height)
{
this.KeyDown({keyCode : 40});
}
}
/**
* Touch is released
*/
Game.prototype.TouchUp = function(event)
{
//this.Message("TouchUp at "+String([event.clientX, event.clientY]));
if (event.preventDefault) {
event.preventDefault();
}
for (var k in this.keyState)
{
this.KeyUp({keyCode : k});
}
this.keyState = [];
}
/**
* Mouse is clicked inside the canvas
*/
Game.prototype.MouseDown = function(event)
{
this.mouseDown = true;
this.TouchDown(event);
}
/**
* Mouse is released
* Buggy - doesn't get called if mouse is released outside of the canvas
*/
Game.prototype.MouseUp = function(event)
{
if (event.preventDefault) {
event.preventDefault()
}
if (this.mouseDown)
{
this.mouseDown = false;
this.TouchUp(event);
}
}