squareOne.js 32 KB

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