offline.js 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173
  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. /**
  5. * T-Rex runner.
  6. * @param {string} outerContainerId Outer containing element id.
  7. * @param {!Object=} opt_config
  8. * @constructor
  9. * @implements {EventListener}
  10. * @export
  11. */
  12. function Runner(outerContainerId, opt_config) {
  13. // Singleton
  14. if (Runner.instance_) {
  15. return Runner.instance_;
  16. }
  17. Runner.instance_ = this;
  18. this.outerContainerEl = document.querySelector(outerContainerId);
  19. this.containerEl = null;
  20. this.snackbarEl = null;
  21. // A div to intercept touch events. Only set while (playing && useTouch).
  22. this.touchController = null;
  23. this.config = opt_config || Object.assign(Runner.config, Runner.normalConfig);
  24. // Logical dimensions of the container.
  25. this.dimensions = Runner.defaultDimensions;
  26. this.gameType = null;
  27. Runner.spriteDefinition = Runner.spriteDefinitionByType['original'];
  28. this.altGameImageSprite = null;
  29. this.altGameModeActive = false;
  30. this.altGameModeFlashTimer = null;
  31. this.fadeInTimer = 0;
  32. this.canvas = null;
  33. this.canvasCtx = null;
  34. this.tRex = null;
  35. this.distanceMeter = null;
  36. this.distanceRan = 0;
  37. this.highestScore = 0;
  38. this.syncHighestScore = false;
  39. this.time = 0;
  40. this.runningTime = 0;
  41. this.msPerFrame = 1000 / FPS;
  42. this.currentSpeed = this.config.SPEED;
  43. Runner.slowDown = false;
  44. this.obstacles = [];
  45. this.activated = false; // Whether the easter egg has been activated.
  46. this.playing = false; // Whether the game is currently in play state.
  47. this.crashed = false;
  48. this.paused = false;
  49. this.inverted = false;
  50. this.invertTimer = 0;
  51. this.resizeTimerId_ = null;
  52. this.playCount = 0;
  53. // Sound FX.
  54. this.audioBuffer = null;
  55. /** @type {Object} */
  56. this.soundFx = {};
  57. this.generatedSoundFx = null;
  58. // Global web audio context for playing sounds.
  59. this.audioContext = null;
  60. // Images.
  61. this.images = {};
  62. this.imagesLoaded = 0;
  63. // Gamepad state.
  64. this.pollingGamepads = false;
  65. this.gamepadIndex = undefined;
  66. this.previousGamepad = null;
  67. if (this.isDisabled()) {
  68. this.setupDisabledRunner();
  69. } else {
  70. if (Runner.isAltGameModeEnabled()) {
  71. this.initAltGameType();
  72. Runner.gameType = this.gameType;
  73. }
  74. this.loadImages();
  75. window['initializeEasterEggHighScore'] =
  76. this.initializeHighScore.bind(this);
  77. }
  78. }
  79. /**
  80. * Default game width.
  81. * @const
  82. */
  83. const DEFAULT_WIDTH = 600;
  84. /**
  85. * Frames per second.
  86. * @const
  87. */
  88. const FPS = 60;
  89. /** @const */
  90. const IS_HIDPI = window.devicePixelRatio > 1;
  91. /** @const */
  92. const IS_IOS = /CriOS/.test(window.navigator.userAgent);
  93. /** @const */
  94. const IS_MOBILE = /Android/.test(window.navigator.userAgent) || IS_IOS;
  95. /** @const */
  96. const IS_RTL = document.querySelector('html').dir == 'rtl';
  97. /** @const */
  98. const ARCADE_MODE_URL = 'chrome://dino/';
  99. /** @const */
  100. const RESOURCE_POSTFIX = 'offline-resources-';
  101. /** @const */
  102. const A11Y_STRINGS = {
  103. ariaLabel: 'dinoGameA11yAriaLabel',
  104. description: 'dinoGameA11yDescription',
  105. gameOver: 'dinoGameA11yGameOver',
  106. highScore: 'dinoGameA11yHighScore',
  107. jump: 'dinoGameA11yJump',
  108. started: 'dinoGameA11yStartGame',
  109. speedLabel: 'dinoGameA11ySpeedToggle',
  110. };
  111. /**
  112. * Default game configuration.
  113. * Shared config for all versions of the game. Additional parameters are
  114. * defined in Runner.normalConfig and Runner.slowConfig.
  115. */
  116. Runner.config = {
  117. AUDIOCUE_PROXIMITY_THRESHOLD: 190,
  118. AUDIOCUE_PROXIMITY_THRESHOLD_MOBILE_A11Y: 250,
  119. BG_CLOUD_SPEED: 0.2,
  120. BOTTOM_PAD: 10,
  121. // Scroll Y threshold at which the game can be activated.
  122. CANVAS_IN_VIEW_OFFSET: -10,
  123. CLEAR_TIME: 3000,
  124. CLOUD_FREQUENCY: 0.5,
  125. FADE_DURATION: 1,
  126. FLASH_DURATION: 1000,
  127. GAMEOVER_CLEAR_TIME: 1200,
  128. INITIAL_JUMP_VELOCITY: 12,
  129. INVERT_FADE_DURATION: 12000,
  130. MAX_BLINK_COUNT: 3,
  131. MAX_CLOUDS: 6,
  132. MAX_OBSTACLE_LENGTH: 3,
  133. MAX_OBSTACLE_DUPLICATION: 2,
  134. RESOURCE_TEMPLATE_ID: 'audio-resources',
  135. SPEED: 6,
  136. SPEED_DROP_COEFFICIENT: 3,
  137. ARCADE_MODE_INITIAL_TOP_POSITION: 35,
  138. ARCADE_MODE_TOP_POSITION_PERCENT: 0.1,
  139. };
  140. Runner.normalConfig = {
  141. ACCELERATION: 0.001,
  142. AUDIOCUE_PROXIMITY_THRESHOLD: 190,
  143. AUDIOCUE_PROXIMITY_THRESHOLD_MOBILE_A11Y: 250,
  144. GAP_COEFFICIENT: 0.6,
  145. INVERT_DISTANCE: 700,
  146. MAX_SPEED: 13,
  147. MOBILE_SPEED_COEFFICIENT: 1.2,
  148. SPEED: 6,
  149. };
  150. Runner.slowConfig = {
  151. ACCELERATION: 0.0005,
  152. AUDIOCUE_PROXIMITY_THRESHOLD: 170,
  153. AUDIOCUE_PROXIMITY_THRESHOLD_MOBILE_A11Y: 220,
  154. GAP_COEFFICIENT: 0.3,
  155. INVERT_DISTANCE: 350,
  156. MAX_SPEED: 9,
  157. MOBILE_SPEED_COEFFICIENT: 1.5,
  158. SPEED: 4.2,
  159. };
  160. /**
  161. * Default dimensions.
  162. */
  163. Runner.defaultDimensions = {
  164. WIDTH: DEFAULT_WIDTH,
  165. HEIGHT: 150,
  166. };
  167. /**
  168. * CSS class names.
  169. * @enum {string}
  170. */
  171. Runner.classes = {
  172. ARCADE_MODE: 'arcade-mode',
  173. CANVAS: 'runner-canvas',
  174. CONTAINER: 'runner-container',
  175. CRASHED: 'crashed',
  176. ICON: 'icon-offline',
  177. INVERTED: 'inverted',
  178. SNACKBAR: 'snackbar',
  179. SNACKBAR_SHOW: 'snackbar-show',
  180. TOUCH_CONTROLLER: 'controller',
  181. };
  182. /**
  183. * Sound FX. Reference to the ID of the audio tag on interstitial page.
  184. * @enum {string}
  185. */
  186. Runner.sounds = {
  187. BUTTON_PRESS: 'offline-sound-press',
  188. HIT: 'offline-sound-hit',
  189. SCORE: 'offline-sound-reached',
  190. };
  191. /**
  192. * Key code mapping.
  193. * @enum {Object}
  194. */
  195. Runner.keycodes = {
  196. JUMP: {'38': 1, '32': 1}, // Up, spacebar
  197. DUCK: {'40': 1}, // Down
  198. RESTART: {'13': 1}, // Enter
  199. };
  200. /**
  201. * Runner event names.
  202. * @enum {string}
  203. */
  204. Runner.events = {
  205. ANIM_END: 'webkitAnimationEnd',
  206. CLICK: 'click',
  207. KEYDOWN: 'keydown',
  208. KEYUP: 'keyup',
  209. POINTERDOWN: 'pointerdown',
  210. POINTERUP: 'pointerup',
  211. RESIZE: 'resize',
  212. TOUCHEND: 'touchend',
  213. TOUCHSTART: 'touchstart',
  214. VISIBILITY: 'visibilitychange',
  215. BLUR: 'blur',
  216. FOCUS: 'focus',
  217. LOAD: 'load',
  218. GAMEPADCONNECTED: 'gamepadconnected',
  219. };
  220. Runner.prototype = {
  221. /**
  222. * Initialize alternative game type.
  223. */
  224. initAltGameType() {
  225. if (GAME_TYPE.length > 0) {
  226. this.gameType = loadTimeData && loadTimeData.valueExists('altGameType') ?
  227. GAME_TYPE[parseInt(loadTimeData.getValue('altGameType'), 10) - 1] :
  228. '';
  229. }
  230. },
  231. /**
  232. * Whether the easter egg has been disabled. CrOS enterprise enrolled devices.
  233. * @return {boolean}
  234. */
  235. isDisabled() {
  236. return loadTimeData && loadTimeData.valueExists('disabledEasterEgg');
  237. },
  238. /**
  239. * For disabled instances, set up a snackbar with the disabled message.
  240. */
  241. setupDisabledRunner() {
  242. this.containerEl = document.createElement('div');
  243. this.containerEl.className = Runner.classes.SNACKBAR;
  244. this.containerEl.textContent = loadTimeData.getValue('disabledEasterEgg');
  245. this.outerContainerEl.appendChild(this.containerEl);
  246. // Show notification when the activation key is pressed.
  247. document.addEventListener(Runner.events.KEYDOWN, function(e) {
  248. if (Runner.keycodes.JUMP[e.keyCode]) {
  249. this.containerEl.classList.add(Runner.classes.SNACKBAR_SHOW);
  250. document.querySelector('.icon').classList.add('icon-disabled');
  251. }
  252. }.bind(this));
  253. },
  254. /**
  255. * Setting individual settings for debugging.
  256. * @param {string} setting
  257. * @param {number|string} value
  258. */
  259. updateConfigSetting(setting, value) {
  260. if (setting in this.config && value !== undefined) {
  261. this.config[setting] = value;
  262. switch (setting) {
  263. case 'GRAVITY':
  264. case 'MIN_JUMP_HEIGHT':
  265. case 'SPEED_DROP_COEFFICIENT':
  266. this.tRex.config[setting] = value;
  267. break;
  268. case 'INITIAL_JUMP_VELOCITY':
  269. this.tRex.setJumpVelocity(value);
  270. break;
  271. case 'SPEED':
  272. this.setSpeed(/** @type {number} */ (value));
  273. break;
  274. }
  275. }
  276. },
  277. /**
  278. * Creates an on page image element from the base 64 encoded string source.
  279. * @param {string} resourceName Name in data object,
  280. * @return {HTMLImageElement} The created element.
  281. */
  282. createImageElement(resourceName) {
  283. const imgSrc = loadTimeData && loadTimeData.valueExists(resourceName) ?
  284. loadTimeData.getString(resourceName) :
  285. null;
  286. if (imgSrc) {
  287. const el =
  288. /** @type {HTMLImageElement} */ (document.createElement('img'));
  289. el.id = resourceName;
  290. el.src = imgSrc;
  291. document.getElementById('offline-resources').appendChild(el);
  292. return el;
  293. }
  294. return null;
  295. },
  296. /**
  297. * Cache the appropriate image sprite from the page and get the sprite sheet
  298. * definition.
  299. */
  300. loadImages() {
  301. let scale = '1x';
  302. this.spriteDef = Runner.spriteDefinition.LDPI;
  303. if (IS_HIDPI) {
  304. scale = '2x';
  305. this.spriteDef = Runner.spriteDefinition.HDPI;
  306. }
  307. Runner.imageSprite = /** @type {HTMLImageElement} */
  308. (document.getElementById(RESOURCE_POSTFIX + scale));
  309. if (this.gameType) {
  310. Runner.altGameImageSprite = /** @type {HTMLImageElement} */
  311. (this.createImageElement('altGameSpecificImage' + scale));
  312. Runner.altCommonImageSprite = /** @type {HTMLImageElement} */
  313. (this.createImageElement('altGameCommonImage' + scale));
  314. }
  315. Runner.origImageSprite = Runner.imageSprite;
  316. // Disable the alt game mode if the sprites can't be loaded.
  317. if (!Runner.altGameImageSprite || !Runner.altCommonImageSprite) {
  318. Runner.isAltGameModeEnabled = () => false;
  319. this.altGameModeActive = false;
  320. }
  321. if (Runner.imageSprite.complete) {
  322. this.init();
  323. } else {
  324. // If the images are not yet loaded, add a listener.
  325. Runner.imageSprite.addEventListener(Runner.events.LOAD,
  326. this.init.bind(this));
  327. }
  328. },
  329. /**
  330. * Load and decode base 64 encoded sounds.
  331. */
  332. loadSounds() {
  333. if (!IS_IOS) {
  334. this.audioContext = new AudioContext();
  335. const resourceTemplate =
  336. document.getElementById(this.config.RESOURCE_TEMPLATE_ID).content;
  337. for (const sound in Runner.sounds) {
  338. let soundSrc =
  339. resourceTemplate.getElementById(Runner.sounds[sound]).src;
  340. soundSrc = soundSrc.substr(soundSrc.indexOf(',') + 1);
  341. const buffer = decodeBase64ToArrayBuffer(soundSrc);
  342. // Async, so no guarantee of order in array.
  343. this.audioContext.decodeAudioData(buffer, function(index, audioData) {
  344. this.soundFx[index] = audioData;
  345. }.bind(this, sound));
  346. }
  347. }
  348. },
  349. /**
  350. * Sets the game speed. Adjust the speed accordingly if on a smaller screen.
  351. * @param {number=} opt_speed
  352. */
  353. setSpeed(opt_speed) {
  354. const speed = opt_speed || this.currentSpeed;
  355. // Reduce the speed on smaller mobile screens.
  356. if (this.dimensions.WIDTH < DEFAULT_WIDTH) {
  357. const mobileSpeed = Runner.slowDown ? speed :
  358. speed * this.dimensions.WIDTH /
  359. DEFAULT_WIDTH * this.config.MOBILE_SPEED_COEFFICIENT;
  360. this.currentSpeed = mobileSpeed > speed ? speed : mobileSpeed;
  361. } else if (opt_speed) {
  362. this.currentSpeed = opt_speed;
  363. }
  364. },
  365. /**
  366. * Game initialiser.
  367. */
  368. init() {
  369. // Hide the static icon.
  370. document.querySelector('.' + Runner.classes.ICON).style.visibility =
  371. 'hidden';
  372. this.adjustDimensions();
  373. this.setSpeed();
  374. const ariaLabel = getA11yString(A11Y_STRINGS.ariaLabel);
  375. this.containerEl = document.createElement('div');
  376. this.containerEl.setAttribute('role', IS_MOBILE ? 'button' : 'application');
  377. this.containerEl.setAttribute('tabindex', '0');
  378. this.containerEl.setAttribute('title', ariaLabel);
  379. this.containerEl.className = Runner.classes.CONTAINER;
  380. // Player canvas container.
  381. this.canvas = createCanvas(this.containerEl, this.dimensions.WIDTH,
  382. this.dimensions.HEIGHT);
  383. // Live region for game status updates.
  384. this.a11yStatusEl = document.createElement('span');
  385. this.a11yStatusEl.className = 'offline-runner-live-region';
  386. this.a11yStatusEl.setAttribute('aria-live', 'assertive');
  387. this.a11yStatusEl.textContent = '';
  388. Runner.a11yStatusEl = this.a11yStatusEl;
  389. // Add checkbox to slow down the game.
  390. this.slowSpeedCheckboxLabel = document.createElement('label');
  391. this.slowSpeedCheckboxLabel.className = 'slow-speed-option hidden';
  392. this.slowSpeedCheckboxLabel.textContent =
  393. getA11yString(A11Y_STRINGS.speedLabel);
  394. this.slowSpeedCheckbox = document.createElement('input');
  395. this.slowSpeedCheckbox.setAttribute('type', 'checkbox');
  396. this.slowSpeedCheckbox.setAttribute(
  397. 'title', getA11yString(A11Y_STRINGS.speedLabel));
  398. this.slowSpeedCheckbox.setAttribute('tabindex', '0');
  399. this.slowSpeedCheckbox.setAttribute('checked', 'checked');
  400. this.slowSpeedToggleEl = document.createElement('span');
  401. this.slowSpeedToggleEl.className = 'slow-speed-toggle';
  402. this.slowSpeedCheckboxLabel.appendChild(this.slowSpeedCheckbox);
  403. this.slowSpeedCheckboxLabel.appendChild(this.slowSpeedToggleEl);
  404. if (IS_IOS) {
  405. this.outerContainerEl.appendChild(this.a11yStatusEl);
  406. } else {
  407. this.containerEl.appendChild(this.a11yStatusEl);
  408. }
  409. announcePhrase(getA11yString(A11Y_STRINGS.description));
  410. this.generatedSoundFx = new GeneratedSoundFx();
  411. this.canvasCtx =
  412. /** @type {CanvasRenderingContext2D} */ (this.canvas.getContext('2d'));
  413. this.canvasCtx.fillStyle = '#f7f7f7';
  414. this.canvasCtx.fill();
  415. Runner.updateCanvasScaling(this.canvas);
  416. // Horizon contains clouds, obstacles and the ground.
  417. this.horizon = new Horizon(this.canvas, this.spriteDef, this.dimensions,
  418. this.config.GAP_COEFFICIENT);
  419. // Distance meter
  420. this.distanceMeter = new DistanceMeter(this.canvas,
  421. this.spriteDef.TEXT_SPRITE, this.dimensions.WIDTH);
  422. // Draw t-rex
  423. this.tRex = new Trex(this.canvas, this.spriteDef.TREX);
  424. this.outerContainerEl.appendChild(this.containerEl);
  425. this.outerContainerEl.appendChild(this.slowSpeedCheckboxLabel);
  426. this.startListening();
  427. this.update();
  428. window.addEventListener(Runner.events.RESIZE,
  429. this.debounceResize.bind(this));
  430. // Handle dark mode
  431. const darkModeMediaQuery =
  432. window.matchMedia('(prefers-color-scheme: dark)');
  433. this.isDarkMode = darkModeMediaQuery && darkModeMediaQuery.matches;
  434. darkModeMediaQuery.addListener((e) => {
  435. this.isDarkMode = e.matches;
  436. });
  437. },
  438. /**
  439. * Create the touch controller. A div that covers whole screen.
  440. */
  441. createTouchController() {
  442. this.touchController = document.createElement('div');
  443. this.touchController.className = Runner.classes.TOUCH_CONTROLLER;
  444. this.touchController.addEventListener(Runner.events.TOUCHSTART, this);
  445. this.touchController.addEventListener(Runner.events.TOUCHEND, this);
  446. this.outerContainerEl.appendChild(this.touchController);
  447. },
  448. /**
  449. * Debounce the resize event.
  450. */
  451. debounceResize() {
  452. if (!this.resizeTimerId_) {
  453. this.resizeTimerId_ =
  454. setInterval(this.adjustDimensions.bind(this), 250);
  455. }
  456. },
  457. /**
  458. * Adjust game space dimensions on resize.
  459. */
  460. adjustDimensions() {
  461. clearInterval(this.resizeTimerId_);
  462. this.resizeTimerId_ = null;
  463. const boxStyles = window.getComputedStyle(this.outerContainerEl);
  464. const padding = Number(boxStyles.paddingLeft.substr(0,
  465. boxStyles.paddingLeft.length - 2));
  466. this.dimensions.WIDTH = this.outerContainerEl.offsetWidth - padding * 2;
  467. if (this.isArcadeMode()) {
  468. this.dimensions.WIDTH = Math.min(DEFAULT_WIDTH, this.dimensions.WIDTH);
  469. if (this.activated) {
  470. this.setArcadeModeContainerScale();
  471. }
  472. }
  473. // Redraw the elements back onto the canvas.
  474. if (this.canvas) {
  475. this.canvas.width = this.dimensions.WIDTH;
  476. this.canvas.height = this.dimensions.HEIGHT;
  477. Runner.updateCanvasScaling(this.canvas);
  478. this.distanceMeter.calcXPos(this.dimensions.WIDTH);
  479. this.clearCanvas();
  480. this.horizon.update(0, 0, true);
  481. this.tRex.update(0);
  482. // Outer container and distance meter.
  483. if (this.playing || this.crashed || this.paused) {
  484. this.containerEl.style.width = this.dimensions.WIDTH + 'px';
  485. this.containerEl.style.height = this.dimensions.HEIGHT + 'px';
  486. this.distanceMeter.update(0, Math.ceil(this.distanceRan));
  487. this.stop();
  488. } else {
  489. this.tRex.draw(0, 0);
  490. }
  491. // Game over panel.
  492. if (this.crashed && this.gameOverPanel) {
  493. this.gameOverPanel.updateDimensions(this.dimensions.WIDTH);
  494. this.gameOverPanel.draw(this.altGameModeActive, this.tRex);
  495. }
  496. }
  497. },
  498. /**
  499. * Play the game intro.
  500. * Canvas container width expands out to the full width.
  501. */
  502. playIntro() {
  503. if (!this.activated && !this.crashed) {
  504. this.playingIntro = true;
  505. this.tRex.playingIntro = true;
  506. // CSS animation definition.
  507. const keyframes = '@-webkit-keyframes intro { ' +
  508. 'from { width:' + Trex.config.WIDTH + 'px }' +
  509. 'to { width: ' + this.dimensions.WIDTH + 'px }' +
  510. '}';
  511. document.styleSheets[0].insertRule(keyframes, 0);
  512. this.containerEl.addEventListener(Runner.events.ANIM_END,
  513. this.startGame.bind(this));
  514. this.containerEl.style.webkitAnimation = 'intro .4s ease-out 1 both';
  515. this.containerEl.style.width = this.dimensions.WIDTH + 'px';
  516. this.setPlayStatus(true);
  517. this.activated = true;
  518. } else if (this.crashed) {
  519. this.restart();
  520. }
  521. },
  522. /**
  523. * Update the game status to started.
  524. */
  525. startGame() {
  526. if (this.isArcadeMode()) {
  527. this.setArcadeMode();
  528. }
  529. this.toggleSpeed();
  530. this.runningTime = 0;
  531. this.playingIntro = false;
  532. this.tRex.playingIntro = false;
  533. this.containerEl.style.webkitAnimation = '';
  534. this.playCount++;
  535. this.generatedSoundFx.background();
  536. announcePhrase(getA11yString(A11Y_STRINGS.started));
  537. if (Runner.audioCues) {
  538. this.containerEl.setAttribute('title', getA11yString(A11Y_STRINGS.jump));
  539. }
  540. // Handle tabbing off the page. Pause the current game.
  541. document.addEventListener(Runner.events.VISIBILITY,
  542. this.onVisibilityChange.bind(this));
  543. window.addEventListener(Runner.events.BLUR,
  544. this.onVisibilityChange.bind(this));
  545. window.addEventListener(Runner.events.FOCUS,
  546. this.onVisibilityChange.bind(this));
  547. },
  548. clearCanvas() {
  549. this.canvasCtx.clearRect(0, 0, this.dimensions.WIDTH,
  550. this.dimensions.HEIGHT);
  551. },
  552. /**
  553. * Checks whether the canvas area is in the viewport of the browser
  554. * through the current scroll position.
  555. * @return boolean.
  556. */
  557. isCanvasInView() {
  558. return this.containerEl.getBoundingClientRect().top >
  559. Runner.config.CANVAS_IN_VIEW_OFFSET;
  560. },
  561. /**
  562. * Enable the alt game mode. Switching out the sprites.
  563. */
  564. enableAltGameMode() {
  565. Runner.imageSprite = Runner.altGameImageSprite;
  566. Runner.spriteDefinition = Runner.spriteDefinitionByType[Runner.gameType];
  567. if (IS_HIDPI) {
  568. this.spriteDef = Runner.spriteDefinition.HDPI;
  569. } else {
  570. this.spriteDef = Runner.spriteDefinition.LDPI;
  571. }
  572. this.altGameModeActive = true;
  573. this.tRex.enableAltGameMode(this.spriteDef.TREX);
  574. this.horizon.enableAltGameMode(this.spriteDef);
  575. this.generatedSoundFx.background();
  576. },
  577. /**
  578. * Update the game frame and schedules the next one.
  579. */
  580. update() {
  581. this.updatePending = false;
  582. const now = getTimeStamp();
  583. let deltaTime = now - (this.time || now);
  584. // Flashing when switching game modes.
  585. if (this.altGameModeFlashTimer < 0 || this.altGameModeFlashTimer === 0) {
  586. this.altGameModeFlashTimer = null;
  587. this.tRex.setFlashing(false);
  588. this.enableAltGameMode();
  589. } else if (this.altGameModeFlashTimer > 0) {
  590. this.altGameModeFlashTimer -= deltaTime;
  591. this.tRex.update(deltaTime);
  592. deltaTime = 0;
  593. }
  594. this.time = now;
  595. if (this.playing) {
  596. this.clearCanvas();
  597. // Additional fade in - Prevents jump when switching sprites
  598. if (this.altGameModeActive &&
  599. this.fadeInTimer <= this.config.FADE_DURATION) {
  600. this.fadeInTimer += deltaTime / 1000;
  601. this.canvasCtx.globalAlpha = this.fadeInTimer;
  602. } else {
  603. this.canvasCtx.globalAlpha = 1;
  604. }
  605. if (this.tRex.jumping) {
  606. this.tRex.updateJump(deltaTime);
  607. }
  608. this.runningTime += deltaTime;
  609. const hasObstacles = this.runningTime > this.config.CLEAR_TIME;
  610. // First jump triggers the intro.
  611. if (this.tRex.jumpCount === 1 && !this.playingIntro) {
  612. this.playIntro();
  613. }
  614. // The horizon doesn't move until the intro is over.
  615. if (this.playingIntro) {
  616. this.horizon.update(0, this.currentSpeed, hasObstacles);
  617. } else if (!this.crashed) {
  618. const showNightMode = this.isDarkMode ^ this.inverted;
  619. deltaTime = !this.activated ? 0 : deltaTime;
  620. this.horizon.update(
  621. deltaTime, this.currentSpeed, hasObstacles, showNightMode);
  622. }
  623. // Check for collisions.
  624. let collision = hasObstacles &&
  625. checkForCollision(this.horizon.obstacles[0], this.tRex);
  626. // For a11y, audio cues.
  627. if (Runner.audioCues && hasObstacles) {
  628. const jumpObstacle =
  629. this.horizon.obstacles[0].typeConfig.type != 'COLLECTABLE';
  630. if (!this.horizon.obstacles[0].jumpAlerted) {
  631. const threshold = Runner.isMobileMouseInput ?
  632. Runner.config.AUDIOCUE_PROXIMITY_THRESHOLD_MOBILE_A11Y :
  633. Runner.config.AUDIOCUE_PROXIMITY_THRESHOLD;
  634. const adjProximityThreshold = threshold +
  635. (threshold * Math.log10(this.currentSpeed / Runner.config.SPEED));
  636. if (this.horizon.obstacles[0].xPos < adjProximityThreshold) {
  637. if (jumpObstacle) {
  638. this.generatedSoundFx.jump();
  639. }
  640. this.horizon.obstacles[0].jumpAlerted = true;
  641. }
  642. }
  643. }
  644. // Activated alt game mode.
  645. if (Runner.isAltGameModeEnabled() && collision &&
  646. this.horizon.obstacles[0].typeConfig.type == 'COLLECTABLE') {
  647. this.horizon.removeFirstObstacle();
  648. this.tRex.setFlashing(true);
  649. collision = false;
  650. this.altGameModeFlashTimer = this.config.FLASH_DURATION;
  651. this.runningTime = 0;
  652. this.generatedSoundFx.collect();
  653. }
  654. if (!collision) {
  655. this.distanceRan += this.currentSpeed * deltaTime / this.msPerFrame;
  656. if (this.currentSpeed < this.config.MAX_SPEED) {
  657. this.currentSpeed += this.config.ACCELERATION;
  658. }
  659. } else {
  660. this.gameOver();
  661. }
  662. const playAchievementSound = this.distanceMeter.update(deltaTime,
  663. Math.ceil(this.distanceRan));
  664. if (!Runner.audioCues && playAchievementSound) {
  665. this.playSound(this.soundFx.SCORE);
  666. }
  667. // Night mode.
  668. if (!Runner.isAltGameModeEnabled()) {
  669. if (this.invertTimer > this.config.INVERT_FADE_DURATION) {
  670. this.invertTimer = 0;
  671. this.invertTrigger = false;
  672. this.invert(false);
  673. } else if (this.invertTimer) {
  674. this.invertTimer += deltaTime;
  675. } else {
  676. const actualDistance =
  677. this.distanceMeter.getActualDistance(Math.ceil(this.distanceRan));
  678. if (actualDistance > 0) {
  679. this.invertTrigger =
  680. !(actualDistance % this.config.INVERT_DISTANCE);
  681. if (this.invertTrigger && this.invertTimer === 0) {
  682. this.invertTimer += deltaTime;
  683. this.invert(false);
  684. }
  685. }
  686. }
  687. }
  688. }
  689. if (this.playing || (!this.activated &&
  690. this.tRex.blinkCount < Runner.config.MAX_BLINK_COUNT)) {
  691. this.tRex.update(deltaTime);
  692. this.scheduleNextUpdate();
  693. }
  694. },
  695. /**
  696. * Event handler.
  697. * @param {Event} e
  698. */
  699. handleEvent(e) {
  700. return (function(evtType, events) {
  701. switch (evtType) {
  702. case events.KEYDOWN:
  703. case events.TOUCHSTART:
  704. case events.POINTERDOWN:
  705. this.onKeyDown(e);
  706. break;
  707. case events.KEYUP:
  708. case events.TOUCHEND:
  709. case events.POINTERUP:
  710. this.onKeyUp(e);
  711. break;
  712. case events.GAMEPADCONNECTED:
  713. this.onGamepadConnected(e);
  714. break;
  715. }
  716. }.bind(this))(e.type, Runner.events);
  717. },
  718. /**
  719. * Initialize audio cues if activated by focus on the canvas element.
  720. * @param {Event} e
  721. */
  722. handleCanvasKeyPress(e) {
  723. if (!this.activated && !Runner.audioCues) {
  724. this.toggleSpeed();
  725. Runner.audioCues = true;
  726. this.generatedSoundFx.init();
  727. Runner.generatedSoundFx = this.generatedSoundFx;
  728. Runner.config.CLEAR_TIME *= 1.2;
  729. } else if (e.keyCode && Runner.keycodes.JUMP[e.keyCode]) {
  730. this.onKeyDown(e);
  731. }
  732. },
  733. /**
  734. * Prevent space key press from scrolling.
  735. * @param {Event} e
  736. */
  737. preventScrolling(e) {
  738. if (e.keyCode === 32) {
  739. e.preventDefault();
  740. }
  741. },
  742. /**
  743. * Toggle speed setting if toggle is shown.
  744. */
  745. toggleSpeed() {
  746. if (Runner.audioCues) {
  747. const speedChange = Runner.slowDown != this.slowSpeedCheckbox.checked;
  748. if (speedChange) {
  749. Runner.slowDown = this.slowSpeedCheckbox.checked;
  750. const updatedConfig =
  751. Runner.slowDown ? Runner.slowConfig : Runner.normalConfig;
  752. Runner.config = Object.assign(Runner.config, updatedConfig);
  753. this.currentSpeed = updatedConfig.SPEED;
  754. this.tRex.enableSlowConfig();
  755. this.horizon.adjustObstacleSpeed();
  756. }
  757. if (this.playing) {
  758. this.disableSpeedToggle(true);
  759. }
  760. }
  761. },
  762. /**
  763. * Show the speed toggle.
  764. * From focus event or when audio cues are activated.
  765. * @param {Event=} e
  766. */
  767. showSpeedToggle(e) {
  768. const isFocusEvent = e && e.type == 'focus';
  769. if (Runner.audioCues || isFocusEvent) {
  770. this.slowSpeedCheckboxLabel.classList.toggle(
  771. HIDDEN_CLASS, isFocusEvent ? false : !this.crashed);
  772. }
  773. },
  774. /**
  775. * Disable the speed toggle.
  776. * @param {boolean} disable
  777. */
  778. disableSpeedToggle(disable) {
  779. if (disable) {
  780. this.slowSpeedCheckbox.setAttribute('disabled', 'disabled');
  781. } else {
  782. this.slowSpeedCheckbox.removeAttribute('disabled');
  783. }
  784. },
  785. /**
  786. * Bind relevant key / mouse / touch listeners.
  787. */
  788. startListening() {
  789. // A11y keyboard / screen reader activation.
  790. this.containerEl.addEventListener(
  791. Runner.events.KEYDOWN, this.handleCanvasKeyPress.bind(this));
  792. if (!IS_MOBILE) {
  793. this.containerEl.addEventListener(
  794. Runner.events.FOCUS, this.showSpeedToggle.bind(this));
  795. }
  796. this.canvas.addEventListener(
  797. Runner.events.KEYDOWN, this.preventScrolling.bind(this));
  798. this.canvas.addEventListener(
  799. Runner.events.KEYUP, this.preventScrolling.bind(this));
  800. // Keys.
  801. document.addEventListener(Runner.events.KEYDOWN, this);
  802. document.addEventListener(Runner.events.KEYUP, this);
  803. // Touch / pointer.
  804. this.containerEl.addEventListener(Runner.events.TOUCHSTART, this);
  805. document.addEventListener(Runner.events.POINTERDOWN, this);
  806. document.addEventListener(Runner.events.POINTERUP, this);
  807. if (this.isArcadeMode()) {
  808. // Gamepad
  809. window.addEventListener(Runner.events.GAMEPADCONNECTED, this);
  810. }
  811. },
  812. /**
  813. * Remove all listeners.
  814. */
  815. stopListening() {
  816. document.removeEventListener(Runner.events.KEYDOWN, this);
  817. document.removeEventListener(Runner.events.KEYUP, this);
  818. if (this.touchController) {
  819. this.touchController.removeEventListener(Runner.events.TOUCHSTART, this);
  820. this.touchController.removeEventListener(Runner.events.TOUCHEND, this);
  821. }
  822. this.containerEl.removeEventListener(Runner.events.TOUCHSTART, this);
  823. document.removeEventListener(Runner.events.POINTERDOWN, this);
  824. document.removeEventListener(Runner.events.POINTERUP, this);
  825. if (this.isArcadeMode()) {
  826. window.removeEventListener(Runner.events.GAMEPADCONNECTED, this);
  827. }
  828. },
  829. /**
  830. * Process keydown.
  831. * @param {Event} e
  832. */
  833. onKeyDown(e) {
  834. // Prevent native page scrolling whilst tapping on mobile.
  835. if (IS_MOBILE && this.playing) {
  836. e.preventDefault();
  837. }
  838. if (this.isCanvasInView()) {
  839. // Allow toggling of speed toggle.
  840. if (Runner.keycodes.JUMP[e.keyCode] &&
  841. e.target == this.slowSpeedCheckbox) {
  842. return;
  843. }
  844. if (!this.crashed && !this.paused) {
  845. // For a11y, screen reader activation.
  846. const isMobileMouseInput = IS_MOBILE &&
  847. e.type === Runner.events.POINTERDOWN &&
  848. e.pointerType == 'mouse' && e.target == this.containerEl ||
  849. (IS_IOS && e.pointerType == 'touch' &&
  850. document.activeElement == this.containerEl);
  851. if (Runner.keycodes.JUMP[e.keyCode] ||
  852. e.type === Runner.events.TOUCHSTART || isMobileMouseInput ||
  853. (Runner.keycodes.DUCK[e.keyCode] && this.altGameModeActive)) {
  854. e.preventDefault();
  855. // Starting the game for the first time.
  856. if (!this.playing) {
  857. // Started by touch so create a touch controller.
  858. if (!this.touchController && e.type === Runner.events.TOUCHSTART) {
  859. this.createTouchController();
  860. }
  861. if (isMobileMouseInput) {
  862. this.handleCanvasKeyPress(e);
  863. }
  864. this.loadSounds();
  865. this.setPlayStatus(true);
  866. this.update();
  867. if (window.errorPageController) {
  868. errorPageController.trackEasterEgg();
  869. }
  870. }
  871. // Start jump.
  872. if (!this.tRex.jumping && !this.tRex.ducking) {
  873. if (Runner.audioCues) {
  874. this.generatedSoundFx.cancelFootSteps();
  875. } else {
  876. this.playSound(this.soundFx.BUTTON_PRESS);
  877. }
  878. this.tRex.startJump(this.currentSpeed);
  879. }
  880. // Ducking is disabled on alt game modes.
  881. } else if (
  882. !this.altGameModeActive && this.playing &&
  883. Runner.keycodes.DUCK[e.keyCode]) {
  884. e.preventDefault();
  885. if (this.tRex.jumping) {
  886. // Speed drop, activated only when jump key is not pressed.
  887. this.tRex.setSpeedDrop();
  888. } else if (!this.tRex.jumping && !this.tRex.ducking) {
  889. // Duck.
  890. this.tRex.setDuck(true);
  891. }
  892. }
  893. }
  894. }
  895. },
  896. /**
  897. * Process key up.
  898. * @param {Event} e
  899. */
  900. onKeyUp(e) {
  901. const keyCode = String(e.keyCode);
  902. const isjumpKey = Runner.keycodes.JUMP[keyCode] ||
  903. e.type === Runner.events.TOUCHEND || e.type === Runner.events.POINTERUP;
  904. if (this.isRunning() && isjumpKey) {
  905. this.tRex.endJump();
  906. } else if (Runner.keycodes.DUCK[keyCode]) {
  907. this.tRex.speedDrop = false;
  908. this.tRex.setDuck(false);
  909. } else if (this.crashed) {
  910. // Check that enough time has elapsed before allowing jump key to restart.
  911. const deltaTime = getTimeStamp() - this.time;
  912. if (this.isCanvasInView() &&
  913. (Runner.keycodes.RESTART[keyCode] || this.isLeftClickOnCanvas(e) ||
  914. (deltaTime >= this.config.GAMEOVER_CLEAR_TIME &&
  915. Runner.keycodes.JUMP[keyCode]))) {
  916. this.handleGameOverClicks(e);
  917. }
  918. } else if (this.paused && isjumpKey) {
  919. // Reset the jump state
  920. this.tRex.reset();
  921. this.play();
  922. }
  923. },
  924. /**
  925. * Process gamepad connected event.
  926. * @param {Event} e
  927. */
  928. onGamepadConnected(e) {
  929. if (!this.pollingGamepads) {
  930. this.pollGamepadState();
  931. }
  932. },
  933. /**
  934. * rAF loop for gamepad polling.
  935. */
  936. pollGamepadState() {
  937. const gamepads = navigator.getGamepads();
  938. this.pollActiveGamepad(gamepads);
  939. this.pollingGamepads = true;
  940. requestAnimationFrame(this.pollGamepadState.bind(this));
  941. },
  942. /**
  943. * Polls for a gamepad with the jump button pressed. If one is found this
  944. * becomes the "active" gamepad and all others are ignored.
  945. * @param {!Array<Gamepad>} gamepads
  946. */
  947. pollForActiveGamepad(gamepads) {
  948. for (let i = 0; i < gamepads.length; ++i) {
  949. if (gamepads[i] && gamepads[i].buttons.length > 0 &&
  950. gamepads[i].buttons[0].pressed) {
  951. this.gamepadIndex = i;
  952. this.pollActiveGamepad(gamepads);
  953. return;
  954. }
  955. }
  956. },
  957. /**
  958. * Polls the chosen gamepad for button presses and generates KeyboardEvents
  959. * to integrate with the rest of the game logic.
  960. * @param {!Array<Gamepad>} gamepads
  961. */
  962. pollActiveGamepad(gamepads) {
  963. if (this.gamepadIndex === undefined) {
  964. this.pollForActiveGamepad(gamepads);
  965. return;
  966. }
  967. const gamepad = gamepads[this.gamepadIndex];
  968. if (!gamepad) {
  969. this.gamepadIndex = undefined;
  970. this.pollForActiveGamepad(gamepads);
  971. return;
  972. }
  973. // The gamepad specification defines the typical mapping of physical buttons
  974. // to button indicies: https://w3c.github.io/gamepad/#remapping
  975. this.pollGamepadButton(gamepad, 0, 38); // Jump
  976. if (gamepad.buttons.length >= 2) {
  977. this.pollGamepadButton(gamepad, 1, 40); // Duck
  978. }
  979. if (gamepad.buttons.length >= 10) {
  980. this.pollGamepadButton(gamepad, 9, 13); // Restart
  981. }
  982. this.previousGamepad = gamepad;
  983. },
  984. /**
  985. * Generates a key event based on a gamepad button.
  986. * @param {!Gamepad} gamepad
  987. * @param {number} buttonIndex
  988. * @param {number} keyCode
  989. */
  990. pollGamepadButton(gamepad, buttonIndex, keyCode) {
  991. const state = gamepad.buttons[buttonIndex].pressed;
  992. let previousState = false;
  993. if (this.previousGamepad) {
  994. previousState = this.previousGamepad.buttons[buttonIndex].pressed;
  995. }
  996. // Generate key events on the rising and falling edge of a button press.
  997. if (state !== previousState) {
  998. const e = new KeyboardEvent(state ? Runner.events.KEYDOWN
  999. : Runner.events.KEYUP,
  1000. { keyCode: keyCode });
  1001. document.dispatchEvent(e);
  1002. }
  1003. },
  1004. /**
  1005. * Handle interactions on the game over screen state.
  1006. * A user is able to tap the high score twice to reset it.
  1007. * @param {Event} e
  1008. */
  1009. handleGameOverClicks(e) {
  1010. if (e.target != this.slowSpeedCheckbox) {
  1011. e.preventDefault();
  1012. if (this.distanceMeter.hasClickedOnHighScore(e) && this.highestScore) {
  1013. if (this.distanceMeter.isHighScoreFlashing()) {
  1014. // Subsequent click, reset the high score.
  1015. this.saveHighScore(0, true);
  1016. this.distanceMeter.resetHighScore();
  1017. } else {
  1018. // First click, flash the high score.
  1019. this.distanceMeter.startHighScoreFlashing();
  1020. }
  1021. } else {
  1022. this.distanceMeter.cancelHighScoreFlashing();
  1023. this.restart();
  1024. }
  1025. }
  1026. },
  1027. /**
  1028. * Returns whether the event was a left click on canvas.
  1029. * On Windows right click is registered as a click.
  1030. * @param {Event} e
  1031. * @return {boolean}
  1032. */
  1033. isLeftClickOnCanvas(e) {
  1034. return e.button != null && e.button < 2 &&
  1035. e.type === Runner.events.POINTERUP &&
  1036. (e.target === this.canvas ||
  1037. (IS_MOBILE && Runner.audioCues && e.target === this.containerEl));
  1038. },
  1039. /**
  1040. * RequestAnimationFrame wrapper.
  1041. */
  1042. scheduleNextUpdate() {
  1043. if (!this.updatePending) {
  1044. this.updatePending = true;
  1045. this.raqId = requestAnimationFrame(this.update.bind(this));
  1046. }
  1047. },
  1048. /**
  1049. * Whether the game is running.
  1050. * @return {boolean}
  1051. */
  1052. isRunning() {
  1053. return !!this.raqId;
  1054. },
  1055. /**
  1056. * Set the initial high score as stored in the user's profile.
  1057. * @param {number} highScore
  1058. */
  1059. initializeHighScore(highScore) {
  1060. this.syncHighestScore = true;
  1061. highScore = Math.ceil(highScore);
  1062. if (highScore < this.highestScore) {
  1063. if (window.errorPageController) {
  1064. errorPageController.updateEasterEggHighScore(this.highestScore);
  1065. }
  1066. return;
  1067. }
  1068. this.highestScore = highScore;
  1069. this.distanceMeter.setHighScore(this.highestScore);
  1070. },
  1071. /**
  1072. * Sets the current high score and saves to the profile if available.
  1073. * @param {number} distanceRan Total distance ran.
  1074. * @param {boolean=} opt_resetScore Whether to reset the score.
  1075. */
  1076. saveHighScore(distanceRan, opt_resetScore) {
  1077. this.highestScore = Math.ceil(distanceRan);
  1078. this.distanceMeter.setHighScore(this.highestScore);
  1079. // Store the new high score in the profile.
  1080. if (this.syncHighestScore && window.errorPageController) {
  1081. if (opt_resetScore) {
  1082. errorPageController.resetEasterEggHighScore();
  1083. } else {
  1084. errorPageController.updateEasterEggHighScore(this.highestScore);
  1085. }
  1086. }
  1087. },
  1088. /**
  1089. * Game over state.
  1090. */
  1091. gameOver() {
  1092. this.playSound(this.soundFx.HIT);
  1093. vibrate(200);
  1094. this.stop();
  1095. this.crashed = true;
  1096. this.distanceMeter.achievement = false;
  1097. this.tRex.update(100, Trex.status.CRASHED);
  1098. // Game over panel.
  1099. if (!this.gameOverPanel) {
  1100. const origSpriteDef = IS_HIDPI ?
  1101. Runner.spriteDefinitionByType.original.HDPI :
  1102. Runner.spriteDefinitionByType.original.LDPI;
  1103. if (this.canvas) {
  1104. if (Runner.isAltGameModeEnabled) {
  1105. this.gameOverPanel = new GameOverPanel(
  1106. this.canvas, origSpriteDef.TEXT_SPRITE, origSpriteDef.RESTART,
  1107. this.dimensions, origSpriteDef.ALT_GAME_END,
  1108. this.altGameModeActive);
  1109. } else {
  1110. this.gameOverPanel = new GameOverPanel(
  1111. this.canvas, origSpriteDef.TEXT_SPRITE, origSpriteDef.RESTART,
  1112. this.dimensions);
  1113. }
  1114. }
  1115. }
  1116. this.gameOverPanel.draw(this.altGameModeActive, this.tRex);
  1117. // Update the high score.
  1118. if (this.distanceRan > this.highestScore) {
  1119. this.saveHighScore(this.distanceRan);
  1120. }
  1121. // Reset the time clock.
  1122. this.time = getTimeStamp();
  1123. if (Runner.audioCues) {
  1124. this.generatedSoundFx.stopAll();
  1125. announcePhrase(
  1126. getA11yString(A11Y_STRINGS.gameOver)
  1127. .replace(
  1128. '$1',
  1129. this.distanceMeter.getActualDistance(this.distanceRan)
  1130. .toString()) +
  1131. ' ' +
  1132. getA11yString(A11Y_STRINGS.highScore)
  1133. .replace(
  1134. '$1',
  1135. this.distanceMeter.getActualDistance(this.highestScore)
  1136. .toString()));
  1137. this.containerEl.setAttribute(
  1138. 'title', getA11yString(A11Y_STRINGS.ariaLabel));
  1139. }
  1140. this.showSpeedToggle();
  1141. this.disableSpeedToggle(false);
  1142. },
  1143. stop() {
  1144. this.setPlayStatus(false);
  1145. this.paused = true;
  1146. cancelAnimationFrame(this.raqId);
  1147. this.raqId = 0;
  1148. this.generatedSoundFx.stopAll();
  1149. },
  1150. play() {
  1151. if (!this.crashed) {
  1152. this.setPlayStatus(true);
  1153. this.paused = false;
  1154. this.tRex.update(0, Trex.status.RUNNING);
  1155. this.time = getTimeStamp();
  1156. this.update();
  1157. this.generatedSoundFx.background();
  1158. }
  1159. },
  1160. restart() {
  1161. if (!this.raqId) {
  1162. this.playCount++;
  1163. this.runningTime = 0;
  1164. this.setPlayStatus(true);
  1165. this.toggleSpeed();
  1166. this.paused = false;
  1167. this.crashed = false;
  1168. this.distanceRan = 0;
  1169. this.setSpeed(this.config.SPEED);
  1170. this.time = getTimeStamp();
  1171. this.containerEl.classList.remove(Runner.classes.CRASHED);
  1172. this.clearCanvas();
  1173. this.distanceMeter.reset();
  1174. this.horizon.reset();
  1175. this.tRex.reset();
  1176. this.playSound(this.soundFx.BUTTON_PRESS);
  1177. this.invert(true);
  1178. this.flashTimer = null;
  1179. this.update();
  1180. this.gameOverPanel.reset();
  1181. this.generatedSoundFx.background();
  1182. this.containerEl.setAttribute('title', getA11yString(A11Y_STRINGS.jump));
  1183. announcePhrase(getA11yString(A11Y_STRINGS.started));
  1184. }
  1185. },
  1186. setPlayStatus(isPlaying) {
  1187. if (this.touchController) {
  1188. this.touchController.classList.toggle(HIDDEN_CLASS, !isPlaying);
  1189. }
  1190. this.playing = isPlaying;
  1191. },
  1192. /**
  1193. * Whether the game should go into arcade mode.
  1194. * @return {boolean}
  1195. */
  1196. isArcadeMode() {
  1197. // In RTL languages the title is wrapped with the left to right mark
  1198. // control characters &#x202A; and &#x202C but are invisible.
  1199. return IS_RTL ? document.title.indexOf(ARCADE_MODE_URL) == 1 :
  1200. document.title === ARCADE_MODE_URL;
  1201. },
  1202. /**
  1203. * Hides offline messaging for a fullscreen game only experience.
  1204. */
  1205. setArcadeMode() {
  1206. document.body.classList.add(Runner.classes.ARCADE_MODE);
  1207. this.setArcadeModeContainerScale();
  1208. },
  1209. /**
  1210. * Sets the scaling for arcade mode.
  1211. */
  1212. setArcadeModeContainerScale() {
  1213. const windowHeight = window.innerHeight;
  1214. const scaleHeight = windowHeight / this.dimensions.HEIGHT;
  1215. const scaleWidth = window.innerWidth / this.dimensions.WIDTH;
  1216. const scale = Math.max(1, Math.min(scaleHeight, scaleWidth));
  1217. const scaledCanvasHeight = this.dimensions.HEIGHT * scale;
  1218. // Positions the game container at 10% of the available vertical window
  1219. // height minus the game container height.
  1220. const translateY = Math.ceil(Math.max(0, (windowHeight - scaledCanvasHeight -
  1221. Runner.config.ARCADE_MODE_INITIAL_TOP_POSITION) *
  1222. Runner.config.ARCADE_MODE_TOP_POSITION_PERCENT)) *
  1223. window.devicePixelRatio;
  1224. const cssScale = IS_RTL ? -scale + ',' + scale : scale;
  1225. this.containerEl.style.transform =
  1226. 'scale(' + cssScale + ') translateY(' + translateY + 'px)';
  1227. },
  1228. /**
  1229. * Pause the game if the tab is not in focus.
  1230. */
  1231. onVisibilityChange(e) {
  1232. if (document.hidden || document.webkitHidden || e.type === 'blur' ||
  1233. document.visibilityState !== 'visible') {
  1234. this.stop();
  1235. } else if (!this.crashed) {
  1236. this.tRex.reset();
  1237. this.play();
  1238. }
  1239. },
  1240. /**
  1241. * Play a sound.
  1242. * @param {AudioBuffer} soundBuffer
  1243. */
  1244. playSound(soundBuffer) {
  1245. if (soundBuffer) {
  1246. const sourceNode = this.audioContext.createBufferSource();
  1247. sourceNode.buffer = soundBuffer;
  1248. sourceNode.connect(this.audioContext.destination);
  1249. sourceNode.start(0);
  1250. }
  1251. },
  1252. /**
  1253. * Inverts the current page / canvas colors.
  1254. * @param {boolean} reset Whether to reset colors.
  1255. */
  1256. invert(reset) {
  1257. const htmlEl = document.firstElementChild;
  1258. if (reset) {
  1259. htmlEl.classList.toggle(Runner.classes.INVERTED,
  1260. false);
  1261. this.invertTimer = 0;
  1262. this.inverted = false;
  1263. } else {
  1264. this.inverted = htmlEl.classList.toggle(
  1265. Runner.classes.INVERTED, this.invertTrigger);
  1266. }
  1267. },
  1268. };
  1269. /**
  1270. * Updates the canvas size taking into
  1271. * account the backing store pixel ratio and
  1272. * the device pixel ratio.
  1273. *
  1274. * See article by Paul Lewis:
  1275. * http://www.html5rocks.com/en/tutorials/canvas/hidpi/
  1276. *
  1277. * @param {HTMLCanvasElement} canvas
  1278. * @param {number=} opt_width
  1279. * @param {number=} opt_height
  1280. * @return {boolean} Whether the canvas was scaled.
  1281. */
  1282. Runner.updateCanvasScaling = function(canvas, opt_width, opt_height) {
  1283. const context =
  1284. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  1285. // Query the various pixel ratios
  1286. const devicePixelRatio = Math.floor(window.devicePixelRatio) || 1;
  1287. /** @suppress {missingProperties} */
  1288. const backingStoreRatio =
  1289. Math.floor(context.webkitBackingStorePixelRatio) || 1;
  1290. const ratio = devicePixelRatio / backingStoreRatio;
  1291. // Upscale the canvas if the two ratios don't match
  1292. if (devicePixelRatio !== backingStoreRatio) {
  1293. const oldWidth = opt_width || canvas.width;
  1294. const oldHeight = opt_height || canvas.height;
  1295. canvas.width = oldWidth * ratio;
  1296. canvas.height = oldHeight * ratio;
  1297. canvas.style.width = oldWidth + 'px';
  1298. canvas.style.height = oldHeight + 'px';
  1299. // Scale the context to counter the fact that we've manually scaled
  1300. // our canvas element.
  1301. context.scale(ratio, ratio);
  1302. return true;
  1303. } else if (devicePixelRatio === 1) {
  1304. // Reset the canvas width / height. Fixes scaling bug when the page is
  1305. // zoomed and the devicePixelRatio changes accordingly.
  1306. canvas.style.width = canvas.width + 'px';
  1307. canvas.style.height = canvas.height + 'px';
  1308. }
  1309. return false;
  1310. };
  1311. /**
  1312. * Whether events are enabled.
  1313. * @return {boolean}
  1314. */
  1315. Runner.isAltGameModeEnabled = function() {
  1316. return loadTimeData && loadTimeData.valueExists('enableAltGameMode');
  1317. };
  1318. /**
  1319. * Generated sound FX class for audio cues.
  1320. * @constructor
  1321. */
  1322. function GeneratedSoundFx() {
  1323. this.audioCues = false;
  1324. this.context = null;
  1325. this.panner = null;
  1326. }
  1327. GeneratedSoundFx.prototype = {
  1328. init() {
  1329. this.audioCues = true;
  1330. if (!this.context) {
  1331. // iOS only supports the webkit version.
  1332. this.context = window.webkitAudioContext ? new webkitAudioContext() :
  1333. new AudioContext();
  1334. if (IS_IOS) {
  1335. this.context.onstatechange = (function() {
  1336. if (this.context.state != 'running') {
  1337. this.context.resume();
  1338. }
  1339. }).bind(this);
  1340. this.context.resume();
  1341. }
  1342. this.panner = this.context.createStereoPanner ?
  1343. this.context.createStereoPanner() :
  1344. null;
  1345. }
  1346. },
  1347. stopAll() {
  1348. this.cancelFootSteps();
  1349. },
  1350. /**
  1351. * Play oscillators at certain frequency and for a certain time.
  1352. * @param {number} frequency
  1353. * @param {number} startTime
  1354. * @param {number} duration
  1355. * @param {?number=} opt_vol
  1356. * @param {number=} opt_pan
  1357. */
  1358. playNote(frequency, startTime, duration, opt_vol, opt_pan) {
  1359. const osc1 = this.context.createOscillator();
  1360. const osc2 = this.context.createOscillator();
  1361. const volume = this.context.createGain();
  1362. // Set oscillator wave type
  1363. osc1.type = 'triangle';
  1364. osc2.type = 'triangle';
  1365. volume.gain.value = 0.1;
  1366. // Set up node routing
  1367. if (this.panner) {
  1368. this.panner.pan.value = opt_pan || 0;
  1369. osc1.connect(volume).connect(this.panner);
  1370. osc2.connect(volume).connect(this.panner);
  1371. this.panner.connect(this.context.destination);
  1372. } else {
  1373. osc1.connect(volume);
  1374. osc2.connect(volume);
  1375. volume.connect(this.context.destination);
  1376. }
  1377. // Detune oscillators for chorus effect
  1378. osc1.frequency.value = frequency + 1;
  1379. osc2.frequency.value = frequency - 2;
  1380. // Fade out
  1381. volume.gain.setValueAtTime(opt_vol || 0.01, startTime + duration - 0.05);
  1382. volume.gain.linearRampToValueAtTime(0.00001, startTime + duration);
  1383. // Start oscillators
  1384. osc1.start(startTime);
  1385. osc2.start(startTime);
  1386. // Stop oscillators
  1387. osc1.stop(startTime + duration);
  1388. osc2.stop(startTime + duration);
  1389. },
  1390. background() {
  1391. if (this.audioCues) {
  1392. const now = this.context.currentTime;
  1393. this.playNote(493.883, now, 0.116);
  1394. this.playNote(659.255, now + 0.116, 0.232);
  1395. this.loopFootSteps();
  1396. }
  1397. },
  1398. loopFootSteps() {
  1399. if (this.audioCues && !this.bgSoundIntervalId) {
  1400. this.bgSoundIntervalId = setInterval(function() {
  1401. this.playNote(73.42, this.context.currentTime, 0.05, 0.16);
  1402. this.playNote(69.30, this.context.currentTime + 0.116, 0.116, 0.16);
  1403. }.bind(this), 280);
  1404. }
  1405. },
  1406. cancelFootSteps() {
  1407. if (this.audioCues && this.bgSoundIntervalId) {
  1408. clearInterval(this.bgSoundIntervalId);
  1409. this.bgSoundIntervalId = null;
  1410. this.playNote(103.83, this.context.currentTime, 0.232, 0.02);
  1411. this.playNote(116.54, this.context.currentTime + 0.116, 0.232, 0.02);
  1412. }
  1413. },
  1414. collect() {
  1415. if (this.audioCues) {
  1416. this.cancelFootSteps();
  1417. const now = this.context.currentTime;
  1418. this.playNote(830.61, now, 0.116);
  1419. this.playNote(1318.51, now + 0.116, 0.232);
  1420. }
  1421. },
  1422. jump() {
  1423. if (this.audioCues) {
  1424. const now = this.context.currentTime;
  1425. this.playNote(659.25, now, 0.116, 0.3, -0.6);
  1426. this.playNote(880, now + 0.116, 0.232, 0.3, -0.6);
  1427. }
  1428. },
  1429. };
  1430. /**
  1431. * Speak a phrase using Speech Synthesis API for a11y.
  1432. * @param {string} phrase Sentence to speak.
  1433. */
  1434. function speakPhrase(phrase) {
  1435. if ('speechSynthesis' in window) {
  1436. const msg = new SpeechSynthesisUtterance(phrase);
  1437. const voices = window.speechSynthesis.getVoices();
  1438. msg.text = phrase;
  1439. speechSynthesis.speak(msg);
  1440. }
  1441. }
  1442. /**
  1443. * For screen readers make an announcement to the live region.
  1444. * @param {string} phrase Sentence to speak.
  1445. */
  1446. function announcePhrase(phrase) {
  1447. if (Runner.a11yStatusEl) {
  1448. Runner.a11yStatusEl.textContent = '';
  1449. Runner.a11yStatusEl.textContent = phrase;
  1450. }
  1451. }
  1452. /**
  1453. * Returns a string from loadTimeData data object.
  1454. * @param {string} stringName
  1455. * @return {string}
  1456. */
  1457. function getA11yString(stringName) {
  1458. return loadTimeData && loadTimeData.valueExists(stringName) ?
  1459. loadTimeData.getString(stringName) :
  1460. '';
  1461. }
  1462. /**
  1463. * Get random number.
  1464. * @param {number} min
  1465. * @param {number} max
  1466. */
  1467. function getRandomNum(min, max) {
  1468. return Math.floor(Math.random() * (max - min + 1)) + min;
  1469. }
  1470. /**
  1471. * Vibrate on mobile devices.
  1472. * @param {number} duration Duration of the vibration in milliseconds.
  1473. */
  1474. function vibrate(duration) {
  1475. if (IS_MOBILE && window.navigator.vibrate) {
  1476. window.navigator.vibrate(duration);
  1477. }
  1478. }
  1479. /**
  1480. * Create canvas element.
  1481. * @param {Element} container Element to append canvas to.
  1482. * @param {number} width
  1483. * @param {number} height
  1484. * @param {string=} opt_classname
  1485. * @return {HTMLCanvasElement}
  1486. */
  1487. function createCanvas(container, width, height, opt_classname) {
  1488. const canvas =
  1489. /** @type {!HTMLCanvasElement} */ (document.createElement('canvas'));
  1490. canvas.className = opt_classname ? Runner.classes.CANVAS + ' ' +
  1491. opt_classname : Runner.classes.CANVAS;
  1492. canvas.width = width;
  1493. canvas.height = height;
  1494. container.appendChild(canvas);
  1495. return canvas;
  1496. }
  1497. /**
  1498. * Decodes the base 64 audio to ArrayBuffer used by Web Audio.
  1499. * @param {string} base64String
  1500. */
  1501. function decodeBase64ToArrayBuffer(base64String) {
  1502. const len = (base64String.length / 4) * 3;
  1503. const str = atob(base64String);
  1504. const arrayBuffer = new ArrayBuffer(len);
  1505. const bytes = new Uint8Array(arrayBuffer);
  1506. for (let i = 0; i < len; i++) {
  1507. bytes[i] = str.charCodeAt(i);
  1508. }
  1509. return bytes.buffer;
  1510. }
  1511. /**
  1512. * Return the current timestamp.
  1513. * @return {number}
  1514. */
  1515. function getTimeStamp() {
  1516. return IS_IOS ? new Date().getTime() : performance.now();
  1517. }
  1518. //******************************************************************************
  1519. /**
  1520. * Game over panel.
  1521. * @param {!HTMLCanvasElement} canvas
  1522. * @param {Object} textImgPos
  1523. * @param {Object} restartImgPos
  1524. * @param {!Object} dimensions Canvas dimensions.
  1525. * @param {Object=} opt_altGameEndImgPos
  1526. * @param {boolean=} opt_altGameActive
  1527. * @constructor
  1528. */
  1529. function GameOverPanel(
  1530. canvas, textImgPos, restartImgPos, dimensions, opt_altGameEndImgPos,
  1531. opt_altGameActive) {
  1532. this.canvas = canvas;
  1533. this.canvasCtx =
  1534. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  1535. this.canvasDimensions = dimensions;
  1536. this.textImgPos = textImgPos;
  1537. this.restartImgPos = restartImgPos;
  1538. this.altGameEndImgPos = opt_altGameEndImgPos;
  1539. this.altGameModeActive = opt_altGameActive;
  1540. // Retry animation.
  1541. this.frameTimeStamp = 0;
  1542. this.animTimer = 0;
  1543. this.currentFrame = 0;
  1544. this.gameOverRafId = null;
  1545. this.flashTimer = 0;
  1546. this.flashCounter = 0;
  1547. this.originalText = true;
  1548. }
  1549. GameOverPanel.RESTART_ANIM_DURATION = 875;
  1550. GameOverPanel.LOGO_PAUSE_DURATION = 875;
  1551. GameOverPanel.FLASH_ITERATIONS = 5;
  1552. /**
  1553. * Animation frames spec.
  1554. */
  1555. GameOverPanel.animConfig = {
  1556. frames: [0, 36, 72, 108, 144, 180, 216, 252],
  1557. msPerFrame: GameOverPanel.RESTART_ANIM_DURATION / 8,
  1558. };
  1559. /**
  1560. * Dimensions used in the panel.
  1561. * @enum {number}
  1562. */
  1563. GameOverPanel.dimensions = {
  1564. TEXT_X: 0,
  1565. TEXT_Y: 13,
  1566. TEXT_WIDTH: 191,
  1567. TEXT_HEIGHT: 11,
  1568. RESTART_WIDTH: 36,
  1569. RESTART_HEIGHT: 32,
  1570. };
  1571. GameOverPanel.prototype = {
  1572. /**
  1573. * Update the panel dimensions.
  1574. * @param {number} width New canvas width.
  1575. * @param {number} opt_height Optional new canvas height.
  1576. */
  1577. updateDimensions(width, opt_height) {
  1578. this.canvasDimensions.WIDTH = width;
  1579. if (opt_height) {
  1580. this.canvasDimensions.HEIGHT = opt_height;
  1581. }
  1582. this.currentFrame = GameOverPanel.animConfig.frames.length - 1;
  1583. },
  1584. drawGameOverText(dimensions, opt_useAltText) {
  1585. const centerX = this.canvasDimensions.WIDTH / 2;
  1586. let textSourceX = dimensions.TEXT_X;
  1587. let textSourceY = dimensions.TEXT_Y;
  1588. let textSourceWidth = dimensions.TEXT_WIDTH;
  1589. let textSourceHeight = dimensions.TEXT_HEIGHT;
  1590. const textTargetX = Math.round(centerX - (dimensions.TEXT_WIDTH / 2));
  1591. const textTargetY = Math.round((this.canvasDimensions.HEIGHT - 25) / 3);
  1592. const textTargetWidth = dimensions.TEXT_WIDTH;
  1593. const textTargetHeight = dimensions.TEXT_HEIGHT;
  1594. if (IS_HIDPI) {
  1595. textSourceY *= 2;
  1596. textSourceX *= 2;
  1597. textSourceWidth *= 2;
  1598. textSourceHeight *= 2;
  1599. }
  1600. if (!opt_useAltText) {
  1601. textSourceX += this.textImgPos.x;
  1602. textSourceY += this.textImgPos.y;
  1603. }
  1604. const spriteSource =
  1605. opt_useAltText ? Runner.altCommonImageSprite : Runner.origImageSprite;
  1606. this.canvasCtx.save();
  1607. if (IS_RTL) {
  1608. this.canvasCtx.translate(this.canvasDimensions.WIDTH, 0);
  1609. this.canvasCtx.scale(-1, 1);
  1610. }
  1611. // Game over text from sprite.
  1612. this.canvasCtx.drawImage(
  1613. spriteSource, textSourceX, textSourceY, textSourceWidth,
  1614. textSourceHeight, textTargetX, textTargetY, textTargetWidth,
  1615. textTargetHeight);
  1616. this.canvasCtx.restore();
  1617. },
  1618. /**
  1619. * Draw additional adornments for alternative game types.
  1620. */
  1621. drawAltGameElements(tRex) {
  1622. // Additional adornments.
  1623. if (this.altGameModeActive && Runner.spriteDefinition.ALT_GAME_END_CONFIG) {
  1624. const altGameEndConfig = Runner.spriteDefinition.ALT_GAME_END_CONFIG;
  1625. let altGameEndSourceWidth = altGameEndConfig.WIDTH;
  1626. let altGameEndSourceHeight = altGameEndConfig.HEIGHT;
  1627. const altGameEndTargetX = tRex.xPos + altGameEndConfig.X_OFFSET;
  1628. const altGameEndTargetY = tRex.yPos + altGameEndConfig.Y_OFFSET;
  1629. if (IS_HIDPI) {
  1630. altGameEndSourceWidth *= 2;
  1631. altGameEndSourceHeight *= 2;
  1632. }
  1633. this.canvasCtx.drawImage(
  1634. Runner.altCommonImageSprite, this.altGameEndImgPos.x,
  1635. this.altGameEndImgPos.y, altGameEndSourceWidth,
  1636. altGameEndSourceHeight, altGameEndTargetX, altGameEndTargetY,
  1637. altGameEndConfig.WIDTH, altGameEndConfig.HEIGHT);
  1638. }
  1639. },
  1640. /**
  1641. * Draw restart button.
  1642. */
  1643. drawRestartButton() {
  1644. const dimensions = GameOverPanel.dimensions;
  1645. let framePosX = GameOverPanel.animConfig.frames[this.currentFrame];
  1646. let restartSourceWidth = dimensions.RESTART_WIDTH;
  1647. let restartSourceHeight = dimensions.RESTART_HEIGHT;
  1648. const restartTargetX =
  1649. (this.canvasDimensions.WIDTH / 2) - (dimensions.RESTART_WIDTH / 2);
  1650. const restartTargetY = this.canvasDimensions.HEIGHT / 2;
  1651. if (IS_HIDPI) {
  1652. restartSourceWidth *= 2;
  1653. restartSourceHeight *= 2;
  1654. framePosX *= 2;
  1655. }
  1656. this.canvasCtx.save();
  1657. if (IS_RTL) {
  1658. this.canvasCtx.translate(this.canvasDimensions.WIDTH, 0);
  1659. this.canvasCtx.scale(-1, 1);
  1660. }
  1661. this.canvasCtx.drawImage(
  1662. Runner.origImageSprite, this.restartImgPos.x + framePosX,
  1663. this.restartImgPos.y, restartSourceWidth, restartSourceHeight,
  1664. restartTargetX, restartTargetY, dimensions.RESTART_WIDTH,
  1665. dimensions.RESTART_HEIGHT);
  1666. this.canvasCtx.restore();
  1667. },
  1668. /**
  1669. * Draw the panel.
  1670. * @param {boolean} opt_altGameModeActive
  1671. * @param {!Trex} opt_tRex
  1672. */
  1673. draw(opt_altGameModeActive, opt_tRex) {
  1674. if (opt_altGameModeActive) {
  1675. this.altGameModeActive = opt_altGameModeActive;
  1676. }
  1677. this.drawGameOverText(GameOverPanel.dimensions, false);
  1678. this.drawRestartButton();
  1679. this.drawAltGameElements(opt_tRex);
  1680. this.update();
  1681. },
  1682. /**
  1683. * Update animation frames.
  1684. */
  1685. update() {
  1686. const now = getTimeStamp();
  1687. const deltaTime = now - (this.frameTimeStamp || now);
  1688. this.frameTimeStamp = now;
  1689. this.animTimer += deltaTime;
  1690. this.flashTimer += deltaTime;
  1691. // Restart Button
  1692. if (this.currentFrame == 0 &&
  1693. this.animTimer > GameOverPanel.LOGO_PAUSE_DURATION) {
  1694. this.animTimer = 0;
  1695. this.currentFrame++;
  1696. this.drawRestartButton();
  1697. } else if (
  1698. this.currentFrame > 0 &&
  1699. this.currentFrame < GameOverPanel.animConfig.frames.length) {
  1700. if (this.animTimer >= GameOverPanel.animConfig.msPerFrame) {
  1701. this.currentFrame++;
  1702. this.drawRestartButton();
  1703. }
  1704. } else if (
  1705. !this.altGameModeActive &&
  1706. this.currentFrame == GameOverPanel.animConfig.frames.length) {
  1707. this.reset();
  1708. return;
  1709. }
  1710. // Game over text
  1711. if (this.altGameModeActive &&
  1712. Runner.spriteDefinitionByType.original.ALT_GAME_OVER_TEXT_CONFIG) {
  1713. const altTextConfig =
  1714. Runner.spriteDefinitionByType.original.ALT_GAME_OVER_TEXT_CONFIG;
  1715. if (this.flashCounter < GameOverPanel.FLASH_ITERATIONS &&
  1716. this.flashTimer > altTextConfig.FLASH_DURATION) {
  1717. this.flashTimer = 0;
  1718. this.originalText = !this.originalText;
  1719. this.clearGameOverTextBounds();
  1720. if (this.originalText) {
  1721. this.drawGameOverText(GameOverPanel.dimensions, false);
  1722. this.flashCounter++;
  1723. } else {
  1724. this.drawGameOverText(altTextConfig, true);
  1725. }
  1726. } else if (this.flashCounter >= GameOverPanel.FLASH_ITERATIONS) {
  1727. this.reset();
  1728. return;
  1729. }
  1730. }
  1731. this.gameOverRafId = requestAnimationFrame(this.update.bind(this));
  1732. },
  1733. /**
  1734. * Clear game over text.
  1735. */
  1736. clearGameOverTextBounds() {
  1737. this.canvasCtx.save();
  1738. this.canvasCtx.clearRect(
  1739. Math.round(
  1740. this.canvasDimensions.WIDTH / 2 -
  1741. (GameOverPanel.dimensions.TEXT_WIDTH / 2)),
  1742. Math.round((this.canvasDimensions.HEIGHT - 25) / 3),
  1743. GameOverPanel.dimensions.TEXT_WIDTH,
  1744. GameOverPanel.dimensions.TEXT_HEIGHT + 4);
  1745. this.canvasCtx.restore();
  1746. },
  1747. reset() {
  1748. if (this.gameOverRafId) {
  1749. cancelAnimationFrame(this.gameOverRafId);
  1750. this.gameOverRafId = null;
  1751. }
  1752. this.animTimer = 0;
  1753. this.frameTimeStamp = 0;
  1754. this.currentFrame = 0;
  1755. this.flashTimer = 0;
  1756. this.flashCounter = 0;
  1757. this.originalText = true;
  1758. },
  1759. };
  1760. //******************************************************************************
  1761. /**
  1762. * Check for a collision.
  1763. * @param {!Obstacle} obstacle
  1764. * @param {!Trex} tRex T-rex object.
  1765. * @param {CanvasRenderingContext2D=} opt_canvasCtx Optional canvas context for
  1766. * drawing collision boxes.
  1767. * @return {Array<CollisionBox>|undefined}
  1768. */
  1769. function checkForCollision(obstacle, tRex, opt_canvasCtx) {
  1770. const obstacleBoxXPos = Runner.defaultDimensions.WIDTH + obstacle.xPos;
  1771. // Adjustments are made to the bounding box as there is a 1 pixel white
  1772. // border around the t-rex and obstacles.
  1773. const tRexBox = new CollisionBox(
  1774. tRex.xPos + 1,
  1775. tRex.yPos + 1,
  1776. tRex.config.WIDTH - 2,
  1777. tRex.config.HEIGHT - 2);
  1778. const obstacleBox = new CollisionBox(
  1779. obstacle.xPos + 1,
  1780. obstacle.yPos + 1,
  1781. obstacle.typeConfig.width * obstacle.size - 2,
  1782. obstacle.typeConfig.height - 2);
  1783. // Debug outer box
  1784. if (opt_canvasCtx) {
  1785. drawCollisionBoxes(opt_canvasCtx, tRexBox, obstacleBox);
  1786. }
  1787. // Simple outer bounds check.
  1788. if (boxCompare(tRexBox, obstacleBox)) {
  1789. const collisionBoxes = obstacle.collisionBoxes;
  1790. let tRexCollisionBoxes = [];
  1791. if (Runner.isAltGameModeEnabled()) {
  1792. tRexCollisionBoxes = Runner.spriteDefinition.TREX.COLLISION_BOXES;
  1793. } else {
  1794. tRexCollisionBoxes = tRex.ducking ? Trex.collisionBoxes.DUCKING :
  1795. Trex.collisionBoxes.RUNNING;
  1796. }
  1797. // Detailed axis aligned box check.
  1798. for (let t = 0; t < tRexCollisionBoxes.length; t++) {
  1799. for (let i = 0; i < collisionBoxes.length; i++) {
  1800. // Adjust the box to actual positions.
  1801. const adjTrexBox =
  1802. createAdjustedCollisionBox(tRexCollisionBoxes[t], tRexBox);
  1803. const adjObstacleBox =
  1804. createAdjustedCollisionBox(collisionBoxes[i], obstacleBox);
  1805. const crashed = boxCompare(adjTrexBox, adjObstacleBox);
  1806. // Draw boxes for debug.
  1807. if (opt_canvasCtx) {
  1808. drawCollisionBoxes(opt_canvasCtx, adjTrexBox, adjObstacleBox);
  1809. }
  1810. if (crashed) {
  1811. return [adjTrexBox, adjObstacleBox];
  1812. }
  1813. }
  1814. }
  1815. }
  1816. }
  1817. /**
  1818. * Adjust the collision box.
  1819. * @param {!CollisionBox} box The original box.
  1820. * @param {!CollisionBox} adjustment Adjustment box.
  1821. * @return {CollisionBox} The adjusted collision box object.
  1822. */
  1823. function createAdjustedCollisionBox(box, adjustment) {
  1824. return new CollisionBox(
  1825. box.x + adjustment.x,
  1826. box.y + adjustment.y,
  1827. box.width,
  1828. box.height);
  1829. }
  1830. /**
  1831. * Draw the collision boxes for debug.
  1832. */
  1833. function drawCollisionBoxes(canvasCtx, tRexBox, obstacleBox) {
  1834. canvasCtx.save();
  1835. canvasCtx.strokeStyle = '#f00';
  1836. canvasCtx.strokeRect(tRexBox.x, tRexBox.y, tRexBox.width, tRexBox.height);
  1837. canvasCtx.strokeStyle = '#0f0';
  1838. canvasCtx.strokeRect(obstacleBox.x, obstacleBox.y,
  1839. obstacleBox.width, obstacleBox.height);
  1840. canvasCtx.restore();
  1841. }
  1842. /**
  1843. * Compare two collision boxes for a collision.
  1844. * @param {CollisionBox} tRexBox
  1845. * @param {CollisionBox} obstacleBox
  1846. * @return {boolean} Whether the boxes intersected.
  1847. */
  1848. function boxCompare(tRexBox, obstacleBox) {
  1849. let crashed = false;
  1850. const tRexBoxX = tRexBox.x;
  1851. const tRexBoxY = tRexBox.y;
  1852. const obstacleBoxX = obstacleBox.x;
  1853. const obstacleBoxY = obstacleBox.y;
  1854. // Axis-Aligned Bounding Box method.
  1855. if (tRexBox.x < obstacleBoxX + obstacleBox.width &&
  1856. tRexBox.x + tRexBox.width > obstacleBoxX &&
  1857. tRexBox.y < obstacleBox.y + obstacleBox.height &&
  1858. tRexBox.height + tRexBox.y > obstacleBox.y) {
  1859. crashed = true;
  1860. }
  1861. return crashed;
  1862. }
  1863. //******************************************************************************
  1864. /**
  1865. * Collision box object.
  1866. * @param {number} x X position.
  1867. * @param {number} y Y Position.
  1868. * @param {number} w Width.
  1869. * @param {number} h Height.
  1870. * @constructor
  1871. */
  1872. function CollisionBox(x, y, w, h) {
  1873. this.x = x;
  1874. this.y = y;
  1875. this.width = w;
  1876. this.height = h;
  1877. }
  1878. //******************************************************************************
  1879. /**
  1880. * Obstacle.
  1881. * @param {CanvasRenderingContext2D} canvasCtx
  1882. * @param {ObstacleType} type
  1883. * @param {Object} spriteImgPos Obstacle position in sprite.
  1884. * @param {Object} dimensions
  1885. * @param {number} gapCoefficient Mutipler in determining the gap.
  1886. * @param {number} speed
  1887. * @param {number=} opt_xOffset
  1888. * @param {boolean=} opt_isAltGameMode
  1889. * @constructor
  1890. */
  1891. function Obstacle(
  1892. canvasCtx, type, spriteImgPos, dimensions, gapCoefficient, speed,
  1893. opt_xOffset, opt_isAltGameMode) {
  1894. this.canvasCtx = canvasCtx;
  1895. this.spritePos = spriteImgPos;
  1896. this.typeConfig = type;
  1897. this.gapCoefficient = Runner.slowDown ? gapCoefficient * 2 : gapCoefficient;
  1898. this.size = getRandomNum(1, Obstacle.MAX_OBSTACLE_LENGTH);
  1899. this.dimensions = dimensions;
  1900. this.remove = false;
  1901. this.xPos = dimensions.WIDTH + (opt_xOffset || 0);
  1902. this.yPos = 0;
  1903. this.width = 0;
  1904. this.collisionBoxes = [];
  1905. this.gap = 0;
  1906. this.speedOffset = 0;
  1907. this.altGameModeActive = opt_isAltGameMode;
  1908. this.imageSprite = this.typeConfig.type == 'COLLECTABLE' ?
  1909. Runner.altCommonImageSprite :
  1910. this.altGameModeActive ? Runner.altGameImageSprite : Runner.imageSprite;
  1911. // For animated obstacles.
  1912. this.currentFrame = 0;
  1913. this.timer = 0;
  1914. this.init(speed);
  1915. }
  1916. /**
  1917. * Coefficient for calculating the maximum gap.
  1918. */
  1919. Obstacle.MAX_GAP_COEFFICIENT = 1.5;
  1920. /**
  1921. * Maximum obstacle grouping count.
  1922. */
  1923. Obstacle.MAX_OBSTACLE_LENGTH = 3;
  1924. Obstacle.prototype = {
  1925. /**
  1926. * Initialise the DOM for the obstacle.
  1927. * @param {number} speed
  1928. */
  1929. init(speed) {
  1930. this.cloneCollisionBoxes();
  1931. // Only allow sizing if we're at the right speed.
  1932. if (this.size > 1 && this.typeConfig.multipleSpeed > speed) {
  1933. this.size = 1;
  1934. }
  1935. this.width = this.typeConfig.width * this.size;
  1936. // Check if obstacle can be positioned at various heights.
  1937. if (Array.isArray(this.typeConfig.yPos)) {
  1938. const yPosConfig =
  1939. IS_MOBILE ? this.typeConfig.yPosMobile : this.typeConfig.yPos;
  1940. this.yPos = yPosConfig[getRandomNum(0, yPosConfig.length - 1)];
  1941. } else {
  1942. this.yPos = this.typeConfig.yPos;
  1943. }
  1944. this.draw();
  1945. // Make collision box adjustments,
  1946. // Central box is adjusted to the size as one box.
  1947. // ____ ______ ________
  1948. // _| |-| _| |-| _| |-|
  1949. // | |<->| | | |<--->| | | |<----->| |
  1950. // | | 1 | | | | 2 | | | | 3 | |
  1951. // |_|___|_| |_|_____|_| |_|_______|_|
  1952. //
  1953. if (this.size > 1) {
  1954. this.collisionBoxes[1].width = this.width - this.collisionBoxes[0].width -
  1955. this.collisionBoxes[2].width;
  1956. this.collisionBoxes[2].x = this.width - this.collisionBoxes[2].width;
  1957. }
  1958. // For obstacles that go at a different speed from the horizon.
  1959. if (this.typeConfig.speedOffset) {
  1960. this.speedOffset = Math.random() > 0.5 ? this.typeConfig.speedOffset :
  1961. -this.typeConfig.speedOffset;
  1962. }
  1963. this.gap = this.getGap(this.gapCoefficient, speed);
  1964. // Increase gap for audio cues enabled.
  1965. if (Runner.audioCues) {
  1966. this.gap *= 2;
  1967. }
  1968. },
  1969. /**
  1970. * Draw and crop based on size.
  1971. */
  1972. draw() {
  1973. let sourceWidth = this.typeConfig.width;
  1974. let sourceHeight = this.typeConfig.height;
  1975. if (IS_HIDPI) {
  1976. sourceWidth = sourceWidth * 2;
  1977. sourceHeight = sourceHeight * 2;
  1978. }
  1979. // X position in sprite.
  1980. let sourceX =
  1981. (sourceWidth * this.size) * (0.5 * (this.size - 1)) + this.spritePos.x;
  1982. // Animation frames.
  1983. if (this.currentFrame > 0) {
  1984. sourceX += sourceWidth * this.currentFrame;
  1985. }
  1986. this.canvasCtx.drawImage(
  1987. this.imageSprite, sourceX, this.spritePos.y, sourceWidth * this.size,
  1988. sourceHeight, this.xPos, this.yPos, this.typeConfig.width * this.size,
  1989. this.typeConfig.height);
  1990. },
  1991. /**
  1992. * Obstacle frame update.
  1993. * @param {number} deltaTime
  1994. * @param {number} speed
  1995. */
  1996. update(deltaTime, speed) {
  1997. if (!this.remove) {
  1998. if (this.typeConfig.speedOffset) {
  1999. speed += this.speedOffset;
  2000. }
  2001. this.xPos -= Math.floor((speed * FPS / 1000) * deltaTime);
  2002. // Update frame
  2003. if (this.typeConfig.numFrames) {
  2004. this.timer += deltaTime;
  2005. if (this.timer >= this.typeConfig.frameRate) {
  2006. this.currentFrame =
  2007. this.currentFrame === this.typeConfig.numFrames - 1 ?
  2008. 0 :
  2009. this.currentFrame + 1;
  2010. this.timer = 0;
  2011. }
  2012. }
  2013. this.draw();
  2014. if (!this.isVisible()) {
  2015. this.remove = true;
  2016. }
  2017. }
  2018. },
  2019. /**
  2020. * Calculate a random gap size.
  2021. * - Minimum gap gets wider as speed increses
  2022. * @param {number} gapCoefficient
  2023. * @param {number} speed
  2024. * @return {number} The gap size.
  2025. */
  2026. getGap(gapCoefficient, speed) {
  2027. const minGap = Math.round(
  2028. this.width * speed + this.typeConfig.minGap * gapCoefficient);
  2029. const maxGap = Math.round(minGap * Obstacle.MAX_GAP_COEFFICIENT);
  2030. return getRandomNum(minGap, maxGap);
  2031. },
  2032. /**
  2033. * Check if obstacle is visible.
  2034. * @return {boolean} Whether the obstacle is in the game area.
  2035. */
  2036. isVisible() {
  2037. return this.xPos + this.width > 0;
  2038. },
  2039. /**
  2040. * Make a copy of the collision boxes, since these will change based on
  2041. * obstacle type and size.
  2042. */
  2043. cloneCollisionBoxes() {
  2044. const collisionBoxes = this.typeConfig.collisionBoxes;
  2045. for (let i = collisionBoxes.length - 1; i >= 0; i--) {
  2046. this.collisionBoxes[i] = new CollisionBox(
  2047. collisionBoxes[i].x, collisionBoxes[i].y, collisionBoxes[i].width,
  2048. collisionBoxes[i].height);
  2049. }
  2050. },
  2051. };
  2052. //******************************************************************************
  2053. /**
  2054. * T-rex game character.
  2055. * @param {HTMLCanvasElement} canvas
  2056. * @param {Object} spritePos Positioning within image sprite.
  2057. * @constructor
  2058. */
  2059. function Trex(canvas, spritePos) {
  2060. this.canvas = canvas;
  2061. this.canvasCtx =
  2062. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  2063. this.spritePos = spritePos;
  2064. this.xPos = 0;
  2065. this.yPos = 0;
  2066. this.xInitialPos = 0;
  2067. // Position when on the ground.
  2068. this.groundYPos = 0;
  2069. this.currentFrame = 0;
  2070. this.currentAnimFrames = [];
  2071. this.blinkDelay = 0;
  2072. this.blinkCount = 0;
  2073. this.animStartTime = 0;
  2074. this.timer = 0;
  2075. this.msPerFrame = 1000 / FPS;
  2076. this.config = Object.assign(Trex.config, Trex.normalJumpConfig);
  2077. // Current status.
  2078. this.status = Trex.status.WAITING;
  2079. this.jumping = false;
  2080. this.ducking = false;
  2081. this.jumpVelocity = 0;
  2082. this.reachedMinHeight = false;
  2083. this.speedDrop = false;
  2084. this.jumpCount = 0;
  2085. this.jumpspotX = 0;
  2086. this.altGameModeEnabled = false;
  2087. this.flashing = false;
  2088. this.init();
  2089. }
  2090. /**
  2091. * T-rex player config.
  2092. */
  2093. Trex.config = {
  2094. DROP_VELOCITY: -5,
  2095. FLASH_OFF: 175,
  2096. FLASH_ON: 100,
  2097. HEIGHT: 47,
  2098. HEIGHT_DUCK: 25,
  2099. INTRO_DURATION: 1500,
  2100. SPEED_DROP_COEFFICIENT: 3,
  2101. SPRITE_WIDTH: 262,
  2102. START_X_POS: 50,
  2103. WIDTH: 44,
  2104. WIDTH_DUCK: 59,
  2105. };
  2106. Trex.slowJumpConfig = {
  2107. GRAVITY: 0.25,
  2108. MAX_JUMP_HEIGHT: 50,
  2109. MIN_JUMP_HEIGHT: 45,
  2110. INITIAL_JUMP_VELOCITY: -20,
  2111. };
  2112. Trex.normalJumpConfig = {
  2113. GRAVITY: 0.6,
  2114. MAX_JUMP_HEIGHT: 30,
  2115. MIN_JUMP_HEIGHT: 30,
  2116. INITIAL_JUMP_VELOCITY: -10,
  2117. };
  2118. /**
  2119. * Used in collision detection.
  2120. * @enum {Array<CollisionBox>}
  2121. */
  2122. Trex.collisionBoxes = {
  2123. DUCKING: [new CollisionBox(1, 18, 55, 25)],
  2124. RUNNING: [
  2125. new CollisionBox(22, 0, 17, 16),
  2126. new CollisionBox(1, 18, 30, 9),
  2127. new CollisionBox(10, 35, 14, 8),
  2128. new CollisionBox(1, 24, 29, 5),
  2129. new CollisionBox(5, 30, 21, 4),
  2130. new CollisionBox(9, 34, 15, 4),
  2131. ],
  2132. };
  2133. /**
  2134. * Animation states.
  2135. * @enum {string}
  2136. */
  2137. Trex.status = {
  2138. CRASHED: 'CRASHED',
  2139. DUCKING: 'DUCKING',
  2140. JUMPING: 'JUMPING',
  2141. RUNNING: 'RUNNING',
  2142. WAITING: 'WAITING',
  2143. };
  2144. /**
  2145. * Blinking coefficient.
  2146. * @const
  2147. */
  2148. Trex.BLINK_TIMING = 7000;
  2149. /**
  2150. * Animation config for different states.
  2151. * @enum {Object}
  2152. */
  2153. Trex.animFrames = {
  2154. WAITING: {
  2155. frames: [44, 0],
  2156. msPerFrame: 1000 / 3,
  2157. },
  2158. RUNNING: {
  2159. frames: [88, 132],
  2160. msPerFrame: 1000 / 12,
  2161. },
  2162. CRASHED: {
  2163. frames: [220],
  2164. msPerFrame: 1000 / 60,
  2165. },
  2166. JUMPING: {
  2167. frames: [0],
  2168. msPerFrame: 1000 / 60,
  2169. },
  2170. DUCKING: {
  2171. frames: [264, 323],
  2172. msPerFrame: 1000 / 8,
  2173. },
  2174. };
  2175. Trex.prototype = {
  2176. /**
  2177. * T-rex player initaliser.
  2178. * Sets the t-rex to blink at random intervals.
  2179. */
  2180. init() {
  2181. this.groundYPos = Runner.defaultDimensions.HEIGHT - this.config.HEIGHT -
  2182. Runner.config.BOTTOM_PAD;
  2183. this.yPos = this.groundYPos;
  2184. this.minJumpHeight = this.groundYPos - this.config.MIN_JUMP_HEIGHT;
  2185. this.draw(0, 0);
  2186. this.update(0, Trex.status.WAITING);
  2187. },
  2188. /**
  2189. * Assign the appropriate jump parameters based on the game speed.
  2190. */
  2191. enableSlowConfig: function() {
  2192. const jumpConfig =
  2193. Runner.slowDown ? Trex.slowJumpConfig : Trex.normalJumpConfig;
  2194. Trex.config = Object.assign(Trex.config, jumpConfig);
  2195. this.adjustAltGameConfigForSlowSpeed();
  2196. },
  2197. /**
  2198. * Enables the alternative game. Redefines the dino config.
  2199. * @param {Object} spritePos New positioning within image sprite.
  2200. */
  2201. enableAltGameMode: function(spritePos) {
  2202. this.altGameModeEnabled = true;
  2203. this.spritePos = spritePos;
  2204. const spriteDefinition = Runner.spriteDefinition['TREX'];
  2205. // Update animation frames.
  2206. Trex.animFrames.RUNNING.frames =
  2207. [spriteDefinition.RUNNING_1.x, spriteDefinition.RUNNING_2.x];
  2208. Trex.animFrames.CRASHED.frames = [spriteDefinition.CRASHED.x];
  2209. if (typeof spriteDefinition.JUMPING.x == 'object') {
  2210. Trex.animFrames.JUMPING.frames = spriteDefinition.JUMPING.x;
  2211. } else {
  2212. Trex.animFrames.JUMPING.frames = [spriteDefinition.JUMPING.x];
  2213. }
  2214. Trex.animFrames.DUCKING.frames =
  2215. [spriteDefinition.RUNNING_1.x, spriteDefinition.RUNNING_2.x];
  2216. // Update Trex config
  2217. Trex.config.GRAVITY = spriteDefinition.GRAVITY || Trex.config.GRAVITY;
  2218. Trex.config.HEIGHT = spriteDefinition.RUNNING_1.h,
  2219. Trex.config.INITIAL_JUMP_VELOCITY = spriteDefinition.INITIAL_JUMP_VELOCITY;
  2220. Trex.config.MAX_JUMP_HEIGHT = spriteDefinition.MAX_JUMP_HEIGHT;
  2221. Trex.config.MIN_JUMP_HEIGHT = spriteDefinition.MIN_JUMP_HEIGHT;
  2222. Trex.config.WIDTH = spriteDefinition.RUNNING_1.w;
  2223. Trex.config.WIDTH_JUMP = spriteDefinition.JUMPING.w;
  2224. Trex.config.INVERT_JUMP = spriteDefinition.INVERT_JUMP;
  2225. this.adjustAltGameConfigForSlowSpeed(spriteDefinition.GRAVITY);
  2226. this.config = Trex.config;
  2227. // Adjust bottom horizon placement.
  2228. this.groundYPos = Runner.defaultDimensions.HEIGHT - this.config.HEIGHT -
  2229. Runner.spriteDefinition['BOTTOM_PAD'];
  2230. this.yPos = this.groundYPos;
  2231. this.reset();
  2232. },
  2233. /**
  2234. * Slow speeds adjustments for the alt game modes.
  2235. * @param {number=} opt_gravityValue
  2236. */
  2237. adjustAltGameConfigForSlowSpeed: function(opt_gravityValue) {
  2238. if (Runner.slowDown) {
  2239. if (opt_gravityValue) {
  2240. Trex.config.GRAVITY = opt_gravityValue / 1.5;
  2241. }
  2242. Trex.config.MIN_JUMP_HEIGHT *= 1.5;
  2243. Trex.config.MAX_JUMP_HEIGHT *= 1.5;
  2244. Trex.config.INITIAL_JUMP_VELOCITY =
  2245. Trex.config.INITIAL_JUMP_VELOCITY * 1.5;
  2246. }
  2247. },
  2248. /**
  2249. * Setter whether dino is flashing.
  2250. * @param {boolean} status
  2251. */
  2252. setFlashing: function(status) {
  2253. this.flashing = status;
  2254. },
  2255. /**
  2256. * Setter for the jump velocity.
  2257. * The approriate drop velocity is also set.
  2258. * @param {number} setting
  2259. */
  2260. setJumpVelocity(setting) {
  2261. this.config.INITIAL_JUMP_VELOCITY = -setting;
  2262. this.config.DROP_VELOCITY = -setting / 2;
  2263. },
  2264. /**
  2265. * Set the animation status.
  2266. * @param {!number} deltaTime
  2267. * @param {Trex.status=} opt_status Optional status to switch to.
  2268. */
  2269. update(deltaTime, opt_status) {
  2270. this.timer += deltaTime;
  2271. // Update the status.
  2272. if (opt_status) {
  2273. this.status = opt_status;
  2274. this.currentFrame = 0;
  2275. this.msPerFrame = Trex.animFrames[opt_status].msPerFrame;
  2276. this.currentAnimFrames = Trex.animFrames[opt_status].frames;
  2277. if (opt_status === Trex.status.WAITING) {
  2278. this.animStartTime = getTimeStamp();
  2279. this.setBlinkDelay();
  2280. }
  2281. }
  2282. // Game intro animation, T-rex moves in from the left.
  2283. if (this.playingIntro && this.xPos < this.config.START_X_POS) {
  2284. this.xPos += Math.round((this.config.START_X_POS /
  2285. this.config.INTRO_DURATION) * deltaTime);
  2286. this.xInitialPos = this.xPos;
  2287. }
  2288. if (this.status === Trex.status.WAITING) {
  2289. this.blink(getTimeStamp());
  2290. } else {
  2291. this.draw(this.currentAnimFrames[this.currentFrame], 0);
  2292. }
  2293. // Update the frame position.
  2294. if (!this.flashing && this.timer >= this.msPerFrame) {
  2295. this.currentFrame = this.currentFrame ==
  2296. this.currentAnimFrames.length - 1 ? 0 : this.currentFrame + 1;
  2297. this.timer = 0;
  2298. }
  2299. if (!this.altGameModeEnabled) {
  2300. // Speed drop becomes duck if the down key is still being pressed.
  2301. if (this.speedDrop && this.yPos === this.groundYPos) {
  2302. this.speedDrop = false;
  2303. this.setDuck(true);
  2304. }
  2305. }
  2306. },
  2307. /**
  2308. * Draw the t-rex to a particular position.
  2309. * @param {number} x
  2310. * @param {number} y
  2311. */
  2312. draw(x, y) {
  2313. let sourceX = x;
  2314. let sourceY = y;
  2315. let sourceWidth = this.ducking && this.status !== Trex.status.CRASHED ?
  2316. this.config.WIDTH_DUCK :
  2317. this.config.WIDTH;
  2318. let sourceHeight = this.config.HEIGHT;
  2319. const outputHeight = sourceHeight;
  2320. let jumpOffset = Runner.spriteDefinition.TREX.JUMPING.xOffset;
  2321. // Width of sprite changes on jump.
  2322. if (this.altGameModeEnabled && this.jumping &&
  2323. this.status !== Trex.status.CRASHED) {
  2324. sourceWidth = this.config.WIDTH_JUMP;
  2325. }
  2326. if (IS_HIDPI) {
  2327. sourceX *= 2;
  2328. sourceY *= 2;
  2329. sourceWidth *= 2;
  2330. sourceHeight *= 2;
  2331. jumpOffset *= 2;
  2332. }
  2333. // Adjustments for sprite sheet position.
  2334. sourceX += this.spritePos.x;
  2335. sourceY += this.spritePos.y;
  2336. // Flashing.
  2337. if (this.flashing) {
  2338. if (this.timer < this.config.FLASH_ON) {
  2339. this.canvasCtx.globalAlpha = 0.5;
  2340. } else if (this.timer > this.config.FLASH_OFF) {
  2341. this.timer = 0;
  2342. }
  2343. }
  2344. // Ducking.
  2345. if (!this.altGameModeEnabled && this.ducking &&
  2346. this.status !== Trex.status.CRASHED) {
  2347. this.canvasCtx.drawImage(Runner.imageSprite, sourceX, sourceY,
  2348. sourceWidth, sourceHeight,
  2349. this.xPos, this.yPos,
  2350. this.config.WIDTH_DUCK, outputHeight);
  2351. } else if (
  2352. this.altGameModeEnabled && this.jumping &&
  2353. this.status !== Trex.status.CRASHED) {
  2354. // Jumping with adjustments.
  2355. this.canvasCtx.drawImage(
  2356. Runner.imageSprite, sourceX, sourceY, sourceWidth, sourceHeight,
  2357. this.xPos - jumpOffset, this.yPos, this.config.WIDTH_JUMP,
  2358. outputHeight);
  2359. } else {
  2360. // Crashed whilst ducking. Trex is standing up so needs adjustment.
  2361. if (this.ducking && this.status === Trex.status.CRASHED) {
  2362. this.xPos++;
  2363. }
  2364. // Standing / running
  2365. this.canvasCtx.drawImage(Runner.imageSprite, sourceX, sourceY,
  2366. sourceWidth, sourceHeight,
  2367. this.xPos, this.yPos,
  2368. this.config.WIDTH, outputHeight);
  2369. }
  2370. this.canvasCtx.globalAlpha = 1;
  2371. },
  2372. /**
  2373. * Sets a random time for the blink to happen.
  2374. */
  2375. setBlinkDelay() {
  2376. this.blinkDelay = Math.ceil(Math.random() * Trex.BLINK_TIMING);
  2377. },
  2378. /**
  2379. * Make t-rex blink at random intervals.
  2380. * @param {number} time Current time in milliseconds.
  2381. */
  2382. blink(time) {
  2383. const deltaTime = time - this.animStartTime;
  2384. if (deltaTime >= this.blinkDelay) {
  2385. this.draw(this.currentAnimFrames[this.currentFrame], 0);
  2386. if (this.currentFrame === 1) {
  2387. // Set new random delay to blink.
  2388. this.setBlinkDelay();
  2389. this.animStartTime = time;
  2390. this.blinkCount++;
  2391. }
  2392. }
  2393. },
  2394. /**
  2395. * Initialise a jump.
  2396. * @param {number} speed
  2397. */
  2398. startJump(speed) {
  2399. if (!this.jumping) {
  2400. this.update(0, Trex.status.JUMPING);
  2401. // Tweak the jump velocity based on the speed.
  2402. this.jumpVelocity = this.config.INITIAL_JUMP_VELOCITY - (speed / 10);
  2403. this.jumping = true;
  2404. this.reachedMinHeight = false;
  2405. this.speedDrop = false;
  2406. if (this.config.INVERT_JUMP) {
  2407. this.minJumpHeight = this.groundYPos + this.config.MIN_JUMP_HEIGHT;
  2408. }
  2409. }
  2410. },
  2411. /**
  2412. * Jump is complete, falling down.
  2413. */
  2414. endJump() {
  2415. if (this.reachedMinHeight &&
  2416. this.jumpVelocity < this.config.DROP_VELOCITY) {
  2417. this.jumpVelocity = this.config.DROP_VELOCITY;
  2418. }
  2419. },
  2420. /**
  2421. * Update frame for a jump.
  2422. * @param {number} deltaTime
  2423. */
  2424. updateJump(deltaTime) {
  2425. const msPerFrame = Trex.animFrames[this.status].msPerFrame;
  2426. const framesElapsed = deltaTime / msPerFrame;
  2427. // Speed drop makes Trex fall faster.
  2428. if (this.speedDrop) {
  2429. this.yPos += Math.round(this.jumpVelocity *
  2430. this.config.SPEED_DROP_COEFFICIENT * framesElapsed);
  2431. } else if (this.config.INVERT_JUMP) {
  2432. this.yPos -= Math.round(this.jumpVelocity * framesElapsed);
  2433. } else {
  2434. this.yPos += Math.round(this.jumpVelocity * framesElapsed);
  2435. }
  2436. this.jumpVelocity += this.config.GRAVITY * framesElapsed;
  2437. // Minimum height has been reached.
  2438. if (this.config.INVERT_JUMP && (this.yPos > this.minJumpHeight) ||
  2439. !this.config.INVERT_JUMP && (this.yPos < this.minJumpHeight) ||
  2440. this.speedDrop) {
  2441. this.reachedMinHeight = true;
  2442. }
  2443. // Reached max height.
  2444. if (this.config.INVERT_JUMP && (this.yPos > -this.config.MAX_JUMP_HEIGHT) ||
  2445. !this.config.INVERT_JUMP && (this.yPos < this.config.MAX_JUMP_HEIGHT) ||
  2446. this.speedDrop) {
  2447. this.endJump();
  2448. }
  2449. // Back down at ground level. Jump completed.
  2450. if ((this.config.INVERT_JUMP && this.yPos) < this.groundYPos ||
  2451. (!this.config.INVERT_JUMP && this.yPos) > this.groundYPos) {
  2452. this.reset();
  2453. this.jumpCount++;
  2454. if (Runner.audioCues) {
  2455. Runner.generatedSoundFx.loopFootSteps();
  2456. }
  2457. }
  2458. },
  2459. /**
  2460. * Set the speed drop. Immediately cancels the current jump.
  2461. */
  2462. setSpeedDrop() {
  2463. this.speedDrop = true;
  2464. this.jumpVelocity = 1;
  2465. },
  2466. /**
  2467. * @param {boolean} isDucking
  2468. */
  2469. setDuck(isDucking) {
  2470. if (isDucking && this.status !== Trex.status.DUCKING) {
  2471. this.update(0, Trex.status.DUCKING);
  2472. this.ducking = true;
  2473. } else if (this.status === Trex.status.DUCKING) {
  2474. this.update(0, Trex.status.RUNNING);
  2475. this.ducking = false;
  2476. }
  2477. },
  2478. /**
  2479. * Reset the t-rex to running at start of game.
  2480. */
  2481. reset() {
  2482. this.xPos = this.xInitialPos;
  2483. this.yPos = this.groundYPos;
  2484. this.jumpVelocity = 0;
  2485. this.jumping = false;
  2486. this.ducking = false;
  2487. this.update(0, Trex.status.RUNNING);
  2488. this.midair = false;
  2489. this.speedDrop = false;
  2490. this.jumpCount = 0;
  2491. },
  2492. };
  2493. //******************************************************************************
  2494. /**
  2495. * Handles displaying the distance meter.
  2496. * @param {!HTMLCanvasElement} canvas
  2497. * @param {Object} spritePos Image position in sprite.
  2498. * @param {number} canvasWidth
  2499. * @constructor
  2500. */
  2501. function DistanceMeter(canvas, spritePos, canvasWidth) {
  2502. this.canvas = canvas;
  2503. this.canvasCtx =
  2504. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  2505. this.image = Runner.imageSprite;
  2506. this.spritePos = spritePos;
  2507. this.x = 0;
  2508. this.y = 5;
  2509. this.currentDistance = 0;
  2510. this.maxScore = 0;
  2511. this.highScore = '0';
  2512. this.container = null;
  2513. this.digits = [];
  2514. this.achievement = false;
  2515. this.defaultString = '';
  2516. this.flashTimer = 0;
  2517. this.flashIterations = 0;
  2518. this.invertTrigger = false;
  2519. this.flashingRafId = null;
  2520. this.highScoreBounds = {};
  2521. this.highScoreFlashing = false;
  2522. this.config = DistanceMeter.config;
  2523. this.maxScoreUnits = this.config.MAX_DISTANCE_UNITS;
  2524. this.canvasWidth = canvasWidth;
  2525. this.init(canvasWidth);
  2526. }
  2527. /**
  2528. * @enum {number}
  2529. */
  2530. DistanceMeter.dimensions = {
  2531. WIDTH: 10,
  2532. HEIGHT: 13,
  2533. DEST_WIDTH: 11,
  2534. };
  2535. /**
  2536. * Y positioning of the digits in the sprite sheet.
  2537. * X position is always 0.
  2538. * @type {Array<number>}
  2539. */
  2540. DistanceMeter.yPos = [0, 13, 27, 40, 53, 67, 80, 93, 107, 120];
  2541. /**
  2542. * Distance meter config.
  2543. * @enum {number}
  2544. */
  2545. DistanceMeter.config = {
  2546. // Number of digits.
  2547. MAX_DISTANCE_UNITS: 5,
  2548. // Distance that causes achievement animation.
  2549. ACHIEVEMENT_DISTANCE: 100,
  2550. // Used for conversion from pixel distance to a scaled unit.
  2551. COEFFICIENT: 0.025,
  2552. // Flash duration in milliseconds.
  2553. FLASH_DURATION: 1000 / 4,
  2554. // Flash iterations for achievement animation.
  2555. FLASH_ITERATIONS: 3,
  2556. // Padding around the high score hit area.
  2557. HIGH_SCORE_HIT_AREA_PADDING: 4,
  2558. };
  2559. DistanceMeter.prototype = {
  2560. /**
  2561. * Initialise the distance meter to '00000'.
  2562. * @param {number} width Canvas width in px.
  2563. */
  2564. init(width) {
  2565. let maxDistanceStr = '';
  2566. this.calcXPos(width);
  2567. this.maxScore = this.maxScoreUnits;
  2568. for (let i = 0; i < this.maxScoreUnits; i++) {
  2569. this.draw(i, 0);
  2570. this.defaultString += '0';
  2571. maxDistanceStr += '9';
  2572. }
  2573. this.maxScore = parseInt(maxDistanceStr, 10);
  2574. },
  2575. /**
  2576. * Calculate the xPos in the canvas.
  2577. * @param {number} canvasWidth
  2578. */
  2579. calcXPos(canvasWidth) {
  2580. this.x = canvasWidth - (DistanceMeter.dimensions.DEST_WIDTH *
  2581. (this.maxScoreUnits + 1));
  2582. },
  2583. /**
  2584. * Draw a digit to canvas.
  2585. * @param {number} digitPos Position of the digit.
  2586. * @param {number} value Digit value 0-9.
  2587. * @param {boolean=} opt_highScore Whether drawing the high score.
  2588. */
  2589. draw(digitPos, value, opt_highScore) {
  2590. let sourceWidth = DistanceMeter.dimensions.WIDTH;
  2591. let sourceHeight = DistanceMeter.dimensions.HEIGHT;
  2592. let sourceX = DistanceMeter.dimensions.WIDTH * value;
  2593. let sourceY = 0;
  2594. const targetX = digitPos * DistanceMeter.dimensions.DEST_WIDTH;
  2595. const targetY = this.y;
  2596. const targetWidth = DistanceMeter.dimensions.WIDTH;
  2597. const targetHeight = DistanceMeter.dimensions.HEIGHT;
  2598. // For high DPI we 2x source values.
  2599. if (IS_HIDPI) {
  2600. sourceWidth *= 2;
  2601. sourceHeight *= 2;
  2602. sourceX *= 2;
  2603. }
  2604. sourceX += this.spritePos.x;
  2605. sourceY += this.spritePos.y;
  2606. this.canvasCtx.save();
  2607. if (IS_RTL) {
  2608. if (opt_highScore) {
  2609. this.canvasCtx.translate(
  2610. this.canvasWidth -
  2611. (DistanceMeter.dimensions.WIDTH * (this.maxScoreUnits + 3)),
  2612. this.y);
  2613. } else {
  2614. this.canvasCtx.translate(
  2615. this.canvasWidth - DistanceMeter.dimensions.WIDTH, this.y);
  2616. }
  2617. this.canvasCtx.scale(-1, 1);
  2618. } else {
  2619. const highScoreX =
  2620. this.x - (this.maxScoreUnits * 2) * DistanceMeter.dimensions.WIDTH;
  2621. if (opt_highScore) {
  2622. this.canvasCtx.translate(highScoreX, this.y);
  2623. } else {
  2624. this.canvasCtx.translate(this.x, this.y);
  2625. }
  2626. }
  2627. this.canvasCtx.drawImage(
  2628. this.image,
  2629. sourceX,
  2630. sourceY,
  2631. sourceWidth,
  2632. sourceHeight,
  2633. targetX,
  2634. targetY,
  2635. targetWidth,
  2636. targetHeight,
  2637. );
  2638. this.canvasCtx.restore();
  2639. },
  2640. /**
  2641. * Covert pixel distance to a 'real' distance.
  2642. * @param {number} distance Pixel distance ran.
  2643. * @return {number} The 'real' distance ran.
  2644. */
  2645. getActualDistance(distance) {
  2646. return distance ? Math.round(distance * this.config.COEFFICIENT) : 0;
  2647. },
  2648. /**
  2649. * Update the distance meter.
  2650. * @param {number} distance
  2651. * @param {number} deltaTime
  2652. * @return {boolean} Whether the acheivement sound fx should be played.
  2653. */
  2654. update(deltaTime, distance) {
  2655. let paint = true;
  2656. let playSound = false;
  2657. if (!this.achievement) {
  2658. distance = this.getActualDistance(distance);
  2659. // Score has gone beyond the initial digit count.
  2660. if (distance > this.maxScore && this.maxScoreUnits ==
  2661. this.config.MAX_DISTANCE_UNITS) {
  2662. this.maxScoreUnits++;
  2663. this.maxScore = parseInt(this.maxScore + '9', 10);
  2664. } else {
  2665. this.distance = 0;
  2666. }
  2667. if (distance > 0) {
  2668. // Achievement unlocked.
  2669. if (distance % this.config.ACHIEVEMENT_DISTANCE === 0) {
  2670. // Flash score and play sound.
  2671. this.achievement = true;
  2672. this.flashTimer = 0;
  2673. playSound = true;
  2674. }
  2675. // Create a string representation of the distance with leading 0.
  2676. const distanceStr = (this.defaultString +
  2677. distance).substr(-this.maxScoreUnits);
  2678. this.digits = distanceStr.split('');
  2679. } else {
  2680. this.digits = this.defaultString.split('');
  2681. }
  2682. } else {
  2683. // Control flashing of the score on reaching acheivement.
  2684. if (this.flashIterations <= this.config.FLASH_ITERATIONS) {
  2685. this.flashTimer += deltaTime;
  2686. if (this.flashTimer < this.config.FLASH_DURATION) {
  2687. paint = false;
  2688. } else if (this.flashTimer > this.config.FLASH_DURATION * 2) {
  2689. this.flashTimer = 0;
  2690. this.flashIterations++;
  2691. }
  2692. } else {
  2693. this.achievement = false;
  2694. this.flashIterations = 0;
  2695. this.flashTimer = 0;
  2696. }
  2697. }
  2698. // Draw the digits if not flashing.
  2699. if (paint) {
  2700. for (let i = this.digits.length - 1; i >= 0; i--) {
  2701. this.draw(i, parseInt(this.digits[i], 10));
  2702. }
  2703. }
  2704. this.drawHighScore();
  2705. return playSound;
  2706. },
  2707. /**
  2708. * Draw the high score.
  2709. */
  2710. drawHighScore() {
  2711. if (parseInt(this.highScore, 10) > 0) {
  2712. this.canvasCtx.save();
  2713. this.canvasCtx.globalAlpha = .8;
  2714. for (let i = this.highScore.length - 1; i >= 0; i--) {
  2715. this.draw(i, parseInt(this.highScore[i], 10), true);
  2716. }
  2717. this.canvasCtx.restore();
  2718. }
  2719. },
  2720. /**
  2721. * Set the highscore as a array string.
  2722. * Position of char in the sprite: H - 10, I - 11.
  2723. * @param {number} distance Distance ran in pixels.
  2724. */
  2725. setHighScore(distance) {
  2726. distance = this.getActualDistance(distance);
  2727. const highScoreStr = (this.defaultString +
  2728. distance).substr(-this.maxScoreUnits);
  2729. this.highScore = ['10', '11', ''].concat(highScoreStr.split(''));
  2730. },
  2731. /**
  2732. * Whether a clicked is in the high score area.
  2733. * @param {Event} e Event object.
  2734. * @return {boolean} Whether the click was in the high score bounds.
  2735. */
  2736. hasClickedOnHighScore(e) {
  2737. let x = 0;
  2738. let y = 0;
  2739. if (e.touches) {
  2740. // Bounds for touch differ from pointer.
  2741. const canvasBounds = this.canvas.getBoundingClientRect();
  2742. x = e.touches[0].clientX - canvasBounds.left;
  2743. y = e.touches[0].clientY - canvasBounds.top;
  2744. } else {
  2745. x = e.offsetX;
  2746. y = e.offsetY;
  2747. }
  2748. this.highScoreBounds = this.getHighScoreBounds();
  2749. return x >= this.highScoreBounds.x && x <=
  2750. this.highScoreBounds.x + this.highScoreBounds.width &&
  2751. y >= this.highScoreBounds.y && y <=
  2752. this.highScoreBounds.y + this.highScoreBounds.height;
  2753. },
  2754. /**
  2755. * Get the bounding box for the high score.
  2756. * @return {Object} Object with x, y, width and height properties.
  2757. */
  2758. getHighScoreBounds() {
  2759. return {
  2760. x: (this.x - (this.maxScoreUnits * 2) * DistanceMeter.dimensions.WIDTH) -
  2761. DistanceMeter.config.HIGH_SCORE_HIT_AREA_PADDING,
  2762. y: this.y,
  2763. width: DistanceMeter.dimensions.WIDTH * (this.highScore.length + 1) +
  2764. DistanceMeter.config.HIGH_SCORE_HIT_AREA_PADDING,
  2765. height: DistanceMeter.dimensions.HEIGHT +
  2766. (DistanceMeter.config.HIGH_SCORE_HIT_AREA_PADDING * 2),
  2767. };
  2768. },
  2769. /**
  2770. * Animate flashing the high score to indicate ready for resetting.
  2771. * The flashing stops following this.config.FLASH_ITERATIONS x 2 flashes.
  2772. */
  2773. flashHighScore() {
  2774. const now = getTimeStamp();
  2775. const deltaTime = now - (this.frameTimeStamp || now);
  2776. let paint = true;
  2777. this.frameTimeStamp = now;
  2778. // Reached the max number of flashes.
  2779. if (this.flashIterations > this.config.FLASH_ITERATIONS * 2) {
  2780. this.cancelHighScoreFlashing();
  2781. return;
  2782. }
  2783. this.flashTimer += deltaTime;
  2784. if (this.flashTimer < this.config.FLASH_DURATION) {
  2785. paint = false;
  2786. } else if (this.flashTimer > this.config.FLASH_DURATION * 2) {
  2787. this.flashTimer = 0;
  2788. this.flashIterations++;
  2789. }
  2790. if (paint) {
  2791. this.drawHighScore();
  2792. } else {
  2793. this.clearHighScoreBounds();
  2794. }
  2795. // Frame update.
  2796. this.flashingRafId =
  2797. requestAnimationFrame(this.flashHighScore.bind(this));
  2798. },
  2799. /**
  2800. * Draw empty rectangle over high score.
  2801. */
  2802. clearHighScoreBounds() {
  2803. this.canvasCtx.save();
  2804. this.canvasCtx.fillStyle = '#fff';
  2805. this.canvasCtx.rect(this.highScoreBounds.x, this.highScoreBounds.y,
  2806. this.highScoreBounds.width, this.highScoreBounds.height);
  2807. this.canvasCtx.fill();
  2808. this.canvasCtx.restore();
  2809. },
  2810. /**
  2811. * Starts the flashing of the high score.
  2812. */
  2813. startHighScoreFlashing() {
  2814. this.highScoreFlashing = true;
  2815. this.flashHighScore();
  2816. },
  2817. /**
  2818. * Whether high score is flashing.
  2819. * @return {boolean}
  2820. */
  2821. isHighScoreFlashing() {
  2822. return this.highScoreFlashing;
  2823. },
  2824. /**
  2825. * Stop flashing the high score.
  2826. */
  2827. cancelHighScoreFlashing() {
  2828. if (this.flashingRafId) {
  2829. cancelAnimationFrame(this.flashingRafId);
  2830. }
  2831. this.flashIterations = 0;
  2832. this.flashTimer = 0;
  2833. this.highScoreFlashing = false;
  2834. this.clearHighScoreBounds();
  2835. this.drawHighScore();
  2836. },
  2837. /**
  2838. * Clear the high score.
  2839. */
  2840. resetHighScore() {
  2841. this.setHighScore(0);
  2842. this.cancelHighScoreFlashing();
  2843. },
  2844. /**
  2845. * Reset the distance meter back to '00000'.
  2846. */
  2847. reset() {
  2848. this.update(0, 0);
  2849. this.achievement = false;
  2850. },
  2851. };
  2852. //******************************************************************************
  2853. /**
  2854. * Cloud background item.
  2855. * Similar to an obstacle object but without collision boxes.
  2856. * @param {HTMLCanvasElement} canvas Canvas element.
  2857. * @param {Object} spritePos Position of image in sprite.
  2858. * @param {number} containerWidth
  2859. * @constructor
  2860. */
  2861. function Cloud(canvas, spritePos, containerWidth) {
  2862. this.canvas = canvas;
  2863. this.canvasCtx =
  2864. /** @type {CanvasRenderingContext2D} */ (this.canvas.getContext('2d'));
  2865. this.spritePos = spritePos;
  2866. this.containerWidth = containerWidth;
  2867. this.xPos = containerWidth;
  2868. this.yPos = 0;
  2869. this.remove = false;
  2870. this.gap =
  2871. getRandomNum(Cloud.config.MIN_CLOUD_GAP, Cloud.config.MAX_CLOUD_GAP);
  2872. this.init();
  2873. }
  2874. /**
  2875. * Cloud object config.
  2876. * @enum {number}
  2877. */
  2878. Cloud.config = {
  2879. HEIGHT: 14,
  2880. MAX_CLOUD_GAP: 400,
  2881. MAX_SKY_LEVEL: 30,
  2882. MIN_CLOUD_GAP: 100,
  2883. MIN_SKY_LEVEL: 71,
  2884. WIDTH: 46,
  2885. };
  2886. Cloud.prototype = {
  2887. /**
  2888. * Initialise the cloud. Sets the Cloud height.
  2889. */
  2890. init() {
  2891. this.yPos = getRandomNum(Cloud.config.MAX_SKY_LEVEL,
  2892. Cloud.config.MIN_SKY_LEVEL);
  2893. this.draw();
  2894. },
  2895. /**
  2896. * Draw the cloud.
  2897. */
  2898. draw() {
  2899. this.canvasCtx.save();
  2900. let sourceWidth = Cloud.config.WIDTH;
  2901. let sourceHeight = Cloud.config.HEIGHT;
  2902. const outputWidth = sourceWidth;
  2903. const outputHeight = sourceHeight;
  2904. if (IS_HIDPI) {
  2905. sourceWidth = sourceWidth * 2;
  2906. sourceHeight = sourceHeight * 2;
  2907. }
  2908. this.canvasCtx.drawImage(Runner.imageSprite, this.spritePos.x,
  2909. this.spritePos.y,
  2910. sourceWidth, sourceHeight,
  2911. this.xPos, this.yPos,
  2912. outputWidth, outputHeight);
  2913. this.canvasCtx.restore();
  2914. },
  2915. /**
  2916. * Update the cloud position.
  2917. * @param {number} speed
  2918. */
  2919. update(speed) {
  2920. if (!this.remove) {
  2921. this.xPos -= Math.ceil(speed);
  2922. this.draw();
  2923. // Mark as removeable if no longer in the canvas.
  2924. if (!this.isVisible()) {
  2925. this.remove = true;
  2926. }
  2927. }
  2928. },
  2929. /**
  2930. * Check if the cloud is visible on the stage.
  2931. * @return {boolean}
  2932. */
  2933. isVisible() {
  2934. return this.xPos + Cloud.config.WIDTH > 0;
  2935. },
  2936. };
  2937. /**
  2938. * Background item.
  2939. * Similar to cloud, without random y position.
  2940. * @param {HTMLCanvasElement} canvas Canvas element.
  2941. * @param {Object} spritePos Position of image in sprite.
  2942. * @param {number} containerWidth
  2943. * @param {string} type Element type.
  2944. * @constructor
  2945. */
  2946. function BackgroundEl(canvas, spritePos, containerWidth, type) {
  2947. this.canvas = canvas;
  2948. this.canvasCtx =
  2949. /** @type {CanvasRenderingContext2D} */ (this.canvas.getContext('2d'));
  2950. this.spritePos = spritePos;
  2951. this.containerWidth = containerWidth;
  2952. this.xPos = containerWidth;
  2953. this.yPos = 0;
  2954. this.remove = false;
  2955. this.type = type;
  2956. this.gap =
  2957. getRandomNum(BackgroundEl.config.MIN_GAP, BackgroundEl.config.MAX_GAP);
  2958. this.animTimer = 0;
  2959. this.switchFrames = false;
  2960. this.spriteConfig = {};
  2961. this.init();
  2962. }
  2963. /**
  2964. * Background element object config.
  2965. * Real values assigned when game type changes.
  2966. * @enum {number}
  2967. */
  2968. BackgroundEl.config = {
  2969. MAX_BG_ELS: 0,
  2970. MAX_GAP: 0,
  2971. MIN_GAP: 0,
  2972. POS: 0,
  2973. SPEED: 0,
  2974. Y_POS: 0,
  2975. MS_PER_FRAME: 0, // only needed when BACKGROUND_EL.FIXED is true
  2976. };
  2977. BackgroundEl.prototype = {
  2978. /**
  2979. * Initialise the element setting the y position.
  2980. */
  2981. init() {
  2982. this.spriteConfig = Runner.spriteDefinition.BACKGROUND_EL[this.type];
  2983. if (this.spriteConfig.FIXED) {
  2984. this.xPos = this.spriteConfig.FIXED_X_POS;
  2985. }
  2986. this.yPos = BackgroundEl.config.Y_POS - this.spriteConfig.HEIGHT +
  2987. this.spriteConfig.OFFSET;
  2988. this.draw();
  2989. },
  2990. /**
  2991. * Draw the element.
  2992. */
  2993. draw() {
  2994. this.canvasCtx.save();
  2995. let sourceWidth = this.spriteConfig.WIDTH;
  2996. let sourceHeight = this.spriteConfig.HEIGHT;
  2997. let sourceX = this.spriteConfig.X_POS;
  2998. const outputWidth = sourceWidth;
  2999. const outputHeight = sourceHeight;
  3000. if (IS_HIDPI) {
  3001. sourceWidth *= 2;
  3002. sourceHeight *= 2;
  3003. sourceX *= 2;
  3004. }
  3005. this.canvasCtx.drawImage(
  3006. Runner.imageSprite, sourceX, this.spritePos.y, sourceWidth,
  3007. sourceHeight, this.xPos, this.yPos, outputWidth, outputHeight);
  3008. this.canvasCtx.restore();
  3009. },
  3010. /**
  3011. * Update the background element position.
  3012. * @param {number} speed
  3013. */
  3014. update(speed) {
  3015. if (!this.remove) {
  3016. if (this.spriteConfig.FIXED) {
  3017. this.animTimer += speed;
  3018. if (this.animTimer > BackgroundEl.config.MS_PER_FRAME) {
  3019. this.animTimer = 0;
  3020. this.switchFrames = !this.switchFrames;
  3021. }
  3022. if (this.spriteConfig.FIXED_Y_POS_1 &&
  3023. this.spriteConfig.FIXED_Y_POS_2) {
  3024. this.yPos = this.switchFrames ? this.spriteConfig.FIXED_Y_POS_1 :
  3025. this.spriteConfig.FIXED_Y_POS_2;
  3026. }
  3027. } else {
  3028. // Fixed speed, regardless of actual game speed.
  3029. this.xPos -= BackgroundEl.config.SPEED;
  3030. }
  3031. this.draw();
  3032. // Mark as removable if no longer in the canvas.
  3033. if (!this.isVisible()) {
  3034. this.remove = true;
  3035. }
  3036. }
  3037. },
  3038. /**
  3039. * Check if the element is visible on the stage.
  3040. * @return {boolean}
  3041. */
  3042. isVisible() {
  3043. return this.xPos + this.spriteConfig.WIDTH > 0;
  3044. },
  3045. };
  3046. //******************************************************************************
  3047. /**
  3048. * Nightmode shows a moon and stars on the horizon.
  3049. * @param {HTMLCanvasElement} canvas
  3050. * @param {number} spritePos
  3051. * @param {number} containerWidth
  3052. * @constructor
  3053. */
  3054. function NightMode(canvas, spritePos, containerWidth) {
  3055. this.spritePos = spritePos;
  3056. this.canvas = canvas;
  3057. this.canvasCtx =
  3058. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  3059. this.xPos = containerWidth - 50;
  3060. this.yPos = 30;
  3061. this.currentPhase = 0;
  3062. this.opacity = 0;
  3063. this.containerWidth = containerWidth;
  3064. this.stars = [];
  3065. this.drawStars = false;
  3066. this.placeStars();
  3067. }
  3068. /**
  3069. * @enum {number}
  3070. */
  3071. NightMode.config = {
  3072. FADE_SPEED: 0.035,
  3073. HEIGHT: 40,
  3074. MOON_SPEED: 0.25,
  3075. NUM_STARS: 2,
  3076. STAR_SIZE: 9,
  3077. STAR_SPEED: 0.3,
  3078. STAR_MAX_Y: 70,
  3079. WIDTH: 20,
  3080. };
  3081. NightMode.phases = [140, 120, 100, 60, 40, 20, 0];
  3082. NightMode.prototype = {
  3083. /**
  3084. * Update moving moon, changing phases.
  3085. * @param {boolean} activated Whether night mode is activated.
  3086. */
  3087. update(activated) {
  3088. // Moon phase.
  3089. if (activated && this.opacity === 0) {
  3090. this.currentPhase++;
  3091. if (this.currentPhase >= NightMode.phases.length) {
  3092. this.currentPhase = 0;
  3093. }
  3094. }
  3095. // Fade in / out.
  3096. if (activated && (this.opacity < 1 || this.opacity === 0)) {
  3097. this.opacity += NightMode.config.FADE_SPEED;
  3098. } else if (this.opacity > 0) {
  3099. this.opacity -= NightMode.config.FADE_SPEED;
  3100. }
  3101. // Set moon positioning.
  3102. if (this.opacity > 0) {
  3103. this.xPos = this.updateXPos(this.xPos, NightMode.config.MOON_SPEED);
  3104. // Update stars.
  3105. if (this.drawStars) {
  3106. for (let i = 0; i < NightMode.config.NUM_STARS; i++) {
  3107. this.stars[i].x =
  3108. this.updateXPos(this.stars[i].x, NightMode.config.STAR_SPEED);
  3109. }
  3110. }
  3111. this.draw();
  3112. } else {
  3113. this.opacity = 0;
  3114. this.placeStars();
  3115. }
  3116. this.drawStars = true;
  3117. },
  3118. updateXPos(currentPos, speed) {
  3119. if (currentPos < -NightMode.config.WIDTH) {
  3120. currentPos = this.containerWidth;
  3121. } else {
  3122. currentPos -= speed;
  3123. }
  3124. return currentPos;
  3125. },
  3126. draw() {
  3127. let moonSourceWidth = this.currentPhase === 3 ? NightMode.config.WIDTH * 2 :
  3128. NightMode.config.WIDTH;
  3129. let moonSourceHeight = NightMode.config.HEIGHT;
  3130. let moonSourceX = this.spritePos.x + NightMode.phases[this.currentPhase];
  3131. const moonOutputWidth = moonSourceWidth;
  3132. let starSize = NightMode.config.STAR_SIZE;
  3133. let starSourceX = Runner.spriteDefinitionByType.original.LDPI.STAR.x;
  3134. if (IS_HIDPI) {
  3135. moonSourceWidth *= 2;
  3136. moonSourceHeight *= 2;
  3137. moonSourceX = this.spritePos.x +
  3138. (NightMode.phases[this.currentPhase] * 2);
  3139. starSize *= 2;
  3140. starSourceX = Runner.spriteDefinitionByType.original.HDPI.STAR.x;
  3141. }
  3142. this.canvasCtx.save();
  3143. this.canvasCtx.globalAlpha = this.opacity;
  3144. // Stars.
  3145. if (this.drawStars) {
  3146. for (let i = 0; i < NightMode.config.NUM_STARS; i++) {
  3147. this.canvasCtx.drawImage(
  3148. Runner.origImageSprite, starSourceX, this.stars[i].sourceY,
  3149. starSize, starSize, Math.round(this.stars[i].x), this.stars[i].y,
  3150. NightMode.config.STAR_SIZE, NightMode.config.STAR_SIZE);
  3151. }
  3152. }
  3153. // Moon.
  3154. this.canvasCtx.drawImage(
  3155. Runner.origImageSprite, moonSourceX, this.spritePos.y, moonSourceWidth,
  3156. moonSourceHeight, Math.round(this.xPos), this.yPos, moonOutputWidth,
  3157. NightMode.config.HEIGHT);
  3158. this.canvasCtx.globalAlpha = 1;
  3159. this.canvasCtx.restore();
  3160. },
  3161. // Do star placement.
  3162. placeStars() {
  3163. const segmentSize = Math.round(this.containerWidth /
  3164. NightMode.config.NUM_STARS);
  3165. for (let i = 0; i < NightMode.config.NUM_STARS; i++) {
  3166. this.stars[i] = {};
  3167. this.stars[i].x = getRandomNum(segmentSize * i, segmentSize * (i + 1));
  3168. this.stars[i].y = getRandomNum(0, NightMode.config.STAR_MAX_Y);
  3169. if (IS_HIDPI) {
  3170. this.stars[i].sourceY =
  3171. Runner.spriteDefinitionByType.original.HDPI.STAR.y +
  3172. NightMode.config.STAR_SIZE * 2 * i;
  3173. } else {
  3174. this.stars[i].sourceY =
  3175. Runner.spriteDefinitionByType.original.LDPI.STAR.y +
  3176. NightMode.config.STAR_SIZE * i;
  3177. }
  3178. }
  3179. },
  3180. reset() {
  3181. this.currentPhase = 0;
  3182. this.opacity = 0;
  3183. this.update(false);
  3184. },
  3185. };
  3186. //******************************************************************************
  3187. /**
  3188. * Horizon Line.
  3189. * Consists of two connecting lines. Randomly assigns a flat / bumpy horizon.
  3190. * @param {HTMLCanvasElement} canvas
  3191. * @param {Object} lineConfig Configuration object.
  3192. * @constructor
  3193. */
  3194. function HorizonLine(canvas, lineConfig) {
  3195. let sourceX = lineConfig.SOURCE_X;
  3196. let sourceY = lineConfig.SOURCE_Y;
  3197. if (IS_HIDPI) {
  3198. sourceX *= 2;
  3199. sourceY *= 2;
  3200. }
  3201. this.spritePos = {x: sourceX, y: sourceY};
  3202. this.canvas = canvas;
  3203. this.canvasCtx =
  3204. /** @type {CanvasRenderingContext2D} */ (canvas.getContext('2d'));
  3205. this.sourceDimensions = {};
  3206. this.dimensions = lineConfig;
  3207. this.sourceXPos = [this.spritePos.x, this.spritePos.x +
  3208. this.dimensions.WIDTH];
  3209. this.xPos = [];
  3210. this.yPos = 0;
  3211. this.bumpThreshold = 0.5;
  3212. this.setSourceDimensions(lineConfig);
  3213. this.draw();
  3214. }
  3215. /**
  3216. * Horizon line dimensions.
  3217. * @enum {number}
  3218. */
  3219. HorizonLine.dimensions = {
  3220. WIDTH: 600,
  3221. HEIGHT: 12,
  3222. YPOS: 127,
  3223. };
  3224. HorizonLine.prototype = {
  3225. /**
  3226. * Set the source dimensions of the horizon line.
  3227. */
  3228. setSourceDimensions(newDimensions) {
  3229. for (const dimension in newDimensions) {
  3230. if (dimension !== 'SOURCE_X' && dimension !== 'SOURCE_Y') {
  3231. if (IS_HIDPI) {
  3232. if (dimension !== 'YPOS') {
  3233. this.sourceDimensions[dimension] = newDimensions[dimension] * 2;
  3234. }
  3235. } else {
  3236. this.sourceDimensions[dimension] = newDimensions[dimension];
  3237. }
  3238. this.dimensions[dimension] = newDimensions[dimension];
  3239. }
  3240. }
  3241. this.xPos = [0, newDimensions.WIDTH];
  3242. this.yPos = newDimensions.YPOS;
  3243. },
  3244. /**
  3245. * Return the crop x position of a type.
  3246. */
  3247. getRandomType() {
  3248. return Math.random() > this.bumpThreshold ? this.dimensions.WIDTH : 0;
  3249. },
  3250. /**
  3251. * Draw the horizon line.
  3252. */
  3253. draw() {
  3254. this.canvasCtx.drawImage(Runner.imageSprite, this.sourceXPos[0],
  3255. this.spritePos.y,
  3256. this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT,
  3257. this.xPos[0], this.yPos,
  3258. this.dimensions.WIDTH, this.dimensions.HEIGHT);
  3259. this.canvasCtx.drawImage(Runner.imageSprite, this.sourceXPos[1],
  3260. this.spritePos.y,
  3261. this.sourceDimensions.WIDTH, this.sourceDimensions.HEIGHT,
  3262. this.xPos[1], this.yPos,
  3263. this.dimensions.WIDTH, this.dimensions.HEIGHT);
  3264. },
  3265. /**
  3266. * Update the x position of an indivdual piece of the line.
  3267. * @param {number} pos Line position.
  3268. * @param {number} increment
  3269. */
  3270. updateXPos(pos, increment) {
  3271. const line1 = pos;
  3272. const line2 = pos === 0 ? 1 : 0;
  3273. this.xPos[line1] -= increment;
  3274. this.xPos[line2] = this.xPos[line1] + this.dimensions.WIDTH;
  3275. if (this.xPos[line1] <= -this.dimensions.WIDTH) {
  3276. this.xPos[line1] += this.dimensions.WIDTH * 2;
  3277. this.xPos[line2] = this.xPos[line1] - this.dimensions.WIDTH;
  3278. this.sourceXPos[line1] = this.getRandomType() + this.spritePos.x;
  3279. }
  3280. },
  3281. /**
  3282. * Update the horizon line.
  3283. * @param {number} deltaTime
  3284. * @param {number} speed
  3285. */
  3286. update(deltaTime, speed) {
  3287. const increment = Math.floor(speed * (FPS / 1000) * deltaTime);
  3288. if (this.xPos[0] <= 0) {
  3289. this.updateXPos(0, increment);
  3290. } else {
  3291. this.updateXPos(1, increment);
  3292. }
  3293. this.draw();
  3294. },
  3295. /**
  3296. * Reset horizon to the starting position.
  3297. */
  3298. reset() {
  3299. this.xPos[0] = 0;
  3300. this.xPos[1] = this.dimensions.WIDTH;
  3301. },
  3302. };
  3303. //******************************************************************************
  3304. /**
  3305. * Horizon background class.
  3306. * @param {HTMLCanvasElement} canvas
  3307. * @param {Object} spritePos Sprite positioning.
  3308. * @param {Object} dimensions Canvas dimensions.
  3309. * @param {number} gapCoefficient
  3310. * @constructor
  3311. */
  3312. function Horizon(canvas, spritePos, dimensions, gapCoefficient) {
  3313. this.canvas = canvas;
  3314. this.canvasCtx =
  3315. /** @type {CanvasRenderingContext2D} */ (this.canvas.getContext('2d'));
  3316. this.config = Horizon.config;
  3317. this.dimensions = dimensions;
  3318. this.gapCoefficient = gapCoefficient;
  3319. this.obstacles = [];
  3320. this.obstacleHistory = [];
  3321. this.horizonOffsets = [0, 0];
  3322. this.cloudFrequency = this.config.CLOUD_FREQUENCY;
  3323. this.spritePos = spritePos;
  3324. this.nightMode = null;
  3325. this.altGameModeActive = false;
  3326. // Cloud
  3327. this.clouds = [];
  3328. this.cloudSpeed = this.config.BG_CLOUD_SPEED;
  3329. // Background elements
  3330. this.backgroundEls = [];
  3331. this.lastEl = null;
  3332. this.backgroundSpeed = this.config.BG_CLOUD_SPEED;
  3333. // Horizon
  3334. this.horizonLine = null;
  3335. this.horizonLines = [];
  3336. this.init();
  3337. }
  3338. /**
  3339. * Horizon config.
  3340. * @enum {number}
  3341. */
  3342. Horizon.config = {
  3343. BG_CLOUD_SPEED: 0.2,
  3344. BUMPY_THRESHOLD: .3,
  3345. CLOUD_FREQUENCY: .5,
  3346. HORIZON_HEIGHT: 16,
  3347. MAX_CLOUDS: 6,
  3348. };
  3349. Horizon.prototype = {
  3350. /**
  3351. * Initialise the horizon. Just add the line and a cloud. No obstacles.
  3352. */
  3353. init() {
  3354. Obstacle.types = Runner.spriteDefinitionByType.original.OBSTACLES;
  3355. this.addCloud();
  3356. // Multiple Horizon lines
  3357. for (let i = 0; i < Runner.spriteDefinition.LINES.length; i++) {
  3358. this.horizonLines.push(
  3359. new HorizonLine(this.canvas, Runner.spriteDefinition.LINES[i]));
  3360. }
  3361. this.nightMode = new NightMode(this.canvas, this.spritePos.MOON,
  3362. this.dimensions.WIDTH);
  3363. },
  3364. /**
  3365. * Update obstacle definitions based on the speed of the game.
  3366. */
  3367. adjustObstacleSpeed: function() {
  3368. for (let i = 0; i < Obstacle.types.length; i++) {
  3369. if (Runner.slowDown) {
  3370. Obstacle.types[i].multipleSpeed = Obstacle.types[i].multipleSpeed / 2;
  3371. Obstacle.types[i].minGap *= 1.5;
  3372. Obstacle.types[i].minSpeed = Obstacle.types[i].minSpeed / 2;
  3373. // Convert variable y position obstacles to fixed.
  3374. if (typeof (Obstacle.types[i].yPos) == 'object') {
  3375. Obstacle.types[i].yPos = Obstacle.types[i].yPos[0];
  3376. Obstacle.types[i].yPosMobile = Obstacle.types[i].yPos[0];
  3377. }
  3378. }
  3379. }
  3380. },
  3381. /**
  3382. * Update sprites to correspond to change in sprite sheet.
  3383. * @param {number} spritePos
  3384. */
  3385. enableAltGameMode: function(spritePos) {
  3386. // Clear existing horizon objects.
  3387. this.clouds = [];
  3388. this.backgroundEls = [];
  3389. this.altGameModeActive = true;
  3390. this.spritePos = spritePos;
  3391. Obstacle.types = Runner.spriteDefinition.OBSTACLES;
  3392. this.adjustObstacleSpeed();
  3393. Obstacle.MAX_GAP_COEFFICIENT = Runner.spriteDefinition.MAX_GAP_COEFFICIENT;
  3394. Obstacle.MAX_OBSTACLE_LENGTH = Runner.spriteDefinition.MAX_OBSTACLE_LENGTH;
  3395. BackgroundEl.config = Runner.spriteDefinition.BACKGROUND_EL_CONFIG;
  3396. this.horizonLines = [];
  3397. for (let i = 0; i < Runner.spriteDefinition.LINES.length; i++) {
  3398. this.horizonLines.push(
  3399. new HorizonLine(this.canvas, Runner.spriteDefinition.LINES[i]));
  3400. }
  3401. this.reset();
  3402. },
  3403. /**
  3404. * @param {number} deltaTime
  3405. * @param {number} currentSpeed
  3406. * @param {boolean} updateObstacles Used as an override to prevent
  3407. * the obstacles from being updated / added. This happens in the
  3408. * ease in section.
  3409. * @param {boolean} showNightMode Night mode activated.
  3410. */
  3411. update(deltaTime, currentSpeed, updateObstacles, showNightMode) {
  3412. this.runningTime += deltaTime;
  3413. if (this.altGameModeActive) {
  3414. this.updateBackgroundEls(deltaTime, currentSpeed);
  3415. }
  3416. for (let i = 0; i < this.horizonLines.length; i++) {
  3417. this.horizonLines[i].update(deltaTime, currentSpeed);
  3418. }
  3419. if (!this.altGameModeActive || Runner.spriteDefinition.HAS_CLOUDS) {
  3420. this.nightMode.update(showNightMode);
  3421. this.updateClouds(deltaTime, currentSpeed);
  3422. }
  3423. if (updateObstacles) {
  3424. this.updateObstacles(deltaTime, currentSpeed);
  3425. }
  3426. },
  3427. /**
  3428. * Update background element positions. Also handles creating new elements.
  3429. * @param {number} elSpeed
  3430. * @param {Array<Object>} bgElArray
  3431. * @param {number} maxBgEl
  3432. * @param {Function} bgElAddFunction
  3433. * @param {number} frequency
  3434. */
  3435. updateBackgroundEl(elSpeed, bgElArray, maxBgEl, bgElAddFunction, frequency) {
  3436. const numElements = bgElArray.length;
  3437. if (numElements) {
  3438. for (let i = numElements - 1; i >= 0; i--) {
  3439. bgElArray[i].update(elSpeed);
  3440. }
  3441. const lastEl = bgElArray[numElements - 1];
  3442. // Check for adding a new element.
  3443. if (numElements < maxBgEl &&
  3444. (this.dimensions.WIDTH - lastEl.xPos) > lastEl.gap &&
  3445. frequency > Math.random()) {
  3446. bgElAddFunction();
  3447. }
  3448. } else {
  3449. bgElAddFunction();
  3450. }
  3451. },
  3452. /**
  3453. * Update the cloud positions.
  3454. * @param {number} deltaTime
  3455. * @param {number} speed
  3456. */
  3457. updateClouds(deltaTime, speed) {
  3458. const elSpeed = this.cloudSpeed / 1000 * deltaTime * speed;
  3459. this.updateBackgroundEl(
  3460. elSpeed, this.clouds, this.config.MAX_CLOUDS, this.addCloud.bind(this),
  3461. this.cloudFrequency);
  3462. // Remove expired elements.
  3463. this.clouds = this.clouds.filter((obj) => !obj.remove);
  3464. },
  3465. /**
  3466. * Update the background element positions.
  3467. * @param {number} deltaTime
  3468. * @param {number} speed
  3469. */
  3470. updateBackgroundEls(deltaTime, speed) {
  3471. this.updateBackgroundEl(
  3472. deltaTime, this.backgroundEls, BackgroundEl.config.MAX_BG_ELS,
  3473. this.addBackgroundEl.bind(this), this.cloudFrequency);
  3474. // Remove expired elements.
  3475. this.backgroundEls = this.backgroundEls.filter((obj) => !obj.remove);
  3476. },
  3477. /**
  3478. * Update the obstacle positions.
  3479. * @param {number} deltaTime
  3480. * @param {number} currentSpeed
  3481. */
  3482. updateObstacles(deltaTime, currentSpeed) {
  3483. const updatedObstacles = this.obstacles.slice(0);
  3484. for (let i = 0; i < this.obstacles.length; i++) {
  3485. const obstacle = this.obstacles[i];
  3486. obstacle.update(deltaTime, currentSpeed);
  3487. // Clean up existing obstacles.
  3488. if (obstacle.remove) {
  3489. updatedObstacles.shift();
  3490. }
  3491. }
  3492. this.obstacles = updatedObstacles;
  3493. if (this.obstacles.length > 0) {
  3494. const lastObstacle = this.obstacles[this.obstacles.length - 1];
  3495. if (lastObstacle && !lastObstacle.followingObstacleCreated &&
  3496. lastObstacle.isVisible() &&
  3497. (lastObstacle.xPos + lastObstacle.width + lastObstacle.gap) <
  3498. this.dimensions.WIDTH) {
  3499. this.addNewObstacle(currentSpeed);
  3500. lastObstacle.followingObstacleCreated = true;
  3501. }
  3502. } else {
  3503. // Create new obstacles.
  3504. this.addNewObstacle(currentSpeed);
  3505. }
  3506. },
  3507. removeFirstObstacle() {
  3508. this.obstacles.shift();
  3509. },
  3510. /**
  3511. * Add a new obstacle.
  3512. * @param {number} currentSpeed
  3513. */
  3514. addNewObstacle(currentSpeed) {
  3515. const obstacleCount =
  3516. Obstacle.types[Obstacle.types.length - 1].type != 'COLLECTABLE' ||
  3517. (Runner.isAltGameModeEnabled() && !this.altGameModeActive ||
  3518. this.altGameModeActive) ?
  3519. Obstacle.types.length - 1 :
  3520. Obstacle.types.length - 2;
  3521. const obstacleTypeIndex =
  3522. obstacleCount > 0 ? getRandomNum(0, obstacleCount) : 0;
  3523. const obstacleType = Obstacle.types[obstacleTypeIndex];
  3524. // Check for multiples of the same type of obstacle.
  3525. // Also check obstacle is available at current speed.
  3526. if ((obstacleCount > 0 && this.duplicateObstacleCheck(obstacleType.type)) ||
  3527. currentSpeed < obstacleType.minSpeed) {
  3528. this.addNewObstacle(currentSpeed);
  3529. } else {
  3530. const obstacleSpritePos = this.spritePos[obstacleType.type];
  3531. this.obstacles.push(new Obstacle(
  3532. this.canvasCtx, obstacleType, obstacleSpritePos, this.dimensions,
  3533. this.gapCoefficient, currentSpeed, obstacleType.width,
  3534. this.altGameModeActive));
  3535. this.obstacleHistory.unshift(obstacleType.type);
  3536. if (this.obstacleHistory.length > 1) {
  3537. this.obstacleHistory.splice(Runner.config.MAX_OBSTACLE_DUPLICATION);
  3538. }
  3539. }
  3540. },
  3541. /**
  3542. * Returns whether the previous two obstacles are the same as the next one.
  3543. * Maximum duplication is set in config value MAX_OBSTACLE_DUPLICATION.
  3544. * @return {boolean}
  3545. */
  3546. duplicateObstacleCheck(nextObstacleType) {
  3547. let duplicateCount = 0;
  3548. for (let i = 0; i < this.obstacleHistory.length; i++) {
  3549. duplicateCount =
  3550. this.obstacleHistory[i] === nextObstacleType ? duplicateCount + 1 : 0;
  3551. }
  3552. return duplicateCount >= Runner.config.MAX_OBSTACLE_DUPLICATION;
  3553. },
  3554. /**
  3555. * Reset the horizon layer.
  3556. * Remove existing obstacles and reposition the horizon line.
  3557. */
  3558. reset() {
  3559. this.obstacles = [];
  3560. for (let l = 0; l < this.horizonLines.length; l++) {
  3561. this.horizonLines[l].reset();
  3562. }
  3563. this.nightMode.reset();
  3564. },
  3565. /**
  3566. * Update the canvas width and scaling.
  3567. * @param {number} width Canvas width.
  3568. * @param {number} height Canvas height.
  3569. */
  3570. resize(width, height) {
  3571. this.canvas.width = width;
  3572. this.canvas.height = height;
  3573. },
  3574. /**
  3575. * Add a new cloud to the horizon.
  3576. */
  3577. addCloud() {
  3578. this.clouds.push(new Cloud(this.canvas, this.spritePos.CLOUD,
  3579. this.dimensions.WIDTH));
  3580. },
  3581. /**
  3582. * Add a random background element to the horizon.
  3583. */
  3584. addBackgroundEl() {
  3585. const backgroundElTypes =
  3586. Object.keys(Runner.spriteDefinition.BACKGROUND_EL);
  3587. if (backgroundElTypes.length > 0) {
  3588. let index = getRandomNum(0, backgroundElTypes.length - 1);
  3589. let type = backgroundElTypes[index];
  3590. // Add variation if available.
  3591. while (type == this.lastEl && backgroundElTypes.length > 1) {
  3592. index = getRandomNum(0, backgroundElTypes.length - 1);
  3593. type = backgroundElTypes[index];
  3594. }
  3595. this.lastEl = type;
  3596. this.backgroundEls.push(new BackgroundEl(
  3597. this.canvas, this.spritePos.BACKGROUND_EL, this.dimensions.WIDTH,
  3598. type));
  3599. }
  3600. },
  3601. };