gameMechanics.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. /***************************************************************
  2. * LInE - Free Education, Private Data - http://www.usp.br/line
  3. *
  4. * This file handles all the game mechanics.
  5. **************************************************************/
  6. /**
  7. * Variable that handles game mechanics.
  8. *
  9. * @namespace
  10. */
  11. const game = {
  12. image: {}, // [Not directly used] Holds cached reference to media.
  13. sprite: {}, // [Not directly used] Holds cached reference to media.
  14. audio: {}, // Holds cached reference to media - game.audio.<name>.play() plays that audio once.
  15. lang: {}, // Holds language dictionary in a key-value format - game.lang.<key> returns <value>.
  16. /**
  17. * Handles game states. <br>
  18. *
  19. * When a state is associated with an object
  20. * it can accessed using game.state.start('state name'). <br>
  21. * That way the object can use the especial functions: preload(), create() and update();
  22. * that behave according to the following rules: <br>
  23. * - preload() : first function to run when a state is called. Loads media. Runs only once. (is optional) <br>
  24. * - create() : called right after preload(). Where the main code goes. Runs only once. (must exist) <br>
  25. * - update() : called right after create(). Is iteratively called by 'game loop' until going to next state. (is optional)
  26. *
  27. * @namespace
  28. */
  29. state: {
  30. // [Not directly used] List of game states.
  31. list: [],
  32. // [Not directly used]
  33. name: undefined,
  34. // progressBar
  35. progressBar: undefined,
  36. progressBarLabel: undefined,
  37. /**
  38. * Create new state. <br>
  39. *
  40. * After a state is created, the object associated with that state
  41. * can be called using game.state.start('state name')
  42. *
  43. * @param {string} name state name
  44. * @param {object} obj object that should be called when accessing the state
  45. */
  46. add: function (name, obj) {
  47. game.state.list[name] = obj;
  48. },
  49. /**
  50. * Start new state.
  51. *
  52. * Will look for the state's preload() to load the files for the current state.
  53. * If there is no preload, will call create().
  54. *
  55. * @param {string} name state name
  56. */
  57. start: function (name) {
  58. document.body.style.cursor = 'auto'; // Set cursor to default
  59. game.loop.stop(); // Stop last game loop
  60. game.event.clear(); // Clears last event queue
  61. game.animation.clear(); // Clears last animation queue
  62. game.loadedCur = 0; // Clears last state's number of loaded media
  63. game.loadedMax = 0; // Clears last state's expected loaded media
  64. game.state.name = name; // Updates state name
  65. navigation.list = [];
  66. self = game.state.list[name]; // Updates self to current state
  67. if (self.preload) {
  68. game.render.clear(); // Clears render queue
  69. // IF there's media to be loaded, creates progress bar
  70. game.add.geom.rect(
  71. 0,
  72. 0,
  73. context.canvas.width,
  74. context.canvas.height,
  75. colors.blueBg,
  76. 1
  77. );
  78. game.add.geom.rect(
  79. context.canvas.width / 2 - 500 / 2,
  80. context.canvas.height / 2 - 40 / 2,
  81. 500,
  82. 40,
  83. colors.white,
  84. 1
  85. );
  86. game.state.progressBar = game.add.geom.rect(
  87. context.canvas.width / 2 - 500 / 2,
  88. context.canvas.height / 2,
  89. 40,
  90. 40,
  91. colors.blue,
  92. 0.4
  93. );
  94. game.state.progressBar.anchor(0, 0.5);
  95. game.state.progressBarLabel = game.add.text(
  96. context.canvas.width / 2,
  97. context.canvas.height / 2 + 80,
  98. 'Loading...',
  99. textStyles.h2_
  100. );
  101. // Calls state's preload() to load the state's media
  102. self.preload();
  103. } else {
  104. game.state.create();
  105. }
  106. },
  107. /**
  108. * [Not directly used] Encapsulate create() function in the current state.
  109. */
  110. create: function () {
  111. game.render.clear(); // Clears render queue, removing 'progress bar' if preload() was called
  112. if (!self.create) {
  113. console.error(
  114. "Game error: The state called does not have a 'create' function. Unable to continue."
  115. );
  116. } else {
  117. self.create(); // Calls create()
  118. game.render.all(); // After create() ends, renders media on canvas
  119. if (self?.restart) {
  120. // If needed, restart state
  121. game.state.start(game.state.name);
  122. } else {
  123. if (self.update) game.loop.start(self); // Calls update() if it exists
  124. }
  125. }
  126. },
  127. },
  128. loadHandler: {
  129. cur: 0, // [Not directly used] CURRENT number of cached media (on current state)
  130. max: 0, // [Not directly used] EXPECTED number of cached media (on current state)
  131. // [Not directly used] media type and status information
  132. type: {
  133. lang: { isLoading: false, cached: 0, length: 0 },
  134. audio: { isLoading: false, cached: 0, length: 0 },
  135. image: { isLoading: false, cached: 0, length: 0 },
  136. sprite: { isLoading: false, cached: 0, length: 0 },
  137. },
  138. /** [Not directly used] Removes the urls that are already in the cache.
  139. *
  140. * @param {string[]} unfilteredUrls array of urls
  141. * @param {object} mediaCategory media category
  142. *
  143. * @returns {string[]} array of uncached urls
  144. */
  145. getUncachedUrlsOnly: function (unfilteredUrls, mediaCategory) {
  146. const uncachedUrls = [];
  147. unfilteredUrls.forEach((url) => {
  148. if (mediaCategory[url[0]] === undefined) uncachedUrls.push(url);
  149. });
  150. return uncachedUrls;
  151. },
  152. /** [Not directly used] Informs ONE media file was loaded to cache. <br>
  153. *
  154. * After ALL FILES of the SAME CATEGORY are cached, calls game.load.cachedAllInOneMediaType()
  155. *
  156. * @param {String} mediaType media category (to update the cached files from that category)
  157. */
  158. cachedOneFile: function (mediaType) {
  159. const length = game.loadHandler.type[mediaType].length;
  160. // Update progress bar on loading screen
  161. if (length - 1 !== 0) {
  162. // if (game.state..progressBarLabel?.name) {
  163. // game.state..progressBarLabel.name = `${game.loadHandler.cur + 1}/${
  164. // game.loadHandler.max
  165. // }`;
  166. // }
  167. game.state.progressBar.width =
  168. (500 / game.loadHandler.max) * game.loadHandler.cur;
  169. game.render.all();
  170. game.loadHandler.cur++;
  171. // console.log(game.loadHandler.cur, game.loadHandler.max);
  172. }
  173. // If reached last index of current media array
  174. if (game.loadHandler.type[mediaType].cached >= length - 1) {
  175. // Resets load manager
  176. game.loadHandler.type[mediaType].isLoading = false;
  177. game.loadHandler.type[mediaType].cached = 0;
  178. game.loadHandler.type[mediaType].length = 0;
  179. // Informs
  180. game.loadHandler.cachedAllInOneMediaType();
  181. } else {
  182. // Updates
  183. game.loadHandler.type[mediaType].cached++;
  184. }
  185. },
  186. /** [Not directly used] Informs ALL MEDIA files from the SAME CATEGORY are cached. <br>
  187. *
  188. * After ALL CATEGORIES of media are cached, calls create() via game.state. <br>
  189. * ATTENTION: Do not call create() directly.
  190. */
  191. cachedAllInOneMediaType: function () {
  192. // Checks if finished loading ALL media categories
  193. let endPreload = true;
  194. for (let key in game.loadHandler.type) {
  195. if (game.loadHandler.type[key].isLoading) {
  196. endPreload = false;
  197. break;
  198. }
  199. }
  200. // If flag doesnt change, all media is cached
  201. if (endPreload) {
  202. game.loadHandler.cur = 0;
  203. game.loadHandler.max = 0;
  204. game.state.create();
  205. }
  206. },
  207. },
  208. /**
  209. * Loads media files to cache. <br>
  210. *
  211. * IMPORTANT: Must ONLY be used inside the function preload(),
  212. * as it calls create() after all media is cached.
  213. *
  214. * @see /js/globals.js for the list of media urls (var url)
  215. *
  216. * @namespace
  217. */
  218. load: {
  219. /**
  220. * Loads language file to cache using Fetch API and
  221. * saves its content as dictionary on game.lang.
  222. *
  223. * @param {string} url url for the selected language
  224. */
  225. lang: function (url) {
  226. game.loadHandler.type.lang.isLoading = true;
  227. game.loadHandler.type.lang.cached = 0;
  228. game.lang = {}; // Clear previously loaded language
  229. fetch(url, { mode: 'same-origin' })
  230. .then((response) => response.text())
  231. .then((text) => {
  232. const lines = text.split('\n');
  233. game.loadHandler.type.lang.length = lines.length;
  234. game.loadHandler.max += lines.length;
  235. lines.forEach((line) => {
  236. try {
  237. const msg = line.split('=');
  238. if (msg.length !== 2)
  239. throw Error('Game error: sintax error in i18y file');
  240. game.lang[msg[0].trim()] = msg[1].trim();
  241. } catch (error) {
  242. console.error(error.message);
  243. }
  244. game.loadHandler.cachedOneFile('lang');
  245. });
  246. })
  247. .catch((error) => {
  248. console.error(error);
  249. });
  250. },
  251. /**
  252. * Loads audio files to cache using Fetch API
  253. * saves references in game.audio.
  254. *
  255. * @param {string[]} urls audio urls for the current state
  256. */
  257. audio: function (urls) {
  258. game.loadHandler.type.audio.isLoading = true;
  259. game.loadHandler.type.audio.cached = 0;
  260. urls = game.loadHandler.getUncachedUrlsOnly(urls, game.audio);
  261. game.loadHandler.type.audio.length = urls.length;
  262. if (urls.length == 0) {
  263. game.loadHandler.cachedOneFile('audio');
  264. } else {
  265. game.loadHandler.max += urls.length;
  266. urls.forEach((url) => {
  267. fetch(url[1][1], { mode: 'same-origin' })
  268. .then((response) => response.blob())
  269. .then((data) => {
  270. game.audio[url[0]] = new Audio(URL.createObjectURL(data));
  271. game.loadHandler.cachedOneFile('audio');
  272. })
  273. .catch((error) => {
  274. console.error(error);
  275. });
  276. });
  277. }
  278. },
  279. /**
  280. * Loads image files to cache using HTMLImageElement
  281. * saves references in game.image.
  282. *
  283. * @param {string[]} urls image urls for the current state
  284. */
  285. image: function (urls) {
  286. game.loadHandler.type.image.isLoading = true;
  287. game.loadHandler.type.image.cached = 0;
  288. urls = game.loadHandler.getUncachedUrlsOnly(urls, game.image);
  289. game.loadHandler.type.image.length = urls.length;
  290. if (urls.length == 0) {
  291. game.loadHandler.cachedOneFile('image');
  292. } else {
  293. game.loadHandler.max += urls.length;
  294. urls.forEach((url) => {
  295. const img = new Image();
  296. img.onload = () => {
  297. game.image[url[0]] = img;
  298. game.loadHandler.cachedOneFile('image');
  299. };
  300. img.onerror = () => {
  301. console.error(
  302. 'Game error: image "' + url[0] + '" not found in sourse files.'
  303. );
  304. game.image[url[0]] = img;
  305. img.src = fallbackImgUrl;
  306. game.loadHandler.cachedOneFile('image');
  307. };
  308. img.src = url[1];
  309. });
  310. }
  311. },
  312. /**
  313. * Loads image files that contains spritesheets to cache using HTMLImageElement
  314. * saves references in game.sprite.
  315. *
  316. * @param {string[]} urls spritesheet urls for the current state
  317. */
  318. sprite: function (urls) {
  319. game.loadHandler.type.sprite.isLoading = true;
  320. game.loadHandler.type.sprite.cached = 0;
  321. urls = game.loadHandler.getUncachedUrlsOnly(urls, game.sprite);
  322. game.loadHandler.type.sprite.length = urls.length;
  323. if (urls.length == 0) {
  324. game.loadHandler.cachedOneFile('sprite');
  325. } else {
  326. game.loadHandler.max += urls.length;
  327. urls.forEach((url) => {
  328. try {
  329. const img = new Image();
  330. img.onload = () => {
  331. game.sprite[url[0]] = img;
  332. game.loadHandler.cachedOneFile('sprite');
  333. };
  334. img.onerror = () => {
  335. console.error('Game error: sprite not found');
  336. game.sprite[url[0]] = img;
  337. img.src = fallbackImgUrl;
  338. img.frames = 1;
  339. game.loadHandler.cachedOneFile('sprite');
  340. };
  341. img.src = url[1];
  342. img.frames = url[2];
  343. } catch (error) {
  344. console.error(error);
  345. }
  346. });
  347. }
  348. },
  349. },
  350. /**
  351. * Adds new media to the 'media queue' (game.render.queue). <br>
  352. *
  353. * All queued media will be rendered on canvas when game.render.all() is called.
  354. *
  355. * @namespace
  356. */
  357. add: {
  358. /**
  359. * Adds image to media queue.
  360. *
  361. * @param {number} x x coordinate for the figure
  362. * @param {number} y y coordinate for the figure
  363. * @param {string} img name of the cached image
  364. * @param {undefined|number} scale scale for the image (default = 1)
  365. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible) (default = 1)
  366. *
  367. * @returns {object} a reference to the created image.
  368. */
  369. image: function (x, y, img, scale, alpha) {
  370. if (x == undefined || y == undefined || img == undefined)
  371. console.error('Game error: missing parameters.');
  372. else if (game.image[img] == undefined)
  373. console.error('Game error: image not found in cache: ' + img + '.');
  374. else {
  375. const med = {
  376. typeOfMedia: 'image',
  377. name: img,
  378. x: x || game.add.default.x,
  379. y: y || game.add.default.y,
  380. _xWithAnchor: x || game.add.default._xWithAnchor,
  381. _yWithAnchor: y || game.add.default._yWithAnchor,
  382. xAnchor: game.add.default.xAnchor,
  383. yAnchor: game.add.default.yAnchor,
  384. shadow: game.add.default.shadow,
  385. shadowColor: game.add.default.shadowColor,
  386. shadowBlur: game.add.default.shadowBlur,
  387. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  388. scale: scale || game.add.default.scale,
  389. width: game.image[img].width,
  390. height: game.image[img].height,
  391. anchor: function (xAnchor, yAnchor) {
  392. this.xAnchor = xAnchor;
  393. this.yAnchor = yAnchor;
  394. },
  395. get xWithAnchor() {
  396. return this.x - this.width * this.scale * this.xAnchor;
  397. },
  398. get yWithAnchor() {
  399. return this.y - this.height * this.scale * this.yAnchor;
  400. },
  401. };
  402. med.initialScale = med.scale;
  403. game.render.queue.push(med);
  404. return med;
  405. }
  406. },
  407. /**
  408. * Adds spritesheet to media queue. <br>
  409. * A spritesheet is an image that can be cropped to show only one 'frame' at a time.
  410. *
  411. * @param {number} x x coordinate for the figure
  412. * @param {number} y Y coordinate for the figure
  413. * @param {string} img name of the cached spritesheet
  414. * @param {undefined|number} curFrame current frame (default = 0)
  415. * @param {undefined|number} scale scale for the spritesheet (default = 1)
  416. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible) (default = 1)
  417. *
  418. * @returns {object} a reference to the created sprite.
  419. */
  420. sprite: function (x, y, img, curFrame, scale, alpha) {
  421. if (x == undefined || y == undefined || img == undefined)
  422. console.error('Game error: missing parameters.');
  423. else if (game.sprite[img] == undefined)
  424. console.error('Game error: sprite not found in cache: ' + img + '.');
  425. else {
  426. const med = {
  427. typeOfMedia: 'sprite',
  428. name: img,
  429. x: x || game.add.default.x,
  430. y: y || game.add.default.y,
  431. _xWithAnchor: x || game.add.default._xWithAnchor,
  432. _yWithAnchor: y || game.add.default._yWithAnchor,
  433. xAnchor: game.add.default.xAnchor,
  434. yAnchor: game.add.default.yAnchor,
  435. shadow: game.add.default.shadow,
  436. shadowColor: game.add.default.shadowColor,
  437. shadowBlur: game.add.default.shadowBlur,
  438. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  439. scale: scale || game.add.default.scale,
  440. width: game.sprite[img].width / game.sprite[img].frames, // Frame width
  441. height: game.sprite[img].height, // Frame height
  442. curFrame: curFrame || 0,
  443. anchor: function (xAnchor, yAnchor) {
  444. this.xAnchor = xAnchor;
  445. this.yAnchor = yAnchor;
  446. },
  447. get xWithAnchor() {
  448. return this.x - this.width * this.scale * this.xAnchor;
  449. },
  450. get yWithAnchor() {
  451. return this.y - this.height * this.scale * this.yAnchor;
  452. },
  453. };
  454. med.initialScale = med.scale;
  455. game.render.queue.push(med);
  456. return med;
  457. }
  458. },
  459. /**
  460. * Adds text to media queue.
  461. *
  462. * @param {number} x x coordinate for the figure
  463. * @param {number} y y coordinate for the figure
  464. * @param {string} text text to be displayed on screen
  465. * @param {object} style object containing font, color and align for the text
  466. *
  467. * @returns {object} a reference to the created text.
  468. */
  469. text: function (x, y, text, style) {
  470. if (
  471. x == undefined ||
  472. y == undefined ||
  473. text == undefined ||
  474. style == undefined
  475. ) {
  476. console.error('Game error: missing parameters.');
  477. } else {
  478. const med = {
  479. typeOfMedia: 'text',
  480. name: style?.increaseLetterSpacing
  481. ? text.split('').join(String.fromCharCode(8202))
  482. : text,
  483. x: x || game.add.default.x,
  484. y: y || game.add.default.y,
  485. _xWithAnchor: x || game.add.default._xWithAnchor,
  486. _yWithAnchor: y || game.add.default._yWithAnchor,
  487. xAnchor: game.add.default.xAnchor,
  488. yAnchor: game.add.default.yAnchor,
  489. shadow: game.add.default.shadow,
  490. shadowColor: game.add.default.shadowColor,
  491. shadowBlur: game.add.default.shadowBlur,
  492. alpha: game.add.default.alpha,
  493. font: style.font || game.add.default.font,
  494. fill: style.fill || game.add.default.fill,
  495. align: style.align || game.add.default.align,
  496. anchor: function () {
  497. console.error("Game error: there's no anchor for text.");
  498. },
  499. set style(style) {
  500. this.font = style.font;
  501. this.fill = style.fill;
  502. this.align = style.align;
  503. },
  504. get xWithAnchor() {
  505. return this.x;
  506. },
  507. get yWithAnchor() {
  508. return this.y;
  509. },
  510. };
  511. game.render.queue.push(med);
  512. return med;
  513. }
  514. },
  515. /**
  516. * Adds geometric shapes.
  517. * @namespace
  518. */
  519. geom: {
  520. /**
  521. * Adds rectangle to media queue.
  522. *
  523. * @param {number} x x coordinate for top left corner of the rectangle
  524. * @param {number} y y coordinate for top left corner of the rectangle
  525. * @param {number} width rectangle width (default = 50)
  526. * @param {undefined|number} height rectangle height (default = 50)
  527. * @param {undefined|string} lineColor stroke color (default = black)
  528. * @param {undefined|number} lineWidth stroke width (default = 1px)
  529. * @param {undefined|string} fillColor fill color (default = no fill)
  530. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  531. *
  532. * @returns {object} a reference to the created rectangle.
  533. */
  534. rect: function (
  535. x,
  536. y,
  537. width,
  538. height,
  539. fillColor,
  540. alpha,
  541. lineColor,
  542. lineWidth
  543. ) {
  544. if (x == undefined || y == undefined || width == undefined)
  545. console.error('Game error: missing parameters.');
  546. else {
  547. const med = {
  548. typeOfMedia: 'rect',
  549. x: x || game.add.default.x,
  550. y: y || game.add.default.y,
  551. _xWithAnchor: x || game.add.default._xWithAnchor,
  552. _yWithAnchor: y || game.add.default._yWithAnchor,
  553. xAnchor: game.add.default.xAnchor,
  554. yAnchor: game.add.default.yAnchor,
  555. shadow: game.add.default.shadow,
  556. shadowColor: game.add.default.shadowColor,
  557. shadowBlur: game.add.default.shadowBlur,
  558. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  559. scale: game.add.default.scale,
  560. width: 0,
  561. height: 0,
  562. lineColor: lineColor || game.add.default.lineColor,
  563. lineWidth: 0,
  564. fillColor: fillColor || game.add.default.fillColor,
  565. anchor: function (xAnchor, yAnchor) {
  566. this.xAnchor = xAnchor;
  567. this.yAnchor = yAnchor;
  568. },
  569. get xWithAnchor() {
  570. return this.x - this.width * this.scale * this.xAnchor;
  571. },
  572. get yWithAnchor() {
  573. return this.y - this.height * this.scale * this.yAnchor;
  574. },
  575. };
  576. med.initialScale = med.scale;
  577. if (width != 0) {
  578. med.width = width || game.add.default.width;
  579. }
  580. if (height != 0) {
  581. med.height = height || width || game.add.default.height;
  582. }
  583. if (lineWidth != 0) {
  584. med.lineWidth = lineWidth || game.add.default.lineWidth;
  585. }
  586. game.render.queue.push(med);
  587. return med;
  588. }
  589. },
  590. /**
  591. * Adds circle to media queue.
  592. *
  593. * @param {number} x x coordinate for the circle center
  594. * @param {number} y y coordinate for the circle center
  595. * @param {number} diameter circle diameter (default = 50)
  596. * @param {undefined|string} lineColor stroke color (default = black)
  597. * @param {undefined|number} lineWidth stroke width (default = 1px)
  598. * @param {undefined|string} fillColor fill color (default = no fill)
  599. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  600. *
  601. * @returns {object} a reference to the created circle.
  602. */
  603. circle: function (
  604. x,
  605. y,
  606. diameter,
  607. lineColor,
  608. lineWidth,
  609. fillColor,
  610. alpha
  611. ) {
  612. if (x == undefined || y == undefined || diameter == undefined)
  613. console.error('Game error: missing parameters.');
  614. else {
  615. const med = {
  616. typeOfMedia: 'arc',
  617. x: x || game.add.default.x,
  618. y: y || game.add.default.y,
  619. _xWithAnchor: x || game.add.default._xWithAnchor,
  620. _yWithAnchor: y || game.add.default._yWithAnchor,
  621. xAnchor: game.add.default.xAnchor,
  622. yAnchor: game.add.default.yAnchor,
  623. shadow: game.add.default.shadow,
  624. shadowColor: game.add.default.shadowColor,
  625. shadowBlur: game.add.default.shadowBlur,
  626. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  627. scale: game.add.default.scale,
  628. diameter: 0,
  629. width: 0,
  630. height: 0,
  631. angleStart: 0,
  632. angleEnd: 2 * Math.PI,
  633. counterclockwise: game.add.default.counterclockwise,
  634. lineColor: lineColor || game.add.default.lineColor,
  635. lineWidth: 0,
  636. fillColor: fillColor || game.add.default.fillColor,
  637. anchor: function (xAnchor, yAnchor) {
  638. this.xAnchor = xAnchor;
  639. this.yAnchor = yAnchor;
  640. },
  641. get xWithAnchor() {
  642. return this.x - this.width * this.scale * this.xAnchor;
  643. },
  644. get yWithAnchor() {
  645. return this.y - this.height * this.scale * this.yAnchor;
  646. },
  647. };
  648. med.initialScale = med.scale;
  649. if (diameter != 0) {
  650. med.diameter = diameter || game.add.default.diameter;
  651. med.width = med.height = med.diameter;
  652. }
  653. if (lineWidth != 0) {
  654. med.lineWidth = lineWidth || game.add.default.lineWidth;
  655. }
  656. game.render.queue.push(med);
  657. return med;
  658. }
  659. },
  660. /**
  661. * Adds arc to media queue.
  662. *
  663. * @param {number} x x coordinate for the arc center
  664. * @param {number} y y coordinate for the arc center
  665. * @param {number} diameter arc diameter
  666. * @param {number} angleStart angle to start the arc
  667. * @param {number} angleEnd angle to end the arc
  668. * @param {undefined|boolean} counterclockwise if true, arc is created counterclockwise (default = false)
  669. * @param {undefined|string} lineColor stroke color (default = black)
  670. * @param {undefined|number} lineWidth stroke width (default = 1px)
  671. * @param {undefined|string} fillColor fill color (default = no fill)
  672. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  673. *
  674. * @returns {object} a reference to the created arc.
  675. */
  676. arc: function (
  677. x,
  678. y,
  679. diameter,
  680. angleStart,
  681. angleEnd,
  682. counterclockwise,
  683. lineColor,
  684. lineWidth,
  685. fillColor,
  686. alpha
  687. ) {
  688. if (
  689. x == undefined ||
  690. y == undefined ||
  691. diameter == undefined ||
  692. angleStart == undefined ||
  693. angleEnd == undefined
  694. )
  695. console.error('Game error: missing parameters.');
  696. else {
  697. const med = {
  698. typeOfMedia: 'arc',
  699. x: x || game.add.default.x,
  700. y: y || game.add.default.y,
  701. _xWithAnchor: x || game.add.default._xWithAnchor,
  702. _yWithAnchor: y || game.add.default._yWithAnchor,
  703. xAnchor: game.add.default.xAnchor,
  704. yAnchor: game.add.default.yAnchor,
  705. shadow: game.add.default.shadow,
  706. shadowColor: game.add.default.shadowColor,
  707. shadowBlur: game.add.default.shadowBlur,
  708. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  709. scale: game.add.default.scale,
  710. diameter: 0,
  711. width: 0,
  712. height: 0,
  713. angleStart: angleStart || 0,
  714. angleEnd: angleEnd || 2 * Math.PI,
  715. counterclockwise:
  716. counterclockwise || game.add.default.counterclockwise,
  717. lineColor: lineColor || game.add.default.lineColor,
  718. lineWidth: 0,
  719. fillColor: fillColor || game.add.default.fillColor,
  720. anchor: function (xAnchor, yAnchor) {
  721. this.xAnchor = xAnchor;
  722. this.yAnchor = yAnchor;
  723. },
  724. get xWithAnchor() {
  725. return this.x - this.width * this.scale * this.xAnchor;
  726. },
  727. get yWithAnchor() {
  728. return this.y - this.height * this.scale * this.yAnchor;
  729. },
  730. };
  731. med.initialScale = med.scale;
  732. if (diameter != 0) {
  733. med.diameter = diameter || game.add.default.diameter;
  734. med.width = med.height = med.diameter;
  735. }
  736. if (lineWidth != 0) {
  737. med.lineWidth = lineWidth || game.add.default.lineWidth;
  738. }
  739. game.render.queue.push(med);
  740. return med;
  741. }
  742. },
  743. },
  744. /**
  745. * [Not directly used] Default values for the media properties.
  746. */
  747. default: {
  748. // Used in: all types of media.
  749. x: 0,
  750. y: 0,
  751. _xWithAnchor: 0,
  752. _yWithAnchor: 0,
  753. xAnchor: 0,
  754. yAnchor: 0,
  755. shadow: false,
  756. shadowColor: '#0075c5',
  757. shadowBlur: 20,
  758. alpha: 1,
  759. // Used in: image, sprite, square, circle.
  760. scale: 1,
  761. // Used in: text.
  762. font: '14px Arial,sans-serif',
  763. fill: '#000',
  764. align: 'center',
  765. // Used in: square, circle (image and sprite have width and height, but do not have default values).
  766. width: 50,
  767. height: 50,
  768. lineColor: '#000',
  769. lineWidth: 0, // No line
  770. fillColor: '#fff', // white fill
  771. // Used in: circle.
  772. diameter: 50,
  773. counterclockwise: false,
  774. },
  775. },
  776. /**
  777. * Renders media on current screen. <br<
  778. * It uses properties of html canvas to draw media on screen during game loop.
  779. *
  780. * @namespace
  781. */
  782. render: {
  783. // [Not directly used] Media queue to be rendered on the current state.
  784. queue: [],
  785. /** [Not directly used] Renders image on canvas.
  786. *
  787. * @param {object} cur current media in media queue
  788. */
  789. image: function (cur) {
  790. const x = cur.xWithAnchor,
  791. y = cur.yWithAnchor;
  792. // Rotation
  793. if (cur.rotate && cur.rotate != 0) {
  794. context.save();
  795. context.translate(cur.x, cur.y);
  796. context.rotate((cur.rotate * Math.PI) / 180);
  797. context.translate(-cur.x, -cur.y);
  798. }
  799. // Alpha
  800. context.globalAlpha = cur.alpha;
  801. // Shadow
  802. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  803. context.shadowColor = cur.shadowColor;
  804. // Image
  805. context.drawImage(
  806. game.image[cur.name],
  807. x,
  808. y,
  809. cur.width * cur.scale,
  810. cur.height * cur.scale
  811. );
  812. // End
  813. context.shadowBlur = 0;
  814. context.globalAlpha = 1;
  815. if (cur.rotate && cur.rotate != 0) context.restore();
  816. },
  817. /** [Not directly used] Renders spritesheet on canvas.
  818. *
  819. * @param {object} cur current media in media queue
  820. */
  821. sprite: function (cur) {
  822. const x = cur.xWithAnchor,
  823. y = cur.yWithAnchor;
  824. // Rotation
  825. if (cur.rotate && cur.rotate != 0) {
  826. context.save();
  827. context.translate(cur.x, cur.y);
  828. context.rotate((cur.rotate * Math.PI) / 180);
  829. context.translate(-cur.x, -cur.y);
  830. }
  831. // Alpha
  832. context.globalAlpha = cur.alpha;
  833. // Shadow
  834. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  835. context.shadowColor = cur.shadowColor;
  836. // Image
  837. context.drawImage(
  838. game.sprite[cur.name],
  839. cur.width * cur.curFrame,
  840. 0,
  841. cur.width,
  842. cur.height,
  843. x,
  844. y,
  845. cur.width * cur.scale,
  846. cur.height * cur.scale
  847. );
  848. // End
  849. context.shadowBlur = 0;
  850. context.globalAlpha = 1;
  851. if (cur.rotate && cur.rotate != 0) context.restore();
  852. },
  853. /** [Not directly used] Renders text on canvas.
  854. *
  855. * @param {object} cur current media in media queue
  856. */
  857. text: function (cur) {
  858. const x = cur.xWithAnchor,
  859. y = cur.yWithAnchor;
  860. // Rotation
  861. if (cur.rotate && cur.rotate != 0) {
  862. context.save();
  863. context.translate(cur.x, cur.y);
  864. context.rotate((cur.rotate * Math.PI) / 180);
  865. context.translate(-cur.x, -cur.y);
  866. }
  867. // Alpha
  868. context.globalAlpha = cur.alpha;
  869. // Shadow
  870. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  871. context.shadowColor = cur.shadowColor;
  872. // Font style
  873. context.font = cur.font;
  874. context.textAlign = cur.align;
  875. context.fillStyle = cur.fill;
  876. // Text
  877. const paragraphs = String(cur.name).split('\n');
  878. let newY = y;
  879. for (let line in paragraphs) {
  880. context.fillText(paragraphs[line], x, newY);
  881. newY += 48;
  882. }
  883. // End
  884. context.shadowBlur = 0;
  885. context.globalAlpha = 1;
  886. if (cur.rotate && cur.rotate != 0) context.restore();
  887. },
  888. /** [Not directly used] Renders geometric shapes on canvas.
  889. *
  890. * @namespace
  891. */
  892. geom: {
  893. /**
  894. * Renders rectangle on canvas.
  895. *
  896. * @param {object} cur current media in media queue
  897. */
  898. rect: function (cur) {
  899. const x = cur.xWithAnchor,
  900. y = cur.yWithAnchor;
  901. // Rotation
  902. if (cur.rotate && cur.rotate != 0) {
  903. context.save();
  904. context.translate(cur.x, cur.y);
  905. context.rotate((cur.rotate * Math.PI) / 180);
  906. context.translate(-cur.x, -cur.y);
  907. }
  908. // Alpha
  909. context.globalAlpha = cur.alpha;
  910. // Shadow
  911. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  912. context.shadowColor = cur.shadowColor;
  913. // Fill
  914. if (cur.fillColor !== 'transparent') {
  915. context.fillStyle = cur.fillColor;
  916. context.fillRect(x, y, cur.width * cur.scale, cur.height * cur.scale);
  917. }
  918. // Stroke
  919. if (cur.lineWidth != 0) {
  920. context.strokeStyle = cur.lineColor;
  921. context.lineWidth = cur.lineWidth;
  922. context.strokeRect(
  923. x,
  924. y,
  925. cur.width * cur.scale,
  926. cur.height * cur.scale
  927. );
  928. }
  929. // End
  930. context.shadowBlur = 0;
  931. context.globalAlpha = 1;
  932. if (cur.rotate && cur.rotate != 0) context.restore();
  933. },
  934. /**
  935. * Renders arc on canvas (arc or circle).
  936. *
  937. * @param {object} cur current media in media queue
  938. */
  939. arc: function (cur) {
  940. const x = cur.xWithAnchor,
  941. y = cur.yWithAnchor;
  942. // Rotation
  943. if (cur.rotate && cur.rotate != 0) {
  944. context.save();
  945. context.translate(cur.x, cur.y);
  946. context.rotate((cur.rotate * Math.PI) / 180);
  947. context.translate(-cur.x, -cur.y);
  948. }
  949. // Alpha
  950. context.globalAlpha = cur.alpha;
  951. // Shadow
  952. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  953. context.shadowColor = cur.shadowColor;
  954. // Fill info
  955. if (cur.fillColor != 0) context.fillStyle = cur.fillColor;
  956. // Stroke info
  957. if (cur.lineWidth != 0) {
  958. context.strokeStyle = cur.lineColor;
  959. context.lineWidth = cur.lineWidth;
  960. }
  961. // Path
  962. context.beginPath();
  963. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  964. context.arc(
  965. x,
  966. y,
  967. (cur.diameter / 2) * cur.scale,
  968. cur.angleStart,
  969. cur.angleEnd,
  970. cur.counterclockwise
  971. );
  972. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  973. // End
  974. if (cur.fillColor != 0) context.fill();
  975. if (cur.lineWidth != 0) context.stroke();
  976. context.shadowBlur = 0;
  977. context.globalAlpha = 1;
  978. if (cur.rotate && cur.rotate != 0) context.restore();
  979. },
  980. },
  981. /**
  982. * Renders all queued media on screen. Called repeatedly by the game loop.
  983. */
  984. all: function () {
  985. game.render.queue.forEach((cur) => {
  986. switch (cur.typeOfMedia) {
  987. case 'image':
  988. this.image(cur);
  989. break;
  990. case 'sprite':
  991. this.sprite(cur);
  992. break;
  993. case 'text':
  994. this.text(cur);
  995. break;
  996. case 'rect':
  997. this.geom.rect(cur);
  998. break;
  999. case 'arc':
  1000. this.geom.arc(cur);
  1001. break;
  1002. }
  1003. });
  1004. },
  1005. /**
  1006. * Clears media queue (used when changing states).
  1007. */
  1008. clear: function () {
  1009. game.render.queue = [];
  1010. },
  1011. },
  1012. /**
  1013. * Math functions.
  1014. *
  1015. * @namespace
  1016. */
  1017. math: {
  1018. /**
  1019. * Returns a random integer in a range (inclusive for min and max).
  1020. *
  1021. * @param {number} min smaller integer
  1022. * @param {number} max larger integer
  1023. *
  1024. * @returns {number} random integer in range
  1025. */
  1026. randomInRange: function (min, max) {
  1027. min = Math.ceil(min);
  1028. max = Math.floor(max);
  1029. return Math.floor(Math.random() * (max - min + 1) + min);
  1030. },
  1031. /**
  1032. * Returns a random divisor for a given number.
  1033. *
  1034. * @param {number} number number
  1035. *
  1036. * @returns {number} random divisor for that number
  1037. */
  1038. randomDivisor: function (number) {
  1039. const validDivisors = [];
  1040. // If 'number' can be divided by 'i', add to list of 'validDivisors'
  1041. for (let i = 2; i < number; i++) {
  1042. if (number % i == 0) validDivisors.push(i);
  1043. }
  1044. const randIndex = game.math.randomInRange(0, validDivisors.length - 1);
  1045. return validDivisors[randIndex];
  1046. },
  1047. /**
  1048. * Converts degree to radian.
  1049. *
  1050. * @param {number} degree number in degrees
  1051. *
  1052. * @returns {number} its radian equivalent
  1053. */
  1054. degreeToRad: function (degree) {
  1055. return (degree * Math.PI) / 180;
  1056. },
  1057. getRadiusFromCircunference: function (circunference) {
  1058. return circunference / (2 * Math.PI);
  1059. },
  1060. /**
  1061. * Returns distance from the center of an icon to mouse/pointer (radius).
  1062. *
  1063. * @param {number} xMouse mouse x coordinate
  1064. * @param {number} xIcon icon x coordinate
  1065. * @param {number} yMouse mouse y coordinate
  1066. * @param {number} yIcon icon y coordinate
  1067. *
  1068. * @returns {number} distance between the two icons
  1069. */
  1070. distanceToPointer: function (xMouse, xIcon, yMouse, yIcon) {
  1071. const a = Math.max(xMouse, xIcon) - Math.min(xMouse, xIcon);
  1072. const b = Math.max(yMouse, yIcon) - Math.min(yMouse, yIcon);
  1073. return Math.sqrt(a * a + b * b);
  1074. },
  1075. mdc: function (num1, num2) {
  1076. if (num2 === 0) return num1;
  1077. return game.math.mdc(num2, num1 % num2);
  1078. },
  1079. mmcArray: (input) => {
  1080. if (toString.call(input) !== '[object Array]') return false;
  1081. var len, a, b;
  1082. len = input.length;
  1083. if (!len) {
  1084. return null;
  1085. }
  1086. a = input[0];
  1087. for (var i = 1; i < len; i++) {
  1088. b = input[i];
  1089. a = game.math.mmcTwoNumbers(a, b);
  1090. }
  1091. return a;
  1092. },
  1093. mmcTwoNumbers: (num1, num2) => {
  1094. var resto, x, y;
  1095. x = num1;
  1096. y = num2;
  1097. while (resto != 0) {
  1098. resto = x % y;
  1099. x = y;
  1100. y = resto;
  1101. }
  1102. return (num1 * num2) / x;
  1103. },
  1104. getFractionFromDecimal: function (fraction) {
  1105. const len = fraction.toString().length - 2;
  1106. let denominator = Math.pow(10, len);
  1107. let numerator = fraction * denominator;
  1108. const divisor = game.math.greatestCommonDivisor(numerator, denominator);
  1109. numerator /= divisor;
  1110. denominator /= divisor;
  1111. return {
  1112. string: Math.floor(numerator) + '/' + Math.floor(denominator),
  1113. numerator: Math.floor(numerator),
  1114. denominator: Math.floor(denominator),
  1115. };
  1116. },
  1117. /**
  1118. * Checks if pointer/mouse is over (rectangular) icon.
  1119. *
  1120. * @param {number} xMouse contains the mouse x coordinate
  1121. * @param {number} yMouse contains the mouse y coordinate
  1122. * @param {object} icon icon
  1123. *
  1124. * @returns {boolean} true if cursor is over icon
  1125. */
  1126. isOverIcon: function (xMouse, yMouse, icon) {
  1127. const x = xMouse,
  1128. y = yMouse,
  1129. cur = icon;
  1130. return (
  1131. y >= cur.yWithAnchor &&
  1132. y <= cur.yWithAnchor + cur.height * cur.scale &&
  1133. x >= cur.xWithAnchor &&
  1134. x <= cur.xWithAnchor + cur.width * cur.scale
  1135. );
  1136. },
  1137. /**
  1138. * Checks if 2 images overlap
  1139. *
  1140. * @param {object} imageA image 1
  1141. * @param {object} imageB image 2
  1142. *
  1143. * @returns {boolean} true if there is overlap
  1144. */
  1145. isOverlap: function (imageA, imageB) {
  1146. const xA = imageA.x;
  1147. const xB = imageB.x;
  1148. // Consider it comming from both sides
  1149. return !(Math.abs(xA - xB) > 14);
  1150. },
  1151. /**
  1152. * Get mouse position coordinates
  1153. *
  1154. * @param {object} mouseEvent
  1155. * @returns {object} x and y mouse coordinates
  1156. */
  1157. getMouse: function (mouseEvent) {
  1158. const c = context.canvas.getBoundingClientRect();
  1159. const canvas_scale = context.canvas.width / parseFloat(c.width);
  1160. return {
  1161. x: (mouseEvent.clientX - c.left) * canvas_scale,
  1162. y: (mouseEvent.clientY - c.top) * canvas_scale,
  1163. };
  1164. },
  1165. /**
  1166. * Calculate spacing for icons on the menu screen
  1167. *
  1168. * @param {number} width width of the desirable part of the screen
  1169. * @param {number} numberOfIcons number or icons to be put on the screen
  1170. *
  1171. * @returns {number} correct spacing between icons
  1172. */
  1173. getOffset: function (width, numberOfIcons) {
  1174. return width / (numberOfIcons + 1);
  1175. },
  1176. /**
  1177. * Converts a given time in seconds (number) to the format HH:MM:SS (string)
  1178. *
  1179. * @param {number} s time in seconds
  1180. *
  1181. * @returns {string} time in the format HH:MM:SS
  1182. */
  1183. convertTime: function (s) {
  1184. let h = 0,
  1185. m = 0;
  1186. if (s > 1200) {
  1187. h = s / 1200;
  1188. s = s % 1200;
  1189. }
  1190. if (s > 60) {
  1191. m = s / 60;
  1192. s = s % 60;
  1193. }
  1194. h = '' + h;
  1195. m = '' + m;
  1196. s = '' + s;
  1197. if (h.length < 2) h = '0' + h;
  1198. if (m.length < 2) m = '0' + m;
  1199. if (s.length < 2) s = '0' + s;
  1200. return h + ':' + m + ':' + s;
  1201. },
  1202. },
  1203. /**
  1204. * Timer used to get the time spent to complete a game.
  1205. *
  1206. * @namespace
  1207. */
  1208. timer: {
  1209. // [Not directly used] Start time.
  1210. _start: 0,
  1211. // [Not directly used] End time.
  1212. end: 0,
  1213. // Elapsed time.
  1214. elapsed: 0,
  1215. /**
  1216. * Reset values and start timer.
  1217. */
  1218. start: function () {
  1219. game.timer._start = game.timer.end = game.timer.elapsed = 0;
  1220. game.timer._start = new Date().getTime();
  1221. },
  1222. /**
  1223. * Stop timer and set elapsed time.
  1224. */
  1225. stop: function () {
  1226. if (game.timer._start != 0 && game.timer.end == 0) {
  1227. // If timer has started but not finished
  1228. game.timer.end = new Date().getTime();
  1229. game.timer.elapsed = Math.floor(
  1230. (game.timer.end - game.timer._start) / 1000
  1231. );
  1232. }
  1233. },
  1234. },
  1235. /**
  1236. * Handles pointer events. <br>
  1237. *
  1238. * @namespace
  1239. */
  1240. event: {
  1241. // [Not directly used] List of events in current state.
  1242. list: [],
  1243. /**
  1244. * Adds new event to current state.
  1245. *
  1246. * @param {string} name event name, can be: 'click' or 'mousemove'
  1247. * @param {function} func function to be called when event is triggered
  1248. */
  1249. add: function (name, func) {
  1250. context.canvas.addEventListener(name, func);
  1251. game.event.list.push([name, func]);
  1252. },
  1253. /** [Not directly used] Clears list of events. Called before moving to new state.
  1254. */
  1255. clear: function () {
  1256. game.event.list.forEach((cur) => {
  1257. context.canvas.removeEventListener(cur[0], cur[1]);
  1258. });
  1259. game.event.list = [];
  1260. },
  1261. },
  1262. /** [Not directly used] Handles 'game loop'. <br>
  1263. *
  1264. * After the media queue is filled in create(), the 'game loop' starts.
  1265. * It calls update() iteratively, re-rendering the screen every time. <br>
  1266. *
  1267. * The 'game loop' is stoped by leaving the current state.
  1268. *
  1269. * @namespace
  1270. */
  1271. loop: {
  1272. // [Not directly used] Holds animation event.
  1273. id: undefined,
  1274. // [Not directly used] State that called the loop.
  1275. curState: undefined,
  1276. // [Not directly used] Loop status, can be: 'on', 'ending' or 'off'.
  1277. status: 'off',
  1278. // [Not directly used]
  1279. waitingToStart: undefined,
  1280. // [Not directly used]
  1281. startTime: 0,
  1282. // [Not directly used] 1000: 1 second | 60: expected frames per second.
  1283. duration: 1000 / 60,
  1284. /** [Not directly used] Starts game loop.
  1285. *
  1286. * @param {object} state current state
  1287. */
  1288. start: function (state) {
  1289. if (game.loop.status == 'off') {
  1290. game.loop.curState = state;
  1291. game.loop.startTime = new Date().getTime();
  1292. game.loop.status = 'on';
  1293. game.loop.id = requestAnimationFrame(game.loop.run);
  1294. } else {
  1295. // If 'game.loop.status' is either 'on' or 'ending'
  1296. game.loop.waitingToStart = state;
  1297. if (game.loop.status == 'on') game.loop.stop();
  1298. }
  1299. },
  1300. /**
  1301. * [Not directly used] Stops game loop.
  1302. */
  1303. stop: function () {
  1304. if (game.loop.status == 'on') game.loop.status = 'ending';
  1305. },
  1306. /**
  1307. * [Not directly used] Executes game loop.
  1308. *
  1309. * This code will run on each iteration of the game loop.
  1310. */
  1311. run: function () {
  1312. if (game.loop.status != 'on') {
  1313. game.loop.clear();
  1314. } else {
  1315. const timestamp = new Date().getTime();
  1316. const runtime = timestamp - game.loop.startTime;
  1317. if (runtime >= game.loop.duration) {
  1318. // Calls state's update()
  1319. game.loop.curState.update();
  1320. // Updates state's animation
  1321. game.animation.run();
  1322. }
  1323. game.loop.id = requestAnimationFrame(game.loop.run); // Loop
  1324. }
  1325. },
  1326. /**
  1327. * [Not directly used] Resets game loop values.
  1328. */
  1329. clear: function () {
  1330. if (game.loop.id != undefined) {
  1331. cancelAnimationFrame(game.loop.id); // Cancel animation event
  1332. game.loop.id = undefined; // Clears object that holds animation event
  1333. game.loop.curState = undefined; // Clears object that holds current state
  1334. game.loop.status = 'off'; // Inform animation must end (read in game.loop.run())
  1335. }
  1336. if (game.loop.waitingToStart != undefined) {
  1337. const temp = game.loop.waitingToStart;
  1338. game.loop.waitingToStart = undefined;
  1339. game.loop.start(temp);
  1340. }
  1341. },
  1342. },
  1343. /**
  1344. * Handles spritesheet animation. <br>
  1345. * It iterates through the spritesheet frames inside the animation queue.
  1346. * Called by game loop.
  1347. *
  1348. * @namespace
  1349. */
  1350. animation: {
  1351. // [Not directly used] Animation queue for the current state.
  1352. queue: [],
  1353. // [Not directly used]
  1354. count: 0,
  1355. /**
  1356. * Plays animation.
  1357. *
  1358. * @param {string} name animation name (identifier)
  1359. */
  1360. play: function (name) {
  1361. let newAnimation;
  1362. // Gets first object in the 'render queue' with that animation name
  1363. for (let i in game.render.queue) {
  1364. if (
  1365. game.render.queue[i].animation != undefined &&
  1366. game.render.queue[i].animation[0] == name
  1367. ) {
  1368. newAnimation = game.render.queue[i];
  1369. break;
  1370. }
  1371. }
  1372. // If found, saves object in the 'animation queue'
  1373. if (newAnimation != undefined) game.animation.queue.push(newAnimation);
  1374. },
  1375. /**
  1376. * Stops animation.
  1377. *
  1378. * @param {string} name animation name
  1379. */
  1380. stop: function (name) {
  1381. // Removes all with that name from the 'animation queue'
  1382. game.animation.queue.forEach((cur) => {
  1383. if (cur.animation[0] == name) {
  1384. game.animation.queue.splice(cur, 1);
  1385. }
  1386. });
  1387. },
  1388. /**
  1389. * [Not directly used] Executes animation.
  1390. */
  1391. run: function () {
  1392. game.animation.queue.forEach((character) => {
  1393. if (
  1394. !character.animation[2] ||
  1395. game.animation.count % character.animation[2] == 0
  1396. ) {
  1397. const i = character.animation[1].indexOf(character.curFrame);
  1398. if (i == -1) {
  1399. // Frame not found
  1400. if (isDebugMode)
  1401. console.error('Game error: animation frame not found.');
  1402. } else if (i < character.animation[1].length - 1) {
  1403. // Go to next frame
  1404. character.curFrame = character.animation[1][i + 1];
  1405. } else {
  1406. character.curFrame = character.animation[1][0]; // If last frame, restart
  1407. }
  1408. }
  1409. });
  1410. game.animation.count++;
  1411. },
  1412. /**
  1413. * [Not directly used] Clears animation queue.
  1414. */
  1415. clear: function () {
  1416. // Resets animation counter
  1417. game.animation.count = 0;
  1418. // Clears property 'animation' from objects in game.render.queue
  1419. game.render.queue.forEach((cur) => {
  1420. if (cur.animation != undefined) {
  1421. delete cur.animation;
  1422. }
  1423. });
  1424. // Clears animation queue
  1425. game.animation.queue = [];
  1426. },
  1427. },
  1428. };