circleOne.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  1. /******************************
  2. * This file holds game states.
  3. ******************************/
  4. /** [GAME STATE]
  5. *
  6. * .....circleOne.... = gameName
  7. * ....../...\.......
  8. * .....a.....b...... = gameMode
  9. * .......\./........
  10. * ........|.........
  11. * ....../.|.\.......
  12. * .plus.minus.mixed. = gameOperation
  13. * ......\.|./.......
  14. * ........|.........
  15. * ......1,2,3....... = gameDifficulty
  16. *
  17. * Character : kid/balloon
  18. * Theme : flying in a balloon
  19. * Concept : 'How much the kid has to walk to get to the balloon?'
  20. * Represent fractions as : circles/arcs
  21. *
  22. * Game modes can be :
  23. *
  24. * a : Player can place balloon position
  25. * Place balloon in position (so the kid can get to it)
  26. * b : Player can select # of circles
  27. * Selects number of circles (that represent distance kid needs to walk to get to the balloon)
  28. *
  29. * Operations can be :
  30. *
  31. * plus : addition of fractions
  32. * Represented by : kid going to the right (floor positions 0..5)
  33. * minus : subtraction of fractions
  34. * Represented by: kid going to the left (floor positions 5..0)
  35. * mixed : Mix addition and subtraction of fractions in same
  36. * Represented by: kid going to the left (floor positions 0..5)
  37. *
  38. * @namespace
  39. */
  40. const circleOne = {
  41. ui: undefined,
  42. control: undefined,
  43. animation: undefined,
  44. road: undefined,
  45. circles: undefined,
  46. kid: undefined,
  47. balloon: undefined,
  48. basket: undefined,
  49. walkedPath: undefined,
  50. /**
  51. * Main code
  52. */
  53. create: function () {
  54. this.ui = {
  55. help: undefined,
  56. message: undefined,
  57. continue: {
  58. // modal: undefined,
  59. button: undefined,
  60. text: undefined,
  61. },
  62. };
  63. const roadMapper = () => {
  64. const _pointWidth = (game.sprite['map_place'].width / 2) * 0.45;
  65. const defaultX = 150;
  66. const defaultY =
  67. context.canvas.height - game.image['floor_grass'].width * 1.5;
  68. const defaultWidth = 1620;
  69. // Initial 'x' coordinate for the kid and the baloon
  70. const x =
  71. gameOperation === 'minus'
  72. ? context.canvas.width - defaultX - _pointWidth / 2
  73. : defaultX + _pointWidth / 2;
  74. const y = defaultY;
  75. const width = defaultWidth - _pointWidth;
  76. const _divisions = 5;
  77. const _subdivisions = gameDifficulty === 3 ? 4 : gameDifficulty;
  78. const numberOfBlocks = _divisions * _subdivisions;
  79. return { x, y, width, numberOfBlocks, defaultX, defaultY, defaultWidth };
  80. };
  81. this.road = roadMapper();
  82. const blocksMapper = () => {
  83. let width = this.road.width / this.road.numberOfBlocks;
  84. if (gameOperation === 'minus') width = -width;
  85. const height = 50;
  86. return { width, height, list: [], cur: undefined };
  87. };
  88. this.blocks = blocksMapper();
  89. this.walkedPath = [];
  90. const pointWidth = (game.sprite['map_place'].width / 2) * 0.45;
  91. const distanceBetweenPoints =
  92. (context.canvas.width - this.road.defaultX * 2 - pointWidth) / 5; // Distance between road points
  93. const y0 = this.road.defaultY + 20;
  94. const x0 = this.road.x;
  95. this.circles = {
  96. diameter: game.math.getRadiusFromCircunference(distanceBetweenPoints) * 2, // (Fixed) Circles Diameter
  97. cur: 0, // Current circle index
  98. list: [], // Circle objects
  99. };
  100. this.control = {
  101. directionModifier: gameOperation === 'minus' ? -1 : 1,
  102. correctX: x0, // Correct position (accumulative)
  103. nextX: undefined, // Next point position
  104. divisorsList: '', // used in postScore (Accumulative)
  105. hasClicked: false, // Checks if user has clicked
  106. checkAnswer: false, // Check kid inside ballon's basket
  107. isCorrect: false, // Informs answer is correct
  108. showEndInfo: false,
  109. endSignX: undefined,
  110. curWalkedPath: 0,
  111. // mode 'b' exclusive
  112. correctIndex: undefined,
  113. selectedIndex: -1, // Index of clicked circle (game (b))
  114. numberOfPlusFractions: undefined,
  115. };
  116. const walkOffsetX = 2;
  117. const walksPerDistanceBetweenPoints = distanceBetweenPoints / walkOffsetX;
  118. this.animation = {
  119. list: {
  120. left: undefined,
  121. right: undefined,
  122. },
  123. invertDirection: undefined,
  124. animateKid: false,
  125. animateBalloon: false,
  126. counter: undefined,
  127. walkOffsetX,
  128. angleOffset: 360 / walksPerDistanceBetweenPoints,
  129. };
  130. renderBackground('farmRoad');
  131. // Calls function that loads navigation icons
  132. // FOR MOODLE
  133. if (moodle) {
  134. navigation.add.right(['audio']);
  135. } else {
  136. navigation.add.left(['back', 'menu', 'show_answer'], 'customMenu');
  137. navigation.add.right(['audio']);
  138. }
  139. const validPath = { x0, y0, distanceBetweenPoints };
  140. this.utils.renderRoadBlocks();
  141. this.utils.renderRoad(validPath);
  142. const [restart, balloonX] = this.utils.renderCircles(validPath);
  143. this.restart = restart;
  144. this.utils.renderCharacters(validPath, balloonX);
  145. this.utils.renderMainUI();
  146. if (!this.restart) {
  147. game.timer.start(); // Set a timer for the current level (used in postScore())
  148. game.event.add('click', this.events.onInputDown);
  149. game.event.add('mousemove', this.events.onInputOver);
  150. }
  151. },
  152. /**
  153. * Game loop
  154. */
  155. update: function () {
  156. // Starts kid animation
  157. if (self.animation.animateKid) {
  158. self.utils.animateKidHandler();
  159. }
  160. // Check if kid is inside the basket
  161. if (self.control.checkAnswer) {
  162. self.utils.checkAnswerHandler();
  163. }
  164. // Starts balloon flying animation
  165. if (self.animation.animateBalloon) {
  166. self.utils.animateBalloonHandler();
  167. }
  168. game.render.all();
  169. },
  170. utils: {
  171. renderRoadBlocks: function () {
  172. for (let i = 0; i < self.road.numberOfBlocks; i++) {
  173. const block = game.add.geom.rect(
  174. self.road.x + i * self.blocks.width,
  175. self.road.y,
  176. self.blocks.width, // If gameOperation is minus, block width is negative
  177. self.blocks.height,
  178. 'transparent',
  179. 0.5,
  180. colors.red,
  181. 2
  182. );
  183. block.info = { index: i };
  184. self.blocks.list.push(block);
  185. }
  186. },
  187. // RENDERS
  188. renderRoad: function (validPath) {
  189. const offset = 40;
  190. for (let i = 0; i <= 5; i++) {
  191. // Gray place
  192. game.add
  193. .sprite(
  194. validPath.x0 +
  195. i *
  196. validPath.distanceBetweenPoints *
  197. self.control.directionModifier,
  198. validPath.y0,
  199. 'map_place',
  200. 0,
  201. 0.45
  202. )
  203. .anchor(0.5, 0.5);
  204. // White circle behind number
  205. const curX =
  206. validPath.x0 +
  207. i * validPath.distanceBetweenPoints * self.control.directionModifier;
  208. game.add.geom
  209. .circle(
  210. curX,
  211. validPath.y0 + 60 + offset,
  212. 60,
  213. undefined,
  214. 0,
  215. colors.white,
  216. 0.8
  217. )
  218. .anchor(0, 0.25);
  219. game.add.geom.rect(
  220. curX,
  221. validPath.y0 + 60 - 28,
  222. 4,
  223. 25,
  224. colors.white,
  225. 0.8,
  226. undefined,
  227. 0
  228. );
  229. // Number
  230. game.add.text(
  231. curX,
  232. validPath.y0 + 60 + offset,
  233. i * self.control.directionModifier,
  234. {
  235. ...textStyles.h2_,
  236. font: 'bold ' + textStyles.h2_.font,
  237. fill: gameOperation === 'minus' ? colors.red : colors.green,
  238. }
  239. );
  240. }
  241. self.utils.renderWalkedPath(
  242. validPath.x0 - 1,
  243. validPath.y0 - 5,
  244. gameOperation === 'minus' ? colors.red : colors.green
  245. );
  246. },
  247. renderWalkedPath: function (x, y, color) {
  248. const path = game.add.geom.rect(x, y, 1, 1, 'transparent', 1, color, 4);
  249. self.walkedPath.push(path);
  250. return path;
  251. },
  252. renderCircles: function (validPath) {
  253. let restart = false;
  254. let hasBaseDifficulty = false;
  255. let balloonX = context.canvas.width / 2;
  256. const fractionX =
  257. validPath.x0 -
  258. (self.circles.diameter - 10) * self.control.directionModifier;
  259. const font = {
  260. ...textStyles.h2_,
  261. font: 'bold ' + textStyles.h2_.font,
  262. };
  263. // Number of circles
  264. const max = gameOperation === 'mixed' ? 6 : curMapPosition + 1;
  265. const min =
  266. curMapPosition === 1 && (gameOperation === 'mixed' || gameMode === 'b')
  267. ? 2
  268. : curMapPosition; // Mixed level has at least 2 fractions
  269. const total = game.math.randomInRange(min, max); // Total number of circles
  270. // For mode 'b'
  271. self.control.numberOfPlusFractions = game.math.randomInRange(
  272. 1,
  273. total - 1
  274. );
  275. for (let i = 0; i < total; i++) {
  276. let curDirection = undefined;
  277. let curLineColor = undefined;
  278. let curFillColor = undefined;
  279. let curAngleDegree = undefined;
  280. let curIsCounterclockwise = undefined;
  281. let curFractionItems = undefined;
  282. let curCircle = undefined;
  283. const curCircleInfo = {
  284. direction: undefined,
  285. direc: undefined,
  286. distance: undefined,
  287. angle: undefined,
  288. fraction: {
  289. labels: [],
  290. nominator: undefined,
  291. denominator: undefined,
  292. },
  293. };
  294. let curDivisor = game.math.randomInRange(1, gameDifficulty); // Set fraction 'divisor' (depends on difficulty)
  295. if (curDivisor === gameDifficulty) hasBaseDifficulty = true; // True if after for ends has at least 1 '1/difficulty' fraction
  296. curDivisor = curDivisor === 3 ? 4 : curDivisor; // Turns 1/3 into 1/4 fractions
  297. self.control.divisorsList += curDivisor + ','; // Add this divisor to the list of divisors (for postScore())
  298. // Set each circle direction
  299. switch (gameOperation) {
  300. case 'plus':
  301. curDirection = 'right';
  302. break;
  303. case 'minus':
  304. curDirection = 'left';
  305. break;
  306. case 'mixed':
  307. curDirection =
  308. i < self.control.numberOfPlusFractions ? 'right' : 'left';
  309. break;
  310. }
  311. curCircleInfo.direction = curDirection;
  312. // Set each circle visual info
  313. if (curDirection === 'right') {
  314. curIsCounterclockwise = true;
  315. curLineColor = colors.green;
  316. curFillColor = colors.greenLight;
  317. curCircleInfo.direc = 1;
  318. } else {
  319. curIsCounterclockwise = false;
  320. curLineColor = colors.red;
  321. curFillColor = colors.redLight;
  322. curCircleInfo.direc = -1;
  323. }
  324. font.fill = curLineColor;
  325. const curCircleY =
  326. validPath.y0 -
  327. 5 -
  328. self.circles.diameter / 2 -
  329. i * self.circles.diameter;
  330. // Draw circles
  331. if (curDivisor === 1) {
  332. curAngleDegree = 360;
  333. curCircle = game.add.geom.circle(
  334. validPath.x0,
  335. curCircleY,
  336. self.circles.diameter,
  337. curLineColor,
  338. 3,
  339. curFillColor,
  340. 1
  341. );
  342. curCircle.counterclockwise = curIsCounterclockwise;
  343. curCircleInfo.angleDegree = curAngleDegree;
  344. curFractionItems = [
  345. {
  346. x: fractionX,
  347. y: curCircleY + 10,
  348. text: '1',
  349. },
  350. {
  351. x: fractionX - 25,
  352. y: curCircleY + 10,
  353. text: curDirection === 'left' ? '-' : '',
  354. },
  355. null,
  356. ];
  357. } else {
  358. curAngleDegree = 360 / curDivisor;
  359. if (curDirection === 'right') curAngleDegree = 360 - curAngleDegree; // counterclockwise equivalent
  360. curCircle = game.add.geom.arc(
  361. validPath.x0,
  362. curCircleY,
  363. self.circles.diameter,
  364. 0,
  365. game.math.degreeToRad(curAngleDegree),
  366. curIsCounterclockwise,
  367. curLineColor,
  368. 3,
  369. curFillColor,
  370. 1
  371. );
  372. curCircleInfo.angleDegree = curAngleDegree;
  373. curFractionItems = [
  374. {
  375. x: fractionX,
  376. y: curCircleY - 2,
  377. text: `1\n${curDivisor}`,
  378. },
  379. {
  380. x: fractionX - 35,
  381. y: curCircleY + 15,
  382. text: curDirection === 'left' ? '-' : '',
  383. },
  384. {
  385. x0: fractionX,
  386. y0: curCircleY + 2,
  387. x1: fractionX + 25,
  388. y1: curCircleY + 2,
  389. lineWidth: 2,
  390. color: curLineColor,
  391. },
  392. ];
  393. }
  394. for (let i = 0; i < 2; i++) {
  395. const item = game.add.text(
  396. curFractionItems[i].x,
  397. curFractionItems[i].y,
  398. curFractionItems[i].text,
  399. font
  400. );
  401. item.lineHeight = 37;
  402. curCircleInfo.fraction.labels.push(item);
  403. }
  404. if (curFractionItems[2]) {
  405. const line = game.add.geom.line(
  406. curFractionItems[2].x0,
  407. curFractionItems[2].y0,
  408. curFractionItems[2].x1,
  409. curFractionItems[2].y1,
  410. curFractionItems[2].lineWidth,
  411. curFractionItems[2].color
  412. );
  413. line.anchor(0.5, 0);
  414. curCircleInfo.fraction.labels.push(line);
  415. } else {
  416. curCircleInfo.fraction.labels.push(null);
  417. }
  418. curCircleInfo.fraction.nominator = curCircleInfo.direc;
  419. curCircleInfo.fraction.denominator = curDivisor;
  420. if (!showFractions) {
  421. curCircleInfo.fraction.labels.forEach((label) => {
  422. if (label) label.alpha = 0;
  423. });
  424. }
  425. curCircle.rotate = 90;
  426. // If game is type (b) (select fractions)
  427. if (gameMode === 'b') {
  428. curCircle.index = i;
  429. }
  430. curCircleInfo.distance = Math.floor(
  431. validPath.distanceBetweenPoints / curDivisor
  432. );
  433. // Add to the list
  434. curCircle.info = curCircleInfo;
  435. self.circles.list.push(curCircle);
  436. self.control.correctX +=
  437. Math.floor(validPath.distanceBetweenPoints / curDivisor) *
  438. curCircle.info.direc;
  439. }
  440. // Restart if
  441. // Does not have at least one fraction of type 1/difficulty
  442. if (!hasBaseDifficulty) {
  443. restart = true;
  444. }
  445. // Calculate next circle
  446. self.control.nextX =
  447. validPath.x0 +
  448. self.circles.list[0].info.distance * self.circles.list[0].info.direc;
  449. let isBeforeMin = (isAfterMax = false);
  450. let finalPosition = self.control.correctX;
  451. // Restart if
  452. // In Game mode 'a' and 'b' : Balloon position is out of bounds
  453. if (gameOperation === 'minus') {
  454. isBeforeMin = finalPosition > validPath.x0;
  455. isAfterMax =
  456. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  457. } else {
  458. isBeforeMin = finalPosition < validPath.x0;
  459. isAfterMax =
  460. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  461. }
  462. if (isBeforeMin || isAfterMax) restart = true;
  463. if (gameMode === 'b') {
  464. // If game is type (b), select a random balloon place
  465. balloonX = validPath.x0;
  466. self.control.correctIndex = game.math.randomInRange(
  467. self.control.numberOfPlusFractions,
  468. self.circles.list.length
  469. );
  470. for (let i = 0; i < self.control.correctIndex; i++) {
  471. balloonX +=
  472. self.circles.list[i].info.distance *
  473. self.circles.list[i].info.direc;
  474. }
  475. finalPosition = balloonX;
  476. self.blocks.list.forEach((cur) => {
  477. self.utils.fillCurrentBlock(balloonX, cur.x, cur);
  478. if (self.utils.isOverBlock(balloonX, cur.x, cur.width, cur))
  479. self.blocks.cur = cur;
  480. });
  481. // Restart if
  482. // In Game mode 'b' : Top circle position is out of bounds (when on the ground)
  483. if (gameOperation === 'minus') {
  484. isBeforeMin = finalPosition > validPath.x0;
  485. isAfterMax =
  486. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  487. } else {
  488. isBeforeMin = finalPosition < validPath.x0;
  489. isAfterMax =
  490. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  491. }
  492. if (isBeforeMin || isAfterMax) restart = true;
  493. }
  494. return [restart, balloonX];
  495. },
  496. renderCharacters: function (validPath, balloonX) {
  497. // KID
  498. self.kid = game.add.sprite(
  499. validPath.x0,
  500. validPath.y0 - 32 - self.circles.list.length * self.circles.diameter,
  501. 'kid_walking',
  502. 0,
  503. 1.2
  504. );
  505. self.kid.anchor(0.5, 0.8);
  506. self.animation.list.right = [
  507. 'right',
  508. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  509. 4,
  510. ];
  511. self.animation.list.left = [
  512. 'left',
  513. [23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12],
  514. 4,
  515. ];
  516. if (gameOperation === 'minus') {
  517. self.kid.animation = self.animation.list.left;
  518. self.kid.curFrame = 23;
  519. } else {
  520. self.kid.animation = self.animation.list.right;
  521. }
  522. // BALLOON
  523. self.balloon = game.add.image(
  524. balloonX,
  525. validPath.y0 - 295,
  526. 'balloon',
  527. 1.5,
  528. 0.5
  529. );
  530. self.balloon.alpha = 0.5;
  531. self.balloon.anchor(0.5, 0.5);
  532. self.basket = game.add.image(
  533. balloonX,
  534. validPath.y0 - 95,
  535. 'balloon_basket',
  536. 1.5
  537. );
  538. self.basket.alpha = 0.8;
  539. self.basket.anchor(0.5, 0.5);
  540. },
  541. renderMainUI: function () {
  542. // Help pointer
  543. self.ui.help = game.add.image(0, 0, 'pointer', 2, 0);
  544. // Intro text
  545. const correctMessage =
  546. gameMode === 'a'
  547. ? game.lang.circleOne_intro_a
  548. : game.lang.circleOne_intro_b;
  549. const treatedMessage = correctMessage.split('\\n');
  550. self.ui.message = [];
  551. self.ui.message.push(
  552. game.add.text(
  553. context.canvas.width / 2,
  554. 170,
  555. treatedMessage[0] + '\n' + treatedMessage[1],
  556. textStyles.h1_
  557. )
  558. );
  559. },
  560. renderOperationUI: function () {
  561. /**
  562. * if game mode A:
  563. * - left: selected balloon position (user selection)
  564. * - right: correct sum of stack of arcs (pre-set)
  565. *
  566. * if game mode B:
  567. * - left: line created from the stack of arcs (user selection)
  568. * - right: baloon position (pre-set)
  569. */
  570. const renderFloorFractions = (lastIndex) => {
  571. const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
  572. const operator = gameOperation === 'minus' ? '-' : '+';
  573. const index = lastIndex;
  574. const blocks = index + 1;
  575. const valueReal = blocks / divisor;
  576. const valueFloor = Math.floor(valueReal);
  577. const valueRest = valueReal - valueFloor;
  578. let fracNomin = (fracDenomin = fracLine = '');
  579. // Adds sign on the left of the equation
  580. if (gameOperation === 'minus') {
  581. fracNomin += ' ';
  582. fracDenomin += ' ';
  583. fracLine += operator;
  584. }
  585. // 1 _ _
  586. if (valueFloor) {
  587. fracNomin += ' ';
  588. fracDenomin += ' ';
  589. fracLine += valueFloor;
  590. }
  591. // _ + _
  592. if (valueFloor && valueRest) {
  593. fracNomin += ' ';
  594. fracDenomin += ' ';
  595. fracLine += operator;
  596. }
  597. // _ _ 1/5
  598. if (valueRest) {
  599. fracNomin += `${valueRest * divisor}`;
  600. fracDenomin += `${divisor}`;
  601. fracLine += '-';
  602. }
  603. return [fracNomin, fracDenomin, fracLine, valueReal];
  604. };
  605. const renderStackFractions = (lastIndex) => {
  606. const operator = gameOperation === 'minus' ? '-' : '+';
  607. const index = lastIndex;
  608. const blocks = index + 1;
  609. const nominators = [];
  610. const denominators = [];
  611. const values = [];
  612. let valueReal = 0;
  613. let fracNomin = (fracDenomin = fracLine = '');
  614. for (let i = 0; i < blocks; i++) {
  615. const m = self.circles.list[i].info.fraction.denominator || 1;
  616. const temp = self.circles.list[i].info.fraction.nominator || 0;
  617. const n = gameOperation === 'minus' ? -temp : +temp;
  618. const nm = n / m;
  619. nominators[i] = n + 0;
  620. denominators[i] = m + 0;
  621. values[i] = nm;
  622. valueReal += nm;
  623. }
  624. for (let i = 0; i < blocks; i++) {
  625. const valueReal = values[i];
  626. const valueFloor = Math.floor(valueReal);
  627. const valueRest = valueReal - valueFloor;
  628. if (i > 0 || gameOperation === 'minus') {
  629. fracNomin += ' ';
  630. fracDenomin += ' ';
  631. fracLine += operator;
  632. }
  633. if (valueFloor && !valueRest) {
  634. fracNomin += ' ';
  635. fracDenomin += ' ';
  636. fracLine += valueFloor;
  637. }
  638. if (valueRest) {
  639. fracNomin += `${nominators[i]}`;
  640. fracDenomin += `${denominators[i]}`;
  641. fracLine += '-';
  642. }
  643. }
  644. return [fracNomin, fracDenomin, fracLine, valueReal];
  645. };
  646. // Initial setup
  647. const font = textStyles.fraction;
  648. font.fill = colors.black;
  649. const padding = 100;
  650. const offsetX = 100;
  651. const widthOfChar = 35;
  652. const x0 = padding;
  653. const y0 = context.canvas.height / 3;
  654. let nextX = x0;
  655. const cardHeight = 400;
  656. const cardX = x0 - padding;
  657. const cardY = y0;
  658. const renderList = [];
  659. // Render Card
  660. const card = game.add.geom.rect(
  661. cardX,
  662. cardY,
  663. 0,
  664. cardHeight,
  665. colors.blueLight,
  666. 0.5,
  667. colors.blueDark,
  668. 8
  669. );
  670. card.id = 'card';
  671. card.anchor(0, 0.5);
  672. renderList.push(card);
  673. // Fraction setup
  674. const [floorNominators, floorDenominators, floorLines, floorValue] =
  675. renderFloorFractions(self.blocks.cur.info.index);
  676. const [stackNominators, stackDenominators, stackLines, stackValue] =
  677. renderStackFractions(self.circles.cur - 1);
  678. const renderFloorOperationLine = (x) => {
  679. font.fill = colors.black;
  680. const floorNom = game.add.text(
  681. x + offsetX / 2,
  682. y0,
  683. floorNominators,
  684. font,
  685. 60
  686. );
  687. const floorDenom = game.add.text(
  688. x + offsetX / 2,
  689. y0 + 70,
  690. floorDenominators,
  691. font,
  692. 60
  693. );
  694. const floorLin = game.add.text(
  695. x + offsetX / 2,
  696. y0 + 35,
  697. floorLines,
  698. font,
  699. 60
  700. );
  701. renderList.push(floorNom);
  702. renderList.push(floorDenom);
  703. renderList.push(floorLin);
  704. };
  705. const renderStackOperationLine = (x) => {
  706. font.fill = colors.black;
  707. const stackNom = game.add.text(
  708. x + offsetX / 2,
  709. y0,
  710. stackNominators,
  711. font,
  712. 60
  713. );
  714. const stackDenom = game.add.text(
  715. x + offsetX / 2,
  716. y0 + 70,
  717. stackDenominators,
  718. font,
  719. 60
  720. );
  721. const stackLin = game.add.text(
  722. x + offsetX / 2,
  723. y0 + 35,
  724. stackLines,
  725. font,
  726. 60
  727. );
  728. renderList.push(stackNom);
  729. renderList.push(stackDenom);
  730. renderList.push(stackLin);
  731. };
  732. // Render LEFT part of the operation
  733. if (gameMode === 'a') renderFloorOperationLine(x0);
  734. else renderStackOperationLine(x0);
  735. let curNominators = gameMode === 'a' ? floorNominators : stackNominators;
  736. nextX = x0 + (curNominators.length + 2) * widthOfChar;
  737. // Render middle sign - equal by default
  738. font.fill = colors.green;
  739. let comparisonSign = '=';
  740. // Render middle sign - if not equal
  741. if (floorValue != stackValue) {
  742. font.fill = colors.red;
  743. let leftSideIsLarger = floorValue > stackValue;
  744. if (gameMode === 'b') leftSideIsLarger = !leftSideIsLarger;
  745. if (gameOperation === 'minus') leftSideIsLarger = !leftSideIsLarger;
  746. comparisonSign = leftSideIsLarger ? '>' : '<';
  747. }
  748. renderList.push(game.add.text(nextX, y0 + 35, comparisonSign, font));
  749. // Render RIGHT part of the operationf
  750. if (gameMode === 'a') renderStackOperationLine(nextX);
  751. else renderFloorOperationLine(nextX);
  752. curNominators = gameMode === 'a' ? stackNominators : floorNominators;
  753. const resultWidth = (curNominators.length + 2) * widthOfChar;
  754. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  755. card.width = cardWidth;
  756. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  757. // Center Card
  758. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  759. self.fractionOperationUI = renderList;
  760. return endSignX;
  761. },
  762. renderEndUI: function () {
  763. let btnColor = colors.green;
  764. let btnText = game.lang.continue;
  765. if (!self.control.isCorrect) {
  766. btnColor = colors.red;
  767. btnText = game.lang.retry;
  768. }
  769. // continue button
  770. self.ui.continue.button = game.add.geom.rect(
  771. context.canvas.width / 2,
  772. context.canvas.height / 2 + 100,
  773. 450,
  774. 100,
  775. btnColor
  776. );
  777. self.ui.continue.button.anchor(0.5, 0.5);
  778. self.ui.continue.text = game.add.text(
  779. context.canvas.width / 2,
  780. context.canvas.height / 2 + 16 + 100,
  781. btnText,
  782. textStyles.btn
  783. );
  784. },
  785. // UPDATE
  786. animateKidHandler: function () {
  787. let canLowerCircles = undefined;
  788. let curCircle = self.circles.list[self.circles.cur];
  789. let curDirec = curCircle.info.direc;
  790. // Move
  791. self.circles.list.forEach((circle) => {
  792. circle.x += self.animation.walkOffsetX * curDirec;
  793. });
  794. self.kid.x += self.animation.walkOffsetX * curDirec;
  795. self.walkedPath[self.control.curWalkedPath].width +=
  796. self.animation.walkOffsetX * curDirec;
  797. // Update arc
  798. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  799. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  800. // When finish current circle
  801. if (curCircle.info.direction === 'right') {
  802. canLowerCircles = curCircle.x >= self.control.nextX;
  803. } else if (curCircle.info.direction === 'left') {
  804. canLowerCircles = curCircle.x <= self.control.nextX;
  805. // If just changed from 'right' to 'left' inform to change direction of kid animation
  806. if (
  807. self.animation.invertDirection === undefined &&
  808. self.circles.cur > 0 &&
  809. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  810. ) {
  811. self.animation.invertDirection = true;
  812. }
  813. }
  814. // Change direction of kid animation
  815. if (self.animation.invertDirection) {
  816. self.animation.invertDirection = false;
  817. game.animation.stop(self.kid.animation[0]);
  818. self.kid.animation = self.animation.list.left;
  819. self.kid.curFrame = 23;
  820. game.animation.play('left');
  821. self.control.curWalkedPath = 1;
  822. self.utils.renderWalkedPath(
  823. curCircle.x,
  824. self.walkedPath[0].y + 8,
  825. colors.red
  826. );
  827. }
  828. if (canLowerCircles) {
  829. // Hide current circle
  830. curCircle.alpha = 0;
  831. // Lowers kid and other circles
  832. self.circles.list.forEach((circle) => {
  833. circle.y += self.circles.diameter;
  834. });
  835. self.kid.y += self.circles.diameter;
  836. self.circles.cur++; // Update index of current circle
  837. if (self.circles.list[self.circles.cur]) {
  838. curCircle = self.circles.list[self.circles.cur];
  839. curDirec = curCircle.info.direc;
  840. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  841. }
  842. }
  843. // When finish all circles (final position)
  844. if (
  845. self.circles.cur === self.circles.list.length ||
  846. curCircle.alpha === 0
  847. ) {
  848. self.animation.animateKid = false;
  849. self.control.checkAnswer = true;
  850. }
  851. },
  852. checkAnswerHandler: function () {
  853. game.timer.stop();
  854. game.animation.stop(self.kid.animation[0]);
  855. self.control.isCorrect = game.math.isOverlap(self.basket, self.kid);
  856. const x = self.utils.renderOperationUI();
  857. if (self.control.isCorrect) {
  858. completedLevels++;
  859. self.kid.curFrame = self.kid.curFrame < 12 ? 24 : 25;
  860. if (audioStatus) game.audio.okSound.play();
  861. game.add
  862. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  863. .anchor(0.5, 0.5);
  864. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  865. } else {
  866. if (audioStatus) game.audio.errorSound.play();
  867. game.add
  868. .image(x, context.canvas.height / 3, 'answer_wrong')
  869. .anchor(0.5, 0.5);
  870. }
  871. self.fetch.postScore();
  872. self.control.checkAnswer = false;
  873. self.animation.counter = 0;
  874. self.animation.animateBalloon = true;
  875. },
  876. animateBalloonHandler: function () {
  877. self.animation.counter++;
  878. self.balloon.y -= 2;
  879. self.basket.y -= 2;
  880. if (self.control.isCorrect) self.kid.y -= 2;
  881. if (self.animation.counter === 100) {
  882. self.utils.renderEndUI();
  883. self.control.showEndInfo = true;
  884. if (self.control.isCorrect) canGoToNextMapPosition = true;
  885. else canGoToNextMapPosition = false;
  886. }
  887. },
  888. endLevel: function () {
  889. game.state.start('map');
  890. },
  891. // INFORMATION
  892. /**
  893. * Show correct answer
  894. */
  895. showAnswer: function () {
  896. if (!self.control.hasClicked) {
  897. // On gameMode (a)
  898. if (gameMode === 'a') {
  899. self.ui.help.x = self.control.correctX - 20;
  900. self.ui.help.y = self.road.defaultY;
  901. // On gameMode (b)
  902. } else {
  903. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  904. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  905. }
  906. self.ui.help.alpha = 1;
  907. }
  908. },
  909. // HANDLERS
  910. /**
  911. * (in gameMode 'b') Function called when player clicked over a valid circle
  912. *
  913. * @param {number|object} cur clicked circle
  914. */
  915. clickCircleHandler: function (cur) {
  916. if (!self.control.hasClicked) {
  917. // On gameMode (a)
  918. if (gameMode === 'a') {
  919. self.balloon.x = cur;
  920. self.basket.x = cur;
  921. }
  922. // On gameMode (b)
  923. if (gameMode === 'b') {
  924. document.body.style.cursor = 'auto';
  925. for (let i in self.circles.list) {
  926. if (i <= cur.index) {
  927. self.circles.list[i].alpha = 1; // Keep selected circle
  928. self.control.selectedIndex = cur.index;
  929. } else {
  930. self.circles.list[i].alpha = 0; // Hide unselected circle
  931. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  932. }
  933. }
  934. }
  935. if (audioStatus) game.audio.popSound.play();
  936. // Hide fractions
  937. if (showFractions) {
  938. self.circles.list.forEach((circle) => {
  939. circle.info.fraction.labels.forEach((labelPart) => {
  940. if (labelPart) labelPart.alpha = 0;
  941. });
  942. });
  943. }
  944. // Hide solution pointer
  945. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  946. self.ui.message[0].alpha = 0;
  947. navigation.disableIcon(navigation.showAnswerIcon);
  948. self.balloon.alpha = 1;
  949. self.basket.alpha = 1;
  950. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  951. self.control.hasClicked = true;
  952. self.animation.animateKid = true;
  953. game.animation.play(self.kid.animation[0]);
  954. }
  955. },
  956. /**
  957. * (in gameMode 'b') Function called when cursor is over a valid circle
  958. *
  959. * @param {object} cur circle the cursor is over
  960. */
  961. overCircleHandler: function (cur) {
  962. if (!self.control.hasClicked) {
  963. document.body.style.cursor = 'pointer';
  964. for (let i in self.circles.list) {
  965. const alpha = i <= cur.index ? 1 : 0.4;
  966. self.circles.list[i].alpha = alpha;
  967. if (showFractions) {
  968. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  969. if (lbl) lbl.alpha = alpha;
  970. });
  971. }
  972. }
  973. }
  974. },
  975. /**
  976. * (in gameMode 'b') Function called when cursor leaves a valid circle
  977. */
  978. outCircleHandler: function () {
  979. if (!self.control.hasClicked) {
  980. document.body.style.cursor = 'auto';
  981. const alpha = 1;
  982. self.circles.list.forEach((circle) => {
  983. circle.alpha = alpha;
  984. if (showFractions) {
  985. circle.info.fraction.labels.forEach((lbl) => {
  986. if (lbl) lbl.alpha = alpha;
  987. });
  988. }
  989. });
  990. }
  991. },
  992. /** TODO */
  993. isOverBlock: function (x, blockX, blockWidth) {
  994. if (
  995. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  996. x >= blockX &&
  997. x < blockX + blockWidth) ||
  998. (gameOperation === 'minus' && x <= blockX && x > blockX + blockWidth)
  999. )
  1000. return true;
  1001. return false;
  1002. },
  1003. /** TODO */
  1004. isOverRoad: function (x, y, roadX, roadWidth) {
  1005. if (y > 150) {
  1006. if (
  1007. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1008. x >= roadX &&
  1009. x < roadX + roadWidth) ||
  1010. (gameOperation === 'minus' &&
  1011. x <= roadX &&
  1012. x > roadX + roadWidth * self.control.directionModifier)
  1013. )
  1014. return true;
  1015. }
  1016. return false;
  1017. },
  1018. /** TODO */
  1019. fillCurrentBlock: function (x, blockX, block) {
  1020. block.fillColor =
  1021. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1022. x > blockX) ||
  1023. (gameOperation === 'minus' && x < blockX)
  1024. ? colors.red
  1025. : 'transparent';
  1026. },
  1027. },
  1028. events: {
  1029. /**
  1030. * Called by mouse click event
  1031. *
  1032. * @param {object} mouseEvent contains the mouse click coordinates
  1033. */
  1034. onInputDown: function (mouseEvent) {
  1035. const x = game.math.getMouse(mouseEvent).x;
  1036. const y = game.math.getMouse(mouseEvent).y;
  1037. // GAME MODE A : click road
  1038. if (gameMode === 'a') {
  1039. const isValidX = self.utils.isOverRoad(
  1040. x,
  1041. y,
  1042. self.road.x,
  1043. self.road.width
  1044. );
  1045. if (isValidX) {
  1046. self.utils.clickCircleHandler(
  1047. self.blocks.cur.x + self.blocks.cur.width
  1048. );
  1049. document.body.style.cursor = 'auto';
  1050. }
  1051. }
  1052. // GAME MODE B : click circle
  1053. if (gameMode === 'b') {
  1054. self.circles.list.forEach((circle) => {
  1055. const isValid =
  1056. game.math.distanceToPointer(
  1057. x,
  1058. circle.xWithAnchor,
  1059. y,
  1060. circle.yWithAnchor
  1061. ) <=
  1062. (circle.diameter / 2) * circle.scale;
  1063. if (isValid) self.utils.clickCircleHandler(circle);
  1064. });
  1065. }
  1066. // Continue button
  1067. if (self.control.showEndInfo) {
  1068. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1069. if (audioStatus) game.audio.popSound.play();
  1070. self.utils.endLevel();
  1071. }
  1072. }
  1073. navigation.onInputDown(x, y);
  1074. game.render.all();
  1075. },
  1076. /**
  1077. * Called by mouse move event
  1078. *
  1079. * @param {object} mouseEvent contains the mouse move coordinates
  1080. */
  1081. onInputOver: function (mouseEvent) {
  1082. const x = game.math.getMouse(mouseEvent).x;
  1083. const y = game.math.getMouse(mouseEvent).y;
  1084. let isOverCircle = false;
  1085. if (gameMode === 'a' && !self.control.hasClicked) {
  1086. const isValidX = self.utils.isOverRoad(
  1087. x,
  1088. y,
  1089. self.road.x,
  1090. self.road.width
  1091. );
  1092. if (isValidX) {
  1093. // GAME MODE A : balloon follow mouse
  1094. self.blocks.cur = self.blocks.list[0];
  1095. self.blocks.list.forEach((cur) => {
  1096. self.utils.fillCurrentBlock(x, cur.x, cur);
  1097. if (self.utils.isOverBlock(x, cur.x, cur.width, cur))
  1098. self.blocks.cur = cur;
  1099. });
  1100. const newX = self.blocks.cur.x + self.blocks.cur.width;
  1101. self.balloon.x = newX;
  1102. self.basket.x = newX;
  1103. document.body.style.cursor = 'pointer';
  1104. } else {
  1105. document.body.style.cursor = 'auto';
  1106. }
  1107. }
  1108. // GAME MODE B : hover circle
  1109. if (gameMode === 'b' && !self.control.hasClicked) {
  1110. self.circles.list.forEach((circle) => {
  1111. const isValid =
  1112. game.math.distanceToPointer(
  1113. x,
  1114. circle.xWithAnchor,
  1115. y,
  1116. circle.yWithAnchor
  1117. ) <=
  1118. (circle.diameter / 2) * circle.scale;
  1119. if (isValid) {
  1120. self.utils.overCircleHandler(circle);
  1121. isOverCircle = true;
  1122. }
  1123. });
  1124. if (!isOverCircle) self.utils.outCircleHandler();
  1125. }
  1126. // Continue button
  1127. if (self.control.showEndInfo) {
  1128. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1129. // If pointer is over icon
  1130. document.body.style.cursor = 'pointer';
  1131. self.ui.continue.button.scale =
  1132. self.ui.continue.button.initialScale * 1.1;
  1133. self.ui.continue.text.style = textStyles.btnLg;
  1134. } else {
  1135. // If pointer is not over icon
  1136. document.body.style.cursor = 'auto';
  1137. self.ui.continue.button.scale =
  1138. self.ui.continue.button.initialScale * 1;
  1139. self.ui.continue.text.style = textStyles.btn;
  1140. }
  1141. }
  1142. navigation.onInputOver(x, y);
  1143. game.render.all();
  1144. },
  1145. },
  1146. fetch: {
  1147. /**
  1148. * Saves players data after level ends - to be sent to database <br>
  1149. *
  1150. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  1151. *
  1152. * @see /php/squareOne.js
  1153. */
  1154. postScore: function () {
  1155. // Creates string that is going to be sent to db
  1156. const data =
  1157. '&line_game=' +
  1158. gameShape +
  1159. '&line_mode=' +
  1160. gameMode +
  1161. '&line_oper=' +
  1162. gameOperation +
  1163. '&line_leve=' +
  1164. gameDifficulty +
  1165. '&line_posi=' +
  1166. curMapPosition +
  1167. '&line_resu=' +
  1168. self.control.isCorrect +
  1169. '&line_time=' +
  1170. game.timer.elapsed +
  1171. '&line_deta=' +
  1172. 'numCircles:' +
  1173. self.circles.list.length +
  1174. ', valCircles: ' +
  1175. self.control.divisorsList +
  1176. ' balloonX: ' +
  1177. self.basket.x +
  1178. ', selIndex: ' +
  1179. self.control.selectedIndex;
  1180. // FOR MOODLE
  1181. sendToDatabase(data);
  1182. },
  1183. },
  1184. };