squareOne.js 35 KB

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