gameMechanics.js 52 KB

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