gameMechanics.js 50 KB

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