-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgame.bundle.js
1315 lines (1110 loc) · 52 KB
/
game.bundle.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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports={
"blocks": [[45,345], [90,345], [45,330], [60,330], [75,330], [90,330], [60,315], [75,315],
[150,345], [195,345], [150,330], [165,330], [180,330], [195,330], [165,315], [180,315],
[255,345], [300,345], [255,330], [270,330], [285,330], [300,330], [270,315], [285,315]],
"invaders": [[0,0],[25,0],[50,0],[75,0],[100,0],[125,0],[150,0],[175,0],[200,0],[225,0],[250,0],[275,0],
[0,25],[25,25],[50,25],[75,25],[100,25],[125,25],[150,25],[175,25],[200,25],[225,25],[250,25],[275,25],
[0,50],[25,50],[50,50],[75,50],[100,50],[125,50],[150,50],[175,50],[200,50],[225,50],[250,50],[275,50],
[0,75],[25,75],[50,75],[75,75],[100,75],[125,75],[150,75],[175,75],[200,75],[225,75],[250,75],[275,75],
[0,100],[25,100],[50,100],[75,100],[100,100],[125,100],[150,100],[175,100],[200,100],[225,100],[250,100],[275,100],]
}
// 31 rows
// 24 cols
},{}],2:[function(require,module,exports){
// /core/game.collision.js
/** Game Collision Module
* Called by the game loop, this module will
* use the game state to check for any collision
* that has taken place in the game.
* It will call all collided entities `collision` methods.
*/
function gameCollision(scope) {
return function collision(tFrame) {
var state = scope.state || {};
// Cleans up entities that are `killed` flagged
// Reset state of used bullets and move them to `inactiveEntites` to be reused
function cleanUpDeadEntities(entities) {
for (var entity in entities) {
if (entities[entity].hasOwnProperty('state') && entities[entity].state.killed) {
if (entities[entity].group === 'bullet') {
entities[entity].reset();
state.inactiveEntities.bullets.push(entities[entity]);
}
delete state.entities[entity];
}
}
return;
}
// If there are entities, iterate through them and if two have collided
// then call their `collision` method.
if (state.hasOwnProperty('entities')) {
var entities = state.entities;
for (var entity in entities) {
// If entity is killed or doesn't collide, skip entity collision check
if (!entities[entity].collides || entities[entity].state.killed) {
continue;
}
// Loop through entities and see if collision has occured
for (var entityOther in entities) {
// If entity can collide, and is not colliding with itself, and is not `killed` flagged,
// and both entites are not of the same group. Then call their `collision` methods.
if (entities[entityOther].collides && entityOther !== entity && !entities[entityOther].state.killed && !entities[entity].state.killed && entities[entity].group !== entities[entityOther].group) {
if (entities[entity].hasCollidedWith(entities[entityOther])) {
entities[entity].collision(entities[entityOther]);
entities[entityOther].collision(entities[entity]);
break;
}
}
}
}
cleanUpDeadEntities(entities); // Clean up any entities that got killed during collision
}
return state;
};
}
module.exports = gameCollision;
},{}],3:[function(require,module,exports){
// /core/game.loop.js
/** Game Loop Module
* This module contains the game loop, which handles
* updating the game state and re-rendering the canvas
* (using the updated state) at the configured FPS.
* (https://github.com/aesinv/javascript-game-demo)
*/
function gameLoop(scope) {
var loop = {};
// Initialize timer variables so we can calculate FPS
var fps = scope.constants.targetFps, // Our target fps
fpsInterval = 1000 / fps, // the interval between animation ticks, in ms (1000 / 60 = ~16.666667)
before = window.performance.now(), // The starting times timestamp
// Set up an object to contain our alternating FPS calculations
cycles = {
new: {
frameCount: 0, // Frames since the start of the cycle
startTime: before, // The starting timestamp
sinceStart: 0 // time elapsed since the startTime
},
old: {
frameCount: 0,
startTime: before,
sineStart: 0
}
},
// Alternating Frame Rate vars
resetInterval = 5, // Frame rate cycle reset interval (in seconds)
resetState = 'new'; // The initial frame rate cycle
loop.fps = 0; // A prop that will expose the current calculated FPS to other modules
// Main game rendering loop
loop.main = function mainLoop (tframe) {
// Request a new Animation Frame
// setting to `stopLoop` so animation can be stopped via
// `window.cancelAnimationFrame( loop.stopLoop )`
loop.stopLoop = window.requestAnimationFrame( loop.main );
// How long ago since last loop?
var now = tframe,
elapsed = now - before,
activeCycle, targetResetInterval;
// If it's been at least our desired interval, render
if (elapsed > fpsInterval) {
// Set before = now for next frame, also adjust for
// specified fpsInterval not being a multiple of rAF's interval (16.7ms)
// ( http://stackoverflow.com/a/19772220 )
before = now - (elapsed % fpsInterval);
// Increment the vals for both the active and the alternate FPS calculations
for (var calc in cycles) {
++cycles[calc].frameCount;
cycles[calc].sinceStart = now - cycles[calc].startTime;
}
// Choose the correct FPS calculation, then update the exposed fps value
activeCycle = cycles[resetState];
loop.fps = Math.round(1000 / (activeCycle.sinceStart / activeCycle.frameCount) * 100) / 100;
// If our frame counts are equal....
targetResetInterval = (cycles.new.frameCount === cycles.old.frameCount ? resetInterval * fps // Wait our interval
: (resetInterval * 2) * fps); // Wait double our interval
// If the active calculation goes over our specified interval,
// reset it to 0 and flag our alternate calculation to be active
// for the next series of animations.
if (activeCycle.frameCount > targetResetInterval) {
cycles[resetState].frameCount = 0;
cycles[resetState].startTime = now;
cycles[resetState].sinceStart = 0;
resetState = (resetState === 'new' ? 'old' : 'new');
}
// Update the game state
scope.update(now);
// Calculate collisions in state
scope.collision();
// Render the next frame
scope.render();
}
};
// Start off main loop
loop.main();
return loop;
}
module.exports = gameLoop;
},{}],4:[function(require,module,exports){
// /core/game.render.js
/** Game Render Module
* Called by the game loop, this module will
* use the game state to re-render the canvas.
* Additionally, it will call all game entities `render` methods.
*/
function gameRender(scope) {
// Setup globals
var w = scope.constants.width,
h = scope.constants.height,
offset = scope.constants.offset;
return function render() {
// Clear out the canvas
scope.context.clearRect(0, 0, w, h);
scope.context.font = '26px Courier';
// If game has been started draw bottom score board divider
if (scope.state.start) {
scope.context.strokeStyle = '#40d870';
scope.context.beginPath();
scope.context.moveTo(0, h - (offset - 5));
scope.context.lineTo(w, h - (offset - 5));
scope.context.lineWidth = 1;
scope.context.stroke();
scope.context.lineWidth = 1;
}
// If we want to show the FPS, then render it in the top right corner.
if (scope.constants.showFps) {
scope.context.fillStyle = '#ff0';
scope.context.fillText(~~scope.loop.fps, w - 50, 30);
}
// If there are entities, iterate through them and call their `render` methods
if (scope.state.hasOwnProperty('entities')) {
var entities = scope.state.entities;
// Loop through entities
for (var entity in entities) {
// Fire off each active entities `render` method
entities[entity].render(scope);
}
}
};
}
module.exports = gameRender;
},{}],5:[function(require,module,exports){
// /core/game.update.js
var gameScore = require('../utils/utils.score.js');
/** Game Update Module
* Called by the game loop, this module will
* perform any state calculations / updates
* to properly render the next frame.
*/
function gameUpdate(scope) {
return function update(tFrame) {
var state = scope.state || {};
gameScore(scope); // Call before we update entities to see if player has lost / won
// If there are entities, iterate through them and call their `update` methods
if (state.hasOwnProperty('entities')) {
var entities = state.entities;
// Loop through entities
for (var entity in entities) {
// If `entity` was `killed` flagged skip `entity`
// Dead entities will get cleaned up in the collision module
if (entities[entity].hasOwnProperty('state') && entities[entity].state.killed) {
continue;
} else {
// Fire off each active entities `update` method
entities[entity].update(scope, tFrame);
}
}
}
return state;
};
}
module.exports = gameUpdate;
},{"../utils/utils.score.js":17}],6:[function(require,module,exports){
// /entities/blocks.js
var Point = require('../utils/utils.math.js').Point;
var Entity = require('./entity.js');
/** Block Module
* Contains the Block Object Constructor
* and the helper function for creating the blocks.
*/
// Create our blocks
function createBlocks(scope, map) {
// Setup block constants
var VELOCITY = 0,
HEALTH = 1,
SPRITE_HEIGHT = 15,
SPRITE_WIDTH = 15,
SPRITE_IMAGE = null,
GROUP_NAME = 'block',
NUM_OF_BLOCKS = 24;
var sprite = {
height: SPRITE_HEIGHT,
width: SPRITE_WIDTH,
image: SPRITE_IMAGE
};
// Instantiate the delegate object (reference to a prototype chain of methods)
// allows group entities to share render / update / collison methods
// over the delegate objects prototype chain.
// Uses a form of Parasitic inheritance.
var delegateObj = new Block();
// Creates all the blocks and their delegate methods
for (var i = 0, block = {}; i < NUM_OF_BLOCKS; i++) {
block = new Entity(GROUP_NAME, new Point(map[i][0], map[i][1]), VELOCITY, HEALTH, sprite);
block.delegate = delegateObj;
scope.state.entities[block.id] = block;
}
}
// Object constructor for our blocks,
function Block() {}
// Block render method
Block.prototype.render = function blockRender (scope){
scope.context.drawImage(
scope.sprites.block,
this.state.position.x,
this.state.position.y,
this.sprite.width,
this.sprite.height);
return this;
};
// Block update method
Block.prototype.update = function blockUpdate (scope) {
return this;
};
// Block collision method
Block.prototype.collision = function blockCollision (entity) {
// Doesn't matter which bullet a block has collided with, result is the same
if (entity.group === 'bullet') {
this.kill();
}
return this;
};
module.exports = createBlocks;
},{"../utils/utils.math.js":15,"./entity.js":8}],7:[function(require,module,exports){
// /entities/Bullet.js
var Point = require('../utils/utils.math.js').Point;
var Entity = require('./entity.js');
/** Bullet Module
* Contains the Bullet Object Constructor
* and the helper function for creating the bullets.
*/
// Create our bullets
function createBullets(scope) {
// Setup bullet constants
var SPRITE_HEIGHT = 8,
SPRITE_WIDTH = 3,
//SPRITE_COLOR = '#E7E7E7',
SPRITE_COLOR = '#EA1D1D',
SPRITE_IMAGE = null,
BULLET_VELOCITY = -6,
BULLET_HEALTH = 1,
BULLET_GROUP_NAME = 'bullet',
BULLET_POINT = null,
NUM_OF_BULLETS = 50;
var sprite = {
color: SPRITE_COLOR,
defaultColor: SPRITE_COLOR,
height: SPRITE_HEIGHT,
width: SPRITE_WIDTH,
image: SPRITE_IMAGE
};
// Instantiate the delegate object (reference to a prototype chain of methods)
// allows group entities to share render / update / collison methods
// over the delegate objects prototype chain.
// Uses a form of Parasitic inheritance.
var delegateObj = new Bullet();
// Instantiate bullets to store as inactive entities,
// this prevent the game from doing uncesseray instantiations every time a bullet is fired
for (var n = 0, bullet = {}; n < NUM_OF_BULLETS; n++) {
bullet = new Entity(BULLET_GROUP_NAME, BULLET_POINT, BULLET_VELOCITY, BULLET_HEALTH, sprite);
bullet.delegate = delegateObj;
bullet.pc = false; // `pc` property defaults to player(false), otherwise invader(true)
scope.state.inactiveEntities.bullets.push(bullet);
}
}
// Bullet object constructor
function Bullet() {}
// Bullet render method
Bullet.prototype.render = function bulletRender (scope) {
scope.context.fillStyle = this.sprite.color;
scope.context.fillRect(
this.state.position.x,
this.state.position.y,
this.sprite.width,
this.sprite.height
);
};
// Bullet update method
Bullet.prototype.update = function bulletUpdate (scope) {
var point = new Point(0, this.state.position.y);
// If bullet is in boundary, update movement,
// otherwise set `killed` flag and remove before next update.
if (this.inBoundary(scope)) {
this.state.position.y += this.state.velocity; // Bullet direction is velocity dependent pos/neg
} else {
this.kill();
return this;
}
};
// Bullet collision method
Bullet.prototype.collision = function (entity) {
if (entity.group === 'player' && this.pc) { // (this.pc) Player's bullets can't collide with player
this.kill();
} else if (entity.group === 'invader' && !this.pc) { // (!this.pc) Invader's bullets can't collide with invader
this.kill();
} else if (entity.group === 'block') {
this.kill();
}
return this;
};
// Bullet reset method
Bullet.prototype.reset = function () {
this.state.killed = false;
this.pc = false;
this.state.velocity = -Math.abs(this.state.velocity); // Restore velocity to default negative number
this.sprite.color = this.sprite.defaultColor;
// console.log('defaultColor', this.sprite.defaultColor);
return this;
};
module.exports = createBullets;
},{"../utils/utils.math.js":15,"./entity.js":8}],8:[function(require,module,exports){
// /entities/entity.js
/** Entity Module
* Contains the main Entity Object Constructor
*/
function Entity(groupName, point, velocity, health, sprite) {
// Every entity gets a unique `id`
Object.defineProperty( this, 'id', { value: Entity.prototype.count++ } );
this.group = groupName;
this.collides = true;
this.delegate = {};
var x = 0,
y = 0,
spriteHeight = 0,
spriteWidth = 0,
spriteImage = null,
entityVelocity = velocity || 0;
entityHealth = health || 1;
if (point) {
x = point.x;
y = point.y;
}
if (sprite) {
spriteColor = sprite.color;
spriteDefaultColor = sprite.defaultColor || null;
spriteHeight = sprite.height;
spriteWidth = sprite.width;
spriteImage = sprite.image;
}
// Create the initial state
this.state = {
killed: false,
position: {
x: x,
y: y
},
velocity: entityVelocity,
health: entityHealth
};
this.sprite = {
color: spriteColor,
defaultColor: spriteDefaultColor,
height: spriteHeight,
width: spriteWidth,
image: spriteImage
};
return this;
}
Entity.prototype.count = 0; // Init the `id` count
// Called on an entity with the current game state
// returns `true` if entity position is inside game boundary.
Entity.prototype.inBoundary = function (scope) {
var maxHeight = scope.constants.height - this.sprite.height - scope.constants.offset,
maxWidth = scope.constants.width - this.sprite.width,
x = this.state.position.x,
y = this.state.position.y;
if (x < 0 || x > maxWidth) return false;
if (y < 0 || y > maxHeight) return false;
return true;
};
// 2D rect collision detection based of:
// https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
Entity.prototype.hasCollidedWith = function (entity) {
var rect1 = { x: this.state.position.x, y: this.state.position.y, width: this.sprite.width, height: this.sprite.height };
var rect2 = { x: entity.state.position.x, y: entity.state.position.y, width: entity.sprite.width, height: entity.sprite.height };
return rect1.x < rect2.x + rect2.width && rect1.x + rect1.width > rect2.x && rect1.y < rect2.y + rect2.height && rect1.height + rect1.y > rect2.y;
};
// Set entity `killed` flag to `true`
Entity.prototype.kill = function () {
this.state.killed = true;
return this;
};
// Delegates to our delegate objects methods on its prototype chain
Entity.prototype.update = function () {
return this.delegate.update.apply(this, arguments);
};
Entity.prototype.render = function () {
return this.delegate.render.apply(this, arguments);
};
Entity.prototype.collision = function () {
return this.delegate.collision.apply(this, arguments);
};
Entity.prototype.reset = function () {
return this.delegate.reset.apply(this, arguments);
};
module.exports = Entity;
},{}],9:[function(require,module,exports){
// /entities/invader.js
var Point = require('../utils/utils.math.js').Point;
var getRandomInt = require('../utils/utils.math.js').getRandomInt;
var Entity = require('./entity.js');
/** Invader Module
* Contains main wrapper Invaders Object constructor,
* Invader Object constructor and helper function for creating the invaders.
*
* Main Invaders Constructor holds all invaders and delegates its methods trough
* the Invader delegate Object, which in turn delegates
* its methods to the each invader entitie.
*/
function createInvaders(scope, map) {
// Setup invader constants
var INVADER_VELOCITY = 1,
INVADERS_VELOCITY_STEP = 0.02,
INVADER_HEALTH = 1,
INVADER_SPRITE_HEIGHT = 18,
INVADER_SPRITE_WIDTH = 18,
INVADER_SPRITE_IMAGE = null,
INVADER_GROUP_NAME = 'invader',
NUM_OF_INVADERS = 60; // (5 rows * 12 cols)
var invaderImages = [
scope.sprites['invader-1'],
scope.sprites['invader-2'],
scope.sprites['invader-3'],
scope.sprites['invader-4'],
scope.sprites['invader-5']];
var invaderSprite = {
height: INVADER_SPRITE_HEIGHT,
width: INVADER_SPRITE_WIDTH,
image: INVADER_SPRITE_IMAGE
};
// Instantiate the wrapper for all our entities
var invaders = new Entity('invaders');
invaders.collides = false; // Delegate Object for our entites will not have a collision method
invaders.before = null; // Helper property for time calc with tFrame
invaders.velocityStep = INVADERS_VELOCITY_STEP; // Each invader's step to update each frame
invaders.state.velocity = INVADER_VELOCITY; // Init velocity
invaders.sprite = {
height: INVADER_SPRITE_HEIGHT * 5, // 5 rows of invaders
width: INVADER_SPRITE_WIDTH * 12, // 12 invaders in every row
image: null
};
invaders.delegate = new Invaders(); // Instantiate our delegate object
scope.state.entities[invaders.id] = invaders;
// Instantiate the delegate object for invader entity
var delegateObj = new Invader();
// Instantiate all the invaders and set them as active entities in the game state
for (var i = 0, invader = {}; i < NUM_OF_INVADERS; i++) {
if (i <= 11) invaderSprite.image = invaderImages[0];
if (i > 11 && i <= 23) invaderSprite.image = invaderImages[1];
if (i > 23 && i <= 35) invaderSprite.image = invaderImages[2];
if (i > 35 && i <= 47) invaderSprite.image = invaderImages[3];
if (i > 47) invaderSprite.image = invaderImages[4];
invader = new Entity(INVADER_GROUP_NAME, new Point(map[i][0], map[i][1]), INVADER_VELOCITY, INVADER_HEALTH, invaderSprite);
invader.delegate = delegateObj;
scope.state.entities[invader.id] = invader;
}
return this;
}
// Invader object constructor
// acts as the wrapper for our invader entities
function Invaders() {}
// Are left empty, they are handled on `Entity` level
Invaders.prototype.render = function () { return this; };
Invaders.prototype.collison = function () { return this; };
// Main update method for all our invaders
Invaders.prototype.update = function invadersUpdate (scope, tFrame) {
var entities = scope.state.entities;
var dimensionMarkers = {};
var entityIdBuffer = [];
var elapsed = 0;
var MIN_MS_FIRE = 2000;
// Get the current dimensions edge marker so that we can determine
// when the invaders have reached an inner/outer edge.
function getDimensions(arr) {
var bottom = new Dimension(0, null);
var right = new Dimension(0, null);
var left = new Dimension(999999, null);
function Dimension(num, id) {
this.num = num;
this.id = id;
return this;
}
// Perform calc to determine dimensions
for (var i = 0; i < arr.length; i++) {
if (entities[arr[i]].state.position.y > bottom.num) {
bottom.num = entities[arr[i]].state.position.y;
bottom.id = arr[i];
}
if (entities[arr[i]].state.position.x > right.num) {
right.num = entities[arr[i]].state.position.x;
right.id = arr[i];
}
if (entities[arr[i]].state.position.x < left.num) {
left.num = entities[arr[i]].state.position.x;
left.id = arr[i];
}
}
return { bottom: bottom.id, right: right.id, left: left.id };
}
// Update all invader entities in the vertical direction
function moveAllVertical(arr) {
arr.forEach(function (id) {
entities[id].state.position.y += entities[id].sprite.height;
}, this);
}
// Update all invader entities in the horizontal direction
function moveAllHorizontal(arr) {
arr.forEach(function (id) {
entities[id].state.position.x += this.state.velocity;
}, this);
}
// Fires a bullet from a random entity
function fireRandomBullet() {
var randomNum = getRandomInt(0, entityIdBuffer.length);
var entity = entities[entityIdBuffer[randomNum]]; // returns a random entity constrained to our `entityIdBuffer`
// Takes one of the inactive bullet entities from our array
// and set its position to the random selected entity
var bullet = scope.state.inactiveEntities.bullets.pop();
bullet.state.velocity *= -1; // switch bullet direction
bullet.pc = true; // set bullet to `pc`
//bullet.sprite.color = '#EA1D1D'; // set bullet sprite color
bullet.state.position.x = entity.state.position.x + (entity.sprite.width / 2) - (bullet.sprite.width / 2);
bullet.state.position.y = entity.state.position.y;
scope.state.entities[bullet.id] = bullet; // Place bullet in our active state of entities
}
// Loop over all entites and store each entity's `id` in a buffer array
// and check if any invader has reached the surface.
for (var entity in entities) {
if (entities[entity].group === 'invader') {
// If invaders reaches the surface then player has lost the game
if (entities[entity].state.position.y > scope.constants.height - scope.constants.offset - entities[entity].sprite.height) {
game.state.lost = true;
}
entityIdBuffer.push(entities[entity].id);
}
}
// If there are not invaders left and `player` hasn't already lost
// then game is set to `win`, otherwise continue updating
if (entityIdBuffer.length === 0 && !game.state.lost) {
game.state.win = true;
} else {
if (!this.before) { // Init to keep track of elapsed time to restrict fire rate
this.before = tFrame;
} else {
elapsed = tFrame - this.before; // Calc elapsed time
if (elapsed > MIN_MS_FIRE) { // Delay and restrict rate of fire for invaders
fireRandomBullet(entityIdBuffer);
this.before = null; // Reset before prop so we can fire again
}
}
dimensionMarkers = getDimensions(entityIdBuffer); // Calc and store our dimension markers
if (this.state.velocity > 0) { // If velocity is a positive number -> invaders are moving right
entities[dimensionMarkers.right].state.position.x += this.state.velocity; // Increase position of the entity furthest right
if (entities[dimensionMarkers.right].inBoundary(scope)) { // If that entity is still in game boundaries
entities[dimensionMarkers.right].state.position.x -= this.state.velocity; // Restore entity position before updating all
moveAllHorizontal.call(this, entityIdBuffer); // Move all entities position horizontally
} else {
entities[dimensionMarkers.right].state.position.x -= this.state.velocity; // Restore entity position
this.state.velocity += this.velocityStep; // Increase velocity
//MIN_MS_FIRE -= 100;
this.state.velocity *= -1; // Switch velocity direction, i.e. negative => postive & postive => negative
moveAllVertical.call(this, entityIdBuffer); // Move all invaders down one row
}
} else { // Else velocity is a negative number -> invaders are moving left
entities[dimensionMarkers.left].state.position.x += this.state.velocity;
if (entities[dimensionMarkers.left].inBoundary(scope)) {
entities[dimensionMarkers.left].state.position.x -= this.state.velocity;
moveAllHorizontal.call(this, entityIdBuffer);
} else {
entities[dimensionMarkers.left].state.position.x -= this.state.velocity;
this.state.velocity *= -1;
this.state.velocity += this.velocityStep;
moveAllVertical.call(this, entityIdBuffer);
}
}
}
};
// Delegate state object constructor for our invaders,
// allows group entities to share render/update/collison functions over the delegate objects prototype chain.
function Invader() {}
// Main render method for all invaders
Invader.prototype.render = function invaderRender (scope) {
scope.context.drawImage(
this.sprite.image,
this.state.position.x,
this.state.position.y,
this.sprite.width,
this.sprite.height);
return this;
};
// Left empty, because it is handled by the global `invaders` update method
Invader.prototype.update = function invaderUpdate (scope) {
return this;
};
// Main collision method for all invaders
Invader.prototype.collision = function invaderCollision (entity, scope) {
if (entity.group === 'bullet' && !entity.pc) {
this.kill();
return this;
} else if (entity.group === 'block') {
entity.kill();
return this;
}
return this;
};
module.exports = createInvaders;
},{"../utils/utils.math.js":15,"./entity.js":8}],10:[function(require,module,exports){
// /entities/player.js
var input = require('../utils/utils.input.js');
var Point = require('../utils/utils.math.js').Point;
var Entity = require('./entity.js');
/** Player Module
* Create main Player Object Constructor
*/
function Player(scope) {
// Setup const player globals
var START_POS_X = scope.constants.width / 2 - 22,
START_POS_Y = scope.constants.height - 45,
SPRITE_COLOR = '#E7E7E7',
SPRITE_HEIGHT = 15,
SPRITE_WIDTH = 45,
SPRITE_IMAGE = scope.sprites.player,
PLAYER_LIVES = 3,
PLAYER_VELOCITY = 3,
PLAYER_HEALTH = 1,
PLAYER_GROUP_NAME = 'player';
// Set up global for 'limbo' timing
var elapsedDead = null,
beforeDead = null,
MIN_MS_DEAD = 1000;
// Set up globals for firing timing
var elapsedFireRate = null,
beforeFireRate = null,
MIN_MS_FIRE = 500;
var point = new Point(START_POS_X, START_POS_Y); // Player starting point
var sprite = {
color: SPRITE_COLOR,
height: SPRITE_HEIGHT,
width: SPRITE_WIDTH,
image: SPRITE_IMAGE
};
// Instantiate Player
var player = new Entity(PLAYER_GROUP_NAME, point, PLAYER_VELOCITY, PLAYER_HEALTH, sprite);
player.state.lives = PLAYER_LIVES;
player.state.died = false;
// Player's input state functions in our state machine
var inputStates = {
moveLeft: function () { // Move player left
this.enter = function () {
player.state.position.x -= player.state.velocity;
if (player.inBoundary(scope)) {
return this;
} else {
player.state.position.x = 0;
}
return this;
};
},
moveRight: function () {
this.enter = function () { // Move player right
player.state.position.x += player.state.velocity;
if (player.inBoundary(scope)) {
return this;
} else {
player.state.position.x = scope.constants.width - player.sprite.width;
}
return this;
};
},
shoot: function (tFrame) { // Player fire bullet
this.enter = function () {
// Takes one of the inactive bullet entities from our array
var bullet = scope.state.inactiveEntities.bullets.pop();
bullet.sprite.color = player.sprite.color;
bullet.state.position.x = player.state.position.x + (player.sprite.width / 2) - (bullet.sprite.width / 2);
bullet.state.position.y = player.state.position.y;
// Place bullet in our active state of entities
scope.state.entities[bullet.id] = bullet;
};
// Set `beforeFireRate` property on shoot-event so we can put a delay and restrict rate of fire
this.beforeFireRate = tFrame;
}
};
// Fired via the global update method.
// Mutates state as needed for proper rendering next state
player.update = function playerUpdate (scope, tFrame) {
// Handles input for player to fire bullets
function fireInputHandler (tFrame) {
if (input.isDown(input.SPACE)) {
var shoot = null;
if (!beforeFireRate) {
shoot = new inputStates.shoot(tFrame);
beforeFireRate = tFrame;
return shoot;
} else {
elapsedFireRate = tFrame - beforeFireRate;
// If elapsedFireRate time is bigger than minimum allowed, we can fire again
if (elapsedFireRate > MIN_MS_FIRE) {
beforeFireRate = null;
return shoot;
}
}
}
}
// Left/right input handler
function moveInputHandler() {
if (input.isDown(input.LEFT)) {
return new inputStates.moveLeft();
} else if (input.isDown(input.RIGHT)) {
return new inputStates.moveRight();
} return null;
}
// If keys are pressed, update the players position.
var moveState = moveInputHandler();
if (moveState) {
moveState.enter();
}
// If key is pressed, fire bullet
var fireState = fireInputHandler(tFrame);
if (fireState && !player.state.died) { // Frevent player from firing if `died` state
fireState.enter();
}
// If player died(lost life), keep in 'limbo' for MIN_MS
if (player.state.died) {
if (!beforeDead) {
beforeDead = tFrame;
} else {
elapsedDead = tFrame - beforeDead;
if (elapsedDead > MIN_MS_DEAD) {
beforeDead = null;
player.state.died = false;
}
}
}
};
// Player collision method
player.collision = function playerCollision (entity) {
// If player gets hit by invader fire and player is not already in
// a dead state, then player lose one life.
if (entity.group === 'bullet' && entity.pc && !player.state.died) {
player.state.lives--;
if (player.state.lives === 0) { // If player has no more lifes, player lost.
game.state.lost = true;
return this;
}
player.state.died = true; // Player state set to `died` for MIN_MS
return this;
} else if (entity.group === 'invader') { // If player collides with an invader, player lost.
game.state.lost = true;
}
return this;
};
// Draw the player on the canvas
player.render = function playerRender () {
if (player.state.died) {
scope.context.globalAlpha = 0.5;
}
scope.context.fillStyle = player.sprite.color;
scope.context.fillRect(
player.state.position.x,
player.state.position.y+5,
sprite.width, sprite.height-5
);
scope.context.fillRect(
player.state.position.x+10,
player.state.position.y,
sprite.width-20, sprite.height
);
scope.context.fillRect(
player.state.position.x+20,
player.state.position.y-10,
sprite.width-40, sprite.height
);
// Renders player lives in bottom left
for (var i = 0, n = 5; i < player.state.lives; i++){
scope.context.drawImage(player.sprite.image, n, scope.constants.height - 16, player.sprite.height, player.sprite.height);
n += 20;
}
scope.context.globalAlpha = 1;
};
return player;
}
module.exports = Player;
},{"../utils/utils.input.js":14,"../utils/utils.math.js":15,"./entity.js":8}],11:[function(require,module,exports){
// /game.js
/**
* This creates an instance of the game 'Space Invaders'.
* Engine and game written in Vanilla JavaScript
*
* Licensed under the MIT license.
*
* Dag Holmberg
* https://github.com/holmberd
*/
var generateCanvas = require('./utils/utils.canvas.js');
var gameLoop = require('./core/game.loop.js');
var gameUpdate = require('./core/game.update.js');
var gameCollision = require('./core/game.collision.js');
var gameRender = require('./core/game.render.js');
var input = require('./utils/utils.input.js');
var Menu = require('./utils/utils.menu.js');
var Player = require('./entities/player.js');
var createInvaders = require('./entities/invader.js');
var createBlocks = require('./entities/blocks.js');
var createBullets = require('./entities/bullet.js');
var loadSprites = require('./utils/utils.sprites.js');
var map = require('./conf/map.json');