gameMechanics.js 53 KB

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