squareOne.js 33 KB

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