gameMechanics.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. const game = {
  2. audio: {}, lang: {}, // Holds cache reference to media : Directly used in code to get audio and dicitonary
  3. image: {}, sprite: {}, // Holds cache reference to media : Not directly used in code
  4. mediaTypes: ['lang', 'audio', 'image', 'sprite'],
  5. loadedMedia: [],
  6. isLoaded: [],
  7. // Loads a list of URL to Cache
  8. load: {
  9. lang: function (url) {
  10. game.isLoaded['lang'] = false;
  11. game.loadedMedia['lang'] = 0;
  12. game.lang = {}; // clear previously loaded language
  13. const init = { mode: "same-origin" };
  14. fetch(url, init)
  15. .then(function (response) {
  16. return response.text();
  17. })
  18. .then(function (text) {
  19. let msg = text.split("\n");
  20. msg.forEach(cur => {
  21. try {
  22. let msg = cur.split("=");
  23. game.lang[msg[0].trim()] = msg[1].trim();
  24. } catch (Error) { if (debugMode) console.log("Sintax error fixed"); }
  25. game.load._informMediaIsLoaded(msg.length - 1, 'lang');
  26. });
  27. });
  28. },
  29. audio: function (urls) {
  30. game.isLoaded['audio'] = false;
  31. game.loadedMedia['audio'] = 0;
  32. urls = this._getNotLoadedUrls(urls, game.audio);
  33. if (urls.length == 0) {
  34. game.load._informMediaIsLoaded(0, 'audio');
  35. } else {
  36. const init = { mode: "same-origin" };
  37. urls.forEach(cur => {
  38. fetch(cur[1][1], init)
  39. .then(response => response.blob())
  40. .then(function (myBlob) {
  41. game.audio[cur[0]] = new Audio(URL.createObjectURL(myBlob));
  42. game.load._informMediaIsLoaded(urls.length - 1, 'audio');
  43. });
  44. });
  45. }
  46. },
  47. image: function (urls) {
  48. game.isLoaded['image'] = false;
  49. game.loadedMedia['image'] = 0;
  50. urls = this._getNotLoadedUrls(urls, game.image);
  51. if (urls.length == 0) {
  52. game.load._informMediaIsLoaded(0, 'image');
  53. } else {
  54. urls.forEach(cur => {
  55. const img = new Image(); //HTMLImageElement
  56. img.onload = () => {
  57. game.image[cur[0]] = img;
  58. game.load._informMediaIsLoaded(urls.length - 1, 'image');
  59. }
  60. img.src = cur[1];
  61. });
  62. }
  63. },
  64. sprite: function (urls) {
  65. game.isLoaded['sprite'] = false;
  66. game.loadedMedia['sprite'] = 0;
  67. urls = this._getNotLoadedUrls(urls, game.sprite);
  68. if (urls.length == 0) {
  69. game.load._informMediaIsLoaded(0, 'sprite');
  70. } else {
  71. urls.forEach(cur => {
  72. const img = new Image(); //HTMLImageElement
  73. img.onload = () => {
  74. game.sprite[cur[0]] = img;
  75. game.load._informMediaIsLoaded(urls.length - 1, 'sprite');
  76. }
  77. img.src = cur[1];
  78. img.frames = cur[2];
  79. });
  80. }
  81. },
  82. // get list of urls and return only valid ones
  83. _getNotLoadedUrls: function (urls, media) {
  84. const newUrls = [];
  85. urls.forEach(cur => { if (media[cur[0]] == undefined) newUrls.push(cur); });
  86. return newUrls;
  87. },
  88. _informMediaIsLoaded: function (last, type) {
  89. if (game.loadedMedia[type] == last) { // if all media of that type was loaded
  90. game.isLoaded[type] = true;
  91. game.load._isPreloadDone(type);
  92. }
  93. game.loadedMedia[type]++;
  94. },
  95. // Calls create() for current screen if all media for screen was loaded
  96. _isPreloadDone: function (type) {
  97. let flag = true;
  98. for (let i in game.mediaTypes) {
  99. // if all media for the screen was loaded flag wont change
  100. if (game.isLoaded[game.mediaTypes[i]] == false) {
  101. flag = false;
  102. break;
  103. }
  104. }
  105. // if flag doesnt change preload is complete
  106. if (flag) {
  107. game.isLoaded = [];
  108. game.loadedMedia[type] = 0;
  109. self.create();
  110. }
  111. }
  112. },
  113. // Adds new media to "media queue" to be rendered by current screen
  114. add: {
  115. default : {
  116. // all
  117. x: 0,
  118. y: 0,
  119. _xWithAnchor: 0,
  120. _yWithAnchor: 0,
  121. xAnchor: 0,
  122. yAnchor: 0,
  123. shadow : false,
  124. shadowColor : "#0075c5",
  125. shadowBlur : 20,
  126. alpha: 1,
  127. // image, sprite, square, circle
  128. scale: 1,
  129. // text
  130. font: '14px Arial,sans-serif',
  131. fill: '#000',
  132. align: 'center',
  133. // square, circle (image and sprite have width and height, but do not have default values)
  134. width: 50,
  135. height: 50,
  136. lineColor: "#000",
  137. lineWidth: 1,
  138. fillColor: 0, // default no fill
  139. // circle
  140. diameter: 50,
  141. anticlockwise: false,
  142. },
  143. // game.add.image(x, y, img)
  144. // game.add.image(x, y, img, scale)
  145. // game.add.image(x, y, img, scale, alpha)
  146. image: function (x, y, img, scale, alpha) {
  147. if (x == undefined || y == undefined || img == undefined) console.error("Game error: parameters missing");
  148. else if (game.image[img] == undefined) console.error("Game error: image not found in cache: " + img);
  149. else {
  150. const med = {
  151. typeOfMedia: 'image',
  152. name: img,
  153. x: x || game.add.default.x,
  154. y: y || game.add.default.y,
  155. _xWithAnchor: x || game.add.default._xWithAnchor,
  156. _yWithAnchor: y || game.add.default._yWithAnchor,
  157. xAnchor: game.add.default.xAnchor,
  158. yAnchor: game.add.default.yAnchor,
  159. shadow : game.add.default.shadow,
  160. shadowColor : game.add.default.shadowColor,
  161. shadowBlur : game.add.default.shadowBlur,
  162. alpha: (alpha != undefined) ? alpha : game.add.default.alpha,
  163. scale: scale || game.add.default.scale,
  164. width: game.image[img].width,
  165. height: game.image[img].height,
  166. anchor: function (xAnchor, yAnchor) {
  167. this.xAnchor = xAnchor;
  168. this.yAnchor = yAnchor;
  169. },
  170. get xWithAnchor() { return this.x - (this.width * this.scale * this.xAnchor); },
  171. get yWithAnchor() { return this.y - (this.height * this.scale * this.yAnchor); }
  172. };
  173. game.render.queue.push(med);
  174. return med;
  175. }
  176. },
  177. // game.add.sprite(x, y, img)
  178. // game.add.sprite(x, y, img, curFrame)
  179. // game.add.sprite(x, y, img, curFrame, scale)
  180. // game.add.sprite(x, y, img, curFrame, scale, alpha)
  181. sprite: function (x, y, img, curFrame, scale, alpha) {
  182. if (x == undefined || y == undefined || img == undefined) console.error("Game error: parameters missing");
  183. else if (game.sprite[img] == undefined) console.error("Game error: sprite not found in cache: " + img);
  184. else {
  185. const med = {
  186. typeOfMedia: 'sprite',
  187. name: img,
  188. x: x || game.add.default.x,
  189. y: y || game.add.default.y,
  190. _xWithAnchor: x || game.add.default._xWithAnchor,
  191. _yWithAnchor: y || game.add.default._yWithAnchor,
  192. xAnchor: game.add.default.xAnchor,
  193. yAnchor: game.add.default.yAnchor,
  194. shadow : game.add.default.shadow,
  195. shadowColor : game.add.default.shadowColor,
  196. shadowBlur : game.add.default.shadowBlur,
  197. alpha: (alpha != undefined) ? alpha : game.add.default.alpha,
  198. scale: scale || game.add.default.scale,
  199. width: game.sprite[img].width / game.sprite[img].frames, // frame width
  200. height: game.sprite[img].height, // frame height
  201. curFrame: curFrame || 0,
  202. anchor: function (xAnchor, yAnchor) {
  203. this.xAnchor = xAnchor;
  204. this.yAnchor = yAnchor;
  205. },
  206. get xWithAnchor() { return this.x - (this.width * this.scale * this.xAnchor); },
  207. get yWithAnchor() { return this.y - (this.height * this.scale * this.yAnchor); }
  208. };
  209. game.render.queue.push(med);
  210. return med;
  211. }
  212. },
  213. // game.add.text(x, y, text, style)
  214. // game.add.text(x, y, text, style, align)
  215. text: function (x, y, text, style, align) {
  216. if (x == undefined || y == undefined || text == undefined || style == undefined) console.error("Game error: parameters missing");
  217. else {
  218. const med = {
  219. typeOfMedia: 'text',
  220. name: text,
  221. x: x || game.add.default.x,
  222. y: y || game.add.default.y,
  223. _xWithAnchor: x || game.add.default._xWithAnchor,
  224. _yWithAnchor: y || game.add.default._yWithAnchor,
  225. xAnchor: game.add.default.xAnchor,
  226. yAnchor: game.add.default.yAnchor,
  227. shadow : game.add.default.shadow,
  228. shadowColor : game.add.default.shadowColor,
  229. shadowBlur : game.add.default.shadowBlur,
  230. alpha: game.add.default.alpha,
  231. font: style.font || game.add.default.font,
  232. fill: style.fill || game.add.default.fill,
  233. align: align || style.align || game.add.default.align,
  234. anchor: function () { console.error("Game error: there's no anchor for text"); },
  235. get xWithAnchor() { return this.x; },
  236. get yWithAnchor() { return this.y; }
  237. };
  238. game.render.queue.push(med);
  239. return med;
  240. }
  241. },
  242. graphic: {
  243. // game.add.graphic.rect(x, y, width, height)
  244. // game.add.graphic.rect(x, y, width, height, lineColor)
  245. // game.add.graphic.rect(x, y, width, height, lineColor, lineWidth)
  246. // game.add.graphic.rect(x, y, width, height, lineColor, lineWidth, fillColor)
  247. // game.add.graphic.rect(x, y, width, height, lineColor, lineWidth, fillColor, alpha)
  248. rect: function (x, y, width, height, lineColor, lineWidth, fillColor, alpha) {
  249. if (x == undefined || y == undefined || width == undefined) console.error("Game error: parameters missing");
  250. else {
  251. const med = {
  252. typeOfMedia: 'rect',
  253. x: x || game.add.default.x,
  254. y: y || game.add.default.y,
  255. _xWithAnchor: x || game.add.default._xWithAnchor,
  256. _yWithAnchor: y || game.add.default._yWithAnchor,
  257. xAnchor: game.add.default.xAnchor,
  258. yAnchor: game.add.default.yAnchor,
  259. shadow : game.add.default.shadow,
  260. shadowColor : game.add.default.shadowColor,
  261. shadowBlur : game.add.default.shadowBlur,
  262. alpha: (alpha != undefined) ? alpha : game.add.default.alpha,
  263. scale: game.add.default.scale,
  264. width: 0,
  265. height: 0,
  266. lineColor: lineColor || game.add.default.lineColor,
  267. lineWidth: 0,
  268. fillColor: fillColor || game.add.default.fillColor,
  269. anchor: function (xAnchor, yAnchor) {
  270. this.xAnchor = xAnchor;
  271. this.yAnchor = yAnchor;
  272. },
  273. get xWithAnchor() { return this.x - (this.width * this.scale * this.xAnchor); },
  274. get yWithAnchor() { return this.y - (this.height * this.scale * this.yAnchor); }
  275. };
  276. if (width != 0) { med.width = width || game.add.default.width; }
  277. if (height != 0) { med.height = height || width || game.add.default.height; }
  278. if (lineWidth != 0) { med.lineWidth = lineWidth || game.add.default.lineWidth; }
  279. game.render.queue.push(med);
  280. return med;
  281. }
  282. },
  283. // game.add.graphic.circle(x, y, diameter)
  284. // game.add.graphic.circle(x, y, diameter, lineColor)
  285. // game.add.graphic.circle(x, y, diameter, lineColor, lineWidth)
  286. // game.add.graphic.circle(x, y, diameter, lineColor, lineWidth, fillColor)
  287. // game.add.graphic.circle(x, y, diameter, lineColor, lineWidth, fillColor, alpha)
  288. circle: function (x, y, diameter, lineColor, lineWidth, fillColor, alpha) {
  289. if (x == undefined || y == undefined || diameter == undefined) console.error("Game error: parameters missing");
  290. else {
  291. const med = {
  292. typeOfMedia: 'arc',
  293. x: x || game.add.default.x,
  294. y: y || game.add.default.y,
  295. _xWithAnchor: x || game.add.default._xWithAnchor,
  296. _yWithAnchor: y || game.add.default._yWithAnchor,
  297. xAnchor: game.add.default.xAnchor,
  298. yAnchor: game.add.default.yAnchor,
  299. shadow : game.add.default.shadow,
  300. shadowColor : game.add.default.shadowColor,
  301. shadowBlur : game.add.default.shadowBlur,
  302. alpha: (alpha != undefined) ? alpha : game.add.default.alpha,
  303. scale: game.add.default.scale,
  304. diameter: 0,
  305. width: 0,
  306. height: 0,
  307. angleStart: 0,
  308. angleEnd: 2 * Math.PI,
  309. anticlockwise: game.add.default.anticlockwise,
  310. lineColor: lineColor || game.add.default.lineColor,
  311. lineWidth: 0,
  312. fillColor: fillColor || game.add.default.fillColor,
  313. anchor: function (xAnchor, yAnchor) {
  314. this.xAnchor = xAnchor;
  315. this.yAnchor = yAnchor;
  316. },
  317. get xWithAnchor() { return this.x - (this.width * this.scale * this.xAnchor); },
  318. get yWithAnchor() { return this.y - (this.height * this.scale * this.yAnchor); }
  319. };
  320. if (diameter != 0) {
  321. med.diameter = diameter || game.add.default.diameter;
  322. med.width = med.height = med.diameter;
  323. }
  324. if (lineWidth != 0) {
  325. med.lineWidth = lineWidth || game.add.default.lineWidth;
  326. }
  327. game.render.queue.push(med);
  328. return med;
  329. }
  330. },
  331. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd)
  332. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd, anticlockWise)
  333. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd, anticlockWise, lineColor)
  334. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd, anticlockWise, lineColor, lineWidth)
  335. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd, anticlockWise, lineColor, lineWidth, fillColor)
  336. // game.add.graphic.arc(x, y, diameter, angleStart, angleEnd, anticlockWise, lineColor, lineWidth, fillColor, alpha)
  337. arc: function (x, y, diameter, angleStart, angleEnd, anticlockwise, lineColor, lineWidth, fillColor, alpha) {
  338. if (x == undefined || y == undefined || diameter == undefined || angleStart == undefined || angleEnd == undefined) console.error("Game error: parameters missing");
  339. else {
  340. const med = {
  341. typeOfMedia: 'arc',
  342. x: x || game.add.default.x,
  343. y: y || game.add.default.y,
  344. _xWithAnchor: x || game.add.default._xWithAnchor,
  345. _yWithAnchor: y || game.add.default._yWithAnchor,
  346. xAnchor: game.add.default.xAnchor,
  347. yAnchor: game.add.default.yAnchor,
  348. shadow : game.add.default.shadow,
  349. shadowColor : game.add.default.shadowColor,
  350. shadowBlur : game.add.default.shadowBlur,
  351. alpha: (alpha != undefined) ? alpha : game.add.default.alpha,
  352. scale: game.add.default.scale,
  353. diameter: 0,
  354. width: 0,
  355. height: 0,
  356. angleStart: angleStart || 0,
  357. angleEnd: angleEnd || 2 * Math.PI,
  358. anticlockwise: anticlockwise || game.add.default.anticlockwise,
  359. lineColor: lineColor || game.add.default.lineColor,
  360. lineWidth: 0,
  361. fillColor: fillColor || game.add.default.fillColor,
  362. anchor: function (xAnchor, yAnchor) {
  363. this.xAnchor = xAnchor;
  364. this.yAnchor = yAnchor;
  365. },
  366. get xWithAnchor() { return this.x - (this.width * this.scale * this.xAnchor); },
  367. get yWithAnchor() { return this.y - (this.height * this.scale * this.yAnchor); }
  368. };
  369. if (diameter != 0) {
  370. med.diameter = diameter || game.add.default.diameter;
  371. med.width = med.height = med.diameter;
  372. }
  373. if (lineWidth != 0) { med.lineWidth = lineWidth || game.add.default.lineWidth; }
  374. game.render.queue.push(med);
  375. return med;
  376. }
  377. }
  378. }
  379. },
  380. // Renders media on current screen
  381. render: {
  382. queue: [], // media queue to be rendered by the current state
  383. _image: function (cur) { // ( x, y, img, scale, alpha)
  384. const x = cur.xWithAnchor, y = cur.yWithAnchor;
  385. if (cur.rotate && cur.rotate != 0) {
  386. context.save();
  387. context.translate(cur.x, cur.y);
  388. context.rotate(cur.rotate * Math.PI / 180);
  389. context.translate(-cur.x, -cur.y);
  390. }
  391. context.globalAlpha = cur.alpha;
  392. context.shadowBlur = (cur.shadow) ? cur.shadowBlur : 0;
  393. context.shadowColor = cur.shadowColor;
  394. context.drawImage(
  395. game.image[cur.name],
  396. x,
  397. y,
  398. cur.width * cur.scale,
  399. cur.height * cur.scale
  400. );
  401. context.shadowBlur = 0;
  402. context.globalAlpha = 1;
  403. if (cur.rotate && cur.rotate != 0) context.restore();
  404. },
  405. _sprite: function (cur) { // ( x, y, img, curFrame, scale, alpha )
  406. const x = cur.xWithAnchor, y = cur.yWithAnchor;
  407. if (cur.rotate && cur.rotate != 0) {
  408. context.save();
  409. context.translate(cur.x, cur.y);
  410. context.rotate(cur.rotate * Math.PI / 180);
  411. context.translate(-cur.x, -cur.y);
  412. }
  413. context.globalAlpha = cur.alpha;
  414. context.shadowBlur = (cur.shadow) ? cur.shadowBlur : 0;
  415. context.shadowColor = cur.shadowColor;
  416. context.drawImage(
  417. game.sprite[cur.name],
  418. cur.width * cur.curFrame,
  419. 0,
  420. cur.width,
  421. cur.height,
  422. x,
  423. y,
  424. cur.width * cur.scale,
  425. cur.height * cur.scale
  426. );
  427. context.shadowBlur = 0;
  428. context.globalAlpha = 1;
  429. if (cur.rotate && cur.rotate != 0) context.restore();
  430. },
  431. _text: function (cur) { // ( x, y, text, style )
  432. const x = cur.xWithAnchor, y = cur.yWithAnchor;
  433. if (cur.rotate && cur.rotate != 0) {
  434. context.save();
  435. context.translate(cur.x, cur.y);
  436. context.rotate(cur.rotate * Math.PI / 180);
  437. context.translate(-cur.x, -cur.y);
  438. }
  439. context.globalAlpha = cur.alpha;
  440. context.shadowBlur = (cur.shadow) ? cur.shadowBlur : 0;
  441. context.shadowColor = cur.shadowColor;
  442. context.font = cur.font;
  443. context.textAlign = cur.align;
  444. context.fillStyle = cur.fill;
  445. context.fillText(cur.name, x, y);
  446. context.shadowBlur = 0;
  447. context.globalAlpha = 1;
  448. if (cur.rotate && cur.rotate != 0) context.restore();
  449. },
  450. _graphic: {
  451. _rect: function (cur) { // ( x, y, width, height, lineColor, lineWidth, fillColor, alpha)
  452. const x = cur.xWithAnchor, y = cur.yWithAnchor;
  453. // rotation
  454. if (cur.rotate && cur.rotate != 0) {
  455. context.save();
  456. context.translate(cur.x, cur.y);
  457. context.rotate(cur.rotate * Math.PI / 180);
  458. context.translate(-cur.x, -cur.y);
  459. }
  460. // alpha
  461. context.globalAlpha = cur.alpha;
  462. // shadow
  463. context.shadowBlur = (cur.shadow) ? cur.shadowBlur : 0;
  464. context.shadowColor = cur.shadowColor;
  465. // fill
  466. if (cur.fillColor != 0) {
  467. context.fillStyle = cur.fillColor;
  468. context.fillRect(x, y, cur.width * cur.scale, cur.height * cur.scale);
  469. }
  470. // stroke
  471. if (cur.lineWidth != 0) {
  472. context.strokeStyle = cur.lineColor;
  473. context.lineWidth = cur.lineWidth;
  474. context.strokeRect(x, y, cur.width * cur.scale, cur.height * cur.scale);
  475. }
  476. // end
  477. context.shadowBlur = 0;
  478. context.globalAlpha = 1;
  479. if (cur.rotate && cur.rotate != 0) context.restore();
  480. },
  481. _arc: function (cur) { // ( x, y, diameter, angleStart, angleEnd, anticlockWise, lineColor, lineWidth, fillColor, alpha);
  482. const x = cur.xWithAnchor, y = cur.yWithAnchor;
  483. // rotation
  484. if (cur.rotate && cur.rotate != 0) {
  485. context.save();
  486. context.translate(cur.x, cur.y);
  487. context.rotate(cur.rotate * Math.PI / 180);
  488. context.translate(-cur.x, -cur.y);
  489. }
  490. // alpha
  491. context.globalAlpha = cur.alpha;
  492. // shadow
  493. context.shadowBlur = (cur.shadow) ? cur.shadowBlur : 0;
  494. context.shadowColor = cur.shadowColor;
  495. // fill info
  496. if (cur.fillColor != 0) context.fillStyle = cur.fillColor;
  497. // stroke info
  498. if (cur.lineWidth != 0) {
  499. context.strokeStyle = cur.lineColor;
  500. context.lineWidth = cur.lineWidth;
  501. }
  502. // path
  503. context.beginPath();
  504. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  505. context.arc(x, y, (cur.diameter / 2) * cur.scale, cur.angleStart, cur.angleEnd, cur.anticlockwise);
  506. if (cur.angleEnd != 2 * Math.PI) context.lineTo(x, y);
  507. // end
  508. if (cur.fillColor != 0) context.fill();
  509. if (cur.lineWidth != 0) context.stroke();
  510. context.shadowBlur = 0;
  511. context.globalAlpha = 1;
  512. if (cur.rotate && cur.rotate != 0) context.restore();
  513. },
  514. },
  515. // game.render.all() : draws all queued media to screen
  516. all: function () {
  517. game.render.queue.forEach(cur => {
  518. switch (cur.typeOfMedia) {
  519. case 'image': this._image(cur); break;
  520. case 'sprite': this._sprite(cur); break;
  521. case 'text': this._text(cur); break;
  522. case 'rect': this._graphic._rect(cur); break;
  523. case 'arc': this._graphic._arc(cur); break;
  524. }
  525. });
  526. },
  527. // game.render.clear() : clears all queued media
  528. clear: function () {
  529. game.render.queue = [];
  530. }
  531. },
  532. // Math functions
  533. math: {
  534. randomInRange: function (min, max) { // integer
  535. min = Math.ceil(min);
  536. max = Math.floor(max);
  537. return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is also inclusive
  538. },
  539. randomDivisor: function (number) { //Get random divisor for a number
  540. const validDivisors = []; // Divisors found
  541. for (let i = 2; i < number; i++) {
  542. // if 'number' can be divided by 'i', add to list of 'validDivisors'
  543. if (number % i == 0) validDivisors.push(i);
  544. }
  545. const randIndex = game.math.randomInRange(0, validDivisors.length - 1);
  546. return validDivisors[randIndex];
  547. },
  548. degreeToRad: function (degree) {
  549. return degree * Math.PI / 180;
  550. },
  551. radToDegree: function (radian) {
  552. return radian * 180 / Math.PI;
  553. },
  554. distanceToPointer: function (xMouse, xIcon, yMouse, yIcon) {
  555. const a = Math.max(xMouse, xIcon) - Math.min(xMouse, xIcon);
  556. const b = Math.max(yMouse, yIcon) - Math.min(yMouse, yIcon);
  557. return Math.sqrt(a * a + b * b);
  558. },
  559. isOverIcon : function (xMouse, yMouse, icon) {
  560. const x = xMouse, y = yMouse, cur = icon;
  561. const valid =
  562. y >= cur.yWithAnchor && y <= (cur.yWithAnchor + cur.height * cur.scale) &&
  563. (x >= cur.xWithAnchor && x <= (cur.xWithAnchor + cur.width * cur.scale));
  564. return valid;
  565. }
  566. },
  567. // Timer
  568. timer: {
  569. _start: 0, // start time
  570. _end: 0, // end time
  571. elapsed: 0, // elapsed time
  572. start: function () {
  573. game.timer._start = game.timer._end = game.timer._elapsed = 0; // clear
  574. game.timer._start = new Date().getTime(); // set start time
  575. },
  576. stop: function () {
  577. if (game.timer._start != 0 && game.timer._end == 0) { // if timer has started but not finished
  578. game.timer._end = new Date().getTime(); // set end time
  579. game.timer._elapsed = Math.floor((game.timer._end - game.timer._start) / 1000); // set elapsed time
  580. }
  581. },
  582. get elapsed() { return game.timer._elapsed; }
  583. },
  584. // Handles to pointer events
  585. event: {
  586. _list: [], // list of events in current state
  587. add: function (name, func) {
  588. canvas.addEventListener(name, func); // param : name of the event, function to be called
  589. game.event._list.push([name, func]);
  590. },
  591. clear: function () {
  592. game.event._list.forEach(cur => {
  593. canvas.removeEventListener(cur[0], cur[1]);
  594. });
  595. game.event._list = [];
  596. },
  597. },
  598. // Game loop : handles repetition of method update and sprite animation
  599. // game.loop.start();
  600. // game.loop.stop();
  601. loop: {
  602. id: undefined, // holds animation event
  603. curState: undefined, // state that called loop
  604. status: "off", // loop status can be : 'on', 'ending' or 'off'
  605. waitingToStart: undefined,
  606. startTime: 0,
  607. DURATION: 1000 / 60, // 1000: 1 second | 60: expected frames per second
  608. start: function (state) {
  609. if (game.loop.status == "off") {
  610. game.loop.curState = state;
  611. game.loop.startTime = new Date().getTime();
  612. game.loop.status = "on";
  613. game.loop.id = requestAnimationFrame(game.loop._run);
  614. } else { // if "game.loop.status" is either "on" or "ending"
  615. game.loop.waitingToStart = state;
  616. if (game.loop.status == "on") game.loop.stop();
  617. }
  618. },
  619. stop: function () {
  620. if (game.loop.status == "on") game.loop.status = "ending";
  621. },
  622. _run: function () {
  623. if (game.loop.status != "on") {
  624. game.loop._clear();
  625. } else {
  626. const timestamp = new Date().getTime();
  627. const runtime = timestamp - game.loop.startTime;
  628. if (runtime >= game.loop.DURATION) {
  629. if (debugMode) {
  630. let fps = runtime / 1000;
  631. fps = Math.round(1 / fps);
  632. displayFps.innerHTML = "Fps: " + fps; // show fps
  633. }
  634. // Update state
  635. game.loop.curState.update();
  636. // Animate state
  637. game.animation._run();
  638. }
  639. game.loop.id = requestAnimationFrame(game.loop._run);
  640. }
  641. },
  642. _clear: function () {
  643. if (game.loop.id != undefined) {
  644. cancelAnimationFrame(game.loop.id); // cancel animation event
  645. game.loop.id = undefined; // clear object that holds animation event
  646. game.loop.curState = undefined; // clear object that holds current state
  647. game.loop.status = "off"; // inform animation must end (read in _run())
  648. displayFps.innerHTML = ""; // Stop showing fps
  649. }
  650. if (game.loop.waitingToStart != undefined) {
  651. const temp = game.loop.waitingToStart;
  652. game.loop.waitingToStart = undefined;
  653. game.loop.start(temp);
  654. }
  655. },
  656. },
  657. // Change frames in queued spritesheets making animation
  658. // game.animation.play(<animationName>);
  659. // game.animation.stop(<animationName>);
  660. // game.animation.clear();
  661. animation: {
  662. queue: [], // animation queue for current level
  663. count: 0,
  664. play: function (name) {
  665. let newAnimation;
  666. // gets first object that has that animation name (name) in game.render.queue
  667. for (let i in game.render.queue) {
  668. if (game.render.queue[i].animation != undefined && game.render.queue[i].animation[0] == name) {
  669. newAnimation = game.render.queue[i];
  670. break;
  671. }
  672. }
  673. // If found, saves object in game.animation.queue
  674. if (newAnimation != undefined) game.animation.queue.push(newAnimation);
  675. },
  676. stop: function (name) {
  677. // remove all with that name is game.animation.queue
  678. game.animation.queue.forEach(cur => {
  679. if (cur.animation[0] == name) {
  680. game.animation.queue.splice(cur, 1);
  681. }
  682. });
  683. },
  684. _run: function () {
  685. game.animation.queue.forEach(character => {
  686. if (!character.animation[2] || game.animation.count % character.animation[2] == 0) {
  687. const i = character.animation[1].indexOf(character.curFrame);
  688. if (i == -1) { // frame not found
  689. if (debugMode) console.error("Game error: animation frame not found");
  690. } else if (i < character.animation[1].length - 1) { // go to next frame
  691. character.curFrame = character.animation[1][i + 1];
  692. } else {
  693. character.curFrame = character.animation[1][0]; // if last frame, restart
  694. }
  695. }
  696. });
  697. game.animation.count++;
  698. },
  699. clear: function () {
  700. // resets animation count
  701. game.animation.count = 0;
  702. // clears property 'animation' from objects in game.render.queue
  703. game.render.queue.forEach(cur => {
  704. if (cur.animation != undefined) {
  705. delete cur.animation;
  706. }
  707. });
  708. // clears game.animation.queue
  709. game.animation.queue = [];
  710. },
  711. }
  712. };