game.js 63 KB

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