gameMechanics.js 51 KB

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