squareOne.js 36 KB

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