gameMechanics.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  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. * @param {object|undefined} lineHeight space between current and next paragraph
  467. *
  468. * @returns {object} a reference to the created text.
  469. */
  470. text: function (x, y, text, style, lineHeight) {
  471. if (
  472. x == undefined ||
  473. y == undefined ||
  474. text == undefined ||
  475. style == undefined
  476. ) {
  477. console.error('Game error: missing parameters.');
  478. } else {
  479. const med = {
  480. typeOfMedia: 'text',
  481. name: style?.increaseLetterSpacing
  482. ? text.split('').join(String.fromCharCode(8202))
  483. : text,
  484. x: x || game.add.default.x,
  485. y: y || game.add.default.y,
  486. _xWithAnchor: x || game.add.default._xWithAnchor,
  487. _yWithAnchor: y || game.add.default._yWithAnchor,
  488. xAnchor: game.add.default.xAnchor,
  489. yAnchor: game.add.default.yAnchor,
  490. shadow: game.add.default.shadow,
  491. shadowColor: game.add.default.shadowColor,
  492. shadowBlur: game.add.default.shadowBlur,
  493. alpha: game.add.default.alpha,
  494. font: style.font || game.add.default.font,
  495. fill: style.fill || game.add.default.fill,
  496. align: style.align || game.add.default.align,
  497. lineHeight: lineHeight || game.add.default.lineHeight,
  498. anchor: function () {
  499. console.error("Game error: there's no anchor for text.");
  500. },
  501. set style(style) {
  502. this.font = style.font;
  503. this.fill = style.fill;
  504. this.align = style.align;
  505. },
  506. get xWithAnchor() {
  507. return this.x;
  508. },
  509. get yWithAnchor() {
  510. return this.y;
  511. },
  512. };
  513. game.render.queue.push(med);
  514. return med;
  515. }
  516. },
  517. /**
  518. * Adds geometric shapes.
  519. * @namespace
  520. */
  521. geom: {
  522. /**
  523. * Adds rectangle to media queue.
  524. *
  525. * @param {number} x x coordinate for top left corner of the rectangle
  526. * @param {number} y y coordinate for top left corner of the rectangle
  527. * @param {number} width rectangle width (default = 50)
  528. * @param {undefined|number} height rectangle height (default = 50)
  529. * @param {undefined|string} lineColor stroke color (default = black)
  530. * @param {undefined|number} lineWidth stroke width (default = 1px)
  531. * @param {undefined|string} fillColor fill color (default = no fill)
  532. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  533. *
  534. * @returns {object} a reference to the created rectangle.
  535. */
  536. rect: function (
  537. x,
  538. y,
  539. width,
  540. height,
  541. fillColor,
  542. alpha,
  543. lineColor,
  544. lineWidth
  545. ) {
  546. if (x == undefined || y == undefined || width == undefined)
  547. console.error('Game error: missing parameters.');
  548. else {
  549. const med = {
  550. typeOfMedia: 'rect',
  551. x: x || game.add.default.x,
  552. y: y || game.add.default.y,
  553. _xWithAnchor: x || game.add.default._xWithAnchor,
  554. _yWithAnchor: y || game.add.default._yWithAnchor,
  555. xAnchor: game.add.default.xAnchor,
  556. yAnchor: game.add.default.yAnchor,
  557. shadow: game.add.default.shadow,
  558. shadowColor: game.add.default.shadowColor,
  559. shadowBlur: game.add.default.shadowBlur,
  560. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  561. scale: game.add.default.scale,
  562. width: 0,
  563. height: 0,
  564. lineColor: lineColor || game.add.default.lineColor,
  565. lineWidth: 0,
  566. fillColor: fillColor || game.add.default.fillColor,
  567. anchor: function (xAnchor, yAnchor) {
  568. this.xAnchor = xAnchor;
  569. this.yAnchor = yAnchor;
  570. },
  571. get xWithAnchor() {
  572. return this.x - this.width * this.scale * this.xAnchor;
  573. },
  574. get yWithAnchor() {
  575. return this.y - this.height * this.scale * this.yAnchor;
  576. },
  577. };
  578. med.initialScale = med.scale;
  579. if (width != 0) {
  580. med.width = width || game.add.default.width;
  581. }
  582. if (height != 0) {
  583. med.height = height || width || game.add.default.height;
  584. }
  585. if (lineWidth != 0) {
  586. med.lineWidth = lineWidth || game.add.default.lineWidth;
  587. }
  588. game.render.queue.push(med);
  589. return med;
  590. }
  591. },
  592. /**
  593. * Adds line to media queue.
  594. *
  595. * @param {number} x x coordinate for top left corner of the rectangle
  596. * @param {number} y y coordinate for top left corner of the rectangle
  597. * @param {number} width rectangle width (default = 50)
  598. * @param {undefined|number} lineWidth stroke width (default = 1px)
  599. * @param {undefined|string} lineColor stroke color (default = black)
  600. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  601. *
  602. * @returns {object} a reference to the created rectangle.
  603. */
  604. line: function (x0, y0, x1, y1, lineWidth, lineColor, alpha) {
  605. if (x0 == undefined || y0 == undefined)
  606. console.error('Game error: missing parameters.');
  607. else {
  608. const med = {
  609. typeOfMedia: 'line',
  610. x0: x0 || game.add.default.x,
  611. y0: y0 || game.add.default.y,
  612. x1: x1 || x0 + 50,
  613. y1: y1 || y0,
  614. x0Anchor: 0,
  615. y0Anchor: 0,
  616. x1Anchor: 0,
  617. y1Anchor: 0,
  618. shadow: game.add.default.shadow,
  619. shadowColor: game.add.default.shadowColor,
  620. shadowBlur: game.add.default.shadowBlur,
  621. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  622. width: 0,
  623. lineColor: lineColor || game.add.default.lineColor,
  624. lineWidth: lineWidth || 1,
  625. anchor: function (xAnchor, yAnchor) {
  626. this.x0Anchor = xAnchor;
  627. this.y0Anchor = yAnchor;
  628. this.x1Anchor = xAnchor;
  629. this.y1Anchor = yAnchor;
  630. },
  631. get x0WithAnchor() {
  632. return this.x0 - this.width * this.x0Anchor;
  633. },
  634. get y0WithAnchor() {
  635. return this.y0 - this.width * this.y0Anchor;
  636. },
  637. get x1WithAnchor() {
  638. return this.x1 - this.width * this.x1Anchor;
  639. },
  640. get y1WithAnchor() {
  641. return this.y1 - this.width * this.y1Anchor;
  642. },
  643. get x() {
  644. return this.x0;
  645. },
  646. get y() {
  647. return this.y0;
  648. },
  649. set x(x0) {
  650. const distance = this.x1 - this.x0;
  651. this.x0 = x0;
  652. this.x1 = x0 + distance;
  653. },
  654. set y(y0) {
  655. const distance = this.y1 - this.y0;
  656. this.y0 = y0;
  657. this.y1 = y0 + distance;
  658. },
  659. };
  660. const width =
  661. (med.x1 - x0) * (med.x1 - x0) + (med.y1 - y0) * (med.y1 - y0);
  662. med.width = Math.sqrt(width);
  663. game.render.queue.push(med);
  664. return med;
  665. }
  666. },
  667. /**
  668. * Adds circle to media queue.
  669. *
  670. * @param {number} x x coordinate for the circle center
  671. * @param {number} y y coordinate for the circle center
  672. * @param {number} diameter circle diameter (default = 50)
  673. * @param {undefined|string} lineColor stroke color (default = black)
  674. * @param {undefined|number} lineWidth stroke width (default = 1px)
  675. * @param {undefined|string} fillColor fill color (default = no fill)
  676. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  677. *
  678. * @returns {object} a reference to the created circle.
  679. */
  680. circle: function (
  681. x,
  682. y,
  683. diameter,
  684. lineColor,
  685. lineWidth,
  686. fillColor,
  687. alpha
  688. ) {
  689. if (x == undefined || y == undefined || diameter == undefined)
  690. console.error('Game error: missing parameters.');
  691. else {
  692. const med = {
  693. typeOfMedia: 'arc',
  694. x: x || game.add.default.x,
  695. y: y || game.add.default.y,
  696. _xWithAnchor: x || game.add.default._xWithAnchor,
  697. _yWithAnchor: y || game.add.default._yWithAnchor,
  698. xAnchor: game.add.default.xAnchor,
  699. yAnchor: game.add.default.yAnchor,
  700. shadow: game.add.default.shadow,
  701. shadowColor: game.add.default.shadowColor,
  702. shadowBlur: game.add.default.shadowBlur,
  703. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  704. scale: game.add.default.scale,
  705. diameter: 0,
  706. width: 0,
  707. height: 0,
  708. angleStart: 0,
  709. angleEnd: 2 * Math.PI,
  710. counterclockwise: game.add.default.counterclockwise,
  711. lineColor: lineColor || game.add.default.lineColor,
  712. lineWidth: 0,
  713. fillColor: fillColor || game.add.default.fillColor,
  714. anchor: function (xAnchor, yAnchor) {
  715. this.xAnchor = xAnchor;
  716. this.yAnchor = yAnchor;
  717. },
  718. get xWithAnchor() {
  719. return this.x - this.width * this.scale * this.xAnchor;
  720. },
  721. get yWithAnchor() {
  722. return this.y - this.height * this.scale * this.yAnchor;
  723. },
  724. };
  725. med.initialScale = med.scale;
  726. if (diameter != 0) {
  727. med.diameter = diameter || game.add.default.diameter;
  728. med.width = med.height = med.diameter;
  729. }
  730. if (lineWidth != 0) {
  731. med.lineWidth = lineWidth || game.add.default.lineWidth;
  732. }
  733. game.render.queue.push(med);
  734. return med;
  735. }
  736. },
  737. /**
  738. * Adds arc to media queue.
  739. *
  740. * @param {number} x x coordinate for the arc center
  741. * @param {number} y y coordinate for the arc center
  742. * @param {number} diameter arc diameter
  743. * @param {number} angleStart angle to start the arc
  744. * @param {number} angleEnd angle to end the arc
  745. * @param {undefined|boolean} counterclockwise if true, arc is created counterclockwise (default = false)
  746. * @param {undefined|string} lineColor stroke color (default = black)
  747. * @param {undefined|number} lineWidth stroke width (default = 1px)
  748. * @param {undefined|string} fillColor fill color (default = no fill)
  749. * @param {undefined|number} alpha level of transparency, from 0 (invisible) to 1 (100% visible)) (default = 1)
  750. *
  751. * @returns {object} a reference to the created arc.
  752. */
  753. arc: function (
  754. x,
  755. y,
  756. diameter,
  757. angleStart,
  758. angleEnd,
  759. counterclockwise,
  760. lineColor,
  761. lineWidth,
  762. fillColor,
  763. alpha
  764. ) {
  765. if (
  766. x == undefined ||
  767. y == undefined ||
  768. diameter == undefined ||
  769. angleStart == undefined ||
  770. angleEnd == undefined
  771. )
  772. console.error('Game error: missing parameters.');
  773. else {
  774. const med = {
  775. typeOfMedia: 'arc',
  776. x: x || game.add.default.x,
  777. y: y || game.add.default.y,
  778. _xWithAnchor: x || game.add.default._xWithAnchor,
  779. _yWithAnchor: y || game.add.default._yWithAnchor,
  780. xAnchor: game.add.default.xAnchor,
  781. yAnchor: game.add.default.yAnchor,
  782. shadow: game.add.default.shadow,
  783. shadowColor: game.add.default.shadowColor,
  784. shadowBlur: game.add.default.shadowBlur,
  785. alpha: alpha != undefined ? alpha : game.add.default.alpha,
  786. scale: game.add.default.scale,
  787. diameter: 0,
  788. width: 0,
  789. height: 0,
  790. angleStart: angleStart || 0,
  791. angleEnd: angleEnd || 2 * Math.PI,
  792. counterclockwise:
  793. counterclockwise || game.add.default.counterclockwise,
  794. lineColor: lineColor || game.add.default.lineColor,
  795. lineWidth: 0,
  796. fillColor: fillColor || game.add.default.fillColor,
  797. anchor: function (xAnchor, yAnchor) {
  798. this.xAnchor = xAnchor;
  799. this.yAnchor = yAnchor;
  800. },
  801. get xWithAnchor() {
  802. return this.x - this.width * this.scale * this.xAnchor;
  803. },
  804. get yWithAnchor() {
  805. return this.y - this.height * this.scale * this.yAnchor;
  806. },
  807. };
  808. med.initialScale = med.scale;
  809. if (diameter != 0) {
  810. med.diameter = diameter || game.add.default.diameter;
  811. med.width = med.height = med.diameter;
  812. }
  813. if (lineWidth != 0) {
  814. med.lineWidth = lineWidth || game.add.default.lineWidth;
  815. }
  816. game.render.queue.push(med);
  817. return med;
  818. }
  819. },
  820. },
  821. /**
  822. * [Not directly used] Default values for the media properties.
  823. */
  824. default: {
  825. // Used in: all types of media.
  826. x: 0,
  827. y: 0,
  828. _xWithAnchor: 0,
  829. _yWithAnchor: 0,
  830. xAnchor: 0,
  831. yAnchor: 0,
  832. shadow: false,
  833. shadowColor: '#0075c5',
  834. shadowBlur: 20,
  835. alpha: 1,
  836. // Used in: image, sprite, square, circle.
  837. scale: 1,
  838. // Used in: text.
  839. font: '14px Arial,sans-serif',
  840. fill: '#000',
  841. align: 'center',
  842. lineHeight: 50,
  843. // Used in: square, circle (image and sprite have width and height, but do not have default values).
  844. width: 50,
  845. height: 50,
  846. lineColor: '#000',
  847. lineWidth: 0, // No line
  848. fillColor: '#fff', // white fill
  849. // Used in: circle.
  850. diameter: 50,
  851. counterclockwise: false,
  852. },
  853. },
  854. /**
  855. * Renders media on current screen. <br<
  856. * It uses properties of html canvas to draw media on screen during game loop.
  857. *
  858. * @namespace
  859. */
  860. render: {
  861. // [Not directly used] Media queue to be rendered on the current state.
  862. queue: [],
  863. /** [Not directly used] Renders image on canvas.
  864. *
  865. * @param {object} cur current media in media queue
  866. */
  867. image: function (cur) {
  868. const x = cur.xWithAnchor,
  869. y = cur.yWithAnchor;
  870. // Rotation
  871. if (cur.rotate && cur.rotate != 0) {
  872. context.save();
  873. context.translate(cur.x, cur.y);
  874. context.rotate((cur.rotate * Math.PI) / 180);
  875. context.translate(-cur.x, -cur.y);
  876. }
  877. // Alpha
  878. context.globalAlpha = cur.alpha;
  879. // Shadow
  880. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  881. context.shadowColor = cur.shadowColor;
  882. // Image
  883. context.drawImage(
  884. game.image[cur.name],
  885. x,
  886. y,
  887. cur.width * cur.scale,
  888. cur.height * cur.scale
  889. );
  890. // End
  891. context.shadowBlur = 0;
  892. context.globalAlpha = 1;
  893. if (cur.rotate && cur.rotate != 0) context.restore();
  894. },
  895. /** [Not directly used] Renders spritesheet on canvas.
  896. *
  897. * @param {object} cur current media in media queue
  898. */
  899. sprite: function (cur) {
  900. const x = cur.xWithAnchor,
  901. y = cur.yWithAnchor;
  902. // Rotation
  903. if (cur.rotate && cur.rotate != 0) {
  904. context.save();
  905. context.translate(cur.x, cur.y);
  906. context.rotate((cur.rotate * Math.PI) / 180);
  907. context.translate(-cur.x, -cur.y);
  908. }
  909. // Alpha
  910. context.globalAlpha = cur.alpha;
  911. // Shadow
  912. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  913. context.shadowColor = cur.shadowColor;
  914. // Image
  915. context.drawImage(
  916. game.sprite[cur.name],
  917. cur.width * cur.curFrame,
  918. 0,
  919. cur.width,
  920. cur.height,
  921. x,
  922. y,
  923. cur.width * cur.scale,
  924. cur.height * cur.scale
  925. );
  926. // End
  927. context.shadowBlur = 0;
  928. context.globalAlpha = 1;
  929. if (cur.rotate && cur.rotate != 0) context.restore();
  930. },
  931. /** [Not directly used] Renders text on canvas.
  932. *
  933. * @param {object} cur current media in media queue
  934. */
  935. text: function (cur) {
  936. const x = cur.xWithAnchor,
  937. y = cur.yWithAnchor;
  938. // Rotation
  939. if (cur.rotate && cur.rotate != 0) {
  940. context.save();
  941. context.translate(cur.x, cur.y);
  942. context.rotate((cur.rotate * Math.PI) / 180);
  943. context.translate(-cur.x, -cur.y);
  944. }
  945. // Alpha
  946. context.globalAlpha = cur.alpha;
  947. // Shadow
  948. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  949. context.shadowColor = cur.shadowColor;
  950. // Font style
  951. context.font = cur.font;
  952. context.textAlign = cur.align;
  953. context.fillStyle = cur.fill;
  954. // Text
  955. const paragraphs = String(cur.name).split('\n');
  956. let newY = y;
  957. for (let line in paragraphs) {
  958. context.fillText(paragraphs[line], x, newY);
  959. newY += cur.lineHeight;
  960. }
  961. // End
  962. context.shadowBlur = 0;
  963. context.globalAlpha = 1;
  964. if (cur.rotate && cur.rotate != 0) context.restore();
  965. },
  966. /** [Not directly used] Renders geometric shapes on canvas.
  967. *
  968. * @namespace
  969. */
  970. geom: {
  971. /**
  972. * Renders rectangle on canvas.
  973. *
  974. * @param {object} cur current media in media queue
  975. */
  976. rect: function (cur) {
  977. const x = cur.xWithAnchor,
  978. y = cur.yWithAnchor;
  979. // Rotation
  980. if (cur.rotate && cur.rotate != 0) {
  981. context.save();
  982. context.translate(cur.x, cur.y);
  983. context.rotate((cur.rotate * Math.PI) / 180);
  984. context.translate(-cur.x, -cur.y);
  985. }
  986. // Alpha
  987. context.globalAlpha = cur.alpha;
  988. // Shadow
  989. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  990. context.shadowColor = cur.shadowColor;
  991. // Fill
  992. if (cur.fillColor !== 'transparent') {
  993. context.fillStyle = cur.fillColor;
  994. context.fillRect(x, y, cur.width * cur.scale, cur.height * cur.scale);
  995. }
  996. // Stroke
  997. if (cur.lineWidth != 0) {
  998. context.strokeStyle = cur.lineColor;
  999. context.lineWidth = cur.lineWidth;
  1000. context.strokeRect(
  1001. x,
  1002. y,
  1003. cur.width * cur.scale,
  1004. cur.height * cur.scale
  1005. );
  1006. }
  1007. // End
  1008. context.shadowBlur = 0;
  1009. context.globalAlpha = 1;
  1010. if (cur.rotate && cur.rotate != 0) context.restore();
  1011. },
  1012. /**
  1013. * Renders line on canvas.
  1014. *
  1015. * @param {object} cur current media in media queue
  1016. */
  1017. line: function (cur) {
  1018. const x0 = cur.x0WithAnchor,
  1019. y0 = cur.y0WithAnchor,
  1020. x1 = cur.x1WithAnchor,
  1021. y1 = cur.y1WithAnchor;
  1022. // Rotation
  1023. if (cur.rotate && cur.rotate != 0) {
  1024. context.save();
  1025. context.translate(cur.x0, cur.y0);
  1026. context.rotate((cur.rotate * Math.PI) / 180);
  1027. context.translate(-cur.x0, -cur.y0);
  1028. }
  1029. // Alpha
  1030. context.globalAlpha = cur.alpha;
  1031. // Shadow
  1032. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  1033. context.shadowColor = cur.shadowColor;
  1034. // Stroke
  1035. if (cur.lineWidth != 0) {
  1036. context.strokeStyle = cur.lineColor;
  1037. context.lineWidth = cur.lineWidth;
  1038. context.beginPath();
  1039. context.moveTo(x0, y0);
  1040. context.lineTo(x1, y1);
  1041. context.stroke();
  1042. }
  1043. // End
  1044. context.shadowBlur = 0;
  1045. context.globalAlpha = 1;
  1046. if (cur.rotate && cur.rotate != 0) context.restore();
  1047. },
  1048. /**
  1049. * Renders arc on canvas (arc or circle).
  1050. *
  1051. * @param {object} cur current media in media queue
  1052. */
  1053. arc: function (cur) {
  1054. const x = cur.xWithAnchor,
  1055. y = cur.yWithAnchor;
  1056. // Rotation
  1057. if (cur.rotate && cur.rotate != 0) {
  1058. context.save();
  1059. context.translate(cur.x, cur.y);
  1060. context.rotate((cur.rotate * Math.PI) / 180);
  1061. context.translate(-cur.x, -cur.y);
  1062. }
  1063. // Alpha
  1064. context.globalAlpha = cur.alpha;
  1065. // Shadow
  1066. context.shadowBlur = cur.shadow ? cur.shadowBlur : 0;
  1067. context.shadowColor = cur.shadowColor;
  1068. // Fill info
  1069. if (cur.fillColor != 0) context.fillStyle = cur.fillColor;
  1070. // Stroke info
  1071. if (cur.lineWidth != 0) {
  1072. context.strokeStyle = cur.lineColor;
  1073. context.lineWidth = cur.lineWidth;
  1074. }
  1075. // Path
  1076. context.beginPath();
  1077. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  1078. context.arc(
  1079. x,
  1080. y,
  1081. (cur.diameter / 2) * cur.scale,
  1082. cur.angleStart,
  1083. cur.angleEnd,
  1084. cur.counterclockwise
  1085. );
  1086. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  1087. // End
  1088. if (cur.fillColor != 0) context.fill();
  1089. if (cur.lineWidth != 0) context.stroke();
  1090. context.shadowBlur = 0;
  1091. context.globalAlpha = 1;
  1092. if (cur.rotate && cur.rotate != 0) context.restore();
  1093. },
  1094. },
  1095. /**
  1096. * Renders all queued media on screen. Called repeatedly by the game loop.
  1097. */
  1098. all: function () {
  1099. game.render.queue.forEach((cur) => {
  1100. switch (cur.typeOfMedia) {
  1101. case 'image':
  1102. this.image(cur);
  1103. break;
  1104. case 'sprite':
  1105. this.sprite(cur);
  1106. break;
  1107. case 'text':
  1108. this.text(cur);
  1109. break;
  1110. case 'rect':
  1111. this.geom.rect(cur);
  1112. break;
  1113. case 'line':
  1114. this.geom.line(cur);
  1115. break;
  1116. case 'arc':
  1117. this.geom.arc(cur);
  1118. break;
  1119. }
  1120. });
  1121. },
  1122. /**
  1123. * Clears media queue (used when changing states).
  1124. */
  1125. clear: function () {
  1126. game.render.queue = [];
  1127. },
  1128. },
  1129. /**
  1130. * Math functions.
  1131. *
  1132. * @namespace
  1133. */
  1134. math: {
  1135. /**
  1136. * Returns a random integer in a range (inclusive for min and max).
  1137. *
  1138. * @param {number} min smaller integer
  1139. * @param {number} max larger integer
  1140. *
  1141. * @returns {number} random integer in range
  1142. */
  1143. randomInRange: function (min, max) {
  1144. min = Math.ceil(min);
  1145. max = Math.floor(max);
  1146. return Math.floor(Math.random() * (max - min + 1) + min);
  1147. },
  1148. /**
  1149. * Returns a random divisor for a given number.
  1150. *
  1151. * @param {number} number number
  1152. *
  1153. * @returns {number} random divisor for that number
  1154. */
  1155. randomDivisor: function (number) {
  1156. const validDivisors = [];
  1157. // If 'number' can be divided by 'i', add to list of 'validDivisors'
  1158. for (let i = 2; i < number; i++) {
  1159. if (number % i == 0) validDivisors.push(i);
  1160. }
  1161. const randIndex = game.math.randomInRange(0, validDivisors.length - 1);
  1162. return validDivisors[randIndex];
  1163. },
  1164. /**
  1165. * Converts degree to radian.
  1166. *
  1167. * @param {number} degree number in degrees
  1168. *
  1169. * @returns {number} its radian equivalent
  1170. */
  1171. degreeToRad: function (degree) {
  1172. return (degree * Math.PI) / 180;
  1173. },
  1174. getRadiusFromCircunference: function (circunference) {
  1175. return circunference / (2 * Math.PI);
  1176. },
  1177. /**
  1178. * Returns distance from the center of an icon to mouse/pointer (radius).
  1179. *
  1180. * @param {number} xMouse mouse x coordinate
  1181. * @param {number} xIcon icon x coordinate
  1182. * @param {number} yMouse mouse y coordinate
  1183. * @param {number} yIcon icon y coordinate
  1184. *
  1185. * @returns {number} distance between the two icons
  1186. */
  1187. distanceToPointer: function (xMouse, xIcon, yMouse, yIcon) {
  1188. const a = Math.max(xMouse, xIcon) - Math.min(xMouse, xIcon);
  1189. const b = Math.max(yMouse, yIcon) - Math.min(yMouse, yIcon);
  1190. return Math.sqrt(a * a + b * b);
  1191. },
  1192. mdc: function (num1, num2) {
  1193. if (num2 === 0) return num1;
  1194. return game.math.mdc(num2, num1 % num2);
  1195. },
  1196. mmcArray: (input) => {
  1197. if (toString.call(input) !== '[object Array]') return false;
  1198. var len, a, b;
  1199. len = input.length;
  1200. if (!len) {
  1201. return null;
  1202. }
  1203. a = input[0];
  1204. for (var i = 1; i < len; i++) {
  1205. b = input[i];
  1206. a = game.math.mmcTwoNumbers(a, b);
  1207. }
  1208. return a;
  1209. },
  1210. mmcTwoNumbers: (num1, num2) => {
  1211. var resto, x, y;
  1212. x = num1;
  1213. y = num2;
  1214. while (resto != 0) {
  1215. resto = x % y;
  1216. x = y;
  1217. y = resto;
  1218. }
  1219. return (num1 * num2) / x;
  1220. },
  1221. getFractionFromDecimal: function (fraction) {
  1222. const len = fraction.toString().length - 2;
  1223. let denominator = Math.pow(10, len);
  1224. let numerator = fraction * denominator;
  1225. const divisor = game.math.greatestCommonDivisor(numerator, denominator);
  1226. numerator /= divisor;
  1227. denominator /= divisor;
  1228. return {
  1229. string: Math.floor(numerator) + '/' + Math.floor(denominator),
  1230. numerator: Math.floor(numerator),
  1231. denominator: Math.floor(denominator),
  1232. };
  1233. },
  1234. /**
  1235. * Checks if pointer/mouse is over (rectangular) icon.
  1236. *
  1237. * @param {number} xMouse contains the mouse x coordinate
  1238. * @param {number} yMouse contains the mouse y coordinate
  1239. * @param {object} icon icon
  1240. *
  1241. * @returns {boolean} true if cursor is over icon
  1242. */
  1243. isOverIcon: function (xMouse, yMouse, icon) {
  1244. const x = xMouse,
  1245. y = yMouse,
  1246. cur = icon;
  1247. return (
  1248. y >= cur.yWithAnchor &&
  1249. y <= cur.yWithAnchor + cur.height * cur.scale &&
  1250. x >= cur.xWithAnchor &&
  1251. x <= cur.xWithAnchor + cur.width * cur.scale
  1252. );
  1253. },
  1254. /**
  1255. * Checks if 2 images overlap
  1256. *
  1257. * @param {object} imageA image 1
  1258. * @param {object} imageB image 2
  1259. *
  1260. * @returns {boolean} true if there is overlap
  1261. */
  1262. isOverlap: function (imageA, imageB) {
  1263. const xA = imageA.x;
  1264. const xB = imageB.x;
  1265. // Consider it comming from both sides
  1266. return !(Math.abs(xA - xB) > 14);
  1267. },
  1268. /**
  1269. * Get mouse position coordinates
  1270. *
  1271. * @param {object} mouseEvent
  1272. * @returns {object} x and y mouse coordinates
  1273. */
  1274. getMouse: function (mouseEvent) {
  1275. const c = context.canvas.getBoundingClientRect();
  1276. const canvas_scale = context.canvas.width / parseFloat(c.width);
  1277. return {
  1278. x: (mouseEvent.clientX - c.left) * canvas_scale,
  1279. y: (mouseEvent.clientY - c.top) * canvas_scale,
  1280. };
  1281. },
  1282. /**
  1283. * Calculate spacing for icons on the menu screen
  1284. *
  1285. * @param {number} width width of the desirable part of the screen
  1286. * @param {number} numberOfIcons number or icons to be put on the screen
  1287. *
  1288. * @returns {number} correct spacing between icons
  1289. */
  1290. getOffset: function (width, numberOfIcons) {
  1291. return width / (numberOfIcons + 1);
  1292. },
  1293. /**
  1294. * Converts a given time in seconds (number) to the format HH:MM:SS (string)
  1295. *
  1296. * @param {number} s time in seconds
  1297. *
  1298. * @returns {string} time in the format HH:MM:SS
  1299. */
  1300. convertTime: function (s) {
  1301. let h = 0,
  1302. m = 0;
  1303. if (s > 1200) {
  1304. h = s / 1200;
  1305. s = s % 1200;
  1306. }
  1307. if (s > 60) {
  1308. m = s / 60;
  1309. s = s % 60;
  1310. }
  1311. h = '' + h;
  1312. m = '' + m;
  1313. s = '' + s;
  1314. if (h.length < 2) h = '0' + h;
  1315. if (m.length < 2) m = '0' + m;
  1316. if (s.length < 2) s = '0' + s;
  1317. return h + ':' + m + ':' + s;
  1318. },
  1319. },
  1320. /**
  1321. * Timer used to get the time spent to complete a game.
  1322. *
  1323. * @namespace
  1324. */
  1325. timer: {
  1326. // [Not directly used] Start time.
  1327. _start: 0,
  1328. // [Not directly used] End time.
  1329. end: 0,
  1330. // Elapsed time.
  1331. elapsed: 0,
  1332. /**
  1333. * Reset values and start timer.
  1334. */
  1335. start: function () {
  1336. game.timer._start = game.timer.end = game.timer.elapsed = 0;
  1337. game.timer._start = new Date().getTime();
  1338. },
  1339. /**
  1340. * Stop timer and set elapsed time.
  1341. */
  1342. stop: function () {
  1343. if (game.timer._start != 0 && game.timer.end == 0) {
  1344. // If timer has started but not finished
  1345. game.timer.end = new Date().getTime();
  1346. game.timer.elapsed = Math.floor(
  1347. (game.timer.end - game.timer._start) / 1000
  1348. );
  1349. }
  1350. },
  1351. },
  1352. /**
  1353. * Handles pointer events. <br>
  1354. *
  1355. * @namespace
  1356. */
  1357. event: {
  1358. // [Not directly used] List of events in current state.
  1359. list: [],
  1360. /**
  1361. * Adds new event to current state.
  1362. *
  1363. * @param {string} name event name, can be: 'click' or 'mousemove'
  1364. * @param {function} func function to be called when event is triggered
  1365. */
  1366. add: function (name, func) {
  1367. context.canvas.addEventListener(name, func);
  1368. game.event.list.push([name, func]);
  1369. },
  1370. /** [Not directly used] Clears list of events. Called before moving to new state.
  1371. */
  1372. clear: function () {
  1373. game.event.list.forEach((cur) => {
  1374. context.canvas.removeEventListener(cur[0], cur[1]);
  1375. });
  1376. game.event.list = [];
  1377. },
  1378. },
  1379. /** [Not directly used] Handles 'game loop'. <br>
  1380. *
  1381. * After the media queue is filled in create(), the 'game loop' starts.
  1382. * It calls update() iteratively, re-rendering the screen every time. <br>
  1383. *
  1384. * The 'game loop' is stoped by leaving the current state.
  1385. *
  1386. * @namespace
  1387. */
  1388. loop: {
  1389. // [Not directly used] Holds animation event.
  1390. id: undefined,
  1391. // [Not directly used] State that called the loop.
  1392. curState: undefined,
  1393. // [Not directly used] Loop status, can be: 'on', 'ending' or 'off'.
  1394. status: 'off',
  1395. // [Not directly used]
  1396. waitingToStart: undefined,
  1397. // [Not directly used]
  1398. startTime: 0,
  1399. // [Not directly used] 1000: 1 second | 60: expected frames per second.
  1400. duration: 1000 / 60,
  1401. /** [Not directly used] Starts game loop.
  1402. *
  1403. * @param {object} state current state
  1404. */
  1405. start: function (state) {
  1406. if (game.loop.status == 'off') {
  1407. game.loop.curState = state;
  1408. game.loop.startTime = new Date().getTime();
  1409. game.loop.status = 'on';
  1410. game.loop.id = requestAnimationFrame(game.loop.run);
  1411. } else {
  1412. // If 'game.loop.status' is either 'on' or 'ending'
  1413. game.loop.waitingToStart = state;
  1414. if (game.loop.status == 'on') game.loop.stop();
  1415. }
  1416. },
  1417. /**
  1418. * [Not directly used] Stops game loop.
  1419. */
  1420. stop: function () {
  1421. if (game.loop.status == 'on') game.loop.status = 'ending';
  1422. },
  1423. /**
  1424. * [Not directly used] Executes game loop.
  1425. *
  1426. * This code will run on each iteration of the game loop.
  1427. */
  1428. run: function () {
  1429. if (game.loop.status != 'on') {
  1430. game.loop.clear();
  1431. } else {
  1432. const timestamp = new Date().getTime();
  1433. const runtime = timestamp - game.loop.startTime;
  1434. if (runtime >= game.loop.duration) {
  1435. // Calls state's update()
  1436. game.loop.curState.update();
  1437. // Updates state's animation
  1438. game.animation.run();
  1439. }
  1440. game.loop.id = requestAnimationFrame(game.loop.run); // Loop
  1441. }
  1442. },
  1443. /**
  1444. * [Not directly used] Resets game loop values.
  1445. */
  1446. clear: function () {
  1447. if (game.loop.id != undefined) {
  1448. cancelAnimationFrame(game.loop.id); // Cancel animation event
  1449. game.loop.id = undefined; // Clears object that holds animation event
  1450. game.loop.curState = undefined; // Clears object that holds current state
  1451. game.loop.status = 'off'; // Inform animation must end (read in game.loop.run())
  1452. }
  1453. if (game.loop.waitingToStart != undefined) {
  1454. const temp = game.loop.waitingToStart;
  1455. game.loop.waitingToStart = undefined;
  1456. game.loop.start(temp);
  1457. }
  1458. },
  1459. },
  1460. /**
  1461. * Handles spritesheet animation. <br>
  1462. * It iterates through the spritesheet frames inside the animation queue.
  1463. * Called by game loop.
  1464. *
  1465. * @namespace
  1466. */
  1467. animation: {
  1468. // [Not directly used] Animation queue for the current state.
  1469. queue: [],
  1470. // [Not directly used]
  1471. count: 0,
  1472. /**
  1473. * Plays animation.
  1474. *
  1475. * @param {string} name animation name (identifier)
  1476. */
  1477. play: function (name) {
  1478. let newAnimation;
  1479. // Gets first object in the 'render queue' with that animation name
  1480. for (let i in game.render.queue) {
  1481. if (
  1482. game.render.queue[i].animation != undefined &&
  1483. game.render.queue[i].animation[0] == name
  1484. ) {
  1485. newAnimation = game.render.queue[i];
  1486. break;
  1487. }
  1488. }
  1489. // If found, saves object in the 'animation queue'
  1490. if (newAnimation != undefined) game.animation.queue.push(newAnimation);
  1491. },
  1492. /**
  1493. * Stops animation.
  1494. *
  1495. * @param {string} name animation name
  1496. */
  1497. stop: function (name) {
  1498. // Removes all with that name from the 'animation queue'
  1499. game.animation.queue.forEach((cur) => {
  1500. if (cur.animation[0] == name) {
  1501. game.animation.queue.splice(cur, 1);
  1502. }
  1503. });
  1504. },
  1505. /**
  1506. * [Not directly used] Executes animation.
  1507. */
  1508. run: function () {
  1509. game.animation.queue.forEach((character) => {
  1510. if (
  1511. !character.animation[2] ||
  1512. game.animation.count % character.animation[2] == 0
  1513. ) {
  1514. const i = character.animation[1].indexOf(character.curFrame);
  1515. if (i == -1) {
  1516. // Frame not found
  1517. if (isDebugMode)
  1518. console.error('Game error: animation frame not found.');
  1519. } else if (i < character.animation[1].length - 1) {
  1520. // Go to next frame
  1521. character.curFrame = character.animation[1][i + 1];
  1522. } else {
  1523. character.curFrame = character.animation[1][0]; // If last frame, restart
  1524. }
  1525. }
  1526. });
  1527. game.animation.count++;
  1528. },
  1529. /**
  1530. * [Not directly used] Clears animation queue.
  1531. */
  1532. clear: function () {
  1533. // Resets animation counter
  1534. game.animation.count = 0;
  1535. // Clears property 'animation' from objects in game.render.queue
  1536. game.render.queue.forEach((cur) => {
  1537. if (cur.animation != undefined) {
  1538. delete cur.animation;
  1539. }
  1540. });
  1541. // Clears animation queue
  1542. game.animation.queue = [];
  1543. },
  1544. },
  1545. };