index.js 87 KB

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