squareOne.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. /******************************
  2. * This file holds game states.
  3. ******************************/
  4. /** [GAME STATE]
  5. *
  6. * ..squareOne... = gameName
  7. * ..../...\.....
  8. * ...a.....b.... = gameMode
  9. * .....\./......
  10. * ......|.......
  11. * ...../.\......
  12. * .plus...minus. = gameOperation
  13. * .....\./......
  14. * ......|.......
  15. * ....1,2,3..... = gameDifficulty
  16. *
  17. * Character : tractor
  18. * Theme : farm
  19. * Concept : Player associates 'blocks carried by the tractor' and 'floor spaces to be filled by them'
  20. * Represent fractions as : blocks/rectangles
  21. *
  22. * Game modes can be :
  23. *
  24. * a : Player can select # of 'floor blocks' (hole in the ground)
  25. * Selects size of hole to be made in the ground (to fill with the blocks in front of the truck)
  26. * b : Player can select # of 'stacked blocks' (in front of the truck)
  27. * Selects number of blocks in front of the truck (to fill the hole on the ground)
  28. *
  29. * Operations can be :
  30. *
  31. * plus : addition of fractions
  32. * Represented by : tractor going to the right (floor positions 0..8)
  33. * minus : subtraction of fractions
  34. * Represented by: tractor going to the left (floor positions 8..0)
  35. *
  36. * @namespace
  37. */
  38. const squareOne = {
  39. default: undefined,
  40. ui: undefined,
  41. control: undefined,
  42. animation: undefined,
  43. tractor: undefined,
  44. stack: undefined,
  45. floor: undefined,
  46. /**
  47. * Main code
  48. */
  49. create: function () {
  50. const truckWidth = 201;
  51. const divisor = gameDifficulty == 3 ? 4 : gameDifficulty; // Make sure valid divisors are 1, 2 and 4 (not 3)
  52. let lineColor = undefined;
  53. let fillColor = undefined;
  54. if (gameOperation === 'minus') {
  55. lineColor = colors.red;
  56. fillColor = colors.redLight;
  57. } else {
  58. lineColor = colors.green;
  59. fillColor = colors.greenLight;
  60. }
  61. this.ui = {
  62. arrow: undefined,
  63. help: undefined,
  64. message: undefined,
  65. continue: {
  66. // modal: undefined,
  67. button: undefined,
  68. text: undefined,
  69. },
  70. };
  71. this.control = {
  72. direc: gameOperation == 'minus' ? -1 : 1, // Will be multiplied to values to easily change tractor direction when needed
  73. divisorsList: '', // Hold the divisors for each fraction on stacked blocks (created for postScore())
  74. lineWidth: 3,
  75. hasClicked: false, // Checks if player 'clicked' on a block
  76. checkAnswer: false, // When true allows game to run 'check answer' code in update
  77. isCorrect: false, // Checks player 'answer'
  78. count: 0, // An 'x' position counter used in the tractor animation
  79. };
  80. this.animation = {
  81. animateTractor: false, // When true allows game to run 'tractor animation' code in update (turns animation of the moving tractor ON/OFF)
  82. animateEnding: false, // When true allows game to run 'tractor ending animation' code in update (turns 'ending' animation of the moving tractor ON/OFF)
  83. speed: 2 * this.control.direc, // X distance in which the tractor moves in each iteration of the animation
  84. };
  85. this.default = {
  86. width: 172, // Base block width,
  87. height: 70, // Base block height
  88. x0:
  89. gameOperation == 'minus'
  90. ? context.canvas.width - truckWidth
  91. : truckWidth, // Initial 'x' coordinate for the tractor and stacked blocks
  92. y0: context.canvas.height - game.image['floor_grass'].width * 1.5,
  93. };
  94. this.default.arrowX0 =
  95. self.default.x0 + self.default.width * self.control.direc;
  96. this.default.arrowXEnd =
  97. self.default.arrowX0 + self.default.width * self.control.direc * 8;
  98. renderBackground();
  99. // FOR MOODLE
  100. if (moodle) {
  101. navigation.add.right(['audio']);
  102. } else {
  103. navigation.add.left(['back', 'menu', 'show_answer'], 'customMenu');
  104. navigation.add.right(['audio']);
  105. }
  106. this.stack = {
  107. list: [],
  108. selectedIndex: undefined,
  109. correctIndex: undefined, // (gameMode 'b') index of the CORRECT 'stacked' block
  110. curIndex: 0, // (needs to be 0)
  111. curBlockEndX: undefined,
  112. };
  113. this.floor = {
  114. list: [],
  115. selectedIndex: undefined,
  116. correctIndex: undefined, // (gameMode 'a') index of the CORRECT 'floor' block
  117. curIndex: -1, // (needs to be -1)
  118. correctX: undefined, // 'x' coordinate of CORRECT 'floor' block
  119. };
  120. let [restart, correctXA] = this.utils.renderStackedBlocks(
  121. this.control.direc,
  122. lineColor,
  123. fillColor,
  124. this.control.lineWidth,
  125. divisor
  126. );
  127. this.utils.renderFloorBlocks(
  128. this.control.direc,
  129. lineColor,
  130. this.control.lineWidth,
  131. divisor,
  132. correctXA
  133. );
  134. this.utils.renderCharacters();
  135. this.utils.renderMainUI();
  136. this.restart = restart;
  137. if (!this.restart) {
  138. game.timer.start(); // Set a timer for the current level (used in postScore())
  139. game.event.add('click', this.events.onInputDown);
  140. game.event.add('mousemove', this.events.onInputOver);
  141. }
  142. },
  143. /**
  144. * Game loop
  145. */
  146. update: function () {
  147. // Starts tractor animation
  148. if (self.animation.animateTractor) {
  149. self.utils.animateTractorHandler();
  150. }
  151. // Check answer after animation ends
  152. if (self.control.checkAnswer) {
  153. self.utils.checkAnswerHandler();
  154. }
  155. // Starts tractor moving animation
  156. if (self.animation.animateEnding) {
  157. self.utils.animateEndingHandler();
  158. }
  159. game.render.all();
  160. },
  161. utils: {
  162. // RENDER
  163. /**
  164. * Create stacked blocks for the level in create()
  165. */
  166. renderStackedBlocks: (direc, lineColor, fillColor, lineWidth, divisor) => {
  167. let restart = false;
  168. let hasBaseDifficulty = false; // Will be true after next for loop if level has at least one '1/difficulty' fraction (if false, restart)
  169. const max = gameMode == 'b' ? 10 : curMapPosition + 4; // Maximum number of stacked blocks for the level
  170. const total = game.math.randomInRange(curMapPosition + 2, max); // Current number of stacked blocks for the level
  171. let correctXA = self.default.x0 + self.default.width * direc;
  172. for (let i = 0; i < total; i++) {
  173. let curFractionItems = undefined;
  174. let font = undefined;
  175. let curDivisor = game.math.randomInRange(1, gameDifficulty); // Set divisor for fraction
  176. if (curDivisor === gameDifficulty) hasBaseDifficulty = true;
  177. if (curDivisor === 3) curDivisor = 4; // Make sure valid divisors are 1, 2 and 4 (not 3)
  178. const curBlockWidth = self.default.width / curDivisor; // Current width is a fraction of the default
  179. self.control.divisorsList += curDivisor + ','; // List of divisors (for postScore())
  180. correctXA += curBlockWidth * direc;
  181. const curBlock = game.add.geom.rect(
  182. self.default.x0,
  183. self.default.y0 - i * self.default.height - lineWidth,
  184. curBlockWidth,
  185. self.default.height,
  186. fillColor,
  187. 1,
  188. lineColor,
  189. lineWidth
  190. );
  191. curBlock.anchor(gameOperation === 'minus' ? 1 : 0, 1);
  192. curBlock.blockValue = divisor / curDivisor;
  193. // If game mode is (b), adding events to stacked blocks
  194. if (gameMode == 'b') {
  195. curBlock.blockIndex = i;
  196. }
  197. self.stack.list.push(curBlock);
  198. // If 'show fractions' is turned on, create labels that display the fractions on the side of each block
  199. const x = self.default.x0 + (curBlockWidth + 40) * direc;
  200. const y = self.default.height + 1;
  201. if (curDivisor === 1) {
  202. font = textStyles.h2_;
  203. curFractionItems = [
  204. {
  205. x: x,
  206. y: self.default.y0 - i * y - 20,
  207. text: '1',
  208. },
  209. {
  210. x: x - 25,
  211. y: self.default.y0 - i * y - 27,
  212. text: gameOperation === 'minus' ? '-' : '',
  213. },
  214. null,
  215. ];
  216. } else {
  217. font = textStyles.p_;
  218. curFractionItems = [
  219. {
  220. x: x,
  221. y: self.default.y0 - i * y - 40,
  222. text: '1\n' + curDivisor,
  223. },
  224. {
  225. x: x - 25,
  226. y: self.default.y0 - i * y - 27,
  227. text: gameOperation === 'minus' ? '-' : '',
  228. },
  229. {
  230. x0: x,
  231. y: self.default.y0 - i * y - 35,
  232. x1: x + 25,
  233. lineWidth: 2,
  234. color: lineColor,
  235. },
  236. ];
  237. }
  238. font = { ...font, font: 'bold ' + font.font, fill: lineColor };
  239. const fractionPartsList = [];
  240. for (let i = 0; i < 2; i++) {
  241. const item = game.add.text(
  242. curFractionItems[i].x,
  243. curFractionItems[i].y,
  244. curFractionItems[i].text,
  245. font
  246. );
  247. item.lineHeight = 30;
  248. fractionPartsList.push(item);
  249. }
  250. if (curFractionItems[2]) {
  251. const line = game.add.geom.line(
  252. curFractionItems[2].x0,
  253. curFractionItems[2].y,
  254. curFractionItems[2].x1,
  255. curFractionItems[2].y,
  256. curFractionItems[2].lineWidth,
  257. curFractionItems[2].color
  258. );
  259. line.anchor(0.5, 0);
  260. fractionPartsList.push(line);
  261. } else {
  262. fractionPartsList.push(null);
  263. }
  264. curBlock.fraction = {
  265. labels: fractionPartsList,
  266. nominator: direc,
  267. denominator: curDivisor,
  268. };
  269. if (!showFractions) {
  270. curBlock.fraction.labels.forEach((label) => {
  271. if (label) label.alpha = 0;
  272. });
  273. }
  274. }
  275. // Computer generated correct stack index
  276. if (gameMode === 'a') self.stack.selectedIndex = total - 1;
  277. // Will be used as a counter in update, adding in the width of each stacked block to check if the end matches the floor selected position
  278. // initial value is end of current block
  279. self.stack.curBlockEndX =
  280. self.default.x0 + self.stack.list[0].width * direc;
  281. // Check for errors (level too easy for its difficulty or end position out of bounds)
  282. if (
  283. !hasBaseDifficulty ||
  284. (gameOperation == 'plus' &&
  285. (correctXA < self.default.x0 + self.default.width ||
  286. correctXA > self.default.x0 + 8 * self.default.width)) ||
  287. (gameOperation == 'minus' &&
  288. (correctXA < self.default.x0 - 8 * self.default.width ||
  289. correctXA > self.default.x0 - self.default.width))
  290. ) {
  291. restart = true; // If any error is found restart the level
  292. }
  293. if (isDebugMode)
  294. console.log(
  295. 'Stacked blocks: ' +
  296. total +
  297. ' (min: ' +
  298. (curMapPosition + 2) +
  299. ', max: ' +
  300. max +
  301. ')'
  302. );
  303. return [restart, correctXA];
  304. },
  305. /**
  306. * Create floor blocks for the level in create()
  307. */
  308. renderFloorBlocks: (direc, lineColor, lineWidth, divisor, correctXA) => {
  309. let correctXB = 0;
  310. let total = 8 * divisor; // Number of floor blocks
  311. const blockWidth = self.default.width / divisor; // Width of each floor block
  312. // If game is type (b), selectiong a random floor x position
  313. if (gameMode == 'b') {
  314. self.stack.correctIndex = game.math.randomInRange(
  315. 0,
  316. self.stack.list.length - 1
  317. ); // Correct stacked index
  318. correctXB = self.default.x0 + self.default.width * direc;
  319. for (let i = 0; i <= self.stack.correctIndex; i++) {
  320. correctXB += self.stack.list[i].width * direc; // Equivalent x position on the floor
  321. }
  322. }
  323. let flag = true;
  324. for (let i = 0; i < total; i++) {
  325. const curX =
  326. self.default.x0 + (self.default.width + i * blockWidth) * direc;
  327. if (flag && gameMode == 'a') {
  328. if (
  329. (gameOperation == 'plus' && curX >= correctXA) ||
  330. (gameOperation == 'minus' && curX <= correctXA)
  331. ) {
  332. self.floor.correctIndex = i - 1; // Set index of correct floor block
  333. flag = false;
  334. }
  335. }
  336. if (gameMode == 'b') {
  337. if (
  338. (gameOperation == 'plus' && curX >= correctXB) ||
  339. (gameOperation == 'minus' && curX <= correctXB)
  340. ) {
  341. total = i;
  342. break;
  343. }
  344. }
  345. // Create floor block
  346. const curBlock = game.add.geom.rect(
  347. curX,
  348. self.default.y0,
  349. blockWidth,
  350. self.default.height + 10,
  351. colors.blueBgInsideLevel,
  352. 1,
  353. colors.gray,
  354. lineWidth
  355. );
  356. const anchor = gameOperation == 'minus' ? 1 : 0;
  357. curBlock.anchor(anchor, 0);
  358. curBlock.blockValue = 1;
  359. // If game is type (a), adding events to floor blocks
  360. if (gameMode == 'a') {
  361. curBlock.fillColor = 'transparent';
  362. curBlock.blockIndex = i;
  363. }
  364. // Add current label to group of labels
  365. self.floor.list.push(curBlock);
  366. }
  367. // Computer generated correct floor index
  368. if (gameMode === 'b') self.floor.selectedIndex = total - 1;
  369. if (gameMode == 'a') self.floor.correctX = correctXA;
  370. else if (gameMode == 'b') self.floor.correctX = correctXB;
  371. // Creates labels on the floor to display the numbers
  372. for (let i = 0; i <= 8; i++) {
  373. const x = self.default.x0 + (i + 1) * self.default.width * direc;
  374. const y = self.default.y0 + self.default.height + 45 - 65;
  375. let numberX = x;
  376. let numberText = i;
  377. let numberCircleSize = 45;
  378. let numberFont = {
  379. ...textStyles.h3_,
  380. fill: lineColor,
  381. font: 'bold ' + textStyles.h3_.font,
  382. };
  383. if (gameOperation === 'minus') {
  384. numberX = i !== 0 ? x - 2 : x;
  385. numberText = -i;
  386. numberCircleSize = 45;
  387. numberFont.font = 'bold ' + textStyles.h4_.font;
  388. }
  389. game.add.geom
  390. .circle(x, y, numberCircleSize, undefined, 0, colors.white, 1)
  391. .anchor(0, 0.25);
  392. game.add.text(numberX, y + 2, numberText, numberFont);
  393. }
  394. },
  395. renderCharacters: () => {
  396. self.tractor = game.add.sprite(
  397. self.default.x0,
  398. self.default.y0,
  399. 'tractor',
  400. 0,
  401. 1
  402. );
  403. if (gameOperation == 'plus') {
  404. self.tractor.anchor(1, 1);
  405. self.tractor.animation = ['move', [0, 1, 2, 3, 4], 4];
  406. } else {
  407. self.tractor.anchor(0, 1);
  408. self.tractor.animation = ['move', [5, 6, 7, 8, 9], 4];
  409. self.tractor.curFrame = 5;
  410. }
  411. },
  412. renderMainUI: () => {
  413. // Help pointer
  414. self.ui.help = game.add.image(0, 0, 'pointer', 1.7, 0);
  415. if (gameMode === 'b') self.ui.help.anchor(0.25, 0.7);
  416. else self.ui.help.anchor(0.2, 0);
  417. // Selection Arrow
  418. if (gameMode == 'a') {
  419. self.ui.arrow = game.add.image(
  420. self.default.arrowX0,
  421. self.default.y0,
  422. 'arrow_down',
  423. 1.5
  424. );
  425. self.ui.arrow.anchor(0.5, 1);
  426. self.ui.arrow.alpha = 0.5;
  427. }
  428. // Intro text
  429. const correctMessage =
  430. gameMode === 'a'
  431. ? game.lang.squareOne_intro_a
  432. : game.lang.squareOne_intro_b;
  433. const treatedMessage = correctMessage.split('\\n');
  434. const font = textStyles.h1_;
  435. self.ui.message = [];
  436. self.ui.message.push(
  437. game.add.text(
  438. context.canvas.width / 2,
  439. 170,
  440. treatedMessage[0] + '\n' + treatedMessage[1],
  441. font
  442. )
  443. );
  444. },
  445. renderOperationUI: () => {
  446. let validBlocks = [];
  447. const lastValidIndex =
  448. gameMode === 'a' ? self.stack.curIndex : self.stack.selectedIndex;
  449. for (let i = 0; i <= lastValidIndex; i++) {
  450. validBlocks.push(self.stack.list[i]);
  451. }
  452. const font = textStyles.fraction;
  453. font.fill = colors.green;
  454. const nominators = [];
  455. const denominators = [];
  456. const renderList = [];
  457. const padding = 100;
  458. const offsetX = 100;
  459. const widthOfChar = 35;
  460. const x0 = padding;
  461. const y0 = context.canvas.height / 3;
  462. let nextX = x0;
  463. const cardHeight = 400;
  464. const cardX = x0 - padding;
  465. const cardY = y0; // + cardHeight / 4;
  466. // Card
  467. const card = game.add.geom.rect(
  468. cardX,
  469. cardY,
  470. 0,
  471. cardHeight,
  472. colors.blueLight,
  473. 0.5,
  474. colors.blueDark,
  475. 8
  476. );
  477. card.id = 'card';
  478. card.anchor(0, 0.5);
  479. renderList.push(card);
  480. // Fraction list
  481. for (let i in validBlocks) {
  482. const curFraction = validBlocks[i].fraction;
  483. const curFractionString = curFraction.labels[0].name;
  484. let curFractionSign = i !== '0' ? '+' : '';
  485. if (curFraction.labels[1].name === '-') {
  486. curFractionSign = '-';
  487. font.fill = colors.red;
  488. }
  489. const fraction = game.add.text(
  490. x0 + i * offsetX + offsetX / 2,
  491. curFractionString === '1' ? y0 + 40 : y0,
  492. curFractionString,
  493. font,
  494. 60
  495. );
  496. fraction.lineHeight = 70;
  497. renderList.push(
  498. game.add.text(x0 + i * offsetX, y0 + 35, curFractionSign, font)
  499. );
  500. renderList.push(fraction);
  501. renderList.push(
  502. game.add.text(
  503. x0 + offsetX / 2 + i * offsetX,
  504. y0,
  505. curFractionString === '1' ? '' : '_',
  506. font
  507. )
  508. );
  509. nominators.push(curFraction.nominator);
  510. denominators.push(curFraction.denominator);
  511. }
  512. // Setup for fraction operation with least common multiple
  513. font.fill = colors.black;
  514. const updatedNominators = [];
  515. const mmc = game.math.mmcArray(denominators);
  516. let resultNominator = 0;
  517. for (let i in nominators) {
  518. const temp = nominators[i] * (mmc / denominators[i]);
  519. updatedNominators.push(temp);
  520. resultNominator += temp;
  521. }
  522. const resultNominatorUnsigned =
  523. resultNominator < 0 ? -resultNominator : resultNominator;
  524. const resultAux = resultNominator / mmc;
  525. const result =
  526. ('' + resultAux).length > 4 ? resultAux.toFixed(2) : resultAux;
  527. // Fraction operation with least common multiple
  528. nextX = x0 + validBlocks.length * offsetX + 20;
  529. // Fraction result
  530. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  531. font.align = 'center';
  532. nextX += offsetX;
  533. if (result < 0) {
  534. nextX += 60;
  535. renderList.push(game.add.text(nextX - 80, y0 + 35, '-', font));
  536. nextX -= 30;
  537. }
  538. const fractionResult = game.add.text(
  539. nextX,
  540. mmc === 1 || resultNominatorUnsigned === 0 ? y0 + 40 : y0,
  541. mmc === 1 || resultNominatorUnsigned === 0
  542. ? resultNominatorUnsigned
  543. : resultNominatorUnsigned + '\n' + mmc,
  544. font
  545. );
  546. fractionResult.lineHeight = 70;
  547. renderList.push(fractionResult);
  548. const fractionLine = game.add.geom.line(
  549. nextX,
  550. y0 + 15,
  551. nextX + 60,
  552. y0 + 15,
  553. 4,
  554. colors.black,
  555. mmc === 1 || resultNominatorUnsigned === 0 ? 0 : 1
  556. );
  557. fractionLine.anchor(0.5, 0);
  558. renderList.push(fractionLine);
  559. // Fraction result simplified setup
  560. const mdcAux = game.math.mdc(resultNominator, mmc);
  561. const mdc = mdcAux < 0 ? -mdcAux : mdcAux;
  562. if (mdc !== 1 && resultNominatorUnsigned !== 0) {
  563. nextX += offsetX;
  564. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  565. nextX += offsetX;
  566. renderList.push(
  567. game.add.text(nextX - 50, y0 + 35, result > 0 ? '' : '-', font)
  568. );
  569. renderList.push(
  570. game.add.text(nextX, y0, resultNominatorUnsigned / mdc, font)
  571. );
  572. renderList.push(game.add.text(nextX, y0 + 70, mmc / mdc, font));
  573. const fractionLine = game.add.geom.line(
  574. nextX,
  575. y0 + 15,
  576. nextX + 60,
  577. y0 + 15,
  578. 4,
  579. colors.black
  580. );
  581. fractionLine.anchor(0.5, 0);
  582. renderList.push(fractionLine);
  583. }
  584. // Decimal result
  585. let resultWidth = '_'.length * widthOfChar;
  586. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  587. card.width = cardWidth;
  588. // Center Card
  589. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  590. self.fractionOperationUI = renderList;
  591. // Feedback on the floor
  592. if (gameMode === 'a') {
  593. if (self.control.isCorrect) {
  594. const floorFlag = game.add.image(
  595. self.floor.list[self.floor.correctIndex].x,
  596. self.tractor.y + 10,
  597. 'flag_green',
  598. 0.7
  599. );
  600. floorFlag.anchor(0, 1);
  601. } else {
  602. let min = self.floor.selectedIndex,
  603. max = self.floor.correctIndex;
  604. if (min > max) {
  605. let aux = min;
  606. min = max;
  607. max = aux;
  608. }
  609. for (let i = min + 1; i <= max; i++) {
  610. self.floor.list[i].fillColor = colors.red;
  611. self.floor.list[i].alpha = 1;
  612. }
  613. }
  614. } else {
  615. if (self.control.isCorrect) {
  616. console.log(self.floor);
  617. const floorFlag = game.add.image(
  618. self.floor.list[self.floor.curIndex].x,
  619. self.tractor.y + 10,
  620. 'flag_green',
  621. 0.7
  622. );
  623. floorFlag.anchor(0, 1);
  624. } else {
  625. let min = self.floor.selectedIndex,
  626. max = self.floor.curIndex;
  627. if (min < max) {
  628. for (let i = min + 1; i <= max; i++) {
  629. self.floor.list[i].fillColor = colors.red;
  630. self.floor.list[i].alpha = 1;
  631. }
  632. }
  633. }
  634. }
  635. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  636. return endSignX;
  637. },
  638. renderEndUI: () => {
  639. let btnColor = colors.green;
  640. let btnText = game.lang.continue;
  641. if (!self.control.isCorrect) {
  642. btnColor = colors.red;
  643. btnText = game.lang.retry;
  644. }
  645. // continue button
  646. self.ui.continue.button = game.add.geom.rect(
  647. context.canvas.width / 2,
  648. context.canvas.height / 2 + 100,
  649. 450,
  650. 100,
  651. btnColor
  652. );
  653. self.ui.continue.button.anchor(0.5, 0.5);
  654. self.ui.continue.text = game.add.text(
  655. context.canvas.width / 2,
  656. context.canvas.height / 2 + 16 + 100,
  657. btnText,
  658. textStyles.btn
  659. );
  660. },
  661. // UPDATE HANDLERS
  662. animateTractorHandler: () => {
  663. // Move
  664. self.tractor.x += self.animation.speed;
  665. self.stack.list.forEach((block) => (block.x += self.animation.speed));
  666. // If the current block is 1/n (not 1/1) we need to consider the
  667. // extra space the truck needs to pass after the blocks falls but
  668. // before reaching the next block
  669. const curBlockExtra =
  670. (self.default.width - self.stack.list[self.stack.curIndex].width) *
  671. self.control.direc;
  672. const canLowerBlocks =
  673. (gameOperation == 'plus' &&
  674. self.stack.list[0].x >= self.stack.curBlockEndX + curBlockExtra) ||
  675. (gameOperation == 'minus' &&
  676. self.stack.list[0].x <= self.stack.curBlockEndX + curBlockExtra);
  677. if (canLowerBlocks) {
  678. const endAnimation = self.utils.lowerBlocksHandler();
  679. if (!endAnimation) {
  680. self.animation.animateTractor = false;
  681. self.control.checkAnswer = true;
  682. }
  683. }
  684. },
  685. lowerBlocksHandler: () => {
  686. self.floor.curIndex += self.stack.list[self.stack.curIndex].blockValue;
  687. const tooManyStackBlocks = self.floor.curIndex > self.floor.selectedIndex;
  688. if (tooManyStackBlocks) return false;
  689. // fill floor
  690. for (let i = 0; i <= self.floor.curIndex; i++) {
  691. self.floor.list[i].fillColor = 'transparent';
  692. }
  693. // lower blocks
  694. self.stack.list.forEach((block) => {
  695. block.y += self.default.height;
  696. });
  697. // hide current block
  698. self.stack.list[self.stack.curIndex].alpha = 0;
  699. const isLastFloorBlock = self.floor.curIndex === self.floor.selectedIndex;
  700. const notEnoughStackBlocks =
  701. self.stack.curIndex === self.stack.list.length - 1;
  702. if (isLastFloorBlock || notEnoughStackBlocks) return false;
  703. // update stack blocks
  704. self.stack.curIndex++;
  705. self.stack.curBlockEndX +=
  706. self.stack.list[self.stack.curIndex].width * self.control.direc;
  707. return true;
  708. },
  709. checkAnswerHandler: () => {
  710. game.timer.stop();
  711. game.animation.stop(self.tractor.animation[0]);
  712. if (gameMode === 'a') self.ui.arrow.alpha = 0;
  713. self.control.isCorrect =
  714. gameMode === 'a'
  715. ? self.floor.selectedIndex === self.floor.correctIndex
  716. : self.stack.selectedIndex === self.stack.correctIndex;
  717. const x = self.utils.renderOperationUI();
  718. // Give feedback to player and turns on sprite animation
  719. if (self.control.isCorrect) {
  720. completedLevels++; // Increases number os finished levels
  721. if (audioStatus) game.audio.okSound.play();
  722. game.animation.play(self.tractor.animation[0]);
  723. game.add
  724. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  725. .anchor(0.5, 0.5);
  726. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  727. } else {
  728. if (audioStatus) game.audio.errorSound.play();
  729. game.add
  730. .image(x, context.canvas.height / 3, 'answer_wrong')
  731. .anchor(0.5, 0.5);
  732. }
  733. self.fetch.postScore();
  734. self.control.checkAnswer = false;
  735. self.animation.animateEnding = true;
  736. },
  737. animateEndingHandler: () => {
  738. // ANIMATE ENDING
  739. self.control.count++;
  740. // If CORRECT ANSWER runs final tractor animation (else tractor desn't move, just wait)
  741. if (self.control.isCorrect) self.tractor.x += self.animation.speed;
  742. if (self.control.count === 100) {
  743. self.utils.renderEndUI();
  744. self.control.showEndInfo = true;
  745. if (self.control.isCorrect) canGoToNextMapPosition = true;
  746. else canGoToNextMapPosition = false;
  747. }
  748. },
  749. endLevel: () => {
  750. game.state.start('map');
  751. },
  752. // INFORMATION
  753. /**
  754. * Display correct answer
  755. */
  756. showAnswer: () => {
  757. // On gameMode (a)
  758. if (gameMode == 'a') {
  759. const aux = self.floor.list[0];
  760. self.ui.help.x =
  761. self.floor.correctX - (aux.width / 2) * self.control.direc;
  762. self.ui.help.y = self.default.y0;
  763. // On gameMode (b)
  764. } else {
  765. const aux = self.stack.list[self.stack.correctIndex];
  766. self.ui.help.x = aux.x + (aux.width / 2) * self.control.direc;
  767. self.ui.help.y = aux.y;
  768. }
  769. if (!self.control.hasClicked) {
  770. self.ui.help.alpha = 0.7;
  771. }
  772. },
  773. // EVENT HANDLERS
  774. /**
  775. * Function called by self.events.onInputDown() when player clicks on a valid rectangle.
  776. */
  777. clickHandler: (clickedIndex, curSet) => {
  778. if (!self.control.hasClicked && !self.animation.animateEnding) {
  779. document.body.style.cursor = 'auto';
  780. // Play beep sound
  781. if (audioStatus) game.audio.popSound.play();
  782. // Disable show answer nav icon
  783. navigation.disableIcon(navigation.showAnswerIcon);
  784. // Hide intro message
  785. self.ui.message[0].alpha = 0;
  786. // Hide labels
  787. if (showFractions) {
  788. self.stack.list.forEach((block) => {
  789. block.fraction.labels.forEach((lbl) => {
  790. if (lbl) lbl.alpha = 0;
  791. });
  792. });
  793. }
  794. // Hide solution pointer
  795. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  796. // Hide unselected blocks
  797. for (let i = curSet.list.length - 1; i > clickedIndex; i--) {
  798. curSet.list[i].alpha = 0;
  799. }
  800. // Save selected index
  801. curSet.selectedIndex = clickedIndex;
  802. if (gameMode == 'a') {
  803. self.ui.arrow.alpha = 0;
  804. } else {
  805. // update list size
  806. self.stack.list.length = curSet.selectedIndex + 1;
  807. }
  808. // Turn tractor animation on
  809. game.animation.play(self.tractor.animation[0]);
  810. self.animation.animateTractor = true;
  811. self.control.hasClicked = true;
  812. }
  813. },
  814. /**
  815. * Function called by self.events.onInputOver() when cursor is over a valid rectangle
  816. *
  817. * @param {object} cur rectangle the cursor is over
  818. */
  819. overHandler: (cur) => {
  820. if (!self.control.hasClicked) {
  821. document.body.style.cursor = 'pointer';
  822. if (gameMode === 'a') {
  823. for (let i in self.floor.list) {
  824. self.floor.list[i].fillColor =
  825. i <= cur.blockIndex ? colors.blueBgInsideLevel : 'transparent';
  826. }
  827. self.floor.selectedIndex = cur.blockIndex;
  828. } else {
  829. for (let i in self.stack.list) {
  830. const alpha = i <= cur.blockIndex ? 1 : 0.4;
  831. self.stack.list[i].alpha = alpha;
  832. if (showFractions) {
  833. self.stack.list[i].fraction.labels.forEach((lbl) => {
  834. if (lbl) lbl.alpha = alpha;
  835. });
  836. }
  837. }
  838. self.stack.selectedIndex = cur.blockIndex;
  839. }
  840. }
  841. },
  842. /**
  843. * Function called by self.events.onInputOver() when cursos is out of a valid rectangle
  844. */
  845. outHandler: () => {
  846. if (!self.control.hasClicked) {
  847. document.body.style.cursor = 'auto';
  848. if (gameMode === 'a') {
  849. for (let i in self.floor.list) {
  850. self.floor.list[i].fillColor = 'transparent';
  851. }
  852. self.floor.selectedIndex = undefined;
  853. } else {
  854. for (let i in self.stack.list) {
  855. self.stack.list[i].alpha = 1;
  856. if (showFractions) {
  857. self.stack.list[i].fraction.labels.forEach((lbl) => {
  858. if (lbl) lbl.alpha = 1;
  859. });
  860. }
  861. }
  862. self.stack.selectedIndex = undefined;
  863. }
  864. }
  865. },
  866. },
  867. events: {
  868. /**
  869. * Called by mouse click event
  870. *
  871. * @param {object} mouseEvent contains the mouse click coordinates
  872. */
  873. onInputDown: (mouseEvent) => {
  874. const x = game.math.getMouse(mouseEvent).x;
  875. const y = game.math.getMouse(mouseEvent).y;
  876. // click blocks
  877. const curSet = gameMode == 'a' ? self.floor : self.stack;
  878. for (let i in curSet.list) {
  879. if (game.math.isOverIcon(x, y, curSet.list[i])) {
  880. self.utils.clickHandler(+i, curSet);
  881. break;
  882. }
  883. }
  884. // Continue button
  885. if (self.control.showEndInfo) {
  886. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  887. if (audioStatus) game.audio.popSound.play();
  888. self.utils.endLevel();
  889. }
  890. }
  891. navigation.onInputDown(x, y);
  892. game.render.all();
  893. },
  894. /**
  895. * Called by mouse move event
  896. *
  897. * @param {object} mouseEvent contains the mouse move coordinates
  898. */
  899. onInputOver: (mouseEvent) => {
  900. const x = game.math.getMouse(mouseEvent).x;
  901. const y = game.math.getMouse(mouseEvent).y;
  902. let isOverFloor = false;
  903. let isOverStack = false;
  904. if (gameMode == 'a') {
  905. self.floor.list.forEach((cur) => {
  906. // hover floor blocks
  907. if (game.math.isOverIcon(x, y, cur)) {
  908. isOverFloor = true;
  909. self.utils.overHandler(cur);
  910. }
  911. // move arrow
  912. if (
  913. !self.control.hasClicked &&
  914. !self.animation.animateEnding &&
  915. game.math.isOverIcon(x, self.default.y0, cur)
  916. ) {
  917. self.ui.arrow.x = x;
  918. }
  919. });
  920. if (!isOverFloor) self.utils.outHandler('a');
  921. }
  922. if (gameMode == 'b') {
  923. // hover stack blocks
  924. self.stack.list.forEach((cur) => {
  925. if (game.math.isOverIcon(x, y, cur)) {
  926. isOverStack = true;
  927. self.utils.overHandler(cur);
  928. }
  929. });
  930. if (!isOverStack) self.utils.outHandler('b');
  931. }
  932. // Continue button
  933. if (self.control.showEndInfo) {
  934. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  935. // If pointer is over icon
  936. document.body.style.cursor = 'pointer';
  937. self.ui.continue.button.scale =
  938. self.ui.continue.button.initialScale * 1.1;
  939. self.ui.continue.text.style = textStyles.btnLg;
  940. } else {
  941. // If pointer is not over icon
  942. document.body.style.cursor = 'auto';
  943. self.ui.continue.button.scale =
  944. self.ui.continue.button.initialScale * 1;
  945. self.ui.continue.text.style = textStyles.btn;
  946. }
  947. }
  948. navigation.onInputOver(x, y);
  949. game.render.all();
  950. },
  951. },
  952. fetch: {
  953. /**
  954. * Saves players data after level ends - to be sent to database <br>
  955. *
  956. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  957. *
  958. * @see /php/save.php
  959. */
  960. postScore: () => {
  961. // Creates string that is going to be sent to db
  962. const data =
  963. '&line_game=' +
  964. gameShape +
  965. '&line_mode=' +
  966. gameMode +
  967. '&line_oper=' +
  968. gameOperation +
  969. '&line_leve=' +
  970. gameDifficulty +
  971. '&line_posi=' +
  972. curMapPosition +
  973. '&line_resu=' +
  974. self.control.isCorrect +
  975. '&line_time=' +
  976. game.timer.elapsed +
  977. '&line_deta=' +
  978. 'numBlocks:' +
  979. self.stack.list.length +
  980. ', valBlocks: ' +
  981. self.control.divisorsList + // Ends in ','
  982. ' blockIndex: ' +
  983. self.stack.selectedIndex +
  984. ', floorIndex: ' +
  985. self.floor.selectedIndex;
  986. // FOR MOODLE
  987. sendToDatabase(data);
  988. },
  989. },
  990. };