OLD | NEW |
---|---|
(Empty) | |
1 // Copyright (c) 2014 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 (function() { | |
5 'use strict'; | |
6 /** | |
7 * T-Rex runner. | |
8 * @param {string} outerContainerId Outer containing element id. | |
9 * @param {object} opt_config | |
10 * @constructor | |
11 * @export | |
12 */ | |
13 function Runner(outerContainerId, opt_config) { | |
14 // Singleton | |
15 if (Runner.instance_) { | |
16 return Runner.instance_; | |
17 } | |
18 Runner.instance_ = this; | |
19 | |
20 this.outerContainerEl = document.querySelector(outerContainerId); | |
21 this.containerEl = null; | |
22 | |
23 this.config = opt_config || Runner.config; | |
24 | |
25 this.dimensions = Runner.defaultDimensions; | |
26 | |
27 this.canvas = null; | |
28 this.canvasCtx = null; | |
29 | |
30 this.tRex = null; | |
31 | |
32 this.distanceMeter = null; | |
33 this.distanceRan = 0; | |
34 | |
35 this.highestScore = 0; | |
36 | |
37 this.time = 0; | |
38 this.runningTime = 0; | |
39 this.msPerFrame = 1000 / FPS; | |
40 this.currentSpeed = this.config.SPEED; | |
41 | |
42 this.obstacles = []; | |
43 | |
44 this.started = false; | |
45 this.activated = false; | |
46 this.crashed = false; | |
47 this.paused = false; | |
48 | |
49 this.resizeTimerId_ = null; | |
50 | |
51 this.playCount = 0; | |
52 | |
53 // Sound FX. | |
54 this.audioBuffer = null; | |
55 this.soundFx = {}; | |
56 | |
57 // Global web audio context for playing sounds. | |
58 this.audioContext = new AudioContext(); | |
59 | |
60 // Images. | |
61 this.images = {}; | |
62 this.imagesLoaded = 0; | |
63 this.loadImages(); | |
64 } | |
65 window['Runner'] = Runner; | |
66 | |
67 | |
68 /** | |
69 * Default game width. | |
70 * @const | |
71 */ | |
72 var DEFAULT_WIDTH = 600; | |
73 | |
74 /** | |
75 * Frames per second. | |
76 * @const | |
77 */ | |
78 var FPS = 60; | |
79 | |
80 | |
81 /** | |
82 * Default game configuration. | |
83 * @enum {string} | |
84 */ | |
85 Runner.config = { | |
86 ACCELERATION: 0.001, | |
87 BG_CLOUD_SPEED: 0.2, | |
88 BOTTOM_PAD: 10, | |
89 CLEAR_TIME: 3000, | |
90 CLOUD_FREQUENCY: 0.5, | |
91 GAMEOVER_CLEAR_TIME: 750, | |
92 GAP_COEFFICIENT: 0.6, | |
93 GRAVITY: 0.6, | |
94 INITIAL_JUMP_VELOCITY: 12, | |
95 MAX_CLOUDS: 6, | |
96 MAX_OBSTACLE_LENGTH: 3, | |
97 MAX_SPEED: 12, | |
98 MIN_JUMP_HEIGHT: 35, | |
99 MOBILE_SPEED_COEFFICIENT: 1.2, | |
100 RESOURCE_TEMPLATE_ID: 'audio-resources', | |
101 SPEED: 6, | |
102 SPEED_DROP_COEFFICIENT: 3 | |
103 }; | |
104 | |
105 | |
106 /** | |
107 * Default dimensions. | |
108 * @enum {string} | |
109 */ | |
110 Runner.defaultDimensions = { | |
111 WIDTH: DEFAULT_WIDTH, | |
112 HEIGHT: 150 | |
113 }; | |
114 | |
115 | |
116 /** | |
117 * CSS class names. | |
118 * @enum {string} | |
119 */ | |
120 Runner.classes = { | |
121 CANVAS: 'runner-canvas', | |
122 CONTAINER: 'runner-container', | |
123 CRASHED: 'crashed', | |
124 ICON: 'icon-offline', | |
125 TOUCH_CONTROLLER: 'controller' | |
126 }; | |
127 | |
128 | |
129 /** | |
130 * Image source urls. | |
131 * @enum {string} | |
132 */ | |
133 Runner.imageSources = { | |
134 LDPI: [ | |
135 {name: 'CACTUS_LARGE', id: '1x-obstacle-large'}, | |
136 {name: 'CACTUS_SMALL', id: '1x-obstacle-small'}, | |
137 {name: 'CLOUD', id: '1x-cloud'}, | |
138 {name: 'HORIZON', id: '1x-horizon'}, | |
139 {name: 'RESTART', id: '1x-restart'}, | |
140 {name: 'TEXT_SPRITE', id: '1x-text'}, | |
141 {name: 'TREX', id: '1x-trex'} | |
142 ], | |
arv (Not doing code reviews)
2014/09/19 18:24:28
-2 spaces
Runner.imageSources = {
LDPI: [
{
edwardjung
2014/09/21 20:26:51
Done.
| |
143 HDPI: [ | |
144 {name: 'CACTUS_LARGE', id: '2x-obstacle-large'}, | |
145 {name: 'CACTUS_SMALL', id: '2x-obstacle-small'}, | |
146 {name: 'CLOUD', id: '2x-cloud'}, | |
147 {name: 'HORIZON', id: '2x-horizon'}, | |
148 {name: 'RESTART', id: '2x-restart'}, | |
149 {name: 'TEXT_SPRITE', id: '2x-text'}, | |
150 {name: 'TREX', id: '2x-trex'} | |
151 ] | |
152 }; | |
153 | |
154 | |
155 /** | |
156 * Sound FX. Reference to the ID of the audio tag on interstitial page. | |
157 * @enum {string} | |
158 */ | |
159 Runner.sounds = { | |
160 BUTTON_PRESS: 'offline-sound-press', | |
161 HIT: 'offline-sound-hit', | |
162 SCORE: 'offline-sound-reached' | |
163 }; | |
164 | |
165 | |
166 /** | |
167 * Key code mapping. | |
168 * @enum {string} | |
169 */ | |
170 Runner.keycodes = { | |
arv (Not doing code reviews)
2014/09/19 18:24:27
No space after { nor before }
Two spaces before /
edwardjung
2014/09/21 20:26:52
Done.
| |
171 JUMP: { '38': 1, '32': 1 }, // Up, spacebar | |
172 DUCK: { '40': 1 }, // Down | |
173 RESTART: { '13': 1 } // Enter | |
174 }; | |
175 | |
176 | |
177 /** | |
178 * Runner event names. | |
179 * @enum {string} | |
180 */ | |
181 Runner.events = { | |
182 ANIM_END: 'webkitAnimationEnd', | |
183 CLICK: 'click', | |
184 KEYDOWN: 'keydown', | |
185 KEYUP: 'keyup', | |
186 MOUSEDOWN: 'mousedown', | |
187 MOUSEUP: 'mouseup', | |
188 RESIZE: 'resize', | |
189 TOUCHEND: 'touchend', | |
190 TOUCHSTART: 'touchstart', | |
191 VISIBILITY: 'visibilitychange', | |
192 BLUR: 'blur', | |
193 FOCUS: 'focus', | |
194 LOAD: 'load' | |
195 }; | |
196 | |
197 | |
198 Runner.prototype = { | |
199 /** | |
200 * Setting individual settings for debugging. | |
201 * @param {string} setting | |
202 * @param {*} value | |
203 */ | |
204 updateConfigSetting: function(setting, value) { | |
205 if (setting in this.config && value != undefined) { | |
206 this.config[setting] = value; | |
207 | |
208 switch (setting) { | |
209 case 'GRAVITY': | |
210 case 'MIN_JUMP_HEIGHT': | |
211 case 'SPEED_DROP_COEFFICIENT': | |
212 this.tRex.config[setting] = value; | |
213 break; | |
214 case 'INITIAL_JUMP_VELOCITY': | |
215 this.tRex.setJumpVelocity(value); | |
216 break; | |
217 case 'SPEED': | |
218 this.setSpeed(value); | |
219 break; | |
220 } | |
221 } | |
222 }, | |
223 | |
224 /** | |
225 * Load and cache the image assets from the page. | |
226 */ | |
227 loadImages: function() { | |
228 var imageSources = Runner.isHDPI ? Runner.imageSources.HDPI : | |
229 Runner.imageSources.LDPI; | |
230 | |
231 var numImages = imageSources.length; | |
232 | |
233 for (var i = numImages - 1; i >= 0; i--) { | |
234 var imgSource = imageSources[i]; | |
235 this.images[imgSource.name] = document.getElementById(imgSource.id); | |
236 } | |
237 this.init(); | |
238 }, | |
239 | |
240 /** | |
241 * Load and decode base 64 encoded sounds. | |
242 */ | |
243 loadSounds: function() { | |
244 var resourceTemplate = | |
245 document.getElementById(this.config.RESOURCE_TEMPLATE_ID).content; | |
246 | |
247 | |
arv (Not doing code reviews)
2014/09/19 18:24:27
remove one empty line
edwardjung
2014/09/21 20:26:52
Done.
| |
248 for (var sound in Runner.sounds) { | |
249 var soundSrc = resourceTemplate.getElementById(Runner.sounds[sound]).src; | |
250 soundSrc = soundSrc.substr(soundSrc.indexOf(',') + 1); | |
251 var buffer = Runner.decodeBase64ToArrayBuffer(soundSrc); | |
252 | |
253 // Async, so no guarantee of order in array. | |
254 this.audioContext.decodeAudioData(buffer, function(index, audioData) { | |
255 this.soundFx[index] = audioData; | |
256 }.bind(this, sound)); | |
257 } | |
258 }, | |
259 | |
260 /** | |
261 * Sets the game speed. Adjust the speed accordingly if on a smaller screen. | |
262 * @param {number} opt_speed | |
263 */ | |
264 setSpeed: function(opt_speed) { | |
265 var speed = opt_speed || this.currentSpeed; | |
266 | |
267 // Reduce the speed on smaller mobile screens. | |
268 if (this.dimensions.WIDTH < DEFAULT_WIDTH) { | |
269 var mobileSpeed = speed * ((this.dimensions.WIDTH / DEFAULT_WIDTH) * | |
arv (Not doing code reviews)
2014/09/19 18:24:28
No need for the parens
var mobileSpeed = sp
edwardjung
2014/09/21 20:26:52
Done.
| |
270 this.config.MOBILE_SPEED_COEFFICIENT); | |
271 this.currentSpeed = mobileSpeed > speed ? speed : mobileSpeed; | |
272 } else if (opt_speed) { | |
273 this.currentSpeed = opt_speed; | |
274 } | |
275 }, | |
276 | |
277 /** | |
278 * Game initialiser. | |
279 */ | |
280 init: function() { | |
281 // Hide the static icon. | |
282 document.querySelector('.' + Runner.classes.ICON).style.visibility = | |
283 'hidden'; | |
284 | |
285 this.adjustDimensions(); | |
286 this.setSpeed(); | |
287 | |
288 this.containerEl = document.createElement('div'); | |
289 this.containerEl.className = Runner.classes.CONTAINER; | |
290 | |
291 // Player canvas container. | |
292 this.canvas = Runner.createCanvas(this.containerEl, this.dimensions.WIDTH, | |
293 this.dimensions.HEIGHT, Runner.classes.PLAYER); | |
294 | |
295 this.canvasCtx = this.canvas.getContext('2d'); | |
296 this.canvasCtx.fillStyle = '#f7f7f7'; | |
297 this.canvasCtx.fill(); | |
298 Runner.updateCanvasScaling(this.canvas); | |
299 | |
300 // Horizon contains clouds, obstacles and the ground. | |
301 this.horizon = new Horizon(this.canvas, this.images, this.dimensions, | |
302 this.config.GAP_COEFFICIENT); | |
303 | |
304 // Distance meter | |
305 this.distanceMeter = new DistanceMeter(this.canvas, | |
306 this.images['TEXT_SPRITE'], this.dimensions.WIDTH); | |
307 | |
308 // Draw t-rex | |
309 this.tRex = new Trex(this.canvas, this.images['TREX']); | |
310 | |
311 this.outerContainerEl.appendChild(this.containerEl); | |
312 | |
313 if (Runner.isMobile) { | |
314 this.createTouchController(); | |
315 } | |
316 | |
317 this.startListening(); | |
318 this.update(); | |
319 this.loadSounds(); | |
320 | |
321 window.addEventListener(Runner.events.RESIZE, | |
322 this.debounceResize.bind(this), false); | |
323 }, | |
324 | |
325 /** | |
326 * Create the touch controller. A div that covers whole screen. | |
327 */ | |
328 createTouchController: function() { | |
329 this.touchController = document.createElement('div'); | |
330 this.touchController.className = Runner.classes.TOUCH_CONTROLLER; | |
331 }, | |
332 | |
333 /** | |
334 * Debounce the resize event. | |
335 */ | |
336 debounceResize: function() { | |
337 if (!this.resizeTimerId_) { | |
338 this.resizeTimerId_ = | |
339 setInterval(this.adjustDimensions.bind(this), 250); | |
340 } | |
341 }, | |
342 | |
343 /** | |
344 * Adjust game space dimensions on resize. | |
345 */ | |
346 adjustDimensions: function() { | |
347 clearInterval(this.resizeTimerId_); | |
348 this.resizeTimerId_ = null; | |
349 | |
350 var boxStyles = window.getComputedStyle(this.outerContainerEl); | |
351 var padding = parseInt(boxStyles.paddingLeft.substr(0, | |
arv (Not doing code reviews)
2014/09/19 18:24:28
Maybe use Number instead? I assume you don't expec
edwardjung
2014/09/21 20:26:51
Done.
| |
352 boxStyles.paddingLeft.length - 2)); | |
353 | |
354 this.dimensions.WIDTH = this.outerContainerEl.offsetWidth - (padding * 2); | |
arv (Not doing code reviews)
2014/09/19 18:24:27
this.dimensions.WIDTH = this.outerContainerEl.offs
edwardjung
2014/09/21 20:26:52
Done.
| |
355 | |
356 // Redraw the elements back onto the canvas. | |
357 if (this.canvas) { | |
358 this.canvas.width = this.dimensions.WIDTH; | |
359 this.canvas.height = this.dimensions.HEIGHT; | |
360 | |
361 Runner.updateCanvasScaling(this.canvas); | |
362 | |
363 this.distanceMeter.calcXPos(this.dimensions.WIDTH); | |
364 this.clearCanvas(); | |
365 this.horizon.update(0, 0, true); | |
366 this.tRex.update(0); | |
367 | |
368 // Outer container and distance meter. | |
369 if (this.activated || this.crashed) { | |
370 this.containerEl.style.width = this.dimensions.WIDTH + 'px'; | |
371 this.containerEl.style.height = this.dimensions.HEIGHT + 'px'; | |
372 this.distanceMeter.update(0, Math.ceil(this.distanceRan)); | |
373 this.stop(); | |
374 } else { | |
375 this.tRex.draw(0, 0); | |
376 } | |
377 | |
378 // Game over panel. | |
379 if (this.crashed && this.gameOverPanel) { | |
380 this.gameOverPanel.updateDimensions(this.dimensions.WIDTH); | |
381 this.gameOverPanel.draw(); | |
382 } | |
383 } | |
384 }, | |
385 | |
386 /** | |
387 * Play the game intro. | |
388 * Canvas container width expands out to the full width. | |
389 */ | |
390 playIntro: function() { | |
391 if (!this.started && !this.crashed) { | |
392 this.playingIntro = true; | |
393 this.tRex.playingIntro = true; | |
394 | |
395 // CSS animation definition. | |
396 var keyframes = '@-webkit-keyframes intro { ' + | |
397 'from { width:' + Trex.config.WIDTH + 'px }' + | |
398 'to { width: ' + this.dimensions.WIDTH + 'px }' + | |
399 '}'; | |
400 document.styleSheets[0].insertRule(keyframes, 0); | |
401 | |
402 this.containerEl.addEventListener(Runner.events.ANIM_END, | |
403 this.startGame.bind(this)); | |
404 | |
405 this.containerEl.style.webkitAnimation = 'intro .4s ease-out 1 both'; | |
406 this.containerEl.style.width = this.dimensions.WIDTH + 'px'; | |
407 | |
408 if (this.touchController) { | |
409 this.outerContainerEl.appendChild(this.touchController); | |
410 } | |
411 this.activated = true; | |
412 this.started = true; | |
413 } else if (this.crashed) { | |
414 this.restart(); | |
415 } | |
416 }, | |
417 | |
418 | |
419 /** | |
420 * Update the game status to started. | |
421 */ | |
422 startGame: function() { | |
423 this.runningTime = 0; | |
424 this.playingIntro = false; | |
425 this.tRex.playingIntro = false; | |
426 this.containerEl.style.webkitAnimation = ''; | |
427 this.playCount++; | |
428 | |
429 // Handle tabbing off the page. Pause the current game. | |
430 window.addEventListener(Runner.events.VISIBILITY, | |
431 this.onVisibilityChange.bind(this), false); | |
432 | |
433 window.addEventListener(Runner.events.BLUR, | |
434 this.onVisibilityChange.bind(this), false); | |
435 | |
436 window.addEventListener(Runner.events.FOCUS, | |
437 this.onVisibilityChange.bind(this), false); | |
438 }, | |
439 | |
440 clearCanvas: function() { | |
441 this.canvasCtx.clearRect(0, 0, this.dimensions.WIDTH, | |
442 this.dimensions.HEIGHT); | |
443 }, | |
444 | |
445 /** | |
446 * Update the game frame. | |
447 */ | |
448 update: function() { | |
449 this.drawPending = false; | |
450 | |
451 var now = performance.now(); | |
452 var deltaTime = now - (this.time || now); | |
453 this.time = now; | |
454 | |
455 if (this.activated) { | |
456 this.clearCanvas(); | |
457 | |
458 if (this.tRex.jumping) { | |
459 this.tRex.updateJump(deltaTime, this.config); | |
460 } | |
461 | |
462 this.runningTime += deltaTime; | |
463 var hasObstacles = this.runningTime > this.config.CLEAR_TIME; | |
464 | |
465 // First jump triggers the intro. | |
466 if (this.tRex.jumpCount == 1 && !this.playingIntro) { | |
467 this.playIntro(); | |
468 } | |
469 | |
470 // The horizon doesn't move until the intro is over. | |
471 if (this.playingIntro) { | |
472 this.horizon.update(0, this.currentSpeed, hasObstacles); | |
473 } else { | |
474 deltaTime = !this.started ? 0 : deltaTime; | |
475 this.horizon.update(deltaTime, this.currentSpeed, hasObstacles); | |
476 } | |
477 | |
478 // Check for collisions. | |
479 var collision = hasObstacles ? | |
arv (Not doing code reviews)
2014/09/19 18:24:27
var collision = hasObstacles &&
Runner.Collisi
edwardjung
2014/09/21 20:26:52
Done.
| |
480 Runner.Collision.check(this.horizon.obstacles[0], this.tRex) : false; | |
481 | |
482 if (!collision) { | |
483 this.distanceRan += this.currentSpeed * (deltaTime / this.msPerFrame); | |
arv (Not doing code reviews)
2014/09/19 18:24:27
this.distanceRan += this.currentSpeed * deltaTime
edwardjung
2014/09/21 20:26:52
Done.
| |
484 | |
485 if (this.currentSpeed < this.config.MAX_SPEED) { | |
486 this.currentSpeed += this.config.ACCELERATION; | |
487 } | |
488 } else { | |
489 this.gameOver(); | |
490 } | |
491 | |
492 if (this.distanceMeter.getActualDistance(this.distanceRan) > | |
493 this.distanceMeter.maxScore) { | |
494 this.distanceRan = 0; | |
495 } | |
496 | |
497 var playAcheivementSound = this.distanceMeter.update(deltaTime, | |
498 Math.ceil(this.distanceRan)); | |
499 | |
500 if (playAcheivementSound) { | |
501 this.playSound(this.soundFx.SCORE); | |
502 } | |
503 } | |
504 | |
505 if (!this.crashed) { | |
506 this.tRex.update(deltaTime); | |
507 this.raq(); | |
508 } | |
509 }, | |
510 | |
511 /** | |
512 * Draw the collision boxes on canvas, for debugging. | |
513 * @param {Runner.CollisionBox} collision T-Rex collison box. | |
514 * @param {Runner.CollisionBox} obstacle Obstacle collison box. | |
515 */ | |
516 drawCollisionBoxes: function(collision, obstacle) { | |
517 this.canvasCtx.save(); | |
518 this.canvasCtx.strokeStyle = '#f00'; | |
519 this.canvasCtx.strokeRect(collision[0].x, collision[0].y, | |
520 collision[0].width, collision[0].height); | |
521 | |
522 this.canvasCtx.strokeStyle = '#00f'; | |
523 this.canvasCtx.strokeRect(collision[1].x, collision[1].y, | |
524 collision[1].width, collision[1].height); | |
525 this.canvasCtx.restore(); | |
526 }, | |
527 | |
528 /** | |
529 * Event handler. | |
530 */ | |
531 handleEvent: function(e) { | |
532 return (function(evtType, events) { | |
533 switch (evtType) { | |
534 case events.KEYDOWN: | |
535 case events.TOUCHSTART: | |
536 case events.MOUSEDOWN: | |
537 this.onKeyDown(e); | |
538 break; | |
539 case events.KEYUP: | |
540 case events.TOUCHEND: | |
541 case events.MOUSEUP: | |
542 this.onKeyUp(e); | |
543 break; | |
544 } | |
545 }.bind(this))(e.type, Runner.events); | |
546 }, | |
547 | |
548 /** | |
549 * Bind relevant key / mouse / touch listeners. | |
550 */ | |
551 startListening: function() { | |
552 // Keys. | |
553 document.addEventListener(Runner.events.KEYDOWN, this); | |
554 document.addEventListener(Runner.events.KEYUP, this); | |
555 | |
556 if (Runner.isMobile) { | |
557 // Mobile only touch devices. | |
558 this.touchController.addEventListener(Runner.events.TOUCHSTART, this); | |
559 this.touchController.addEventListener(Runner.events.TOUCHEND, this); | |
560 this.containerEl.addEventListener(Runner.events.TOUCHSTART, this); | |
561 } else { | |
562 // Mouse. | |
563 document.addEventListener(Runner.events.MOUSEDOWN, this, false); | |
arv (Not doing code reviews)
2014/09/19 18:24:27
or
document.addEventListener(Runner.events.MOUSED
edwardjung
2014/09/21 20:26:51
Done.
| |
564 document.addEventListener(Runner.events.MOUSEUP, this, false); | |
565 } | |
566 }, | |
567 | |
568 /** | |
569 * Remove all listeners. | |
570 */ | |
571 stopListening: function() { | |
572 document.removeEventListener(Runner.events.KEYDOWN, this); | |
573 document.removeEventListener(Runner.events.KEYUP, this); | |
574 | |
575 if (Runner.isMobile) { | |
576 this.touchController.removeEventListener(Runner.events.TOUCHSTART, this); | |
577 this.touchController.removeEventListener(Runner.events.TOUCHEND, this); | |
578 this.containerEl.removeEventListener(Runner.events.TOUCHSTART, this); | |
579 } else { | |
580 document.removeEventListener(Runner.events.MOUSEDOWN, this, false); | |
581 document.removeEventListener(Runner.events.MOUSEUP, this, false); | |
582 } | |
583 }, | |
584 | |
585 /** | |
586 * Process keydown. | |
587 * @param {Event} e | |
588 */ | |
589 onKeyDown: function(e) { | |
590 | |
arv (Not doing code reviews)
2014/09/19 18:24:28
remove empty line
edwardjung
2014/09/21 20:26:51
Done.
| |
591 if (!this.crashed && (Runner.keycodes.JUMP[String(e.keyCode)] || | |
592 e.type == Runner.events.TOUCHSTART)) { | |
593 if (!this.activated) { | |
594 this.activated = true; | |
595 } | |
596 | |
597 if (!this.tRex.jumping) { | |
598 this.playSound(this.soundFx.BUTTON_PRESS); | |
599 this.tRex.startJump(); | |
600 } | |
601 } | |
602 | |
603 if (this.crashed && e.type == Runner.events.TOUCHSTART && | |
604 e.currentTarget == this.containerEl) { | |
605 this.restart(); | |
606 } | |
607 | |
608 // Speed drop, activated only when jump key is not pressed. | |
609 if (Runner.keycodes.DUCK[e.keyCode] && this.tRex.jumping) { | |
610 e.preventDefault(); | |
611 this.tRex.setSpeedDrop(); | |
612 } | |
613 }, | |
614 | |
615 | |
616 /** | |
617 * Process key up. | |
618 * @param {Event} e | |
619 */ | |
620 onKeyUp: function(e) { | |
621 var keyCode = String(e.keyCode); | |
622 var isjumpKey = Runner.keycodes.JUMP[keyCode] || | |
623 e.type == Runner.events.TOUCHEND || | |
624 e.type == Runner.events.MOUSEDOWN; | |
625 | |
626 if (this.isRunning() && isjumpKey) { | |
627 this.tRex.endJump(); | |
628 } else if (Runner.keycodes.DUCK[keyCode]) { | |
629 this.tRex.speedDrop = false; | |
630 } else if (this.crashed) { | |
631 // Check that enough time has elapsed before allowing jump key to restart. | |
632 var deltaTime = performance.now() - this.time; | |
633 | |
634 if (Runner.keycodes.RESTART[keyCode] || | |
635 (e.type == Runner.events.MOUSEUP && e.target == this.canvas) || | |
636 (deltaTime >= this.config.GAMEOVER_CLEAR_TIME && | |
637 Runner.keycodes.JUMP[keyCode])) { | |
638 this.restart(); | |
639 } | |
640 } else if (this.paused && isjumpKey) { | |
641 this.play(); | |
642 } | |
643 }, | |
644 | |
645 /** | |
646 * RequestAnimationFrame wrapper. | |
647 */ | |
648 raq: function() { | |
649 if (!this.drawPending) { | |
650 this.drawPending = true; | |
651 this.raqId = requestAnimationFrame(this.update.bind(this)); | |
652 } | |
653 }, | |
654 | |
655 /** | |
656 * Whether the game is running. | |
657 * @return {boolean} | |
658 */ | |
659 isRunning: function() { | |
660 return !!this.raqId; | |
661 }, | |
662 | |
663 /** | |
664 * Game over state. | |
665 */ | |
666 gameOver: function() { | |
667 this.playSound(this.soundFx.HIT); | |
668 Runner.vibrate(200); | |
669 | |
670 this.stop(); | |
671 this.crashed = true; | |
672 this.distanceMeter.acheivement = false; | |
673 | |
674 this.tRex.update(100, Trex.status.CRASHED); | |
675 | |
676 // Game over panel. | |
677 if (!this.gameOverPanel) { | |
678 this.gameOverPanel = new Runner.GameOverPanel(this.canvas, | |
679 this.images['TEXT_SPRITE'], this.images['RESTART'], | |
680 this.dimensions); | |
681 } else { | |
682 this.gameOverPanel.draw(); | |
683 } | |
684 | |
685 // Update the high score. | |
686 if (this.distanceRan > this.highestScore) { | |
687 this.highestScore = Math.ceil(this.distanceRan); | |
688 this.distanceMeter.setHighScore(this.highestScore); | |
689 } | |
690 | |
691 // Reset the time clock. | |
692 this.time = performance.now(); | |
693 }, | |
694 | |
695 stop: function() { | |
696 this.activated = false; | |
697 this.paused = true; | |
698 cancelAnimationFrame(this.raqId); | |
699 this.raqId = 0; | |
700 }, | |
701 | |
702 play: function() { | |
703 if (!this.crashed) { | |
704 this.activated = true; | |
705 this.paused = false; | |
706 this.tRex.update(0, Trex.status.RUNNING); | |
707 this.time = performance.now(); | |
708 this.update(); | |
709 } | |
710 }, | |
711 | |
712 restart: function() { | |
713 if (!this.raqId) { | |
714 this.playCount++; | |
715 this.runningTime = 0; | |
716 this.activated = true; | |
717 this.crashed = false; | |
718 this.distanceRan = 0; | |
719 this.setSpeed(this.config.SPEED); | |
720 | |
721 this.time = performance.now(); | |
722 this.containerEl.classList.remove(Runner.classes.CRASHED); | |
723 this.clearCanvas(); | |
724 this.distanceMeter.reset(this.highestScore); | |
725 this.horizon.reset(); | |
726 this.tRex.reset(); | |
727 this.playSound(this.soundFx.BUTTON_PRESS); | |
728 | |
729 this.update(); | |
730 } | |
731 }, | |
732 | |
733 /** | |
734 * Pause the game if the tab is not in focus. | |
735 */ | |
736 onVisibilityChange: function(e) { | |
737 if (document.hidden || document.webkitHidden || e.type == 'blur') { | |
738 this.stop(); | |
739 } else { | |
740 this.play(); | |
741 } | |
742 }, | |
743 | |
744 /** | |
745 * Play a sound. | |
746 * @param {SoundBuffer} soundBuffer | |
747 */ | |
748 playSound: function(soundBuffer) { | |
749 if (soundBuffer) { | |
750 var sourceNode = this.audioContext['createBufferSource'](); | |
751 sourceNode.buffer = soundBuffer; | |
752 sourceNode['connect'](this.audioContext['destination']); | |
753 sourceNode['start'](0); | |
754 } | |
755 } | |
756 }; | |
757 | |
758 | |
759 /** | |
760 * Updates the canvas size taking into | |
761 * account the backing store pixel ratio and | |
762 * the device pixel ratio. | |
763 * | |
764 * See article by Paul Lewis: | |
765 * http://www.html5rocks.com/en/tutorials/canvas/hidpi/ | |
766 * | |
767 * @param {HTMLCanvasElement} canvas | |
768 * @param {number} opt_width | |
769 * @param {number} opt_height | |
770 * @return {boolean} Whether the canvas was scaled. | |
771 */ | |
772 Runner.updateCanvasScaling = function(canvas, opt_width, opt_height) { | |
773 | |
774 var context = canvas.getContext('2d'); | |
775 | |
776 // Query the various pixel ratios | |
777 var devicePixelRatio = Math.floor(window.devicePixelRatio) || 1; | |
778 var backingStoreRatio = Math.floor(context.webkitBackingStorePixelRatio) || 1; | |
779 var ratio = devicePixelRatio / backingStoreRatio; | |
780 | |
781 // Upscale the canvas if the two ratios don't match | |
782 if (devicePixelRatio !== backingStoreRatio) { | |
783 | |
784 var oldWidth = opt_width || canvas.width; | |
785 var oldHeight = opt_height || canvas.height; | |
786 | |
787 canvas.width = oldWidth * ratio; | |
788 canvas.height = oldHeight * ratio; | |
789 | |
790 canvas.style.width = oldWidth + 'px'; | |
791 canvas.style.height = oldHeight + 'px'; | |
792 | |
793 // Scale the context to counter the fact that we've manually scaled | |
794 // our canvas element. | |
795 context.scale(ratio, ratio); | |
796 return true; | |
797 } | |
798 return false; | |
799 }; | |
800 | |
801 | |
802 /** | |
803 * Get random number. | |
804 * @param {number} min | |
805 * @param {number} max | |
806 * @param {number} A random number. | |
807 */ | |
808 Runner.getRandomNum = function(min, max) { | |
809 return Math.floor(Math.random() * (max - min + 1)) + min; | |
810 }; | |
811 | |
812 | |
813 /** | |
814 * Vibrate on mobile devices. | |
815 * @param {number} duration Duration of the vibration in milliseconds. | |
816 */ | |
817 Runner.vibrate = function(duration) { | |
818 if (Runner.isMobile) { | |
819 window.navigator['vibrate'](duration); | |
820 } | |
821 }; | |
822 | |
823 | |
824 /** | |
825 * Create canvas element. | |
826 * @param {HTMLElement} container Element to append canvas to. | |
827 * @param {number} width | |
828 * @param {number} height | |
829 * @param {string} opt_classname | |
830 * @return {HTMLCanvasElement} | |
831 */ | |
832 Runner.createCanvas = function(container, width, height, opt_classname) { | |
833 var canvas = document.createElement('canvas'); | |
834 canvas.className = opt_classname ? Runner.classes.CANVAS + ' ' + | |
835 opt_classname : Runner.classes.CANVAS; | |
836 canvas.width = width; | |
837 canvas.height = height; | |
838 container.appendChild(canvas); | |
839 | |
840 return canvas; | |
841 }; | |
842 | |
843 | |
844 /** | |
845 * Decodes the base 64 audio to ArrayBuffer used by Web Audio. | |
846 * @param {string} base64String | |
847 */ | |
848 Runner.decodeBase64ToArrayBuffer = function(base64String) { | |
849 | |
850 var len = (base64String.length / 4) * 3; | |
851 var str = atob(base64String); | |
852 var arrayBuffer = new ArrayBuffer(len); | |
853 var bytes = new Uint8Array(arrayBuffer); | |
854 | |
855 for (var i = 0; i < len; i++) { | |
856 bytes[i] = str.charCodeAt(i); | |
857 } | |
858 return bytes.buffer; | |
859 }; | |
860 | |
861 | |
862 Runner.test = {}; | |
arv (Not doing code reviews)
2014/09/19 18:24:27
No need for the extra functions.
Runner.test = {
edwardjung
2014/09/21 20:26:52
Done.
| |
863 | |
864 /** | |
865 * Test for mobile platform. | |
866 * @return {boolean} Whether the platform is mobile. | |
867 */ | |
868 Runner.test.mobile = function() { | |
869 return window.navigator.userAgent.indexOf('Mobi') > -1; | |
870 }; | |
871 | |
872 /** | |
873 * Test for hi DPI. | |
874 * @return {boolean} Whether the device has a high device pixel ratio. | |
875 */ | |
876 Runner.test.hiDPI = function() { | |
877 return window.devicePixelRatio > 1; | |
878 }; | |
879 | |
880 | |
881 /** | |
882 * Test for touch. | |
883 * @return {boolean} Whether touch support is available. | |
884 */ | |
885 Runner.test.touchEnabled = function() { | |
886 return 'ontouchstart' in window; | |
887 }; | |
888 | |
889 | |
890 Runner.isHDPI = Runner.test.hiDPI(); | |
891 | |
892 Runner.isMobile = Runner.test.mobile(); | |
893 | |
894 Runner.isTouchEnabled = Runner.test.touchEnabled(); | |
895 | |
896 | |
897 //****************************************************************************** | |
898 | |
899 | |
900 /** | |
901 * Game over panel. | |
902 * @param {!HTMLCanvasElement} canvas | |
903 * @param {!HTMLImage} textSprite | |
904 * @param {!HTMLImage} restartImg | |
905 * @param {!Object} dimensions Canvas dimensions. | |
906 * @constructor | |
907 */ | |
908 Runner.GameOverPanel = function(canvas, textSprite, restartImg, dimensions) { | |
arv (Not doing code reviews)
2014/09/19 18:24:28
Runner.GameOverPanel = function(canvas, textSprite
edwardjung
2014/09/21 20:26:52
Done.
| |
909 this.canvas = canvas; | |
910 | |
911 this.canvasCtx = canvas.getContext('2d'); | |
912 | |
913 this.canvasDimensions = dimensions; | |
914 | |
915 this.textSprite = textSprite; | |
916 | |
917 this.restartImg = restartImg; | |
918 | |
919 this.draw(); | |
920 }; | |
921 | |
922 | |
923 /** | |
924 * Dimensions used in the panel. | |
925 * @enum {string} | |
926 */ | |
927 Runner.GameOverPanel.dimensions = { | |
928 TEXT_X: 0, | |
929 TEXT_Y: 13, | |
930 TEXT_WIDTH: 191, | |
931 TEXT_HEIGHT: 11, | |
932 RESTART_WIDTH: 36, | |
933 RESTART_HEIGHT: 32 | |
934 }; | |
935 | |
936 | |
937 Runner.GameOverPanel.prototype = { | |
938 /** | |
939 * Update the panel dimensions. | |
940 * @param {number} width New canvas width. | |
941 * @param {number} opt_height Optional new canvas height. | |
942 */ | |
943 updateDimensions: function(width, opt_height) { | |
944 this.canvasDimensions.WIDTH = width; | |
945 if (opt_height) { | |
946 this.canvasDimensions.HEIGHT = opt_height; | |
947 } | |
948 }, | |
949 | |
950 /** | |
951 * Draw the panel. | |
952 */ | |
953 draw: function() { | |
954 var dimensions = Runner.GameOverPanel.dimensions; | |
955 | |
956 var centerX = this.canvasDimensions.WIDTH / 2; | |
957 | |
958 // Game over text. | |
959 var textSourceX = dimensions.TEXT_X; | |
960 var textSourceY = dimensions.TEXT_Y; | |
961 var textSourceWidth = dimensions.TEXT_WIDTH; | |
962 var textSourceHeight = dimensions.TEXT_HEIGHT; | |
963 | |
964 var textTargetX = Math.round(centerX - (dimensions.TEXT_WIDTH / 2)); | |
965 var textTargetY = Math.round((this.canvasDimensions.HEIGHT - 25) / 3); | |
966 var textTargetWidth = dimensions.TEXT_WIDTH; | |
967 var textTargetHeight = dimensions.TEXT_HEIGHT; | |
968 | |
969 var restartSourceWidth = dimensions.RESTART_WIDTH; | |
970 var restartSourceHeight = dimensions.RESTART_HEIGHT; | |
971 var restartTargetX = centerX - (dimensions.RESTART_WIDTH / 2); | |
972 var restartTargetY = this.canvasDimensions.HEIGHT / 2; | |
973 | |
974 | |
975 if (Runner.isHDPI) { | |
976 textSourceY *= 2; | |
977 textSourceX *= 2; | |
978 textSourceWidth = textSourceWidth * 2; | |
arv (Not doing code reviews)
2014/09/19 18:24:27
Why not *= here too?
edwardjung
2014/09/21 20:26:52
Done.
| |
979 textSourceHeight = textSourceHeight * 2; | |
980 restartSourceWidth = restartSourceWidth * 2; | |
981 restartSourceHeight = restartSourceHeight * 2; | |
982 } | |
983 | |
984 // Game over text from sprite. | |
985 this.canvasCtx.drawImage(this.textSprite, | |
986 textSourceX, textSourceY, textSourceWidth, textSourceHeight, | |
987 textTargetX, textTargetY, textTargetWidth, textTargetHeight); | |
988 | |
989 // Restart button. | |
990 this.canvasCtx.drawImage(this.restartImg, 0, 0, | |
991 restartSourceWidth, restartSourceHeight, | |
992 restartTargetX, restartTargetY, dimensions.RESTART_WIDTH, | |
993 dimensions.RESTART_HEIGHT); | |
994 } | |
995 }; | |
996 | |
997 | |
998 | |
999 //****************************************************************************** | |
1000 | |
1001 /** | |
1002 * Collision checker utilities. | |
1003 */ | |
1004 Runner.Collision = function() {}; | |
1005 | |
1006 | |
1007 /** | |
1008 * Check for a collision. | |
1009 * @param {!Runner.Obstacle} obstacle | |
1010 * @param {!Trex} tRex T-rex object. | |
1011 * @param {HTMLCanvasContext} opt_canvasCtx Optional canvas context for drawing | |
1012 * collision boxes. | |
1013 * @return {Array.<Runner.CollisionBox>} | |
1014 */ | |
1015 Runner.Collision.check = function(obstacle, tRex, opt_canvasCtx) { | |
1016 var obstacleBoxXPos = Runner.defaultDimensions.WIDTH + obstacle.xPos; | |
1017 | |
1018 // Adjustments are made to the bounding box as there is a 1 pixel white | |
1019 // border around the t-rex and obstacles. | |
1020 var tRexBox = new Runner.CollisionBox( | |
arv (Not doing code reviews)
2014/09/19 18:24:27
var tRexBox = new Runner.CollisionBox(
tRex.
edwardjung
2014/09/21 20:26:51
Done.
| |
1021 tRex.xPos + 1, | |
1022 tRex.yPos + 1, | |
1023 tRex.config.WIDTH - 2, | |
1024 tRex.config.HEIGHT - 2 | |
1025 ); | |
1026 | |
1027 var obstacleBox = new Runner.CollisionBox( | |
1028 obstacle.xPos + 1, | |
1029 obstacle.yPos + 1, | |
1030 obstacle.typeConfig.width * obstacle.size - 2, | |
1031 obstacle.typeConfig.height - 2 | |
1032 ); | |
1033 | |
1034 // Debug outer box | |
1035 if (opt_canvasCtx) { | |
1036 Runner.Collision.drawCollisionBoxes(opt_canvasCtx, tRexBox, obstacleBox); | |
1037 } | |
1038 | |
1039 // Simple outer bounds check. | |
1040 if (Runner.Collision.boxCompare(tRexBox, obstacleBox)) { | |
1041 var collisionBoxes = obstacle.collisionBoxes; | |
1042 var tRexCollisionBoxes = Trex.collisionBoxes; | |
1043 | |
1044 // Detailed axis aligned box check. | |
1045 for (var t = 0; t < tRexCollisionBoxes.length; t++) { | |
1046 for (var i = 0; i < collisionBoxes.length; i++) { | |
1047 // Adjust the box to actual positions. | |
1048 var adjTrexBox = | |
1049 Runner.Collision.createAdjustedCollisionBox(tRexCollisionBoxes[t], | |
1050 tRexBox); | |
1051 var adjObstacleBox = | |
1052 Runner.Collision.createAdjustedCollisionBox(collisionBoxes[i], | |
1053 obstacleBox); | |
1054 | |
1055 var crashed = Runner.Collision.boxCompare(adjTrexBox, adjObstacleBox); | |
1056 | |
1057 // Draw boxes for debug. | |
1058 if (opt_canvasCtx) { | |
1059 Runner.Collision.drawCollisionBoxes(opt_canvasCtx, | |
1060 adjTrexBox, adjObstacleBox); | |
1061 } | |
1062 | |
1063 if (crashed) { | |
1064 return [adjTrexBox, adjObstacleBox]; | |
1065 } | |
1066 } | |
1067 } | |
1068 } | |
1069 return false; | |
1070 }; | |
1071 | |
1072 | |
1073 /** | |
1074 * Adjust the collision box. | |
1075 * @param {!Runner.CollisionBox} box The original box. | |
1076 * @param {!Runner.CollisionBox} adjustment Adjustment box. | |
1077 * @return {Runner.CollisionBox} The adjusted collision box object. | |
1078 */ | |
1079 Runner.Collision.createAdjustedCollisionBox = function(box, adjustment) { | |
1080 return new Runner.CollisionBox( | |
1081 box.x + adjustment.x, | |
1082 box.y + adjustment.y, | |
1083 box.width, | |
1084 box.height); | |
1085 }; | |
1086 | |
1087 | |
1088 /** | |
1089 * Draw the collision box for debug. | |
1090 */ | |
1091 Runner.Collision.drawCollisionBoxes = | |
1092 function(canvasCtx, tRexBox, obstacleBox) { | |
1093 canvasCtx.save(); | |
1094 canvasCtx.strokeStyle = '#f00'; | |
1095 canvasCtx.strokeRect(tRexBox.x, tRexBox.y, | |
1096 tRexBox.width, tRexBox.height); | |
1097 | |
1098 canvasCtx.strokeStyle = '#0f0'; | |
1099 canvasCtx.strokeRect(obstacleBox.x, obstacleBox.y, | |
1100 obstacleBox.width, obstacleBox.height); | |
1101 canvasCtx.restore(); | |
1102 }; | |
1103 | |
1104 | |
1105 /** | |
1106 * Compare two collision boxes for a collision. | |
1107 * @param {Runner.CollisionBox} tRexBox | |
1108 * @param {Runner.CollisionBox} obstacleBox | |
1109 * @return {boolean} Whether the boxes intersected. | |
1110 */ | |
1111 Runner.Collision.boxCompare = function(tRexBox, obstacleBox) { | |
1112 var crashed = false; | |
1113 var tRexBoxX = tRexBox.x; | |
1114 var tRexBoxY = tRexBox.y; | |
1115 | |
1116 var obstacleBoxX = obstacleBox.x; | |
1117 var obstacleBoxY = obstacleBox.y; | |
1118 | |
1119 // Axis-Aligned Bounding Box method. | |
1120 if (tRexBox.x < obstacleBoxX + obstacleBox.width && | |
1121 tRexBox.x + tRexBox.width > obstacleBoxX && | |
1122 tRexBox.y < obstacleBox.y + obstacleBox.height && | |
1123 tRexBox.height + tRexBox.y > obstacleBox.y) { | |
1124 crashed = true; | |
1125 } | |
1126 | |
1127 return crashed; | |
1128 }; | |
1129 | |
1130 | |
1131 //****************************************************************************** | |
1132 | |
1133 /** | |
1134 * Collision box object. | |
1135 * @param {number} x X position. | |
1136 * @param {number} y Y Position. | |
1137 * @param {number} w Width. | |
1138 * @param {number} h Height. | |
1139 */ | |
1140 Runner.CollisionBox = function(x, y, w, h) { | |
1141 this.x = x; | |
1142 this.y = y; | |
1143 this.width = w; | |
1144 this.height = h; | |
1145 }; | |
1146 | |
1147 | |
1148 //****************************************************************************** | |
1149 | |
1150 /** | |
1151 * Obstacle. | |
1152 * @param {HTMLCanvasCtx} canvasCtx | |
1153 * @param {Runner.Obstacle.type} type | |
1154 * @param {image} obstacleImg Image sprite. | |
1155 * @param {Object} dimensions | |
1156 * @param {number} gapCoefficient Mutipler in determining the gap. | |
1157 * @param {number} speed | |
1158 */ | |
1159 Runner.Obstacle = function(canvasCtx, type, obstacleImg, dimensions, | |
1160 gapCoefficient, speed) { | |
1161 | |
1162 this.canvasCtx = canvasCtx; | |
1163 | |
1164 this.image = obstacleImg; | |
1165 | |
1166 this.typeConfig = type; | |
1167 | |
1168 this.gapCoefficient = gapCoefficient; | |
1169 | |
1170 this.size = Runner.getRandomNum(1, Runner.Obstacle.MAX_OBSTACLE_LENGTH); | |
1171 | |
1172 this.dimensions = dimensions; | |
1173 | |
1174 this.remove = false; | |
1175 | |
1176 this.xPos = 0; | |
1177 | |
1178 this.yPos = this.typeConfig.yPos; | |
1179 | |
1180 this.width = 0; | |
1181 | |
1182 this.collisionBoxes = []; | |
1183 | |
1184 this.gap = 0; | |
1185 | |
1186 this.init(speed); | |
1187 }; | |
1188 | |
1189 /** | |
1190 * | |
1191 */ | |
1192 Runner.Obstacle.MAX_GAP_COEFFICIENT = 1.5; | |
1193 | |
1194 /** | |
1195 * Maximum obstacle grouping count. | |
1196 */ | |
1197 Runner.Obstacle.MAX_OBSTACLE_LENGTH = 3, | |
1198 | |
1199 | |
1200 Runner.Obstacle.prototype = { | |
1201 /** | |
1202 * Initialise the DOM for the obstacle. | |
1203 * @param {number} speed | |
1204 */ | |
1205 init: function(speed) { | |
1206 this.cloneCollisionBoxes(); | |
1207 | |
1208 // Only allow sizing if we're at the right speed. | |
1209 if (this.size > 1 && this.typeConfig.multipleSpeed > speed) { | |
1210 this.size = 1; | |
1211 } | |
1212 | |
1213 this.width = this.typeConfig.width * this.size; | |
1214 | |
1215 this.xPos = this.dimensions.WIDTH - this.width; | |
1216 | |
1217 this.draw(); | |
1218 | |
1219 // Make collision box adjustments, | |
1220 // Central box is adjusted to the size as one box. | |
1221 // ____ ______ ________ | |
1222 // _| |-| _| |-| _| |-| | |
1223 // | |<->| | | |<--->| | | |<----->| | | |
1224 // | | 1 | | | | 2 | | | | 3 | | | |
1225 // |_|___|_| |_|_____|_| |_|_______|_| | |
1226 // | |
1227 if (this.size > 1) { | |
1228 this.collisionBoxes[1].width = this.width - this.collisionBoxes[0].width - | |
1229 this.collisionBoxes[2].width; | |
1230 this.collisionBoxes[2].x = this.width - this.collisionBoxes[2].width; | |
1231 } | |
1232 | |
1233 this.gap = this.getGap(this.gapCoefficient, speed); | |
1234 }, | |
1235 | |
1236 /** | |
1237 * Draw and crop based on size. | |
1238 */ | |
1239 draw: function() { | |
1240 var sourceWidth = this.typeConfig.width; | |
1241 var sourceHeight = this.typeConfig.height; | |
1242 | |
1243 if (Runner.isHDPI) { | |
1244 sourceWidth = sourceWidth * 2; | |
1245 sourceHeight = sourceHeight * 2; | |
1246 } | |
1247 | |
1248 // Sprite | |
1249 var sourceX = (sourceWidth * this.size) * (0.5 * (this.size - 1)); | |
1250 this.canvasCtx.drawImage(this.image, | |
1251 sourceX, 0, | |
1252 sourceWidth * this.size, sourceHeight, | |
1253 this.xPos, this.yPos, | |
1254 this.typeConfig.width * this.size, this.typeConfig.height); | |
1255 }, | |
1256 | |
1257 /** | |
1258 * Obstacle frame update. | |
1259 * @param {number} deltaTime | |
1260 * @param {number} speed | |
1261 */ | |
1262 update: function(deltaTime, speed) { | |
1263 if (!this.remove) { | |
1264 this.xPos -= Math.floor((speed * FPS / 1000) * deltaTime); | |
1265 this.draw(); | |
1266 | |
1267 if (!this.isVisible()) { | |
1268 this.remove = true; | |
1269 } | |
1270 } | |
1271 }, | |
1272 | |
1273 /** | |
1274 * Calculate a random gap size. | |
1275 * - Minimum gap gets wider as speed increses | |
1276 * @param {number} gapCoefficient | |
1277 * @param {number} speed | |
1278 * @return {number} The gap size. | |
1279 */ | |
1280 getGap: function(gapCoefficient, speed) { | |
1281 var minGap = Math.round((this.width * speed) + | |
arv (Not doing code reviews)
2014/09/19 18:24:28
useless parens
edwardjung
2014/09/21 20:26:52
Done.
| |
1282 (this.typeConfig.minGap * gapCoefficient)); | |
arv (Not doing code reviews)
2014/09/19 18:24:28
useless parens
edwardjung
2014/09/21 20:26:52
Done.
| |
1283 var maxGap = Math.round(minGap * Runner.Obstacle.MAX_GAP_COEFFICIENT); | |
1284 return Runner.getRandomNum(minGap, maxGap); | |
1285 }, | |
1286 | |
1287 /** | |
1288 * Check if obstacle is visible. | |
1289 * @return {boolean} Whether the obstacle is in the game area. | |
1290 */ | |
1291 isVisible: function() { | |
1292 return (this.xPos + this.width) > 0; | |
arv (Not doing code reviews)
2014/09/19 18:24:28
useless parens
edwardjung
2014/09/21 20:26:51
Done.
| |
1293 }, | |
1294 | |
1295 /** | |
1296 * Make a copy of the collision boxes, since these will change based on | |
1297 * obstacle type and size. | |
1298 */ | |
1299 cloneCollisionBoxes: function() { | |
1300 var collisionBoxes = this.typeConfig.collisionBoxes; | |
1301 | |
1302 for (var i = collisionBoxes.length - 1; i >= 0; i--) { | |
1303 this.collisionBoxes[i] = new Runner.CollisionBox(collisionBoxes[i].x, | |
1304 collisionBoxes[i].y, collisionBoxes[i].width, | |
1305 collisionBoxes[i].height); | |
1306 } | |
1307 } | |
1308 }; | |
1309 | |
1310 | |
1311 /** | |
1312 * Obstacle definitions. | |
1313 * minGap: minimum pixel space betweeen obstacles. | |
1314 * multipleSpeed: Speed at which multiples are allowed. | |
1315 */ | |
1316 Runner.Obstacle.types = [ | |
1317 { | |
1318 type: 'CACTUS_SMALL', | |
1319 className: ' cactus cactus-small ', | |
1320 width: 17, | |
1321 height: 35, | |
1322 yPos: 105, | |
1323 multipleSpeed: 3, | |
1324 minGap: 120, | |
1325 collisionBoxes: [ | |
1326 new Runner.CollisionBox(0, 7, 5, 27), | |
1327 new Runner.CollisionBox(4, 0, 6, 34), | |
1328 new Runner.CollisionBox(10, 4, 7, 14) | |
1329 ] | |
1330 }, | |
1331 { | |
1332 type: 'CACTUS_LARGE', | |
1333 className: ' cactus cactus-large ', | |
1334 width: 25, | |
1335 height: 50, | |
1336 yPos: 90, | |
1337 multipleSpeed: 6, | |
1338 minGap: 120, | |
1339 collisionBoxes: [ | |
1340 new Runner.CollisionBox(0, 12, 7, 38), | |
1341 new Runner.CollisionBox(8, 0, 7, 49), | |
1342 new Runner.CollisionBox(13, 10, 10, 38) | |
1343 ] | |
1344 } | |
1345 ]; | |
1346 | |
1347 | |
1348 //****************************************************************************** | |
1349 /** | |
1350 * T-rex game character. | |
1351 * @param {HTMLCanvas} canvas | |
1352 * @param {HTMLImage} image Character image. | |
1353 * @constructor | |
1354 */ | |
1355 function Trex(canvas, image) { | |
1356 this.canvas = canvas; | |
1357 this.canvasCtx = canvas.getContext('2d'); | |
1358 | |
1359 this.image = image; | |
1360 | |
1361 this.xPos = 0; | |
1362 | |
1363 this.yPos = 0; | |
1364 | |
1365 // Position when on the ground. | |
1366 this.groundYPos = 0; | |
1367 | |
1368 this.currentFrame = 0; | |
1369 | |
1370 this.currentAnimFrames = []; | |
1371 | |
1372 this.blinkDelay = 0; | |
1373 | |
1374 this.animStartTime = 0; | |
1375 | |
1376 this.timer = 0; | |
1377 | |
1378 this.msPerFrame = 1000 / FPS; | |
1379 | |
1380 this.config = Trex.config; | |
1381 | |
1382 // Current status. | |
1383 this.status = Trex.status.WAITING; | |
1384 | |
1385 this.jumping = false; | |
1386 | |
1387 this.jumpVelocity = 0; | |
1388 | |
1389 this.reachedMinHeight = false; | |
1390 | |
1391 this.speedDrop = false; | |
1392 | |
1393 this.jumpCount = 0; | |
1394 | |
1395 this.jumpspotX = 0; | |
1396 | |
1397 this.init(); | |
1398 }; | |
1399 | |
1400 | |
1401 /** | |
1402 * T-rex player config. | |
1403 */ | |
1404 Trex.config = { | |
1405 DROP_VELOCITY: -5, | |
1406 GRAVITY: 0.6, | |
1407 HEIGHT: 47, | |
1408 INIITAL_JUMP_VELOCITY: -10, | |
1409 INTRO_DURATION: 1500, | |
1410 MAX_JUMP_HEIGHT: 30, | |
1411 MIN_JUMP_HEIGHT: 30, | |
1412 SPEED_DROP_COEFFICIENT: 3, | |
1413 SPRITE_WIDTH: 262, | |
1414 START_X_POS: 50, | |
1415 WIDTH: 44 | |
1416 }; | |
1417 | |
1418 | |
1419 /** | |
1420 * Used in collision detection. | |
1421 * @type {Array.<Runner.CollisionBox>} | |
1422 */ | |
1423 Trex.collisionBoxes = [ | |
1424 new Runner.CollisionBox(1, -1, 30, 26), | |
1425 new Runner.CollisionBox(32, 0, 8, 16), | |
1426 new Runner.CollisionBox(10, 35, 14, 8), | |
1427 new Runner.CollisionBox(1, 24, 29, 5), | |
1428 new Runner.CollisionBox(5, 30, 21, 4), | |
1429 new Runner.CollisionBox(9, 34, 15, 4) | |
1430 ]; | |
1431 | |
1432 | |
1433 /** | |
1434 * Animation states. | |
1435 * @enum {string} | |
1436 */ | |
1437 Trex.status = { | |
1438 CRASHED: 'crashed', | |
1439 JUMPING: 'jumping', | |
1440 RUNNING: 'running', | |
1441 WAITING: 'waiting' | |
1442 }; | |
1443 | |
1444 // Blinking coefficient. | |
1445 Trex.BLINK_TIMING = 7000; | |
1446 | |
1447 | |
1448 /** | |
1449 * Animation config for different states. | |
1450 */ | |
1451 Trex.animFrames = { | |
1452 'waiting': { | |
1453 frames: [44, 0], | |
1454 msPerFrame: 1000 / 3 | |
1455 }, | |
1456 'running': { | |
1457 frames: [88, 132], | |
1458 msPerFrame: 1000 / 12 | |
1459 }, | |
1460 'crashed': { | |
1461 frames: [220], | |
1462 msPerFrame: 1000 / 60 | |
1463 }, | |
1464 'jumping': { | |
1465 frames: [0], | |
1466 msPerFrame: 1000 / 60 | |
1467 } | |
1468 }; | |
1469 | |
1470 | |
1471 Trex.prototype = { | |
1472 /** | |
1473 * T-rex player initaliser. | |
1474 * Sets the t-rex to blink at random intervals. | |
1475 */ | |
1476 init: function() { | |
1477 this.blinkDelay = this.setBlinkDelay(); | |
1478 this.groundYPos = Runner.defaultDimensions.HEIGHT - this.config.HEIGHT - | |
1479 Runner.config.BOTTOM_PAD; | |
1480 this.yPos = this.groundYPos; | |
1481 | |
1482 this.minJumpHeight = this.groundYPos - this.config.MIN_JUMP_HEIGHT; | |
1483 | |
1484 this.draw(0, 0); | |
1485 this.update(0, Trex.status.WAITING); | |
1486 }, | |
1487 | |
1488 /** | |
1489 * Setter for the jump velocity. | |
1490 * The approriate drop velocity is also set. | |
1491 */ | |
1492 setJumpVelocity: function(setting) { | |
1493 this.config.INIITAL_JUMP_VELOCITY = -setting; | |
1494 this.config.DROP_VELOCITY = -setting / 2; | |
1495 }, | |
1496 | |
1497 /** | |
1498 * Set the animation status. | |
1499 * @param {!number} deltaTime | |
1500 * @param {Trex.status} status Optional status to switch to. | |
1501 */ | |
1502 update: function(deltaTime, opt_status) { | |
1503 this.timer += deltaTime; | |
1504 | |
1505 // Update the status. | |
1506 if (opt_status) { | |
1507 this.status = opt_status; | |
1508 this.currentFrame = 0; | |
1509 this.msPerFrame = Trex.animFrames[opt_status].msPerFrame; | |
1510 this.currentAnimFrames = Trex.animFrames[opt_status].frames; | |
1511 | |
1512 if (opt_status == Trex.status.WAITING) { | |
1513 this.animStartTime = performance.now(); | |
1514 this.setBlinkDelay(); | |
1515 } | |
1516 } | |
1517 | |
1518 // Game intro animation, t-rex moves in from the left. | |
1519 if (this.playingIntro && this.xPos < this.config.START_X_POS) { | |
1520 this.xPos += Math.round((this.config.START_X_POS / | |
1521 this.config.INTRO_DURATION) * deltaTime); | |
1522 } | |
1523 | |
1524 if (this.status == Trex.status.WAITING) { | |
1525 this.blink(performance.now()); | |
1526 } else { | |
1527 this.draw(this.currentAnimFrames[this.currentFrame], 0); | |
1528 } | |
1529 | |
1530 // Update the frame position. | |
1531 if (this.timer >= this.msPerFrame) { | |
1532 this.currentFrame = this.currentFrame == | |
1533 this.currentAnimFrames.length - 1 ? 0 : this.currentFrame + 1; | |
1534 this.timer = 0; | |
1535 } | |
1536 }, | |
1537 | |
1538 | |
1539 /** | |
1540 * Draw the t-rex to a particular position. | |
1541 * @param {number} x | |
1542 * @param {number} y | |
1543 */ | |
1544 draw: function(x, y) { | |
1545 var sourceX = x; | |
1546 var sourceY = y; | |
1547 var sourceWidth = this.config.WIDTH; | |
1548 var sourceHeight = this.config.HEIGHT; | |
1549 | |
1550 if (Runner.isHDPI) { | |
1551 sourceX *= 2; | |
1552 sourceY *= 2; | |
1553 sourceWidth *= 2; | |
1554 sourceHeight *= 2; | |
1555 } | |
1556 | |
1557 this.canvasCtx.drawImage(this.image, sourceX, sourceY, | |
1558 sourceWidth, sourceHeight, | |
1559 this.xPos, this.yPos, | |
1560 this.config.WIDTH, this.config.HEIGHT); | |
1561 }, | |
1562 | |
1563 /** | |
1564 * Sets a random time for the blink to happen. | |
1565 */ | |
1566 setBlinkDelay: function() { | |
1567 this.blinkDelay = Math.ceil(Math.random() * Trex.BLINK_TIMING); | |
1568 }, | |
1569 | |
1570 /** | |
1571 * Make t-rex blink at random intervals. | |
1572 * @param {number} time Current time in milliseconds. | |
1573 */ | |
1574 blink: function(time) { | |
1575 var deltaTime = time - this.animStartTime; | |
1576 | |
1577 if (deltaTime >= this.blinkDelay) { | |
1578 this.draw(this.currentAnimFrames[this.currentFrame], 0); | |
1579 | |
1580 if (this.currentFrame == 1) { | |
1581 // Set new random delay to blink. | |
1582 this.setBlinkDelay(); | |
1583 this.animStartTime = time; | |
1584 } | |
1585 } | |
1586 }, | |
1587 | |
1588 /** | |
1589 * Initialise a jump. | |
1590 */ | |
1591 startJump: function() { | |
1592 if (!this.jumping) { | |
1593 this.update(0, Trex.status.JUMPING); | |
1594 this.jumpVelocity = this.config.INIITAL_JUMP_VELOCITY; | |
1595 this.jumping = true; | |
1596 this.reachedMinHeight = false; | |
1597 this.speedDrop = false; | |
1598 } | |
1599 }, | |
1600 | |
1601 /** | |
1602 * Jump is complete, falling down. | |
1603 */ | |
1604 endJump: function() { | |
1605 if (this.reachedMinHeight && | |
1606 this.jumpVelocity < this.config.DROP_VELOCITY) { | |
1607 this.jumpVelocity = this.config.DROP_VELOCITY; | |
1608 } | |
1609 }, | |
1610 | |
1611 /** | |
1612 * Update frame for a jump. | |
1613 * @param {number} deltaTime | |
1614 */ | |
1615 updateJump: function(deltaTime) { | |
1616 var msPerFrame = Trex.animFrames[this.status].msPerFrame; | |
1617 var framesElapsed = deltaTime / msPerFrame; | |
1618 | |
1619 // Speed drop makes Trex fall faster. | |
1620 if (this.speedDrop) { | |
1621 this.yPos += Math.round(this.jumpVelocity * | |
1622 this.config.SPEED_DROP_COEFFICIENT * framesElapsed); | |
1623 } else { | |
1624 this.yPos += Math.round(this.jumpVelocity * framesElapsed); | |
1625 } | |
1626 | |
1627 this.jumpVelocity += this.config.GRAVITY * framesElapsed; | |
1628 | |
1629 // Minimum height has been reached. | |
1630 if (this.yPos < this.minJumpHeight || this.speedDrop) { | |
1631 this.reachedMinHeight = true; | |
1632 } | |
1633 | |
1634 // Reached max height | |
1635 if (this.yPos < this.config.MAX_JUMP_HEIGHT || this.speedDrop) { | |
1636 this.endJump(); | |
1637 } | |
1638 | |
1639 // Back down at ground level. Jump completed. | |
1640 if (this.yPos > this.groundYPos) { | |
1641 this.reset(); | |
1642 this.jumpCount++; | |
1643 } | |
1644 | |
1645 this.update(deltaTime); | |
1646 }, | |
1647 | |
1648 /** | |
1649 * Set the speed drop. Immediately cancels the current jump. | |
1650 */ | |
1651 setSpeedDrop: function() { | |
1652 this.speedDrop = true; | |
1653 this.jumpVelocity = 1; | |
1654 }, | |
1655 | |
1656 /** | |
1657 * Reset the t-rex to running at start of game. | |
1658 */ | |
1659 reset: function() { | |
1660 this.yPos = this.groundYPos; | |
1661 this.jumpVelocity = 0; | |
1662 this.jumping = false; | |
1663 this.update(0, Trex.status.RUNNING); | |
1664 this.midair = false; | |
1665 this.speedDrop = false; | |
1666 this.jumpCount = 0; | |
1667 } | |
1668 }; | |
1669 | |
1670 | |
1671 //****************************************************************************** | |
1672 | |
1673 /** | |
1674 * Handles displaying the distance meter. | |
1675 * @param {!HTMLCanvasElement} canvas | |
1676 * @param {!HTMLImage} spriteSheet Image sprite. | |
1677 * @param {number} canvasWidth | |
1678 * @constructor | |
1679 */ | |
1680 function DistanceMeter(canvas, spriteSheet, canvasWidth) { | |
1681 this.canvas = canvas; | |
1682 this.canvasCtx = canvas.getContext('2d'); | |
1683 this.image = spriteSheet; | |
1684 this.x = 0; | |
1685 this.y = 5; | |
1686 | |
1687 this.currentDistance = 0; | |
1688 this.maxScore = 0; | |
1689 this.highScore = 0; | |
1690 this.container = null; | |
1691 | |
1692 this.digits = []; | |
1693 this.acheivement = false; | |
1694 this.defaultString = ''; | |
1695 this.flashTimer = 0; | |
1696 this.flashIterations = 0; | |
1697 | |
1698 this.config = DistanceMeter.config; | |
1699 this.init(canvasWidth); | |
1700 }; | |
1701 | |
1702 | |
1703 DistanceMeter.dimensions = { | |
1704 WIDTH: 10, | |
1705 HEIGHT: 13, | |
1706 DEST_WIDTH: 11 | |
1707 }; | |
1708 | |
1709 | |
1710 /** | |
1711 * Y positioning of the digits in the sprite sheet. | |
1712 * X position is always 0. | |
1713 */ | |
1714 DistanceMeter.yPos = [0, 13, 27, 40, 53, 67, 80, 93, 107, 120]; | |
1715 | |
1716 | |
1717 /** | |
1718 * Distance meter config. | |
1719 * @enum {string} | |
1720 */ | |
1721 DistanceMeter.config = { | |
1722 // Number of digits. | |
1723 MAX_DISTANCE_UNITS: 5, | |
1724 | |
1725 // Distance that causes achievement animation. | |
1726 ACHIEVEMENT_DISTANCE: 100, | |
1727 | |
1728 // Used for conversion from pixel distance to a scaled unit. | |
1729 COEFFICIENT: 0.025, | |
1730 | |
1731 // Flash duration in milliseconds. | |
1732 FLASH_DURATION: 1000 / 4, | |
1733 | |
1734 // Flash iterations for achievement animation. | |
1735 FLASH_ITERATIONS: 3 | |
1736 }; | |
1737 | |
1738 | |
1739 /** | |
1740 * Initialise the distance meter to '00000'. | |
1741 * @param {number} width Canvas width in px. | |
1742 */ | |
1743 DistanceMeter.prototype = { | |
1744 init: function(width) { | |
1745 var maxDistanceStr = ''; | |
1746 | |
1747 this.calcXPos(width); | |
1748 this.maxScore = this.config.MAX_DISTANCE_UNITS; | |
1749 for (var i = 0; i < this.config.MAX_DISTANCE_UNITS; i++) { | |
1750 this.draw(i, 0); | |
1751 this.defaultString += '0'; | |
1752 maxDistanceStr += '9'; | |
1753 } | |
1754 | |
1755 this.maxScore = parseInt(maxDistanceStr); | |
1756 }, | |
1757 | |
1758 /** | |
1759 * Calculate the xPos in the canvas. | |
1760 */ | |
1761 calcXPos: function(canvasWidth) { | |
1762 this.x = canvasWidth - (DistanceMeter.dimensions.DEST_WIDTH * | |
1763 (this.config.MAX_DISTANCE_UNITS + 1)); | |
1764 }, | |
1765 | |
1766 /** | |
1767 * Draw a digit to canvas. | |
1768 * @param {number} digitPos Position of the digit. | |
1769 * @param {number} value Digit value 0-9. | |
1770 * @param {boolean} opt_highScore Whether we a drawing the high score. | |
1771 */ | |
1772 draw: function(digitPos, value, opt_highScore) { | |
1773 var sourceWidth = DistanceMeter.dimensions.WIDTH; | |
1774 var sourceHeight = DistanceMeter.dimensions.HEIGHT; | |
1775 var sourceX = DistanceMeter.dimensions.WIDTH * value; | |
1776 | |
1777 var targetX = digitPos * DistanceMeter.dimensions.DEST_WIDTH; | |
1778 var targetY = this.y; | |
1779 var targetWidth = DistanceMeter.dimensions.WIDTH; | |
1780 var targetHeight = DistanceMeter.dimensions.HEIGHT; | |
1781 | |
1782 // For high DPI we 2x source values. | |
1783 if (Runner.isHDPI) { | |
1784 sourceWidth = sourceWidth * 2; | |
1785 sourceHeight = sourceHeight * 2; | |
1786 sourceX = sourceX * 2; | |
1787 } | |
1788 | |
1789 this.canvasCtx.save(); | |
1790 | |
1791 if (opt_highScore) { | |
1792 // Left of the current score. | |
1793 var highScoreX = this.x - | |
1794 (this.config.MAX_DISTANCE_UNITS * 2) * | |
1795 DistanceMeter.dimensions.WIDTH; | |
1796 | |
1797 this.canvasCtx.translate(highScoreX, this.y); | |
1798 } else { | |
1799 this.canvasCtx.translate(this.x, this.y); | |
1800 } | |
1801 | |
1802 this.canvasCtx.drawImage(this.image, sourceX, 0, | |
1803 sourceWidth, sourceHeight, | |
1804 targetX, targetY, | |
1805 targetWidth, targetHeight | |
1806 ); | |
1807 | |
1808 this.canvasCtx.restore(); | |
1809 }, | |
1810 | |
1811 /** | |
1812 * Covert pixel distance to a 'real' distance. | |
1813 * @param {number} distance Pixel distance ran. | |
1814 * @return {number} The 'real' distance ran. | |
1815 */ | |
1816 getActualDistance: function(distance) { | |
1817 return distance ? | |
1818 Math.round(distance * this.config.COEFFICIENT) : 0; | |
1819 }, | |
1820 | |
1821 /** | |
1822 * Update the distance meter. | |
1823 * @param {number} deltaTime | |
1824 * @param {number} distance | |
1825 * @return {boolean} Whether the acheivement sound fx should be played. | |
1826 */ | |
1827 update: function(deltaTime, distance) { | |
1828 var paint = true; | |
1829 var playSound = false; | |
1830 | |
1831 if (!this.acheivement) { | |
1832 distance = this.getActualDistance(distance); | |
1833 | |
1834 if (distance > 0) { | |
1835 // Acheivement unlocked | |
1836 if (distance % this.config.ACHIEVEMENT_DISTANCE == 0) { | |
1837 // Flash score and play sound. | |
1838 this.acheivement = true; | |
1839 this.flashTimer = 0; | |
1840 // Runner.playSound(sound); | |
1841 playSound = true; | |
1842 } | |
1843 | |
1844 // Create a string representation of the distance with leading 0. | |
1845 var distanceStr = (this.defaultString + | |
1846 distance).substr(-this.config.MAX_DISTANCE_UNITS); | |
1847 this.digits = String(distanceStr).split(''); | |
1848 } else { | |
1849 this.digits = this.defaultString.split(''); | |
1850 } | |
1851 } else { | |
1852 // Control flashing of the score on reaching acheivement. | |
1853 if (this.flashIterations <= this.config.FLASH_ITERATIONS) { | |
1854 this.flashTimer += deltaTime; | |
1855 | |
1856 if (this.flashTimer < this.config.FLASH_DURATION) { | |
1857 paint = false; | |
1858 } else if (this.flashTimer > | |
1859 (this.config.FLASH_DURATION * 2)) { | |
1860 this.flashTimer = 0; | |
1861 this.flashIterations++; | |
1862 } | |
1863 } else { | |
1864 this.acheivement = false; | |
1865 this.flashIterations = 0; | |
1866 this.flashTimer = 0; | |
1867 } | |
1868 } | |
1869 | |
1870 // Draw the digits if not flashing. | |
1871 if (paint) { | |
1872 for (var i = this.digits.length - 1; i >= 0; i--) { | |
1873 this.draw(i, parseInt(this.digits[i])); | |
1874 } | |
1875 } | |
1876 | |
1877 this.drawHighScore(); | |
1878 | |
1879 return playSound; | |
1880 }, | |
1881 | |
1882 /** | |
1883 * Draw the high score. | |
1884 */ | |
1885 drawHighScore: function() { | |
1886 this.canvasCtx.save(); | |
1887 this.canvasCtx.globalAlpha = .8; | |
1888 for (var i = this.highScore.length - 1; i >= 0; i--) { | |
1889 this.draw(i, parseInt(this.highScore[i], 10), true); | |
1890 } | |
1891 this.canvasCtx.restore(); | |
1892 }, | |
1893 | |
1894 /** | |
1895 * Set the highscore as a array string. | |
1896 * Position of char in the sprite: H - 10 in and I - 11. | |
1897 * @param {number} distance Distance ran in pixels. | |
1898 */ | |
1899 setHighScore: function(distance) { | |
1900 distance = this.getActualDistance(distance); | |
1901 var highScoreStr = (this.defaultString + | |
1902 distance).substr(-this.config.MAX_DISTANCE_UNITS); | |
1903 | |
1904 this.highScore = ['10', '11', ''].concat(highScoreStr.split('')); | |
1905 }, | |
1906 | |
1907 /** | |
1908 * Reset the distance meter back to '00000'. | |
1909 */ | |
1910 reset: function() { | |
1911 this.update(0); | |
1912 this.acheivement = false; | |
1913 } | |
1914 }; | |
1915 | |
1916 | |
1917 //****************************************************************************** | |
1918 | |
1919 /** | |
1920 * Cloud background item. | |
1921 * Similar to an obstacle object but without collision boxes. | |
1922 * @param {HTMLCanvasElement} canvas Canvas element. | |
1923 * @param {Image} cloudImg | |
1924 * @param {number} containerWidth | |
1925 */ | |
1926 function Cloud(canvas, cloudImg, containerWidth) { | |
1927 this.canvas = canvas; | |
1928 | |
1929 this.canvasCtx = this.canvas.getContext('2d'); | |
1930 | |
1931 this.image = cloudImg; | |
1932 | |
1933 this.containerWidth = containerWidth; | |
1934 | |
1935 this.xPos = containerWidth; | |
1936 | |
1937 this.yPos = 0; | |
1938 | |
1939 this.remove = false; | |
1940 | |
1941 this.cloudGap = Runner.getRandomNum(Cloud.config.MIN_CLOUD_GAP, | |
1942 Cloud.config.MAX_CLOUD_GAP); | |
1943 | |
1944 this.init(); | |
1945 }; | |
1946 | |
1947 | |
1948 /** | |
1949 * Cloud object config. | |
1950 * @enum {string} | |
1951 */ | |
1952 Cloud.config = { | |
1953 HEIGHT: 13, | |
1954 MAX_CLOUD_GAP: 400, | |
1955 MAX_SKY_LEVEL: 30, | |
1956 MIN_CLOUD_GAP: 100, | |
1957 MIN_SKY_LEVEL: 71, | |
1958 WIDTH: 46 | |
1959 }; | |
1960 | |
1961 | |
1962 Cloud.prototype = { | |
1963 /** | |
1964 * Initialise the cloud. Sets the Cloud height. | |
1965 */ | |
1966 init: function() { | |
1967 this.yPos = Runner.getRandomNum(Cloud.config.MAX_SKY_LEVEL, | |
1968 Cloud.config.MIN_SKY_LEVEL); | |
1969 this.draw(); | |
1970 }, | |
1971 | |
1972 /** | |
1973 * Draw the cloud. | |
1974 */ | |
1975 draw: function() { | |
1976 this.canvasCtx.save(); | |
1977 var sourceWidth = Cloud.config.WIDTH; | |
1978 var sourceHeight = Cloud.config.HEIGHT; | |
1979 | |
1980 if (Runner.isHDPI) { | |
1981 sourceWidth = sourceWidth * 2; | |
1982 sourceHeight = sourceHeight * 2; | |
1983 } | |
1984 | |
1985 this.canvasCtx.drawImage(this.image, 0, 0, | |
1986 sourceWidth, sourceHeight, | |
1987 this.xPos, this.yPos, | |
1988 Cloud.config.WIDTH, Cloud.config.HEIGHT); | |
1989 | |
1990 this.canvasCtx.restore(); | |
1991 }, | |
1992 | |
1993 /** | |
1994 * Update the cloud position. | |
1995 * @param {number} speed | |
1996 */ | |
1997 update: function(speed) { | |
1998 if (!this.remove) { | |
1999 this.xPos -= Math.ceil(speed); | |
2000 this.draw(); | |
2001 | |
2002 // Mark as removeable if no longer in the canvas. | |
2003 if (!this.isVisible()) { | |
2004 this.remove = true; | |
2005 } | |
2006 } | |
2007 }, | |
2008 | |
2009 /** | |
2010 * Check if the cloud is visible on the stage. | |
2011 * @return {boolean} Whether the cloud is visible. | |
2012 */ | |
2013 isVisible: function() { | |
2014 return this.xPos + Cloud.config.WIDTH > 0; | |
2015 } | |
2016 }; | |
2017 | |
2018 | |
2019 //****************************************************************************** | |
2020 | |
2021 /** | |
2022 * Horizon Line. | |
2023 * Consists of two connecting lines. Randomly assigns a flat / bumpy horizon. | |
2024 * @param {HTMLCanvasElement} canvas | |
2025 * @param {HTMLImage} bgImg Horizon line sprite. | |
2026 * @constructor | |
2027 */ | |
2028 function HorizonLine(canvas, bgImg) { | |
2029 this.image = bgImg; | |
2030 this.canvas = canvas; | |
2031 this.canvasCtx = canvas.getContext('2d'); | |
2032 this.sourceDimensions = {}; | |
2033 this.dimensions = HorizonLine.dimensions; | |
2034 this.sourceXPos = [0, this.dimensions.WIDTH]; | |
2035 this.xPos = []; | |
2036 this.yPos = 0; | |
2037 this.bumpThreshold = 0.5; | |
2038 | |
2039 this.setSourceDimensions(); | |
2040 this.draw(); | |
2041 }; | |
2042 | |
2043 | |
2044 /** | |
2045 * Horizon line dimensions. | |
2046 * @enum {number} | |
2047 */ | |
2048 HorizonLine.dimensions = { | |
2049 WIDTH: 600, | |
2050 HEIGHT: 12, | |
2051 YPOS: 127 | |
2052 }; | |
2053 | |
2054 | |
2055 HorizonLine.prototype = { | |
2056 /** | |
2057 * Set the source dimensions of the horizon line. | |
2058 */ | |
2059 setSourceDimensions: function() { | |
2060 | |
2061 for (var dimension in HorizonLine.dimensions) { | |
2062 if (Runner.isHDPI) { | |
2063 if (dimension != 'YPOS') { | |
2064 this.sourceDimensions[dimension] = | |
2065 Runner.HorizonLine.dimensions[dimension] * 2; | |
2066 } | |
2067 } else { | |
2068 this.sourceDimensions[dimension] = | |
2069 HorizonLine.dimensions[dimension]; | |
2070 } | |
2071 this.dimensions[dimension] = HorizonLine.dimensions[dimension]; | |
2072 } | |
2073 | |
2074 this.xPos = [0, HorizonLine.dimensions.WIDTH]; | |
2075 this.yPos = HorizonLine.dimensions.YPOS; | |
2076 }, | |
2077 | |
2078 /** | |
2079 * Return the crop x position of a type. | |
2080 */ | |
2081 getRandomType: function() { | |
2082 return Math.random() > this.bumpThreshold ? this.dimensions.WIDTH : 0; | |
2083 }, | |
2084 | |
2085 /** | |
2086 * Draw the horizon line. | |
2087 */ | |
2088 draw: function() { | |
2089 this.canvasCtx.drawImage(this.image, this.sourceXPos[0], 0, | |
2090 this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT, | |
2091 this.xPos[0], this.yPos, | |
2092 this.dimensions.WIDTH, this.dimensions.HEIGHT); | |
2093 | |
2094 this.canvasCtx.drawImage(this.image, this.sourceXPos[1], 0, | |
2095 this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT, | |
2096 this.xPos[1], this.yPos, | |
2097 this.dimensions.WIDTH, this.dimensions.HEIGHT); | |
2098 }, | |
2099 | |
2100 /** | |
2101 * Update the x position of an indivdual piece of the line. | |
2102 * @param {number} pos Line position. | |
2103 * @param {number} increment | |
2104 */ | |
2105 updateXPos: function(pos, increment) { | |
2106 var line1 = pos; | |
2107 var line2 = pos == 0 ? 1 : 0; | |
2108 | |
2109 this.xPos[line1] -= increment; | |
2110 this.xPos[line2] = this.xPos[line1] + this.dimensions.WIDTH; | |
2111 | |
2112 if (this.xPos[line1] <= -this.dimensions.WIDTH) { | |
2113 this.xPos[line1] += this.dimensions.WIDTH * 2; | |
2114 this.xPos[line2] = this.xPos[line1] - this.dimensions.WIDTH; | |
2115 this.sourceXPos[line1] = this.getRandomType(); | |
2116 } | |
2117 }, | |
2118 | |
2119 /** | |
2120 * Update the horizon line. | |
2121 * @param {number} deltaTime | |
2122 * @param {number} speed | |
2123 */ | |
2124 update: function(deltaTime, speed) { | |
2125 var increment = Math.floor(speed * (FPS / 1000) * deltaTime); | |
2126 | |
2127 if (this.xPos[0] <= 0) { | |
2128 this.updateXPos(0, increment); | |
2129 } else { | |
2130 this.updateXPos(1, increment); | |
2131 } | |
2132 this.draw(); | |
2133 }, | |
2134 | |
2135 /** | |
2136 * Reset horizon to the starting position. | |
2137 */ | |
2138 reset: function() { | |
2139 this.xPos[0] = 0; | |
2140 this.xPos[1] = HorizonLine.dimensions.WIDTH; | |
2141 } | |
2142 }; | |
2143 | |
2144 | |
2145 //****************************************************************************** | |
2146 | |
2147 /** | |
2148 * Horizon background class. | |
2149 * @param {HTMLCanvasElement} canvas | |
2150 * @param {Array.<HTMLImageElement>} images | |
2151 * @param {object} dimensions Canvas dimensions. | |
2152 * @param {number} gapCoefficient | |
2153 * @constructor | |
2154 */ | |
2155 function Horizon(canvas, images, dimensions, gapCoefficient) { | |
2156 this.canvas = canvas; | |
2157 this.canvasCtx = this.canvas.getContext('2d'); | |
2158 this.config = Horizon.config; | |
2159 this.dimensions = dimensions; | |
2160 this.gapCoefficient = gapCoefficient; | |
2161 | |
2162 // Cloud | |
2163 this.clouds = []; | |
2164 this.cloudImg = images.CLOUD; | |
2165 this.cloudSpeed = this.config.BG_CLOUD_SPEED; | |
2166 | |
2167 // Horizon | |
2168 this.horizonImg = images.HORIZON; | |
2169 this.horizonLine = null; | |
2170 | |
2171 // Obstacles | |
2172 this.obstacleImgs = { | |
2173 CACTUS_SMALL: images.CACTUS_SMALL, | |
2174 CACTUS_LARGE: images.CACTUS_LARGE | |
2175 }; | |
2176 | |
2177 this.obstacles = []; | |
2178 | |
2179 this.horizonOffsets = [0, 0]; | |
2180 | |
2181 this.cloudFrequency = this.config.CLOUD_FREQUENCY; | |
2182 | |
2183 this.init(); | |
2184 }; | |
2185 | |
2186 | |
2187 /** | |
2188 * Horizon config. | |
2189 * @enum {string} | |
2190 */ | |
2191 Horizon.config = { | |
2192 BG_CLOUD_SPEED: 0.2, | |
2193 BUMPY_THRESHOLD: .3, | |
2194 CLOUD_FREQUENCY: .5, | |
2195 HORIZON_HEIGHT: 16, | |
2196 MAX_CLOUDS: 6 | |
2197 }; | |
2198 | |
2199 | |
2200 Horizon.prototype = { | |
2201 /** | |
2202 * Initialise the horizon. Just add the line and a cloud. No obstacles. | |
2203 */ | |
2204 init: function() { | |
2205 this.addCloud(); | |
2206 | |
2207 this.horizonLine = new HorizonLine(this.canvas, this.horizonImg); | |
2208 }, | |
2209 | |
2210 /** | |
2211 * @param {number} deltaTime | |
2212 * @param {number} currentSpeed | |
2213 * @param {boolean} updateObstacles Used as an override to prevent | |
2214 * the obstacles from being updated / added. This happens in the | |
2215 * ease in section. | |
2216 */ | |
2217 update: function(deltaTime, currentSpeed, updateObstacles) { | |
2218 | |
2219 this.runningTime += deltaTime; | |
2220 | |
2221 this.horizonLine.update(deltaTime, currentSpeed); | |
2222 this.updateClouds(deltaTime, currentSpeed); | |
2223 | |
2224 if (updateObstacles) { | |
2225 this.updateObstacles(deltaTime, currentSpeed); | |
2226 } | |
2227 }, | |
2228 | |
2229 /** | |
2230 * Update the cloud positions. | |
2231 * @param {number} deltaTime | |
2232 * @param {number} currentSpeed | |
2233 */ | |
2234 updateClouds: function(deltaTime, speed) { | |
2235 var cloudSpeed = this.cloudSpeed / 1000 * deltaTime * speed; | |
2236 var numClouds = this.clouds.length; | |
2237 | |
2238 if (numClouds) { | |
2239 for (var i = numClouds - 1; i >= 0; i--) { | |
2240 this.clouds[i].update(cloudSpeed); | |
2241 } | |
2242 | |
2243 var lastCloud = this.clouds[numClouds - 1]; | |
2244 | |
2245 // Check for adding a new cloud. | |
2246 if (numClouds < this.config.MAX_CLOUDS && | |
2247 (this.dimensions.WIDTH - lastCloud.xPos) > lastCloud.cloudGap && | |
2248 this.cloudFrequency > Math.random()) { | |
2249 this.addCloud(); | |
2250 } | |
2251 | |
2252 // Remove expired clouds. | |
2253 this.clouds = this.clouds.filter(function(obj) { | |
2254 return !obj.remove; | |
2255 }); | |
2256 } | |
2257 }, | |
2258 | |
2259 /** | |
2260 * Update the obstacle positions. | |
2261 * @param {number} deltaTime | |
2262 * @param {number} currentSpeed | |
2263 */ | |
2264 updateObstacles: function(deltaTime, currentSpeed) { | |
2265 // Obstacles, move to Horizon layer. | |
2266 var updatedObstacles = this.obstacles.slice(0); | |
2267 | |
2268 for (var i = 0; i < this.obstacles.length; i++) { | |
2269 var obstacle = this.obstacles[i]; | |
2270 obstacle.update(deltaTime, currentSpeed); | |
2271 | |
2272 // Clean up existing obstacles. | |
2273 if (obstacle.remove) { | |
2274 updatedObstacles.shift(); | |
2275 } | |
2276 } | |
2277 this.obstacles = updatedObstacles; | |
2278 | |
2279 if (this.obstacles.length > 0) { | |
2280 var lastObstacle = this.obstacles[this.obstacles.length - 1]; | |
2281 | |
2282 if (lastObstacle && !lastObstacle.followingObstacleCreated && | |
2283 lastObstacle.isVisible() && | |
2284 (lastObstacle.xPos + lastObstacle.width + lastObstacle.gap) < | |
2285 this.dimensions.WIDTH) { | |
2286 this.addNewObstacle(currentSpeed); | |
2287 lastObstacle.followingObstacleCreated = true; | |
2288 } | |
2289 } else { | |
2290 // Create new obstacles. | |
2291 this.addNewObstacle(currentSpeed); | |
2292 } | |
2293 }, | |
2294 | |
2295 /** | |
2296 * Add a new obstacle. | |
2297 * @param {number} currentSpeed | |
2298 */ | |
2299 addNewObstacle: function(currentSpeed) { | |
2300 var obstacleTypeIndex = | |
2301 Runner.getRandomNum(0, Runner.Obstacle.types.length - 1); | |
2302 var obstacleType = Runner.Obstacle.types[obstacleTypeIndex]; | |
2303 var obstacleImg = this.obstacleImgs[obstacleType.type]; | |
2304 | |
2305 this.obstacles.push(new Runner.Obstacle(this.canvasCtx, obstacleType, | |
2306 obstacleImg, this.dimensions, this.gapCoefficient, currentSpeed)); | |
2307 }, | |
2308 | |
2309 /** | |
2310 * Reset the horizon layer. | |
2311 * Remove existing obstacles and reposition the horizon line. | |
2312 */ | |
2313 reset: function() { | |
2314 this.obstacles = []; | |
2315 this.horizonLine.reset(); | |
2316 }, | |
2317 | |
2318 /** | |
2319 * Update the canvas width and scaling. | |
2320 * @param {number} width Canvas width. | |
2321 * @param {number} height Canvas height. | |
2322 */ | |
2323 resize: function(width, height) { | |
2324 this.canvas.width = width; | |
2325 this.canvas.height = height; | |
2326 }, | |
2327 | |
2328 /** | |
2329 * Add a new cloud to the horizon. | |
2330 */ | |
2331 addCloud: function() { | |
2332 this.clouds.push(new Cloud(this.canvas, this.cloudImg, | |
2333 this.dimensions.WIDTH)); | |
2334 } | |
2335 }; | |
2336 })(); | |
OLD | NEW |