squareOne.js 37 KB

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