squareOne.js 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  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. /**
  524. *
  525. * if game mode A:
  526. * - left: (1) selected floor position (user selection)
  527. * - right: (2) expected floor position equivalent to the stack of blocks (pre-set)
  528. *
  529. * if game mode B:
  530. * - left: (3) floor position equivalent to the stack of blocks (user selection)
  531. * - right: (4) generated floor position (pre-set)
  532. */
  533. const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
  534. const renderFloorFractions = (lastIndex, divisor) => {
  535. const operator = gameOperation === 'minus' ? '-' : '+';
  536. const index = lastIndex;
  537. const blocks = index + 1;
  538. const valueReal = blocks / divisor;
  539. const valueFloor = Math.floor(valueReal);
  540. const valueRest = valueReal - valueFloor;
  541. let fracNomin = (fracDenomin = fracLine = '');
  542. // adds sign on the left of the equation
  543. if (gameOperation === 'minus') {
  544. fracNomin += ' ';
  545. fracDenomin += ' ';
  546. fracLine += operator;
  547. }
  548. // 1 _ _
  549. if (valueFloor) {
  550. fracNomin += ' ';
  551. fracDenomin += ' ';
  552. fracLine += valueFloor;
  553. }
  554. // _ + _
  555. if (valueFloor && valueRest) {
  556. fracNomin += ' ';
  557. fracDenomin += ' ';
  558. fracLine += operator;
  559. }
  560. // _ _ 1/5
  561. if (valueRest) {
  562. fracNomin += `${valueRest * divisor}`;
  563. fracDenomin += `${divisor}`;
  564. fracLine += '-';
  565. }
  566. return [fracNomin, fracDenomin, fracLine, valueReal];
  567. };
  568. const renderStackFractions = (lastIndex) => {
  569. const operator = gameOperation === 'minus' ? '-' : '+';
  570. const index = lastIndex;
  571. const blocks = index + 1;
  572. const nominators = [];
  573. const denominators = [];
  574. const values = [];
  575. let valueReal = 0;
  576. let fracNomin = (fracDenomin = fracLine = '');
  577. for (let i = 0; i < blocks; i++) {
  578. const m = self.stack.list[i].fraction.denominator || 1;
  579. const temp = self.stack.list[i].fraction.nominator || 0;
  580. const n = gameOperation === 'minus' ? -temp : +temp;
  581. const nm = n / m;
  582. nominators[i] = n + 0;
  583. denominators[i] = m + 0;
  584. values[i] = nm;
  585. valueReal += nm;
  586. }
  587. for (let i = 0; i < blocks; i++) {
  588. const valueReal = values[i];
  589. const valueFloor = Math.floor(valueReal);
  590. const valueRest = valueReal - valueFloor;
  591. if (i > 0 || gameOperation === 'minus') {
  592. fracNomin += ' ';
  593. fracDenomin += ' ';
  594. fracLine += operator;
  595. }
  596. if (valueFloor && !valueRest) {
  597. fracNomin += ' ';
  598. fracDenomin += ' ';
  599. fracLine += valueFloor;
  600. }
  601. if (valueRest) {
  602. fracNomin += `${nominators[i]}`;
  603. fracDenomin += `${denominators[i]}`;
  604. fracLine += '-';
  605. }
  606. }
  607. return [fracNomin, fracDenomin, fracLine, valueReal];
  608. };
  609. // Initial setup
  610. const font = textStyles.fraction;
  611. font.fill = colors.black;
  612. const padding = 100;
  613. const offsetX = 100;
  614. const widthOfChar = 35;
  615. const x0 = padding;
  616. const y0 = context.canvas.height / 3;
  617. let nextX = x0;
  618. const cardHeight = 400;
  619. const cardX = x0 - padding;
  620. const cardY = y0;
  621. const renderList = [];
  622. // Render Card
  623. const card = game.add.geom.rect(
  624. cardX,
  625. cardY,
  626. 0,
  627. cardHeight,
  628. colors.blueLight,
  629. 0.5,
  630. colors.blueDark,
  631. 8
  632. );
  633. card.id = 'card';
  634. card.anchor(0, 0.5);
  635. renderList.push(card);
  636. // Fraction setup
  637. console.clear();
  638. const [floorNominators, floorDenominators, floorLines, floorValue] =
  639. renderFloorFractions(
  640. self.floor.selectedIndex,
  641. divisor
  642. // 'LEFT SIDE - a fração escolhida no chão é...\n\n'
  643. );
  644. renderFloorFractions(
  645. self.floor.correctIndex,
  646. divisor
  647. // '\n\nRIGHT SIDE 1 - a fração CORRETA no chão é...\n\n'
  648. );
  649. const [stackNominators, stackDenominators, stackLines, stackValue] =
  650. renderStackFractions(
  651. self.stack.selectedIndex
  652. // '\n\nRIGHT SIDE 2 - a fração CORRETA na stack é...\n\n'
  653. );
  654. const renderFloorOperationLine = (x) => {
  655. font.fill = colors.black;
  656. const floorNom = game.add.text(
  657. x + offsetX / 2,
  658. y0,
  659. floorNominators,
  660. font,
  661. 60
  662. );
  663. const floorDenom = game.add.text(
  664. x + offsetX / 2,
  665. y0 + 70,
  666. floorDenominators,
  667. font,
  668. 60
  669. );
  670. const floorLin = game.add.text(
  671. x + offsetX / 2,
  672. y0 + 35,
  673. floorLines,
  674. font,
  675. 60
  676. );
  677. renderList.push(floorNom);
  678. renderList.push(floorDenom);
  679. renderList.push(floorLin);
  680. };
  681. const renderStackOperationLine = (x) => {
  682. font.fill = colors.black;
  683. const stackNom = game.add.text(
  684. x + offsetX / 2,
  685. y0,
  686. stackNominators,
  687. font,
  688. 60
  689. );
  690. const stackDenom = game.add.text(
  691. x + offsetX / 2,
  692. y0 + 70,
  693. stackDenominators,
  694. font,
  695. 60
  696. );
  697. const stackLin = game.add.text(
  698. x + offsetX / 2,
  699. y0 + 35,
  700. stackLines,
  701. font,
  702. 60
  703. );
  704. renderList.push(stackNom);
  705. renderList.push(stackDenom);
  706. renderList.push(stackLin);
  707. };
  708. // Render LEFT part of the operation
  709. if (gameMode === 'a') renderFloorOperationLine(x0);
  710. else renderStackOperationLine(x0);
  711. let curNominators = gameMode === 'a' ? floorNominators : stackNominators;
  712. nextX = x0 + (curNominators.length + 2) * widthOfChar;
  713. // Render middle sign - equal by default
  714. font.fill = colors.green;
  715. let comparisonSign = '=';
  716. // Render middle sign - if not equal
  717. if (floorValue != stackValue) {
  718. font.fill = colors.red;
  719. let leftSideIsLarger = floorValue > stackValue;
  720. if (gameMode === 'b') leftSideIsLarger = !leftSideIsLarger;
  721. if (gameOperation === 'minus') leftSideIsLarger = !leftSideIsLarger;
  722. comparisonSign = leftSideIsLarger ? '>' : '<';
  723. }
  724. renderList.push(game.add.text(nextX, y0 + 35, comparisonSign, font));
  725. // Render RIGHT part of the operation
  726. if (gameMode === 'a') renderStackOperationLine(nextX);
  727. else renderFloorOperationLine(nextX);
  728. curNominators = gameMode === 'a' ? stackNominators : floorNominators;
  729. const resultWidth = (curNominators.length + 2) * widthOfChar;
  730. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  731. card.width = cardWidth;
  732. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  733. // Center Card
  734. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  735. self.fractionOperationUI = renderList;
  736. return endSignX;
  737. },
  738. renderEndUI: () => {
  739. let btnColor = colors.green;
  740. let btnText = game.lang.continue;
  741. if (!self.control.isCorrect) {
  742. btnColor = colors.red;
  743. btnText = game.lang.retry;
  744. }
  745. // continue button
  746. self.ui.continue.button = game.add.geom.rect(
  747. context.canvas.width / 2,
  748. context.canvas.height / 2 + 100,
  749. 450,
  750. 100,
  751. btnColor
  752. );
  753. self.ui.continue.button.anchor(0.5, 0.5);
  754. self.ui.continue.text = game.add.text(
  755. context.canvas.width / 2,
  756. context.canvas.height / 2 + 16 + 100,
  757. btnText,
  758. textStyles.btn
  759. );
  760. },
  761. // UPDATE HANDLERS
  762. animateTractorHandler: () => {
  763. // Move
  764. self.tractor.x += self.animation.speed;
  765. self.stack.list.forEach((block) => (block.x += self.animation.speed));
  766. // If the current block is 1/n (not 1/1) we need to consider the
  767. // extra space the truck needs to pass after the blocks falls but
  768. // before reaching the next block
  769. const curBlockExtra =
  770. (self.default.width - self.stack.list[self.stack.curIndex].width) *
  771. self.control.direc;
  772. const canLowerBlocks =
  773. (gameOperation == 'plus' &&
  774. self.stack.list[0].x >= self.stack.curBlockEndX + curBlockExtra) ||
  775. (gameOperation == 'minus' &&
  776. self.stack.list[0].x <= self.stack.curBlockEndX + curBlockExtra);
  777. if (canLowerBlocks) {
  778. const endAnimation = self.utils.lowerBlocksHandler();
  779. if (!endAnimation) {
  780. self.animation.animateTractor = false;
  781. self.control.checkAnswer = true;
  782. }
  783. }
  784. },
  785. lowerBlocksHandler: () => {
  786. self.floor.curIndex += self.stack.list[self.stack.curIndex].blockValue;
  787. const tooManyStackBlocks = self.floor.curIndex > self.floor.selectedIndex;
  788. if (tooManyStackBlocks) return false;
  789. // fill floor
  790. for (let i = 0; i <= self.floor.curIndex; i++) {
  791. self.floor.list[i].fillColor = 'transparent';
  792. }
  793. // lower blocks
  794. self.stack.list.forEach((block) => {
  795. block.y += self.default.height;
  796. });
  797. // hide current block
  798. self.stack.list[self.stack.curIndex].alpha = 0;
  799. const isLastFloorBlock = self.floor.curIndex === self.floor.selectedIndex;
  800. const notEnoughStackBlocks =
  801. self.stack.curIndex === self.stack.list.length - 1;
  802. if (isLastFloorBlock || notEnoughStackBlocks) return false;
  803. // update stack blocks
  804. self.stack.curIndex++;
  805. self.stack.curBlockEndX +=
  806. self.stack.list[self.stack.curIndex].width * self.control.direc;
  807. return true;
  808. },
  809. checkAnswerHandler: () => {
  810. game.timer.stop();
  811. game.animation.stop(self.tractor.animation[0]);
  812. if (gameMode === 'a') self.ui.arrow.alpha = 0;
  813. self.control.isCorrect =
  814. gameMode === 'a'
  815. ? self.floor.selectedIndex === self.floor.correctIndex
  816. : self.stack.selectedIndex === self.stack.correctIndex;
  817. const x = self.utils.renderOperationUI();
  818. // Give feedback to player and turns on sprite animation
  819. if (self.control.isCorrect) {
  820. completedLevels++; // Increases number os finished levels
  821. if (audioStatus) game.audio.okSound.play();
  822. game.animation.play(self.tractor.animation[0]);
  823. game.add
  824. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  825. .anchor(0.5, 0.5);
  826. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  827. } else {
  828. if (audioStatus) game.audio.errorSound.play();
  829. game.add
  830. .image(x, context.canvas.height / 3, 'answer_wrong')
  831. .anchor(0.5, 0.5);
  832. }
  833. self.fetch.postScore();
  834. self.control.checkAnswer = false;
  835. self.animation.animateEnding = true;
  836. },
  837. animateEndingHandler: () => {
  838. // ANIMATE ENDING
  839. self.control.count++;
  840. // If CORRECT ANSWER runs final tractor animation (else tractor desn't move, just wait)
  841. if (self.control.isCorrect) self.tractor.x += self.animation.speed;
  842. if (self.control.count === 100) {
  843. self.utils.renderEndUI();
  844. self.control.showEndInfo = true;
  845. if (self.control.isCorrect) canGoToNextMapPosition = true;
  846. else canGoToNextMapPosition = false;
  847. }
  848. },
  849. endLevel: () => {
  850. game.state.start('map');
  851. },
  852. // INFORMATION
  853. /**
  854. * Display correct answer
  855. */
  856. showAnswer: () => {
  857. if (!self.control.hasClicked) {
  858. // On gameMode (a)
  859. if (gameMode === 'a') {
  860. const aux = self.floor.list[0];
  861. self.ui.help.x =
  862. self.floor.correctX - (aux.width / 2) * self.control.direc;
  863. self.ui.help.y = self.default.y0;
  864. // On gameMode (b)
  865. } else {
  866. const aux = self.stack.list[self.stack.correctIndex];
  867. self.ui.help.x = aux.x + (aux.width / 2) * self.control.direc;
  868. self.ui.help.y = aux.y;
  869. }
  870. self.ui.help.alpha = 0.7;
  871. }
  872. },
  873. // EVENT HANDLERS
  874. /**
  875. * Function called by self.events.onInputDown() when player clicks on a valid rectangle.
  876. */
  877. clickHandler: (clickedIndex, curSet) => {
  878. if (!self.control.hasClicked && !self.animation.animateEnding) {
  879. document.body.style.cursor = 'auto';
  880. // Play beep sound
  881. if (audioStatus) game.audio.popSound.play();
  882. // Disable show answer nav icon
  883. navigation.disableIcon(navigation.showAnswerIcon);
  884. // Hide intro message
  885. self.ui.message[0].alpha = 0;
  886. // Hide labels
  887. if (showFractions) {
  888. self.stack.list.forEach((block) => {
  889. block.fraction.labels.forEach((lbl) => {
  890. if (lbl) lbl.alpha = 0;
  891. });
  892. });
  893. }
  894. // Hide solution pointer
  895. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  896. // Hide unselected blocks
  897. for (let i = curSet.list.length - 1; i > clickedIndex; i--) {
  898. curSet.list[i].alpha = 0;
  899. }
  900. // Save selected index
  901. curSet.selectedIndex = clickedIndex;
  902. if (gameMode === 'a') {
  903. self.ui.arrow.alpha = 0;
  904. } else {
  905. // update list size
  906. self.stack.list.length = curSet.selectedIndex + 1;
  907. }
  908. // Turn tractor animation on
  909. game.animation.play(self.tractor.animation[0]);
  910. self.animation.animateTractor = true;
  911. self.control.hasClicked = true;
  912. }
  913. },
  914. /**
  915. * Function called by self.events.onInputOver() when cursor is over a valid rectangle
  916. *
  917. * @param {object} cur rectangle the cursor is over
  918. */
  919. overHandler: (cur) => {
  920. if (!self.control.hasClicked) {
  921. document.body.style.cursor = 'pointer';
  922. if (gameMode === 'a') {
  923. for (let i in self.floor.list) {
  924. self.floor.list[i].fillColor =
  925. i <= cur.blockIndex ? colors.blueBgInsideLevel : 'transparent';
  926. }
  927. self.floor.selectedIndex = cur.blockIndex;
  928. } else {
  929. for (let i in self.stack.list) {
  930. const alpha = i <= cur.blockIndex ? 1 : 0.4;
  931. self.stack.list[i].alpha = alpha;
  932. if (showFractions) {
  933. self.stack.list[i].fraction.labels.forEach((lbl) => {
  934. if (lbl) lbl.alpha = alpha;
  935. });
  936. }
  937. }
  938. self.stack.selectedIndex = cur.blockIndex;
  939. }
  940. }
  941. },
  942. /**
  943. * Function called by self.events.onInputOver() when cursos is out of a valid rectangle
  944. */
  945. outHandler: () => {
  946. if (!self.control.hasClicked) {
  947. document.body.style.cursor = 'auto';
  948. if (gameMode === 'a') {
  949. for (let i in self.floor.list) {
  950. self.floor.list[i].fillColor = 'transparent';
  951. }
  952. self.floor.selectedIndex = undefined;
  953. } else {
  954. for (let i in self.stack.list) {
  955. self.stack.list[i].alpha = 1;
  956. if (showFractions) {
  957. self.stack.list[i].fraction.labels.forEach((lbl) => {
  958. if (lbl) lbl.alpha = 1;
  959. });
  960. }
  961. }
  962. self.stack.selectedIndex = undefined;
  963. }
  964. }
  965. },
  966. },
  967. events: {
  968. /**
  969. * Called by mouse click event
  970. *
  971. * @param {object} mouseEvent contains the mouse click coordinates
  972. */
  973. onInputDown: (mouseEvent) => {
  974. const x = game.math.getMouse(mouseEvent).x;
  975. const y = game.math.getMouse(mouseEvent).y;
  976. // click blocks
  977. const curSet = gameMode == 'a' ? self.floor : self.stack;
  978. for (let i in curSet.list) {
  979. if (game.math.isOverIcon(x, y, curSet.list[i])) {
  980. self.utils.clickHandler(+i, curSet);
  981. break;
  982. }
  983. }
  984. // Continue button
  985. if (self.control.showEndInfo) {
  986. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  987. if (audioStatus) game.audio.popSound.play();
  988. self.utils.endLevel();
  989. }
  990. }
  991. navigation.onInputDown(x, y);
  992. game.render.all();
  993. },
  994. /**
  995. * Called by mouse move event
  996. *
  997. * @param {object} mouseEvent contains the mouse move coordinates
  998. */
  999. onInputOver: (mouseEvent) => {
  1000. const x = game.math.getMouse(mouseEvent).x;
  1001. const y = game.math.getMouse(mouseEvent).y;
  1002. let isOverFloor = false;
  1003. let isOverStack = false;
  1004. if (gameMode === 'a') {
  1005. self.floor.list.forEach((cur) => {
  1006. // hover floor blocks
  1007. if (game.math.isOverIcon(x, y, cur)) {
  1008. isOverFloor = true;
  1009. self.utils.overHandler(cur);
  1010. }
  1011. // move arrow
  1012. if (
  1013. !self.control.hasClicked &&
  1014. !self.animation.animateEnding &&
  1015. game.math.isOverIcon(x, self.default.y0, cur)
  1016. ) {
  1017. self.ui.arrow.x = x;
  1018. }
  1019. });
  1020. if (!isOverFloor) self.utils.outHandler('a');
  1021. }
  1022. if (gameMode === 'b') {
  1023. // hover stack blocks
  1024. self.stack.list.forEach((cur) => {
  1025. if (game.math.isOverIcon(x, y, cur)) {
  1026. isOverStack = true;
  1027. self.utils.overHandler(cur);
  1028. }
  1029. });
  1030. if (!isOverStack) self.utils.outHandler('b');
  1031. }
  1032. // Continue button
  1033. if (self.control.showEndInfo) {
  1034. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1035. // If pointer is over icon
  1036. document.body.style.cursor = 'pointer';
  1037. self.ui.continue.button.scale =
  1038. self.ui.continue.button.initialScale * 1.1;
  1039. self.ui.continue.text.style = textStyles.btnLg;
  1040. } else {
  1041. // If pointer is not over icon
  1042. document.body.style.cursor = 'auto';
  1043. self.ui.continue.button.scale =
  1044. self.ui.continue.button.initialScale * 1;
  1045. self.ui.continue.text.style = textStyles.btn;
  1046. }
  1047. }
  1048. navigation.onInputOver(x, y);
  1049. game.render.all();
  1050. },
  1051. },
  1052. fetch: {
  1053. /**
  1054. * Saves players data after level ends - to be sent to database <br>
  1055. *
  1056. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  1057. *
  1058. * @see /php/save.php
  1059. */
  1060. postScore: () => {
  1061. // Creates string that is going to be sent to db
  1062. const data =
  1063. '&line_game=' +
  1064. gameShape +
  1065. '&line_mode=' +
  1066. gameMode +
  1067. '&line_oper=' +
  1068. gameOperation +
  1069. '&line_leve=' +
  1070. gameDifficulty +
  1071. '&line_posi=' +
  1072. curMapPosition +
  1073. '&line_resu=' +
  1074. self.control.isCorrect +
  1075. '&line_time=' +
  1076. game.timer.elapsed +
  1077. '&line_deta=' +
  1078. 'numBlocks:' +
  1079. self.stack.list.length +
  1080. ', valBlocks: ' +
  1081. self.control.divisorsList + // Ends in ','
  1082. ' blockIndex: ' +
  1083. self.stack.selectedIndex +
  1084. ', floorIndex: ' +
  1085. self.floor.selectedIndex;
  1086. // FOR MOODLE
  1087. sendToDatabase(data);
  1088. },
  1089. },
  1090. };