-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.js
848 lines (723 loc) · 18.9 KB
/
engine.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
/*!
* Abstract Game Engine
*/
(function( window ) {
if ( window.Game ) {
// Don't include this file twice.
return;
}
var Game = window.Game = {
/**
* Holds game settings. Contains the required default settings.
* But additional game settings can be added based on what your
* game needs.
* @object Game.settings
* @prop fps {Number} Frames per second
* @prop startTime {Number} The start time in milliseconds of the game
* @prop time {Number} The time in milliseconds that can be used in various ways
* @prop canvas {CanvasElement} The main canvas
* @prop ctx {Canvas2DContext} The canvas 2D context
*/
settings: {
fps: 0,
startTime: 0,
time: 0,
canvas: null,
ctx: null,
canvasOffset: { x: 0, y: 0 }
},
/**
* Holds game entities
*/
entities: [],
/**
* Holds the game entities that will be destroyed this update
*/
killList: [],
/**
* If the game engine is initialized or not
*/
initialized: false,
/**
* Initialization of the game engine
*/
init: function( canvas, fps ) {
if ( !canvas ) { // quick and dirty way to check if it is null or undefined
throw "Init function requires 'canvas' parameter";
}
this.settings.canvas = canvas;
this.settings.ctx = canvas.getContext( "2d" );
if ( !this.settings.ctx ) {
throw "Could not get canvas 2D context";
}
this.settings.fps = fps;
var canvasBound = canvas.getBoundingClientRect();
this.settings.canvasOffset = _.make( Game.Vector2 ).init(
canvasBound.left,
canvasBound.top
);
this.InputManager.init();
this.initialized = true;
return this;
},
/**
* State-based game
* addState takes a String, and a callback.
* Callback will be used in update and draw function.
* Callback is an object that has two methods: update and draw
* update should take one parameter: delta (time elapsed between update calls)
* draw should take one parameter: ctx (canvas 2D context)
*/
StateManager: {
states: {},
state: null,
add: function( name, callback, first ) {
// Checks if there's already state with the name
if ( this.states[name] === undefined || this.states[ name ] === null ) {
this.states[name] = callback;
if ( first ) {
this.state = callback;
}
} else {
throw "State already added: " + name;
}
},
change: function( name ) {
if ( !this.states[name] ) {
throw "State doesn't exist: " + name;
}
this.state = this.states[name];
}
},
/**
* If the game engine is running and false if not.
*/
alive: false,
/**
* Starts the game engine
*/
start: function() {
if ( !this.initialized ) {
throw "Game engine not initialized";
}
if ( !this.alive ) {
this.settings.startTime = Date.now();
this.settings.time = this.settings.startTime;
setInterval( this.tick, 1000 / ( this.settings.fps || 30 ) );
this.alive = true;
}
},
/**
* Stops the game enegine
*/
stop: function() {
clearInterval( this.tick );
this.alive = false;
},
/**
* Function to call each frame
*/
tick: function() {
Game.update();
Game.draw();
},
/**
* Updates the game state. Should not be overridden.
* Override state's update function instead.
*/
update: function() {
var now = Date.now();
var delta = now - this.settings.time;
updateNorm = this.StateManager.state.update( delta );
if ( updateNorm ) {
for ( var i = 0; i < this.entities.length; i++ ) {
this.entities[i].update( delta );
}
this.InputManager.unload();
}
this.settings.time = now;
},
/**
* Draws the current game state to the canvas.
* Should not be overridden.
* Override state's draw function instead.
*/
draw: function() {
drawNorm = this.StateManager.state.draw( this.settings.ctx );
if ( drawNorm ) {
for ( var i = 0; i < this.entities.length; i++ ) {
this.entities[i].draw( this.settings.ctx );
}
}
},
/**
* Asset object
* Holds necessary information about an asset
* callback is called when the asset has loaded
*/
Asset: {
// Default properties
type: null,
src: "",
callback: function( asset ) {},
init: function( type, src, callback ) {
this.type = type;
this.src = src;
if ( callback ) {
this.callback = callback;
}
return this;
}
},
/**
* Object for holding and loading assets
* It is a singleton.
*/
AssetManager: {
/**
* Holds Game assets
*/
assets: {},
/**
* asset types
* users can add custom asset types.
* callback should have one parameter: asset
* for convenient purposes.
*/
assetType: {
image: function( asset, callback ) {
var img = new Image();
img.onload = function() {
callback( asset );
};
img.src = asset.src;
asset.content = img;
},
audio: function( asset, callback ) {
var audio = document.createElement( "audio" );
audio.onload = function() {
callback( asset );
};
audio.src = asset.src;
asset.content = audio;
},
json: function( asset, callback ) {
_.ajax( asset.src, null, function( msg ) {
asset.content = JSON.parse( msg );
if ( callback ) {
callback( asset );
}
});
}
},
/**
* number assets
*/
assetCount: 0,
loadedCount: 0,
/**
* Adds an asset
*/
add: function( name, asset ) {
this.assets[name] = asset;
this.assetCount++;
},
/**
* Gets an asset
*/
get: function( name ) {
return this.assets[name];
},
/**
* Checks if all assets in asset manager have been loaded
*/
get loaded() { return this.assetCount === this.loadedCount },
/**
* Loads all assets currently in the asset manager
*/
load: function( onAllLoad, onEachLoad ) {
this.callback = onAllLoad;
var that = this;
for ( var i in this.assets ) {
if ( this.assets.hasOwnProperty( i ) ) {
this.assets[i].type( this.assets[i], function( asset ) {
that.loadedCount++;
if ( onEachLoad ) {
onEachLoad();
}
asset.callback( asset );
if ( that.loaded && that.callback ) {
that.callback();
}
} );
}
}
}
},
/**
* Object for handling input event
* Singleton
*/
InputManager: {
// Default properties
events: [],
initalized: false,
init: function() {
var that = this;
_.bind( Game.settings.canvas, "click", function( e ) {
return that.handleClick( e );
} );
this.initalized = true;
},
handleClick: function( e ) {
var event = {
type: "click",
x: e.pageX - Game.settings.canvasOffset.x,
y: e.pageY - Game.settings.canvasOffset.y
};
this.events.push( event );
return false;
},
unload: function() {
// Loop through events
for ( var i = 0; i < this.events.length; i++ ) {
e = this.events[i];
if ( e.type == "click" ) {
for ( var j = Game.entities.length - 1; j >= 0; j-- ) {
Game.entities[j].click();
}
}
}
// Clear events
this.events = [];
}
},
/**
* Abstract object for representing an entity in the game.
*/
Entity: {
// Default properties
// Dummy object in place of Game.Box
bound: { x: 0, y: 0, w: 0, h: 0 },
img: null,
angle: 0,
// Didn't say init because init would get overriden by "subclasses"
entityInit: function( img, x, y, w, h ) {
// ensures that this.bound is Game.Box
this.bound = _.make( Game.Box ).init( x, y, w, h );
this.img = img;
this.angle = 0;
},
/**
* Updates the entity
*/
update: function( delta ) {
},
/**
* Draws the entity to the canvas
*/
draw: function( ctx ) {
if ( this.img ) {
ctx.save();
ctx.translate( this.bound.x, this.bound.y );
// Rotate the image
if ( this.angle ) {
ctx.rotate( this.angle );
}
// Draw the image
var translatedBound = this.bound.copy();
translatedBound.center = [0, 0];
this.img.drawAt( ctx, translatedBound );
ctx.restore();
} else {
// Set color
ctx.fillStyle = "black";
ctx.save();
ctx.translate( this.bound.centerx, this.bound.centery );
// Rotate the image
if ( this.angle ) {
ctx.rotate( this.angle );
}
// Draw the image
ctx.fillRect( -this.bound.w / 2, -this.bound.h / 2, this.bound.w, this.bound.h );
ctx.restore();
}
},
click: function() {
}
},
/**
* A clickable entity for game UIs
*/
Button: {
text: null,
font: null,
text_color: null,
bg_color: null,
/**
* Initalize button
* text: {String} The button's text
* font: {Game.Font} The font used
* x & y: {Integer} & {Integer} x and y location of the button
* padding_x: {Integer} Padding on the x axis of the button
* padding_y: {Integer} Padding on the y axis of the button
* text_color: {String} Color of the text
* bg_color: {String} Color of the background
*/
init: function( text, font, x, y, padding_x, padding_y, text_color, bg_color ) {
this.text = text;
this.font = font;
this.text_color = text_color;
this.bg_color = bg_color;
this.entityInit( null, x, y, font.measureText( text ) + padding_x * 2, font.size + padding_y * 2 );
return this;
},
/**
* Draws the button to the canvas
*/
draw: function( ctx ) {
ctx.save();
ctx.translate( this.bound.centerx, this.bound.centery );
// Rotate the button
if ( this.angle ) {
ctx.rotate( this.angle );
}
// Draw the button's background
ctx.fillStyle = this.bg_color;
ctx.fillRect( -this.bound.w / 2, -this.bound.h / 2, this.bound.w, this.bound.h );
// Draw the button's text
ctx.fillStyle = this.text_color;
ctx.font = this.font.toString();
ctx.fillText( this.text, -this.font.measureText( this.text ) / 2, this.font.size / 3 )
ctx.restore();
}
},
/**
* tile stub for 2D tile map
* It really is a stub, so please override this
*/
Tile: {
/**
*Default properties
* Row and column for representing the index of the map,
* and x and y for representing pixel values
*/
row: 0,
col: 0,
init: function( row, col, map, img ) {
this.row = row;
this.col = col;
var bound = _.make( Game.Box ).init( map.toCoords( row, col ), map.tileLength, map.tileLength );
this.entityInit( img, bound );
}
},
/**
* 2D tile map
*/
TileMap: {
/**
* Default properties
* mapOffset: offset from the canvasOffset. Shows where the top left of the map is
* layout: 2D Array with numbers that corressponds with Tile.tiles
* tileLength: The pixel value of each tile length
* tileLayout: 2D Array that has Tile objects instead of numbers from layout
*/
mapOffset: { x: 0, y: 0 },
layout: [],
tileLength: 0,
rows: 0,
cols: 0,
tileLayout: [],
init: function( layout, tileLength ) {
this.layout = layout;
this.tileLength = tileLength;
this.rows = layout.length;
this.cols = layout[0].length; // Assuming it's not a zig-zagged 2D Array
this.tileLayout = [];
for ( var row = 0; row < this.rows; row++ ) {
this.tileLayout.push( [] );
}
this.convertLayout();
},
/**
* For converting from layout to tileLayout
* Override this if you want a custom Tile object.
*/
convertLayout: function() {
for ( var row = 0; row < this.rows; row++ ) {
for ( var col = 0; col < this.cols; col++ ) {
this.tileLayout[row][col] = _.make( Game.Tile ).init( row, col, this );
}
}
},
draw: function( ctx ) {
this.forEach( function( tile ) {
tile.draw( ctx );
} );
},
/**
* Iterate each tiles and do something
* fn takes a parameter: tile.
*/
forEach: function( fn ) {
for ( var row = 0; row < this.rows; row++ ) {
for ( var col = 0; col < this.cols; col++ ) {
fn( this.tileLayout[row][col] );
}
}
},
/**
* Converting coordinates to map index
*/
toMapIndex: function( x, y ) {
var row = Math.floor( ( y - this.mapOffset.y ) / this.tileLength );
var col = Math.floor( ( x - this.mapOffset.x ) / this.tileLength );
return { row: row, col: col };
},
/**
* Converting map index to coordinates
*/
toCoords: function( row, col ) {
var y = this.mapOffset.y + row * this.tileLength;
var x = this.mapOffset.x + col * this.tileLength;
return _.make( Game.Vector2 ).init( x, y );
}
},
/**
* Font object constructor
*/
Font: {
/**
* size: {Integer} Height of the font
* family: {String} Font name (e.g. 'Arial' or 'Times New Roman')
*/
size: 0,
family: 0,
init: function( size, family ) {
this.size = size;
this.family = family;
return this;
},
/**
* Measure the width of a string
* text: {String} text to measure
*/
measureText: function( text ) {
fontTMP = Game.settings.ctx.font;
Game.settings.ctx.font = this.toString();
return Game.settings.ctx.measureText( text ).width;
Game.settings.ctx.font = fontTMP;
},
/**
* Converts font to string
* Usage: `ctx.font = [FontObject].toString();`
*/
toString: function() {
return this.size.toString() + "px " + this.family;
}
},
/**
* Box object constructor. Box object will define most of dimensions.
* @function Box
* @param x {Number, Vector2, Box} X value of top left corner, vector representing top left corner, Box to copy
* @param y {Number, Number, undefined} Y value of top left corner, width
* @param w {Number, Number, undefined} Width, height
* @param h {Number, undefined, undefined} Height
*/
Box: {
// Default properties
x: 0,
y: 0,
w: 0,
h: 0,
init: function( x, y, w, h ) {
if ( this.canBeBox( x ) ) {
this.set( x );
} else if ( Game.Vector2.canBeVector2( x ) ) {
this.topLeft = x;
this.w = y || 0;
this.h = w || 0;
} else {
this.x = x || 0;
this.y = y || 0;
this.w = w || 0;
this.h = h || 0;
}
return this;
},
/**
* Getters and setters
*/
get left() { return this.x; },
get top() { return this.y; },
get right() { return this.x + this.w; },
get bottom() { return this.y + this.h; },
get centerx() { return this.x + this.w / 2; },
get centery() { return this.y + this.h / 2; },
get center() { return _.make( Game.Vector2 ).init( this.centerx, this.centery ); },
get topLeft() { return _.make( Game.Vector2 ).init( this.left, this.top ); },
get topRight() { return _.make( Game.Vector2 ).init( this.right, this.top ); },
get bottomLeft() { return _.make( Game.Vector2 ).init( this.left, this.bottom ); },
get bottomRight() { return _.make( Game.Vector2 ).init( this.right, this.bottom ); },
get size() { return { w: this.w, h: this.h }; },
set left( value ) { this.x = value; },
set top( value ) { this.y = value; },
set right( value ) { this.x = value - this.w; },
set bottom( value ) { this.y = value - this.h; },
set centerx( value ) { this.x = value - this.w / 2; },
set centery( value ) { this.y = value - this.h / 2; },
// Basically, you can put any Object with x or y value e.g. Game.Vector2
// or an array e.g. [123, 284]
set center( value ) {
this.centerx = value.x || value[0] || 0;
this.centery = value.y || value[1] || 0;
},
set topLeft( value ) {
this.left = value.x || value[0] || 0;
this.top = value.y || value[1] || 0;
},
set topRight( value ) {
this.right = value.x || value[0] || 0;
this.top = value.y || value[1] || 0;
},
set bottomLeft( value ) {
this.left = value.x || value[0] || 0;
this.bottom = value.y || value[1] || 0;
},
set bottomRight( value ) {
this.right = value.x || value[0] || 0;
this.bottom = value.y || value[1] || 0;
},
set size( value ) {
this.w = value.w || value[0] || 0;
this.h = value.h || value[1] || 0;
},
/**
* Set this box with another box's property
*/
set: function( box ) {
// This works because of the setters of topLeft and size
this.topLeft = box;
this.size = box;
return this;
},
/**
* Returns a copy
*/
copy: function() {
return _.make( Game.Box ).init( this.x, this.y, this.w, this.h );
},
/**
* Basic collision with other Box
*/
collideWith: function( box ) {
return !(
this.bottom < box.top ||
this.top > box.bottom ||
this.right < box.left ||
this.left > box.right
);
},
/**
* Check collision with a point
*/
isPointInside: function( x, y ) {
return this.left < x && x < this.right &&
this.top < y && y < this.bottom;
},
/**
* Check if it can be a box
* meaning has x, y, w, h
*/
canBeBox: function( box ) {
return Game.Vector2.canBeVector2( box ) &&
box.hasOwnProperty( "w" ) && box.hasOwnProperty( "h" );
}
},
/*
* Vector2 Object Constructor
* It holds position or vector, either one
* @function Vector2
* @params x {Number, Vector2} X value, vector to copy
* @params y {Number, undefined} Y value
*/
Vector2: {
// Default properties
x: 0,
y: 0,
init: function( x, y ) {
if ( this.canBeVector2( x ) ) {
this.set( x );
} else {
this.x = x || 0;
this.y = y || 0;
}
return this;
},
/**
* Operations, since JavaScript doesn't have operation overloading
* add: Returns the sum of the two vectors
* sub: subtract - Returns the difference between the two vectors
* mul: multiply - Returns the component-wise multiplication of the vectors
* div: divide - Returns the component-wise division of the vectors
*/
add: function( other ) {
return _.make( Vector2 ).init( this.x + other.x, this.y + other.y );
},
sub: function( other ) {
return _.make( Vector2 ).init( this.x - other.x, this.y - other.y );
},
mul: function( other ) {
return _.make( Vector2 ).init( this.x * other.x, this.y * other.y );
},
div: function( other ) {
return _.make( Vector2 ).init( this.x / other.x, this.y / other.y );
},
get squaredLength() { return this.x * this.x + this.y * this.y; },
get length() { return Math.sqrt( this.squaredLength ); },
get angle() { return Math.atan2( this.y, this.x ); },
/*
* Set this vector with other vector's property
*/
set: function( other ) {
this.x = other.x || 0;
this.y = other.y || 0;
return this;
},
/*
* Returns a copy of this vector
*/
copy: function() {
return _.make( Vector2 ).init( this.x, this.y );
},
// Returns the vector with all components multiplied by the scalar parameter
// You would use reciprocal if you are dividing
scale: function( scale ) {
return _.make( Vector2 ).init( this.x * scale, this.y * scale );
},
// Returns the dot product between the two vectors
dot: function( other ) {
return this.x * other.x + this.y * other.y;
},
// Returns a vector pointing on the same direction, but with a length of 1
unit: function() {
return this.scale( 1 / this.length );
},
// Rotates the vector by the specified angle
rotate: function( angle ) {
this.x = this.x * Math.cos( angle ) - this.y * Math.sin( angle );
this.y = this.x * Math.sin( angle ) + this.y * Math.cos( angle );
return this;
},
/**
* Check if it can be a vector2 or not
* meaning if it has x and y
*/
canBeVector2: function( vec ) {
return vec.hasOwnProperty( "x" ) && vec.hasOwnProperty( "y" );
}
}
}
_.extend( Game.Button, Game.Entity );
_.extend( Game.Tile, Game.Entity );
})( window );