gameMechanics.js 53 KB

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