squareOne.js 32 KB

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