gameMechanics.js 25 KB

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