squareOne.js 33 KB

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