squareOne.js 32 KB

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