squareOne.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. if (showFractions) {
  200. const x = self.default.x0 + (curBlockWidth + 40) * direc;
  201. const y = self.default.height + 1;
  202. if (curDivisor === 1) {
  203. font = textStyles.h2_;
  204. curFractionItems = [
  205. {
  206. x: x,
  207. y: self.default.y0 - i * y - 20,
  208. text: '1',
  209. },
  210. {
  211. x: x - 25,
  212. y: self.default.y0 - i * y - 27,
  213. text: gameOperation === 'minus' ? '-' : '',
  214. },
  215. null,
  216. ];
  217. } else {
  218. font = textStyles.p_;
  219. curFractionItems = [
  220. {
  221. x: x,
  222. y: self.default.y0 - i * y - 40,
  223. text: '1\n' + curDivisor,
  224. },
  225. {
  226. x: x - 25,
  227. y: self.default.y0 - i * y - 27,
  228. text: gameOperation === 'minus' ? '-' : '',
  229. },
  230. {
  231. x0: x,
  232. y: self.default.y0 - i * y - 35,
  233. x1: x + 25,
  234. lineWidth: 2,
  235. color: lineColor,
  236. },
  237. ];
  238. }
  239. font = { ...font, font: 'bold ' + font.font, fill: lineColor };
  240. const fractionPartsList = [];
  241. for (let i = 0; i < 2; i++) {
  242. const item = game.add.text(
  243. curFractionItems[i].x,
  244. curFractionItems[i].y,
  245. curFractionItems[i].text,
  246. font
  247. );
  248. item.lineHeight = 30;
  249. fractionPartsList.push(item);
  250. }
  251. if (curFractionItems[2]) {
  252. const line = game.add.geom.line(
  253. curFractionItems[2].x0,
  254. curFractionItems[2].y,
  255. curFractionItems[2].x1,
  256. curFractionItems[2].y,
  257. curFractionItems[2].lineWidth,
  258. curFractionItems[2].color
  259. );
  260. line.anchor(0.5, 0);
  261. fractionPartsList.push(line);
  262. } else {
  263. fractionPartsList.push(null);
  264. }
  265. curBlock.fraction = {
  266. labels: fractionPartsList,
  267. nominator: direc,
  268. denominator: curDivisor,
  269. };
  270. }
  271. }
  272. // Computer generated correct stack index
  273. if (gameMode === 'a') self.stack.selectedIndex = total - 1;
  274. // 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
  275. // initial value is end of current block
  276. self.stack.curBlockEndX =
  277. self.default.x0 + self.stack.list[0].width * direc;
  278. // Check for errors (level too easy for its difficulty or end position out of bounds)
  279. if (
  280. !hasBaseDifficulty ||
  281. (gameOperation == 'plus' &&
  282. (correctXA < self.default.x0 + self.default.width ||
  283. correctXA > self.default.x0 + 8 * self.default.width)) ||
  284. (gameOperation == 'minus' &&
  285. (correctXA < self.default.x0 - 8 * self.default.width ||
  286. correctXA > self.default.x0 - self.default.width))
  287. ) {
  288. restart = true; // If any error is found restart the level
  289. }
  290. if (isDebugMode)
  291. console.log(
  292. 'Stacked blocks: ' +
  293. total +
  294. ' (min: ' +
  295. (curMapPosition + 2) +
  296. ', max: ' +
  297. max +
  298. ')'
  299. );
  300. return [restart, correctXA];
  301. },
  302. /**
  303. * Create floor blocks for the level in create()
  304. */
  305. renderFloorBlocks: (direc, lineColor, lineWidth, divisor, correctXA) => {
  306. let correctXB = 0;
  307. let total = 8 * divisor; // Number of floor blocks
  308. const blockWidth = self.default.width / divisor; // Width of each floor block
  309. // If game is type (b), selectiong a random floor x position
  310. if (gameMode == 'b') {
  311. self.stack.correctIndex = game.math.randomInRange(
  312. 0,
  313. self.stack.list.length - 1
  314. ); // Correct stacked index
  315. correctXB = self.default.x0 + self.default.width * direc;
  316. for (let i = 0; i <= self.stack.correctIndex; i++) {
  317. correctXB += self.stack.list[i].width * direc; // Equivalent x position on the floor
  318. }
  319. }
  320. let flag = true;
  321. for (let i = 0; i < total; i++) {
  322. const curX =
  323. self.default.x0 + (self.default.width + i * blockWidth) * direc;
  324. if (flag && gameMode == 'a') {
  325. if (
  326. (gameOperation == 'plus' && curX >= correctXA) ||
  327. (gameOperation == 'minus' && curX <= correctXA)
  328. ) {
  329. self.floor.correctIndex = i - 1; // Set index of correct floor block
  330. flag = false;
  331. }
  332. }
  333. if (gameMode == 'b') {
  334. if (
  335. (gameOperation == 'plus' && curX >= correctXB) ||
  336. (gameOperation == 'minus' && curX <= correctXB)
  337. ) {
  338. total = i;
  339. break;
  340. }
  341. }
  342. // Create floor block
  343. const curBlock = game.add.geom.rect(
  344. curX,
  345. self.default.y0,
  346. blockWidth,
  347. self.default.height + 10,
  348. colors.blueBgInsideLevel,
  349. 1,
  350. colors.gray,
  351. lineWidth
  352. );
  353. const anchor = gameOperation == 'minus' ? 1 : 0;
  354. curBlock.anchor(anchor, 0);
  355. curBlock.blockValue = 1;
  356. // If game is type (a), adding events to floor blocks
  357. if (gameMode == 'a') {
  358. curBlock.fillColor = 'transparent';
  359. curBlock.blockIndex = i;
  360. }
  361. // Add current label to group of labels
  362. self.floor.list.push(curBlock);
  363. }
  364. // Computer generated correct floor index
  365. if (gameMode === 'b') self.floor.selectedIndex = total - 1;
  366. if (gameMode == 'a') self.floor.correctX = correctXA;
  367. else if (gameMode == 'b') self.floor.correctX = correctXB;
  368. // Creates labels on the floor to display the numbers
  369. for (let i = 0; i <= 8; i++) {
  370. const x = self.default.x0 + (i + 1) * self.default.width * direc;
  371. const y = self.default.y0 + self.default.height + 45 - 65;
  372. let numberX = x;
  373. let numberText = i;
  374. let numberCircleSize = 45;
  375. let numberFont = {
  376. ...textStyles.h3_,
  377. fill: lineColor,
  378. font: 'bold ' + textStyles.h3_.font,
  379. };
  380. if (gameOperation === 'minus') {
  381. numberX = i !== 0 ? x - 2 : x;
  382. numberText = -i;
  383. numberCircleSize = 45;
  384. numberFont.font = 'bold ' + textStyles.h4_.font;
  385. }
  386. game.add.geom
  387. .circle(x, y, numberCircleSize, undefined, 0, colors.white, 1)
  388. .anchor(0, 0.25);
  389. game.add.text(numberX, y + 2, numberText, numberFont);
  390. }
  391. },
  392. renderCharacters: () => {
  393. self.tractor = game.add.sprite(
  394. self.default.x0,
  395. self.default.y0,
  396. 'tractor',
  397. 0,
  398. 1
  399. );
  400. if (gameOperation == 'plus') {
  401. self.tractor.anchor(1, 1);
  402. self.tractor.animation = ['move', [0, 1, 2, 3, 4], 4];
  403. } else {
  404. self.tractor.anchor(0, 1);
  405. self.tractor.animation = ['move', [5, 6, 7, 8, 9], 4];
  406. self.tractor.curFrame = 5;
  407. }
  408. },
  409. renderMainUI: () => {
  410. // Help pointer
  411. self.ui.help = game.add.image(0, 0, 'pointer', 1.7, 0);
  412. if (gameMode === 'b') self.ui.help.anchor(0.25, 0.7);
  413. else self.ui.help.anchor(0.2, 0);
  414. // Selection Arrow
  415. if (gameMode == 'a') {
  416. self.ui.arrow = game.add.image(
  417. self.default.arrowX0,
  418. self.default.y0,
  419. 'arrow_down',
  420. 1.5
  421. );
  422. self.ui.arrow.anchor(0.5, 1);
  423. self.ui.arrow.alpha = 0.5;
  424. }
  425. // Intro text
  426. const correctMessage =
  427. gameMode === 'a'
  428. ? game.lang.squareOne_intro_a
  429. : game.lang.squareOne_intro_b;
  430. const treatedMessage = correctMessage.split('\\n');
  431. const font = textStyles.h1_;
  432. self.ui.message = [];
  433. self.ui.message.push(
  434. game.add.text(
  435. context.canvas.width / 2,
  436. 170,
  437. treatedMessage[0] + '\n' + treatedMessage[1],
  438. font
  439. )
  440. );
  441. },
  442. renderOperationUI: () => {
  443. let validBlocks = [];
  444. const lastValidIndex =
  445. gameMode === 'a' ? self.stack.curIndex : self.stack.selectedIndex;
  446. for (let i = 0; i <= lastValidIndex; i++) {
  447. validBlocks.push(self.stack.list[i]);
  448. }
  449. const font = textStyles.fraction;
  450. font.fill = colors.green;
  451. const nominators = [];
  452. const denominators = [];
  453. const renderList = [];
  454. const padding = 100;
  455. const offsetX = 100;
  456. const widthOfChar = 35;
  457. const x0 = padding;
  458. const y0 = context.canvas.height / 3;
  459. let nextX = x0;
  460. const cardHeight = 400;
  461. const cardX = x0 - padding;
  462. const cardY = y0; // + cardHeight / 4;
  463. // Card
  464. const card = game.add.geom.rect(
  465. cardX,
  466. cardY,
  467. 0,
  468. cardHeight,
  469. colors.blueLight,
  470. 0.5,
  471. colors.blueDark,
  472. 8
  473. );
  474. card.id = 'card';
  475. card.anchor(0, 0.5);
  476. renderList.push(card);
  477. // Fraction list
  478. for (let i in validBlocks) {
  479. const curFraction = validBlocks[i].fraction;
  480. const curFractionString = curFraction.labels[0].name;
  481. let curFractionSign = i !== '0' ? '+' : '';
  482. if (curFraction.labels[1].name === '-') {
  483. curFractionSign = '-';
  484. font.fill = colors.red;
  485. }
  486. const fraction = game.add.text(
  487. x0 + i * offsetX + offsetX / 2,
  488. curFractionString === '1' ? y0 + 40 : y0,
  489. curFractionString,
  490. font,
  491. 60
  492. );
  493. fraction.lineHeight = 70;
  494. renderList.push(
  495. game.add.text(x0 + i * offsetX, y0 + 35, curFractionSign, font)
  496. );
  497. renderList.push(fraction);
  498. renderList.push(
  499. game.add.text(
  500. x0 + offsetX / 2 + i * offsetX,
  501. y0,
  502. curFractionString === '1' ? '' : '_',
  503. font
  504. )
  505. );
  506. nominators.push(curFraction.nominator);
  507. denominators.push(curFraction.denominator);
  508. }
  509. // Setup for fraction operation with least common multiple
  510. font.fill = colors.black;
  511. const updatedNominators = [];
  512. const mmc = game.math.mmcArray(denominators);
  513. let resultNominator = 0;
  514. for (let i in nominators) {
  515. const temp = nominators[i] * (mmc / denominators[i]);
  516. updatedNominators.push(temp);
  517. resultNominator += temp;
  518. }
  519. const resultNominatorUnsigned =
  520. resultNominator < 0 ? -resultNominator : resultNominator;
  521. const resultAux = resultNominator / mmc;
  522. const result =
  523. ('' + resultAux).length > 4 ? resultAux.toFixed(2) : resultAux;
  524. // Fraction operation with least common multiple
  525. nextX = x0 + validBlocks.length * offsetX + 20;
  526. // Fraction result
  527. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  528. font.align = 'center';
  529. nextX += offsetX;
  530. if (result < 0) {
  531. nextX += 60;
  532. renderList.push(game.add.text(nextX - 80, y0 + 35, '-', font));
  533. nextX -= 30;
  534. }
  535. const fractionResult = game.add.text(
  536. nextX,
  537. mmc === 1 || resultNominatorUnsigned === 0 ? y0 + 40 : y0,
  538. mmc === 1 || resultNominatorUnsigned === 0
  539. ? resultNominatorUnsigned
  540. : resultNominatorUnsigned + '\n' + mmc,
  541. font
  542. );
  543. fractionResult.lineHeight = 70;
  544. renderList.push(fractionResult);
  545. const fractionLine = game.add.geom.line(
  546. nextX,
  547. y0 + 15,
  548. nextX + 60,
  549. y0 + 15,
  550. 4,
  551. colors.black,
  552. mmc === 1 || resultNominatorUnsigned === 0 ? 0 : 1
  553. );
  554. fractionLine.anchor(0.5, 0);
  555. renderList.push(fractionLine);
  556. // Fraction result simplified setup
  557. const mdcAux = game.math.mdc(resultNominator, mmc);
  558. const mdc = mdcAux < 0 ? -mdcAux : mdcAux;
  559. if (mdc !== 1 && resultNominatorUnsigned !== 0) {
  560. nextX += offsetX;
  561. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  562. nextX += offsetX;
  563. renderList.push(
  564. game.add.text(nextX - 50, y0 + 35, result > 0 ? '' : '-', font)
  565. );
  566. renderList.push(
  567. game.add.text(nextX, y0, resultNominatorUnsigned / mdc, font)
  568. );
  569. renderList.push(game.add.text(nextX, y0 + 70, mmc / mdc, font));
  570. const fractionLine = game.add.geom.line(
  571. nextX,
  572. y0 + 15,
  573. nextX + 60,
  574. y0 + 15,
  575. 4,
  576. colors.black
  577. );
  578. fractionLine.anchor(0.5, 0);
  579. renderList.push(fractionLine);
  580. }
  581. // Decimal result
  582. let resultWidth = '_'.length * widthOfChar;
  583. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  584. card.width = cardWidth;
  585. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  586. // Center Card
  587. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  588. self.fractionOperationUI = renderList;
  589. return endSignX;
  590. },
  591. renderEndUI: () => {
  592. let btnColor = colors.green;
  593. let btnText = game.lang.continue;
  594. if (!self.control.isCorrect) {
  595. btnColor = colors.red;
  596. btnText = game.lang.retry;
  597. }
  598. // continue button
  599. self.ui.continue.button = game.add.geom.rect(
  600. context.canvas.width / 2,
  601. context.canvas.height / 2 + 100,
  602. 450,
  603. 100,
  604. btnColor
  605. );
  606. self.ui.continue.button.anchor(0.5, 0.5);
  607. self.ui.continue.text = game.add.text(
  608. context.canvas.width / 2,
  609. context.canvas.height / 2 + 16 + 100,
  610. btnText,
  611. textStyles.btn
  612. );
  613. },
  614. // UPDATE HANDLERS
  615. animateTractorHandler: () => {
  616. // Move
  617. self.tractor.x += self.animation.speed;
  618. self.stack.list.forEach((block) => (block.x += self.animation.speed));
  619. // If the current block is 1/n (not 1/1) we need to consider the
  620. // extra space the truck needs to pass after the blocks falls but
  621. // before reaching the next block
  622. const curBlockExtra =
  623. (self.default.width - self.stack.list[self.stack.curIndex].width) *
  624. self.control.direc;
  625. const canLowerBlocks =
  626. (gameOperation == 'plus' &&
  627. self.stack.list[0].x >= self.stack.curBlockEndX + curBlockExtra) ||
  628. (gameOperation == 'minus' &&
  629. self.stack.list[0].x <= self.stack.curBlockEndX + curBlockExtra);
  630. if (canLowerBlocks) {
  631. const endAnimation = self.utils.lowerBlocksHandler();
  632. if (!endAnimation) {
  633. self.animation.animateTractor = false;
  634. self.control.checkAnswer = true;
  635. }
  636. }
  637. },
  638. lowerBlocksHandler: () => {
  639. self.floor.curIndex += self.stack.list[self.stack.curIndex].blockValue;
  640. const tooManyStackBlocks = self.floor.curIndex > self.floor.selectedIndex;
  641. if (tooManyStackBlocks) return false;
  642. // fill floor
  643. for (let i = 0; i <= self.floor.curIndex; i++) {
  644. self.floor.list[i].fillColor = 'transparent';
  645. }
  646. // lower blocks
  647. self.stack.list.forEach((block) => {
  648. block.y += self.default.height;
  649. });
  650. // hide current block
  651. self.stack.list[self.stack.curIndex].alpha = 0;
  652. const isLastFloorBlock = self.floor.curIndex === self.floor.selectedIndex;
  653. const notEnoughStackBlocks =
  654. self.stack.curIndex === self.stack.list.length - 1;
  655. if (isLastFloorBlock || notEnoughStackBlocks) return false;
  656. // update stack blocks
  657. self.stack.curIndex++;
  658. self.stack.curBlockEndX +=
  659. self.stack.list[self.stack.curIndex].width * self.control.direc;
  660. return true;
  661. },
  662. checkAnswerHandler: () => {
  663. game.timer.stop();
  664. game.animation.stop(self.tractor.animation[0]);
  665. if (gameMode === 'a') self.ui.arrow.alpha = 0;
  666. self.control.isCorrect =
  667. gameMode === 'a'
  668. ? self.floor.selectedIndex === self.floor.correctIndex
  669. : self.stack.selectedIndex === self.stack.correctIndex;
  670. const x = self.utils.renderOperationUI();
  671. // Give feedback to player and turns on sprite animation
  672. if (self.control.isCorrect) {
  673. completedLevels++; // Increases number os finished levels
  674. if (audioStatus) game.audio.okSound.play();
  675. game.animation.play(self.tractor.animation[0]);
  676. game.add
  677. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  678. .anchor(0.5, 0.5);
  679. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  680. } else {
  681. if (audioStatus) game.audio.errorSound.play();
  682. game.add
  683. .image(x, context.canvas.height / 3, 'answer_wrong')
  684. .anchor(0.5, 0.5);
  685. }
  686. self.fetch.postScore();
  687. self.control.checkAnswer = false;
  688. self.animation.animateEnding = true;
  689. },
  690. animateEndingHandler: () => {
  691. // ANIMATE ENDING
  692. self.control.count++;
  693. // If CORRECT ANSWER runs final tractor animation (else tractor desn't move, just wait)
  694. if (self.control.isCorrect) self.tractor.x += self.animation.speed;
  695. if (self.control.count === 100) {
  696. self.utils.renderEndUI();
  697. self.control.showEndInfo = true;
  698. if (self.control.isCorrect) canGoToNextMapPosition = true;
  699. else canGoToNextMapPosition = false;
  700. }
  701. },
  702. endLevel: () => {
  703. game.state.start('map');
  704. },
  705. // INFORMATION
  706. /**
  707. * Display correct answer
  708. */
  709. showAnswer: () => {
  710. if (!self.control.hasClicked) {
  711. // On gameMode (a)
  712. if (gameMode == 'a') {
  713. const aux = self.floor.list[0];
  714. self.ui.help.x =
  715. self.floor.correctX - (aux.width / 2) * self.control.direc;
  716. self.ui.help.y = self.default.y0;
  717. // On gameMode (b)
  718. } else {
  719. const aux = self.stack.list[self.stack.correctIndex];
  720. self.ui.help.x = aux.x + (aux.width / 2) * self.control.direc;
  721. self.ui.help.y = aux.y;
  722. }
  723. self.ui.help.alpha = 0.7;
  724. }
  725. },
  726. // EVENT HANDLERS
  727. /**
  728. * Function called by self.events.onInputDown() when player clicks on a valid rectangle.
  729. */
  730. clickHandler: (clickedIndex, curSet) => {
  731. if (!self.control.hasClicked && !self.animation.animateEnding) {
  732. document.body.style.cursor = 'auto';
  733. // Play beep sound
  734. if (audioStatus) game.audio.popSound.play();
  735. // Disable show answer nav icon
  736. navigation.disableIcon(navigation.showAnswerIcon);
  737. // Hide intro message
  738. self.ui.message[0].alpha = 0;
  739. // Hide labels
  740. if (showFractions) {
  741. self.stack.list.forEach((block) => {
  742. block.fraction.labels.forEach((lbl) => {
  743. if (lbl) lbl.alpha = 0;
  744. });
  745. });
  746. }
  747. // Hide solution pointer
  748. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  749. // Hide unselected blocks
  750. for (let i = curSet.list.length - 1; i > clickedIndex; i--) {
  751. curSet.list[i].alpha = 0;
  752. }
  753. // Save selected index
  754. curSet.selectedIndex = clickedIndex;
  755. if (gameMode == 'a') {
  756. self.ui.arrow.alpha = 0;
  757. } else {
  758. // update list size
  759. self.stack.list.length = curSet.selectedIndex + 1;
  760. }
  761. // Turn tractor animation on
  762. game.animation.play(self.tractor.animation[0]);
  763. self.animation.animateTractor = true;
  764. self.control.hasClicked = true;
  765. }
  766. },
  767. /**
  768. * Function called by self.events.onInputOver() when cursor is over a valid rectangle
  769. *
  770. * @param {object} cur rectangle the cursor is over
  771. */
  772. overHandler: (cur) => {
  773. if (!self.control.hasClicked) {
  774. document.body.style.cursor = 'pointer';
  775. if (gameMode === 'a') {
  776. for (let i in self.floor.list) {
  777. self.floor.list[i].fillColor =
  778. i <= cur.blockIndex ? colors.blueBgInsideLevel : 'transparent';
  779. }
  780. self.floor.selectedIndex = cur.blockIndex;
  781. } else {
  782. for (let i in self.stack.list) {
  783. const alpha = i <= cur.blockIndex ? 1 : 0.4;
  784. self.stack.list[i].alpha = alpha;
  785. self.stack.list[i].fraction.labels.forEach((lbl) => {
  786. if (lbl) lbl.alpha = alpha;
  787. });
  788. }
  789. self.stack.selectedIndex = cur.blockIndex;
  790. }
  791. }
  792. },
  793. /**
  794. * Function called by self.events.onInputOver() when cursos is out of a valid rectangle
  795. */
  796. outHandler: () => {
  797. if (!self.control.hasClicked) {
  798. document.body.style.cursor = 'auto';
  799. if (gameMode === 'a') {
  800. for (let i in self.floor.list) {
  801. self.floor.list[i].fillColor = 'transparent';
  802. }
  803. self.floor.selectedIndex = undefined;
  804. } else {
  805. for (let i in self.stack.list) {
  806. self.stack.list[i].alpha = 1;
  807. self.stack.list[i].fraction.labels.forEach((lbl) => {
  808. if (lbl) lbl.alpha = 1;
  809. });
  810. }
  811. self.stack.selectedIndex = undefined;
  812. }
  813. }
  814. },
  815. },
  816. events: {
  817. /**
  818. * Called by mouse click event
  819. *
  820. * @param {object} mouseEvent contains the mouse click coordinates
  821. */
  822. onInputDown: (mouseEvent) => {
  823. const x = game.math.getMouse(mouseEvent).x;
  824. const y = game.math.getMouse(mouseEvent).y;
  825. // click blocks
  826. const curSet = gameMode == 'a' ? self.floor : self.stack;
  827. for (let i in curSet.list) {
  828. if (game.math.isOverIcon(x, y, curSet.list[i])) {
  829. self.utils.clickHandler(+i, curSet);
  830. break;
  831. }
  832. }
  833. // Continue button
  834. if (self.control.showEndInfo) {
  835. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  836. if (audioStatus) game.audio.popSound.play();
  837. self.utils.endLevel();
  838. }
  839. }
  840. navigation.onInputDown(x, y);
  841. game.render.all();
  842. },
  843. /**
  844. * Called by mouse move event
  845. *
  846. * @param {object} mouseEvent contains the mouse move coordinates
  847. */
  848. onInputOver: (mouseEvent) => {
  849. const x = game.math.getMouse(mouseEvent).x;
  850. const y = game.math.getMouse(mouseEvent).y;
  851. let isOverFloor = false;
  852. let isOverStack = false;
  853. if (gameMode == 'a') {
  854. self.floor.list.forEach((cur) => {
  855. // hover floor blocks
  856. if (game.math.isOverIcon(x, y, cur)) {
  857. isOverFloor = true;
  858. self.utils.overHandler(cur);
  859. }
  860. // move arrow
  861. if (
  862. !self.control.hasClicked &&
  863. !self.animation.animateEnding &&
  864. game.math.isOverIcon(x, self.default.y0, cur)
  865. ) {
  866. self.ui.arrow.x = x;
  867. }
  868. });
  869. if (!isOverFloor) self.utils.outHandler('a');
  870. }
  871. if (gameMode == 'b') {
  872. // hover stack blocks
  873. self.stack.list.forEach((cur) => {
  874. if (game.math.isOverIcon(x, y, cur)) {
  875. isOverStack = true;
  876. self.utils.overHandler(cur);
  877. }
  878. });
  879. if (!isOverStack) self.utils.outHandler('b');
  880. }
  881. // Continue button
  882. if (self.control.showEndInfo) {
  883. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  884. // If pointer is over icon
  885. document.body.style.cursor = 'pointer';
  886. self.ui.continue.button.scale =
  887. self.ui.continue.button.initialScale * 1.1;
  888. self.ui.continue.text.style = textStyles.btnLg;
  889. } else {
  890. // If pointer is not over icon
  891. document.body.style.cursor = 'auto';
  892. self.ui.continue.button.scale =
  893. self.ui.continue.button.initialScale * 1;
  894. self.ui.continue.text.style = textStyles.btn;
  895. }
  896. }
  897. navigation.onInputOver(x, y);
  898. game.render.all();
  899. },
  900. },
  901. fetch: {
  902. /**
  903. * Saves players data after level ends - to be sent to database <br>
  904. *
  905. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  906. *
  907. * @see /php/save.php
  908. */
  909. postScore: () => {
  910. // Creates string that is going to be sent to db
  911. const data =
  912. '&line_game=' +
  913. gameShape +
  914. '&line_mode=' +
  915. gameMode +
  916. '&line_oper=' +
  917. gameOperation +
  918. '&line_leve=' +
  919. gameDifficulty +
  920. '&line_posi=' +
  921. curMapPosition +
  922. '&line_resu=' +
  923. self.control.isCorrect +
  924. '&line_time=' +
  925. game.timer.elapsed +
  926. '&line_deta=' +
  927. 'numBlocks:' +
  928. self.stack.list.length +
  929. ', valBlocks: ' +
  930. self.control.divisorsList + // Ends in ','
  931. ' blockIndex: ' +
  932. self.stack.selectedIndex +
  933. ', floorIndex: ' +
  934. self.floor.selectedIndex;
  935. // FOR MOODLE
  936. sendToDatabase(data);
  937. },
  938. },
  939. };