index.js 86 KB

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