-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimpleGame.js
More file actions
1334 lines (1140 loc) · 40 KB
/
simpleGame.js
File metadata and controls
1334 lines (1140 loc) · 40 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* simpleGame.js
a game library for the canvas tag
loosely based on Python gameEngine
and Scratch
expects an HTML5-compliant browser
includes support for mobile browsers
Main code and design: Andy Harris - 2011/2012
Animation and tile elements by Tyler Mitchell
var keyword added to local variables in all
functions by James Larson @ Codecademy.com
*/
//variable holding key being pressed
var currentKey = null;
var keysDown = new Array(256);
var virtKeys = false;
function Sprite(scene, imageFile, width, height){
//core class for game engine
this.scene = scene;
this.canvas = scene.canvas;
this.context = this.canvas.getContext("2d");
this.image = new Image();
this.image.src = imageFile;
this.animation = false; // becomes Animation Class
this.width = width;
this.height = height;
this.cHeight = parseInt(this.canvas.height,10);
this.cWidth = parseInt(this.canvas.width,10);
this.x = 200;
this.y = 200;
this.dx = 10;
this.dy = 0;
this.imgAngle = 0;
this.moveAngle = 0;
this.speed = 10;
this.camera = false;
this.visible = true;
this.boundAction = WRAP;
this.changeImage = function(imgFile){
this.image.src = imgFile;
}; // end this.changeImage
this.setImage = function(imgFile){
//set and change image are the same thing.
this.image.src = imgFile;
}; // end this.setImage
this.setPosition = function(x, y){
//position is position of center
this.x = x;
this.y = y;
}; // end setPosition function
this.setX = function (nx){ this.x = nx; };
this.setY = function (ny){ this.y = ny; };
this.setChangeX = function (ndx){ this.dx = ndx; };
this.setChangeY = function (ndy){ this.dx = ndx; };
this.setDX = function(newDX){
this.dx = newDX;
};
this.setDY = function(newDY){
this.dy = newDY;
};
this.changeXby = function(tdx){ this.x += tdx;};
this.changeYby = function(tdy){ this.y += tdy;};
this.hide = function(){this.visible = false; };
this.show = function(){this.visible = true; };
this.draw = function(){
//draw self on canvas;
//intended only to be called from update, should never
//need to be deliberately called by user
var ctx = this.context;
ctx.save();
//The following lines are for Tyler's code. Removed for now
//if( this.camera ){
// ctx.translate(this.x - this.camera.cameraOffsetX, this.y - this.camera.cameraOffsetY); }
//else{ ctx.translate(this.x, this.y); }
//transform element
ctx.translate(this.x, this.y);
ctx.rotate(this.imgAngle);
//draw image with center on origin
if( this.animation !== false ){
this.animation.drawFrame(ctx);
}
else{
ctx.drawImage(this.image,
0 - (this.width / 2),
0 - (this.height / 2),
this.width, this.height);
}
ctx.restore();
}; // end draw function
this.update = function(){
this.x += this.dx;
this.y += this.dy;
this.checkBounds();
if (this.visible){
this.draw();
} // end if
}; // end update
this.setBoundAction = function(action){
this.boundAction = action;
}; // end setBoundAction
this.checkBounds = function(){
//behavior changes based on
//boundAction property
var camX = 0;
var camY = 0;
if(this.camera){
camX = this.camera.cameraOffsetX; camY = this.camera.cameraOffsetY;
}
var rightBorder = this.cWidth + camX;
var leftBorder = camX;
var topBorder = camY;
var bottomBorder = this.cHeight + camY;
var offRight = false;
var offLeft = false;
var offTop = false;
var offBottom = false;
if (this.x > rightBorder){
offRight = true;
}
if (this.x < leftBorder){
offLeft = true;
}
if (this.y > bottomBorder){
offBottom = true;
}
if (this.y < 0){
offTop = true;
}
if (this.boundAction == WRAP){
if (offRight){
this.x = leftBorder;
} // end if
if (offBottom){
this.y = topBorder;
} // end if
if (offLeft){
this.x = rightBorder;
} // end if
if (offTop){
this.y = bottomBorder;
}
} else if (this.boundAction == BOUNCE){
if (offTop || offBottom){
this.dy *= -1;
this.calcSpeedAngle();
this.imgAngle = this.moveAngle;
}
if (offLeft || offRight){
this.dx *= -1;
this.calcSpeedAngle();
this.imgAngle = this.moveAngle;
}
} else if (this.boundAction == STOP){
if (offLeft || offRight || offTop || offBottom){
this.setSpeed(0);
}
} else if (this.boundAction == DIE){
if (offLeft || offRight || offTop || offBottom){
this.hide();
this.setSpeed(0);
}
} else {
//keep on going forever
}
}; // end checkbounds
this.loadAnimation = function (imgWidth, imgHeight, cellWidth, cellHeight){
this.animation = new Animation(this.image, imgWidth, imgHeight, cellWidth, cellHeight);
this.animation.setup();
};
//animation methods
this.generateAnimationCycles = function(slicingFlag, framesArray){
//Default: assume each row is a cycle and give them names Cycle1, Cycle2, ... , CycleN
//SINGLE_ROW: all the sprites are in one row on the sheet, the second parameter is either
// a number saying each cycle is that many frames or a list of how many frames each cycle is
//SINGLE_COLUMN: all the sprites are in one column on the sheet, the second parameter is
// either a number saying each cycle is that many frames or a list of how many frames each cycle is
//VARIABLE_LENGTH: How many frames are in each cycle. framesArray must be defined.
var cWidth = this.animation.cellWidth;
var cHeight = this.animation.cellHeight;
var iWidth = this.animation.imgWidth;
var iHeight = this.animation.imgHeight;
var numCycles = 0;
var i, nextStartingFrame = 0;
if(typeof framesArray == "number" || typeof slicingFlag == "undefined"){
if( slicingFlag == SINGLE_COLUMN ){
numCycles = (iHeight/cHeight)/framesArray;
}
else if( typeof slicingFlag == "undefined" ){
numCycles = (iHeight/cHeight); framesArray = iWidth/cWidth;
}
else{
numCycles = (iWidth/cWidth)/framesArray;
}
for(i = 0; i < numCycles; i++){
cycleName = "cycle" + (i+1);
this.specifyCycle(cycleName, i*framesArray, framesArray);
}
}
else{
numCycles = framesArray.length;
for(i = 0; i < numCycles; i++){
cycleName = "cycle" + (i+1);
this.specifyCycle(cycleName, nextStartingFrame, framesArray[i]);
nextStartingFrame += framesArray[i];
}
}
this.setCurrentCycle("cycle1");
};
this.renameCycles = function(cycleNames){ this.animation.renameCycles(cycleNames); };
this.specifyCycle = function(cycleName, startingCell, frames){
this.animation.addCycle(cycleName, startingCell, frames);
};
this.specifyState = function(stateName, cellName){ this.animation.addCycle(stateName, cellName, 1); };
this.setCurrentCycle = function(cycleName){ this.animation.setCycle(cycleName); };
this.pauseAnimation = function(){ this.animation.pause(); };
this.playAnimation = function(){ this.animation.play(); };
this.resetAnimation = function(){ this.animation.reset(); };
this.setAnimationSpeed = function(speed){ this.animation.setAnimationSpeed(speed); };
this.calcVector = function(){
//used throughout speed / angle calculations to
//recalculate dx and dy based on speed and angle
this.dx = this.speed * Math.cos(this.moveAngle);
this.dy = this.speed * Math.sin(this.moveAngle);
}; // end calcVector
this.calcSpeedAngle = function(){
//opposite of calcVector:
//sets speed and moveAngle based on dx, dy
this.speed = Math.sqrt((this.dx * this.dx) + (this.dy * this.dy));
this.moveAngle = Math.atan2(this.dy, this.dx);
};
this.setSpeed = function(speed){
this.speed = speed;
this.calcVector();
}; // end setSpeed
this.getSpeed = function(){
//calculate speed based on current dx and dy
speed = Math.sqrt((this.dx * this.dx) + (this.dy * this.dy));
return speed;
}; // end getSpeed
this.changeSpeedBy = function(diff){
this.speed += diff;
this.calcVector();
}; // end changeSpeedBy
this.setImgAngle = function(degrees){
//offset degrees by 90
degrees -= 90;
//convert degrees to radians
this.imgAngle = degrees * Math.PI / 180;
}; // end setImgAngle
this.getImgAngle = function(){
//imgAngle is stored in radians.
//return it in degrees
//don't forget we offset the angle by 90 degrees
return (this.imgAngle * 180 / Math.PI) + 90;
};
this.changeImgAngleBy = function(degrees){
var rad = degrees * Math.PI / 180;
this.imgAngle += rad;
}; // end changeImgAngle
this.setMoveAngle = function(degrees){
//take movement angle in degrees
// offset degrees by 90
degrees -= 90;
//convert to radians
this.moveAngle = degrees * Math.PI / 180;
this.calcVector();
}; // end setMoveAngle
this.changeMoveAngleBy = function(degrees){
//convert diff to radians
var diffRad = degrees * Math.PI / 180;
//add radian diff to moveAngle
this.moveAngle += diffRad;
this.calcVector();
}; // end changeMoveAngleBy
this.getMoveAngle = function(){
//moveAngle is stored in radians.
//return it in degrees
//don't forget we offset the angle by 90 degrees
return (this.moveAngle * 180 / Math.PI) + 90;
};
//convenience functions combine move and img angles
this.setAngle = function(degrees){
this.setMoveAngle(degrees);
this.setImgAngle(degrees);
}; // end setAngle
this.changeAngleBy = function(degrees){
this.changeMoveAngleBy(degrees);
this.changeImgAngleBy(degrees);
}; // end changeAngleBy
this.turnBy = function(degrees){
//same as changeAngleBy
this.changeAngleBy(degrees);
};
this.addVector = function(degrees, thrust){
//Modify the current motion vector by adding a new vector to it.
//offset angle by 90 degrees
degrees -= 90;
//input angle is in degrees - convert to radians
angle = degrees * Math.PI / 180;
//calculate dx and dy
var newDX = thrust * Math.cos(angle);
var newDY = thrust * Math.sin(angle);
this.dx += newDX;
this.dy += newDY;
//ensure speed and angle are updated
this.calcSpeedAngle();
}; // end addVector
this.collidesWith = function(sprite){
//check for collision with another sprite
//collisions only activated when both sprites are visible
var collision = false;
if (this.visible){
if (sprite.visible){
//define borders
var myLeft = this.x - (this.width / 2);
var myRight = this.x + (this.width / 2);
var myTop = this.y - (this.height / 2);
var myBottom = this.y + (this.height / 2);
var otherLeft = sprite.x - (sprite.width / 2);
var otherRight = sprite.x + (sprite.width / 2);
var otherTop = sprite.y - (sprite.height / 2);
var otherBottom = sprite.y + (sprite.height / 2);
//assume collision
collision = true;
//determine non-colliding states
if ((myBottom < otherTop) ||
(myTop > otherBottom) ||
(myRight < otherLeft) ||
(myLeft > otherRight)) {
collision = false;
} // end if
} // end 'other visible' if
} // end 'I'm visible' if
return collision;
}; // end collidesWith
this.distanceTo = function(sprite){
var diffX = this.x - sprite.x;
var diffY = this.y - sprite.y;
var dist = Math.sqrt((diffX * diffX) + (diffY * diffY));
return dist;
}; // end distanceTo
this.angleTo = function(sprite){
//get centers of sprites
var myX = this.x + (this.width/2);
var myY = this.y + (this.height/2);
var otherX = sprite.x + (sprite.width/2);
var otherY = sprite.y + (sprite.height/2);
//calculate difference
var diffX = myX - otherX;
var diffY = myY - otherY;
var radians = Math.atan2(diffY, diffX);
var degrees = radians * 180 / Math.PI;
//degrees are offset
degrees += 90;
return degrees;
}; // end angleTo
this.isMouseDown = function(){
//determines if mouse is clicked on this element
var mx = this.scene.getMouseX();
var my = this.scene.getMouseY();
var sLeft = this.x - (this.width / 2);
var sRight = this.x + (this.width / 2);
var sTop = this.y - (this.height / 2);
var sBottom = this.y + (this.height / 2);
var hit = false;
if (mx > sLeft){
if (mx < sRight){
if (my > sTop){
if (my < sBottom){
if (this.scene.touchable){
//if it's a touchable interface,
//this is a hit
hit = true;
} else {
//for a normal mouse, check for clicked, too
if (this.scene.getMouseClicked()){
hit = true;
}
}
}
}
}
}
return hit;
}; // end isMouseDown
this.isClicked = function(){
//eventually return true only when mouse is released;
//for now, simply another name for isMouseDown
return this.isMouseDown();
/*
var hit = false;
if (this.isMouseDown()){
if (this.released){
hit = true;
} // end if
} // end if
return hit;
*/
}; // end isClicked
this.setCameraRelative = function( cam ){ this.camera = cam; };
this.report = function(){
//used only for debugging. Requires browser with JS console
console.log ("x: " + this.x + ", y: " + this.y + ", dx: " +
this.dx + ", dy: " + this.dy +
", speed: " + this.speed +
", angle: " + this.moveAngle);
}; // end report
} // end Sprite class def
function Scene(){
//Scene that encapsulates the animation background
//determine if it's a touchscreen device
this.touchable = 'createTouch' in document;
//dynamically create a canvas element
this.canvas = document.createElement("canvas");
this.canvas.style.backgroundColor = "yellow";
document.body.appendChild(this.canvas);
this.context = this.canvas.getContext("2d");
this.clear = function(){
this.context.clearRect(0, 0, this.width, this.height);
};
this.start = function(){
//set up keyboard reader if not a touch screen.
if (!this.touchable){
this.initKeys();
document.onkeydown = this.updateKeys;
document.onkeyup = this.clearKeys;
} // end if
this.intID = setInterval(localUpdate, 50);
document.onmousemove = this.updateMousePos;
document.mouseClicked = false;
document.onmousedown = function(){
this.mouseDown = true;
this.mouseClicked = true;
};
document.onmouseup = function(){
this.mouseDown = false;
this.mouseClicked = false;
};
};
this.stop = function(){
clearInterval(this.intID);
};
this.updateKeys = function(e){
//set current key
currentKey = e.keyCode;
//console.log(e.keyCode);
keysDown[e.keyCode] = true;
}; // end updateKeys
this.clearKeys = function(e){
currentKey = null;
keysDown[e.keyCode] = false;
}; // end clearKeys
this.initKeys = function(){
//initialize keys array to all false
for (keyNum = 0; keyNum < 256; keyNum++){
keysDown[keyNum] = false;
} // end for
}; // end initKeys
this.setSizePos = function(height, width, top, left){
//convenience function. Cals setSize and setPos
this.setSize(height, width);
this.setPos(top, left);
}; // end setSizePos
this.setSize = function(width, height){
//set the width and height of the canvas in pixels
this.width = width;
this.height = height;
this.canvas.width = this.width;
this.canvas.height = this.height;
}; // end setSize
this.setPos = function(left, top){
//set the left and top position of the canvas
//offset from the page
this.left = left;
this.top = top;
//CSS3 transform to move elements.
//Cross-browser compatibility would be awesome, guys...
this.canvas.style.MozTransform = "translate(" + left + "px, " + top + "px)";
this.canvas.style.WebkitTransform = "translate(" + left + "px, " + top + "px)";
this.canvas.style.OTransform = "translate(" + left + "px, " + top + "px)";
}; // end setPos
this.setBG = function(color){
this.canvas.style.backgroundColor = color;
}; // end this.setBG
this.updateMousePos = function(e){
this.mouseX = e.pageX;
this.mouseY = e.pageY;
}; // end function
this.hideCursor = function(){
this.canvas.style.cursor = "none";
};
this.showCursor = function(){
this.canvas.style.cursor = "default";
};
this.getMouseX = function(){
//incorporate offset for canvas position
return document.mouseX - this.left;
};
this.getMouseY = function(){
//incorporate offset for canvas position
return document.mouseY - this.top;
};
this.getMouseClicked = function(){
return document.mouseClicked;
};
this.hide = function(){
this.canvas.style.display = "none";
};
this.show = function(){
this.canvas.style.display = "block";
};
this.setSize(800, 600);
this.setPos(10, 10);
this.setBG("lightgray");
} // end Scene class def
function Sound(src){
//sound effect class
//builds a sound effect based on a url
//may need both ogg and mp3.
this.snd = document.createElement("audio");
this.snd.src = src;
//preload sounds if possible (won't work on IOS)
this.snd.setAttribute("preload", "auto");
//hide controls for now
this.snd.setAttribute("controls", "none");
this.snd.style.display = "none";
//attach to document so controls will show when needed
document.body.appendChild(this.snd);
this.play = function(){
this.snd.play();
}; // end play function
this.showControls = function(){
//generally not needed.
//crude hack for IOS
this.snd.setAttribute("controls", "controls");
this.snd.style.display = "block";
}; // end showControls
} // end sound class def
function Joy(){
//virtual joystick for ipad
//console.log("joystick created");
//when activated, document will have the following properties
//mouseX, mouseY: touch read as mouse input
//diffX, diffY: touch motion read as a joystick input
//if virtKeys is set true
//joystick inputs will be read as arrow keys
//properties
SENSITIVITY = 50;
var diffX = 0;
var diffY = 0;
var touches = [];
var startX;
var startY;
//define event handlers
this.onTouchStart = function(event){
var result = "touch: ";
var touches = event.touches;
var startX = touches[0].screenX;
var startY = touches[0].screenY;
result += "x: " + startX + ", y: " + startY;
//define mouse position based on touch position
this.mouseX = startX;
this.mouseY = startY;
//console.log(result);
}; // end onTouchStart
this.onTouchMove = function(event){
var result = "move: ";
event.preventDefault();
var touches = event.touches;
//map touch position to mouse position
this.mouseX = touches[0].screenX;
this.mouseY = touches[0].screenY;
this.diffX = touches[0].screenX - startX;
this.diffY = touches[0].screenY - startY;
result += "dx: " + this.diffX + ", dy: " + this.diffY;
//manage virtual keys if enabled
if (virtKeys){
var THRESHHOLD = 10;
if (this.diffX > THRESHHOLD){
keysDown[K_RIGHT] = true;
} else {
keysDown[K_RIGHT] = false;
} // end if
if (this.diffX < -THRESHHOLD){
keysDown[K_LEFT] = true;
} else {
keysDown[K_LEFT] = false;
} // end if
if (this.diffY > THRESHHOLD){
keysDown[K_DOWN] = true;
} else {
keysDown[K_DOWN] = false;
} // end if
if (this.diffY < -THRESHHOLD){
keysDown[K_UP] = true;
} else {
keysDown[K_UP] = false;
} // end if
} // end if
}; // end onTouchMove
this.onTouchEnd = function(event){
var result = "no touch";
var touches = event.touches;
this.diffX = 0;
this.diffY = 0;
//turn off all virtual keys
if (virtKeys){
keysDown[K_LEFT] = false;
keysDown[K_RIGHT] = false;
keysDown[K_UP] = false;
keysDown[K_DOWN] = false;
}
}; // end onTouchEnd
// add utility methods to retrieve various attributes
this.getDiffX = function(){
//compensate for possible null
if (document.diffX === null){
document.diffX = 0;
} // end if
return document.diffX;
};
this.getDiffY = function(){
//compensate for possible null
if (document.diffY === null){
document.diffY = 0;
} // end if
return document.diffY;
};
this.getMouseX = function(){return document.mouseX;};
this.getMouseY = function(){return document.mouseY;};
//add event handlers if appropriate
touchable = 'createTouch' in document;
if (touchable){
document.addEventListener('touchstart', this.onTouchStart, false);
document.addEventListener('touchmove', this.onTouchMove, false);
document.addEventListener('touchend', this.onTouchEnd, false);
} // end if
} // end joy class def
function Accel(){
//virtual accelerometer
//properties
var ax;
var ay;
var az;
var rotX;
var rotY;
var rotZ;
if (window.DeviceMotionEvent===undefined){
console.log("This program requires an accelerometer");
} else {
window.ondevicemotion = function(event){
this.ax = event.accelerationIncludingGravity.x;
this.ay = event.accelerationIncludingGravity.y;
this.az = event.accelerationIncludingGravity.z;
rotation = event.rotationRate;
if (rotation !== null){
this.rotX = Math.round(rotation.alpha);
this.rotY = Math.round(rotation.beta);
this.rotZ = Math.round(rotation.gamma);
} // end if
}; // end event handler
} // end if
//return values with utility methods
this.getAX = function(){
if (window.ax === null){
window.ax = 0;
}
return window.ax;
}; // end getAx
this.getAY = function(){
if (window.ay === null){
window.ay = 0;
}
return window.ay;
}; // end getAx
this.getAZ = function(){
if (window.az === null){
window.az = 0;
}
return window.az;
}; // end getAx
this.getRotX = function(){return rotX;};
this.getRotY = function(){return rotY;};
this.getRotZ = function(){return rotZ;};
} // end class def
function Timer(){
//simple timer
this.reset = function(){
this.date = new Date();
this.startTime = this.date.getTime();
this.elapsedTime = 0;
}; // end reset
this.getCurrentTime = function(){
this.date = new Date();
return this.date.getTime();
}; // end getCurrentTime
this.getElapsedTime = function(){
var current = this.getCurrentTime();
return (current - this.startTime) / 1000;
}; // end getElapsedTime
//make alias functions for animations...
this.start = this.reset;
this.getTimeElapsed = this.getElapsedTime;
this.reset();
} // end Timer def
var AnimTimer = function() {
//special timer for animations
this.date = new Date();
this.lastTime = 0;
this.currentTime = 0;
this.start = function(){
this.currentTime = Date.now();
};
this.reset = function(){
this.currentTime = Date.now();
};
this.getTimeElapsed = function(){
this.lastTime = this.currentTime;
this.currentTime = Date.now();
return (this.currentTime - this.lastTime);
};
};
function localUpdate(){
//will be called once per frame
//calls the update function defined by
//the user
update();
} // end localUpdate
/* tile and event stuff added by Tyler */
function GameButton(label){
/*
This object creates a button that can be sized
and positioned wherever you wish. The label will
be displayed, but can be complete HTML (including
an image tag if you wish.) Use isClicked() to
get the current status of the button (true or false.)
Responds to touch events on mobile devices.
*/
this.clicked = false;
this.button = document.createElement("button");
this.button.setAttribute("type", "button");
this.button.innerHTML = label;
this.button.style.position = "absolute";
this.button.style.left = "0px";
this.button.style.top = "0px";
this.button.onmousedown = function(){
this.clicked = true;
}; // end mousedown
this.button.ontouchstart = function(){
this.clicked = true;
}; // end touchstart
this.button.onmouseup = function(){
this.clicked = false;
}; // end onmouseup
this.isClicked = function(){
return this.button.clicked;
}; // end isClicked
this.setPos = function(left, top){
this.button.style.left = left + "px";
this.button.style.top = top + "px";
}; // end setPos
this.setPosition = function(left, top){
//utility alias for setPos
this.setPos(left, top);
};
this.setSize = function(width, height){
this.button.style.width = width + "px";
this.button.style.height = height + "px";
}; // end setSize
document.body.appendChild(this.button);
} // end gameButton class def
function Animation(spriteSheet, imgWidth, imgHeight, cellWidth, cellHeight){
//Animation class by Tyler Mitchell
//for simplicity, all cells must be the same width and height combination
this.sheet = spriteSheet;
this.imgWidth = imgWidth;
this.imgHeight = imgHeight;
this.cellWidth = cellWidth;
this.cellHeight = cellHeight;
this.animationLength = 1000;
this.changeLength = false;
this.cycles = [];
this.currentCycleName = "";
this.currentCycle = null;
this.cyclePlaySettings = new Array( PLAY_LOOP, PLAY_LOOP, PLAY_LOOP, PLAY_LOOP );
this.changeAnimation = false;
this.timer = new AnimTimer();
this.framesPerRow = 0;
this.framesPerColumn = 0;
this.totalCycleTime = 0;
this.fps = 0;
this.isPaused = false;
this.setup = function(){
this.timer.start();
this.framesPerRow = this.imgWidth / this.cellWidth;
this.framesPerColumn = this.imgHeight / this.cellHeight;
};
this.addCycle = function(cycleName, startingCell, frames){
var cycle = new Array(cycleName, startingCell, frames);
this.cycles.push(cycle);
};
this.drawFrame = function(ctx){
//most of the math in this function could be done only once if we want to make it faster
var i, currentFrame;
this.fps += 1;
if( !this.isPaused ){ this.totalCycleTime += this.timer.getTimeElapsed(); }
if(this.changeAnimation === true){// find the correct animation in
for( i = 0; i < this.cycles.length; i++ ){
if( this.cycles[i][0] == this.currentCycleName ){
this.currentCycle = this.cycles[i];
}
}
}
if( this.changeAnimation || this.changeLength ){
this.frameDelta = this.animationLength / this.currentCycle[2];
// this will be how much time should pass at a minimum before switching to the next frame
this.changeAnimation = false;
this.changeLength = false;
this.fps = 0;
}
//console.log("Cycletime: " + this.totalCycleTime);
//console.log("Frame Delta: " + this.frameDelta);
//I think the following line is the trouble spot
//currentFrame = Math.floor( (this.totalCycleTime % this.animationLength) / this.frameDelta );
var elTime = this.totalCycleTime % this.animationLength;
currentFrame = Math.floor(elTime / this.frameDelta);
//console.log(elTime);
//document.getElementById("FPS").innerHTML = this.animationLength;//for debugging
var row = Math.floor( ( this.currentCycle[1] + currentFrame ) / this.framesPerRow );
var col = (this.currentCycle[1] + currentFrame) - (row * Math.floor(this.imgWidth / this.cellWidth));
var frameY = row * this.cellHeight;
var frameX = col * this.cellWidth;
ctx.drawImage(this.sheet, frameX, frameY, this.cellWidth, this.cellHeight,
0 - (this.cellWidth / 2), 0 - (this.cellHeight / 2), this.cellWidth, this.cellHeight);
};
this.setCycle = function(cycleName){
this.currentCycleName = cycleName;
this.changeAnimation = true;
this.totalCycleTime = 0;
};
this.renameCycles = function(cycleNames){
var i, number;
for(i = 0; i < cycleNames.length; i++){
number = parseInt( this.cycles[i][0].slice(5),10 );
if(this.currentCycleName == this.cycles[i][0]){
this.currentCycleName = cycleNames[number-1]; }