runner.js 68 KB

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