circleOne.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. this.road = {
  64. x: 150,
  65. y: context.canvas.height - game.image['floor_grass'].width * 1.5,
  66. width: 1620,
  67. };
  68. this.walkedPath = [];
  69. const pointWidth = (game.sprite['map_place'].width / 2) * 0.45;
  70. const distanceBetweenPoints =
  71. (context.canvas.width - this.road.x * 2 - pointWidth) / 5; // Distance between road points
  72. const y0 = this.road.y + 20;
  73. const x0 =
  74. gameOperation === 'minus'
  75. ? context.canvas.width - this.road.x - pointWidth / 2
  76. : this.road.x + pointWidth / 2; // Initial 'x' coordinate for the kid and the baloon
  77. const diameter =
  78. game.math.getRadiusFromCircunference(distanceBetweenPoints) * 2;
  79. this.circles = {
  80. diameter: diameter, // (Fixed) Circles Diameter
  81. cur: 0, // Current circle index
  82. list: [], // Circle objects
  83. };
  84. this.control = {
  85. correctX: x0, // Correct position (accumulative)
  86. nextX: undefined, // Next point position
  87. divisorsList: '', // used in postScore (Accumulative)
  88. hasClicked: false, // Checks if user has clicked
  89. checkAnswer: false, // Check kid inside ballon's basket
  90. isCorrect: false, // Informs answer is correct
  91. showEndInfo: false,
  92. endSignX: undefined,
  93. curWalkedPath: 0,
  94. // mode 'b' exclusive
  95. correctIndex: undefined,
  96. selectedIndex: -1, // Index of clicked circle (game (b))
  97. numberOfPlusFractions: undefined,
  98. };
  99. const walkOffsetX = 2;
  100. const walksPerDistanceBetweenPoints = distanceBetweenPoints / walkOffsetX;
  101. this.animation = {
  102. list: {
  103. left: undefined,
  104. right: undefined,
  105. },
  106. invertDirection: undefined,
  107. animateKid: false,
  108. animateBalloon: false,
  109. counter: undefined,
  110. walkOffsetX,
  111. angleOffset: 360 / walksPerDistanceBetweenPoints,
  112. };
  113. renderBackground('farmRoad');
  114. // Calls function that loads navigation icons
  115. // FOR MOODLE
  116. if (moodle) {
  117. navigation.add.right(['audio']);
  118. } else {
  119. navigation.add.left(['back', 'menu', 'show_answer'], 'customMenu');
  120. navigation.add.right(['audio']);
  121. }
  122. const validPath = { x0, y0, distanceBetweenPoints };
  123. this.utils.renderRoad(validPath);
  124. const [restart, balloonX] = this.utils.renderCircles(validPath);
  125. this.restart = restart;
  126. this.utils.renderCharacters(validPath, balloonX);
  127. this.utils.renderMainUI();
  128. if (!this.restart) {
  129. game.timer.start(); // Set a timer for the current level (used in postScore())
  130. game.event.add('click', this.events.onInputDown);
  131. game.event.add('mousemove', this.events.onInputOver);
  132. }
  133. },
  134. /**
  135. * Game loop
  136. */
  137. update: function () {
  138. // Starts kid animation
  139. if (self.animation.animateKid) {
  140. self.utils.animateKidHandler();
  141. }
  142. // Check if kid is inside the basket
  143. if (self.control.checkAnswer) {
  144. self.utils.checkAnswerHandler();
  145. }
  146. // Starts balloon flying animation
  147. if (self.animation.animateBalloon) {
  148. self.utils.animateBalloonHandler();
  149. }
  150. game.render.all();
  151. },
  152. utils: {
  153. // RENDERS
  154. renderRoad: function (validPath) {
  155. const directionModifier = gameOperation === 'minus' ? -1 : 1;
  156. for (let i = 0; i <= 5; i++) {
  157. // place
  158. game.add
  159. .sprite(
  160. validPath.x0 +
  161. i * validPath.distanceBetweenPoints * directionModifier,
  162. validPath.y0,
  163. 'map_place',
  164. 0,
  165. 0.45
  166. )
  167. .anchor(0.5, 0.5);
  168. // circle behind number
  169. game.add.geom
  170. .circle(
  171. validPath.x0 +
  172. i * validPath.distanceBetweenPoints * directionModifier,
  173. validPath.y0 + 60,
  174. 60,
  175. undefined,
  176. 0,
  177. colors.white,
  178. 0.8
  179. )
  180. .anchor(0, 0.25);
  181. // number
  182. game.add.text(
  183. validPath.x0 +
  184. i * validPath.distanceBetweenPoints * directionModifier,
  185. validPath.y0 + 60,
  186. i * directionModifier,
  187. {
  188. ...textStyles.h2_,
  189. font: 'bold ' + textStyles.h2_.font,
  190. fill: directionModifier === 1 ? colors.green : colors.red,
  191. }
  192. );
  193. }
  194. self.utils.renderWalkedPath(
  195. validPath.x0 - 1,
  196. validPath.y0 - 5,
  197. gameOperation === 'minus' ? colors.red : colors.green
  198. );
  199. },
  200. renderWalkedPath: function (x, y, color) {
  201. const path = game.add.geom.rect(x, y, 1, 1, 'transparent', 1, color, 4);
  202. self.walkedPath.push(path);
  203. return path;
  204. },
  205. renderCircles: function (validPath) {
  206. let restart = false;
  207. let hasBaseDifficulty = false;
  208. let balloonX = context.canvas.width / 2;
  209. const directionModifier = gameOperation === 'minus' ? -1 : 1;
  210. const fractionX =
  211. validPath.x0 - (self.circles.diameter - 10) * directionModifier;
  212. const font = {
  213. ...textStyles.h2_,
  214. font: 'bold ' + textStyles.h2_.font,
  215. };
  216. // Number of circles
  217. const max = gameOperation === 'mixed' ? 6 : curMapPosition + 1;
  218. const min =
  219. curMapPosition === 1 && (gameOperation === 'mixed' || gameMode === 'b')
  220. ? 2
  221. : curMapPosition; // Mixed level has at least 2 fractions
  222. const total = game.math.randomInRange(min, max); // Total number of circles
  223. // for mode 'b'
  224. self.control.numberOfPlusFractions = game.math.randomInRange(
  225. 1,
  226. total - 1
  227. );
  228. for (let i = 0; i < total; i++) {
  229. let curDirection = undefined;
  230. let curLineColor = undefined;
  231. let curFillColor = undefined;
  232. let curAngleDegree = undefined;
  233. let curIsCounterclockwise = undefined;
  234. let curFractionItems = undefined;
  235. let curCircle = undefined;
  236. const curCircleInfo = {
  237. direction: undefined,
  238. direc: undefined,
  239. distance: undefined,
  240. angle: undefined,
  241. fraction: {
  242. labels: [],
  243. nominator: undefined,
  244. denominator: undefined,
  245. },
  246. };
  247. const curDivisor = game.math.randomInRange(1, gameDifficulty); // Set fraction 'divisor' (depends on difficulty)
  248. if (curDivisor === gameDifficulty) hasBaseDifficulty = true; // True if after for ends has at least 1 '1/difficulty' fraction
  249. self.control.divisorsList += curDivisor + ','; // Add this divisor to the list of divisors (for postScore())
  250. // Set each circle direction
  251. switch (gameOperation) {
  252. case 'plus':
  253. curDirection = 'right';
  254. break;
  255. case 'minus':
  256. curDirection = 'left';
  257. break;
  258. case 'mixed':
  259. curDirection =
  260. i < self.control.numberOfPlusFractions ? 'right' : 'left';
  261. break;
  262. }
  263. curCircleInfo.direction = curDirection;
  264. // Set each circle visual info
  265. if (curDirection === 'right') {
  266. curIsCounterclockwise = true;
  267. curLineColor = colors.green;
  268. curFillColor = colors.greenLight;
  269. curCircleInfo.direc = 1;
  270. } else {
  271. curIsCounterclockwise = false;
  272. curLineColor = colors.red;
  273. curFillColor = colors.redLight;
  274. curCircleInfo.direc = -1;
  275. }
  276. font.fill = curLineColor;
  277. const curCircleY =
  278. validPath.y0 -
  279. 5 -
  280. self.circles.diameter / 2 -
  281. i * self.circles.diameter;
  282. // Draw circles
  283. if (curDivisor === 1) {
  284. curAngleDegree = 360;
  285. curCircle = game.add.geom.circle(
  286. validPath.x0,
  287. curCircleY,
  288. self.circles.diameter,
  289. curLineColor,
  290. 3,
  291. curFillColor,
  292. 1
  293. );
  294. curCircle.counterclockwise = curIsCounterclockwise;
  295. curCircleInfo.angleDegree = curAngleDegree;
  296. curFractionItems = [
  297. {
  298. x: fractionX,
  299. y: curCircleY + 10,
  300. text: '1',
  301. },
  302. {
  303. x: fractionX - 25,
  304. y: curCircleY + 10,
  305. text: curDirection === 'left' ? '-' : '',
  306. },
  307. null,
  308. ];
  309. } else {
  310. curAngleDegree = 360 / curDivisor;
  311. if (curDirection === 'right') curAngleDegree = 360 - curAngleDegree; // counterclockwise equivalent
  312. curCircle = game.add.geom.arc(
  313. validPath.x0,
  314. curCircleY,
  315. self.circles.diameter,
  316. 0,
  317. game.math.degreeToRad(curAngleDegree),
  318. curIsCounterclockwise,
  319. curLineColor,
  320. 3,
  321. curFillColor,
  322. 1
  323. );
  324. curCircleInfo.angleDegree = curAngleDegree;
  325. curFractionItems = [
  326. {
  327. x: fractionX,
  328. y: curCircleY - 2,
  329. text: `1\n${curDivisor}`,
  330. },
  331. {
  332. x: fractionX - 35,
  333. y: curCircleY + 15,
  334. text: curDirection === 'left' ? '-' : '',
  335. },
  336. {
  337. x0: fractionX,
  338. y0: curCircleY + 2,
  339. x1: fractionX + 25,
  340. y1: curCircleY + 2,
  341. lineWidth: 2,
  342. color: curLineColor,
  343. },
  344. ];
  345. }
  346. for (let i = 0; i < 2; i++) {
  347. const item = game.add.text(
  348. curFractionItems[i].x,
  349. curFractionItems[i].y,
  350. curFractionItems[i].text,
  351. font
  352. );
  353. item.lineHeight = 37;
  354. curCircleInfo.fraction.labels.push(item);
  355. }
  356. if (curFractionItems[2]) {
  357. const line = game.add.geom.line(
  358. curFractionItems[2].x0,
  359. curFractionItems[2].y0,
  360. curFractionItems[2].x1,
  361. curFractionItems[2].y1,
  362. curFractionItems[2].lineWidth,
  363. curFractionItems[2].color
  364. );
  365. line.anchor(0.5, 0);
  366. curCircleInfo.fraction.labels.push(line);
  367. } else {
  368. curCircleInfo.fraction.labels.push(null);
  369. }
  370. curCircleInfo.fraction.nominator = curCircleInfo.direc;
  371. curCircleInfo.fraction.denominator = curDivisor;
  372. if (!showFractions) {
  373. curCircleInfo.fraction.labels.forEach((label) => {
  374. if (label) label.alpha = 0;
  375. });
  376. }
  377. curCircle.rotate = 90;
  378. // If game is type (b) (select fractions)
  379. if (gameMode === 'b') {
  380. curCircle.index = i;
  381. }
  382. curCircleInfo.distance = Math.floor(
  383. validPath.distanceBetweenPoints / curDivisor
  384. );
  385. // Add to the list
  386. curCircle.info = curCircleInfo;
  387. self.circles.list.push(curCircle);
  388. self.control.correctX +=
  389. Math.floor(validPath.distanceBetweenPoints / curDivisor) *
  390. curCircle.info.direc;
  391. }
  392. // Restart if
  393. // Does not have at least one fraction of type 1/difficulty
  394. if (!hasBaseDifficulty) {
  395. restart = true;
  396. }
  397. // Calculate next circle
  398. self.control.nextX =
  399. validPath.x0 +
  400. self.circles.list[0].info.distance * self.circles.list[0].info.direc;
  401. let isBeforeMin = (isAfterMax = false);
  402. let finalPosition = self.control.correctX;
  403. // Restart if
  404. // In Game mode 'a' and 'b' : Balloon position is out of bounds
  405. if (gameOperation === 'minus') {
  406. isBeforeMin = finalPosition > validPath.x0;
  407. isAfterMax =
  408. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  409. } else {
  410. isBeforeMin = finalPosition < validPath.x0;
  411. isAfterMax =
  412. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  413. }
  414. if (isBeforeMin || isAfterMax) restart = true;
  415. if (gameMode === 'b') {
  416. // If game is type (b), select a random balloon place
  417. balloonX = validPath.x0;
  418. self.control.correctIndex = game.math.randomInRange(
  419. self.control.numberOfPlusFractions,
  420. self.circles.list.length
  421. );
  422. for (let i = 0; i < self.control.correctIndex; i++) {
  423. balloonX +=
  424. self.circles.list[i].info.distance *
  425. self.circles.list[i].info.direc;
  426. }
  427. finalPosition = balloonX;
  428. // Restart if
  429. // In Game mode 'b' : Top circle position is out of bounds (when on the ground)
  430. if (gameOperation === 'minus') {
  431. isBeforeMin = finalPosition > validPath.x0;
  432. isAfterMax =
  433. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  434. } else {
  435. isBeforeMin = finalPosition < validPath.x0;
  436. isAfterMax =
  437. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  438. }
  439. if (isBeforeMin || isAfterMax) restart = true;
  440. }
  441. return [restart, balloonX];
  442. },
  443. renderCharacters: function (validPath, balloonX) {
  444. // KID
  445. self.kid = game.add.sprite(
  446. validPath.x0,
  447. validPath.y0 - 32 - self.circles.list.length * self.circles.diameter,
  448. 'kid_walking',
  449. 0,
  450. 1.2
  451. );
  452. self.kid.anchor(0.5, 0.8);
  453. self.animation.list.right = [
  454. 'right',
  455. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  456. 4,
  457. ];
  458. self.animation.list.left = [
  459. 'left',
  460. [23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12],
  461. 4,
  462. ];
  463. if (gameOperation === 'minus') {
  464. self.kid.animation = self.animation.list.left;
  465. self.kid.curFrame = 23;
  466. } else {
  467. self.kid.animation = self.animation.list.right;
  468. }
  469. // BALLOON
  470. self.balloon = game.add.image(
  471. balloonX,
  472. validPath.y0 - 295,
  473. 'balloon',
  474. 1.5,
  475. 0.5
  476. );
  477. self.balloon.alpha = 0.5;
  478. self.balloon.anchor(0.5, 0.5);
  479. self.basket = game.add.image(
  480. balloonX,
  481. validPath.y0 - 95,
  482. 'balloon_basket',
  483. 1.5
  484. );
  485. self.basket.alpha = 0.8;
  486. self.basket.anchor(0.5, 0.5);
  487. },
  488. renderMainUI: function () {
  489. // Help pointer
  490. self.ui.help = game.add.image(0, 0, 'pointer', 2, 0);
  491. // Intro text
  492. const correctMessage =
  493. gameMode === 'a'
  494. ? game.lang.circleOne_intro_a
  495. : game.lang.circleOne_intro_b;
  496. const treatedMessage = correctMessage.split('\\n');
  497. self.ui.message = [];
  498. self.ui.message.push(
  499. game.add.text(
  500. context.canvas.width / 2,
  501. 170,
  502. treatedMessage[0] + '\n' + treatedMessage[1],
  503. textStyles.h1_
  504. )
  505. );
  506. },
  507. renderOperationUI: function () {
  508. let validCircles = self.circles.list;
  509. if (gameMode === 'b') {
  510. validCircles = [];
  511. for (let i = 0; i <= self.control.selectedIndex; i++) {
  512. validCircles.push(self.circles.list[i]);
  513. }
  514. }
  515. const font = textStyles.fraction;
  516. font.fill = colors.green;
  517. const nominators = [];
  518. const denominators = [];
  519. const renderList = [];
  520. const padding = 100;
  521. const offsetX = 100;
  522. const widthOfChar = 35;
  523. const x0 = padding;
  524. const y0 = context.canvas.height / 3;
  525. let nextX = x0;
  526. const cardHeight = 400;
  527. const cardX = x0 - padding;
  528. const cardY = y0;
  529. // Card
  530. const card = game.add.geom.rect(
  531. cardX,
  532. cardY,
  533. 0,
  534. cardHeight,
  535. colors.blueLight,
  536. 0.5,
  537. colors.blueDark,
  538. 8
  539. );
  540. card.id = 'card';
  541. card.anchor(0, 0.5);
  542. renderList.push(card);
  543. // Fraction list
  544. for (let i in validCircles) {
  545. const curFraction = validCircles[i].info.fraction;
  546. const curFractionString = curFraction.labels[0].name;
  547. let curFractionSign = i !== '0' ? '+' : '';
  548. if (curFraction.labels[1].name === '-') {
  549. curFractionSign = '-';
  550. font.fill = colors.red;
  551. }
  552. const fractionText = game.add.text(
  553. x0 + i * offsetX + offsetX / 2,
  554. curFractionString === '1' ? y0 + 40 : y0,
  555. curFractionString,
  556. font
  557. );
  558. fractionText.lineHeight = 70;
  559. renderList.push(
  560. game.add.text(x0 + i * offsetX, y0 + 35, curFractionSign, font)
  561. );
  562. renderList.push(fractionText);
  563. renderList.push(
  564. game.add.text(
  565. x0 + offsetX / 2 + i * offsetX,
  566. y0,
  567. curFractionString === '1' ? '' : '_',
  568. font
  569. )
  570. );
  571. nominators.push(curFraction.nominator);
  572. denominators.push(curFraction.denominator);
  573. }
  574. // Setup for fraction operation with least common multiple
  575. font.fill = colors.black;
  576. const updatedNominators = [];
  577. const mmc = game.math.mmcArray(denominators);
  578. let resultNominator = 0;
  579. for (let i in nominators) {
  580. const temp = nominators[i] * (mmc / denominators[i]);
  581. updatedNominators.push(temp);
  582. resultNominator += temp;
  583. }
  584. const resultNominatorUnsigned =
  585. resultNominator < 0 ? -resultNominator : resultNominator;
  586. const resultAux = resultNominator / mmc;
  587. const result =
  588. ('' + resultAux).length > 4 ? resultAux.toFixed(2) : resultAux;
  589. // Fraction operation with least common multiple
  590. nextX = x0 + validCircles.length * offsetX + 20;
  591. // Fraction result
  592. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  593. font.align = 'center';
  594. nextX += offsetX;
  595. if (result < 0) {
  596. nextX -= 30;
  597. renderList.push(game.add.text(nextX, y0 + 35, '-', font));
  598. nextX += 60;
  599. }
  600. const fractionResult = game.add.text(
  601. nextX,
  602. mmc === 1 || resultNominatorUnsigned === 0 ? y0 + 40 : y0,
  603. mmc === 1 || resultNominatorUnsigned === 0
  604. ? resultNominatorUnsigned
  605. : resultNominatorUnsigned + '\n' + mmc,
  606. font
  607. );
  608. fractionResult.lineHeight = 70;
  609. renderList.push(fractionResult);
  610. const fractionLine = game.add.geom.line(
  611. nextX,
  612. y0 + 15,
  613. nextX + 60,
  614. y0 + 15,
  615. 4,
  616. colors.black,
  617. mmc === 1 || resultNominatorUnsigned === 0 ? 0 : 1
  618. );
  619. fractionLine.anchor(0.5, 0);
  620. renderList.push(fractionLine);
  621. // Fraction result simplified setup
  622. const mdcAux = game.math.mdc(resultNominator, mmc);
  623. const mdc = mdcAux < 0 ? -mdcAux : mdcAux;
  624. if (mdc !== 1 && resultNominatorUnsigned !== 0) {
  625. // alert(mdc + ' ' + resultNominatorUnsigned);
  626. nextX += offsetX;
  627. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  628. nextX += offsetX;
  629. renderList.push(
  630. game.add.text(nextX - 50, y0 + 35, result > 0 ? '' : '-', font)
  631. );
  632. renderList.push(
  633. game.add.text(nextX, y0, resultNominatorUnsigned / mdc, font)
  634. );
  635. renderList.push(game.add.text(nextX, y0 + 70, mmc / mdc, font));
  636. const fractionLine = game.add.geom.line(
  637. nextX,
  638. y0 + 15,
  639. nextX + 60,
  640. y0 + 15,
  641. 4,
  642. colors.black
  643. );
  644. fractionLine.anchor(0.5, 0);
  645. renderList.push(fractionLine);
  646. }
  647. // Decimal result
  648. let resultWidth = '_'.length * widthOfChar;
  649. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  650. card.width = cardWidth;
  651. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  652. // Center Card
  653. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  654. self.fractionOperationUI = renderList;
  655. return endSignX;
  656. },
  657. renderEndUI: () => {
  658. let btnColor = colors.green;
  659. let btnText = game.lang.continue;
  660. if (!self.control.isCorrect) {
  661. btnColor = colors.red;
  662. btnText = game.lang.retry;
  663. }
  664. // continue button
  665. self.ui.continue.button = game.add.geom.rect(
  666. context.canvas.width / 2,
  667. context.canvas.height / 2 + 100,
  668. 450,
  669. 100,
  670. btnColor
  671. );
  672. self.ui.continue.button.anchor(0.5, 0.5);
  673. self.ui.continue.text = game.add.text(
  674. context.canvas.width / 2,
  675. context.canvas.height / 2 + 16 + 100,
  676. btnText,
  677. textStyles.btn
  678. );
  679. },
  680. // UPDATE
  681. animateKidHandler: function () {
  682. let canLowerCircles = undefined;
  683. let curCircle = self.circles.list[self.circles.cur];
  684. let curDirec = curCircle.info.direc;
  685. // Move
  686. self.circles.list.forEach((circle) => {
  687. circle.x += self.animation.walkOffsetX * curDirec;
  688. });
  689. self.kid.x += self.animation.walkOffsetX * curDirec;
  690. self.walkedPath[self.control.curWalkedPath].width +=
  691. self.animation.walkOffsetX * curDirec;
  692. // Update arc
  693. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  694. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  695. // When finish current circle
  696. if (curCircle.info.direction === 'right') {
  697. canLowerCircles = curCircle.x >= self.control.nextX;
  698. } else if (curCircle.info.direction === 'left') {
  699. canLowerCircles = curCircle.x <= self.control.nextX;
  700. // If just changed from 'right' to 'left' inform to change direction of kid animation
  701. if (
  702. self.animation.invertDirection === undefined &&
  703. self.circles.cur > 0 &&
  704. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  705. ) {
  706. self.animation.invertDirection = true;
  707. }
  708. }
  709. // Change direction of kid animation
  710. if (self.animation.invertDirection) {
  711. self.animation.invertDirection = false;
  712. game.animation.stop(self.kid.animation[0]);
  713. self.kid.animation = self.animation.list.left;
  714. self.kid.curFrame = 23;
  715. game.animation.play('left');
  716. self.control.curWalkedPath = 1;
  717. self.utils.renderWalkedPath(
  718. curCircle.x,
  719. self.walkedPath[0].y + 8,
  720. colors.red
  721. );
  722. }
  723. if (canLowerCircles) {
  724. // Hide current circle
  725. curCircle.alpha = 0;
  726. // Lowers kid and other circles
  727. self.circles.list.forEach((circle) => {
  728. circle.y += self.circles.diameter;
  729. });
  730. self.kid.y += self.circles.diameter;
  731. self.circles.cur++; // Update index of current circle
  732. if (self.circles.list[self.circles.cur]) {
  733. curCircle = self.circles.list[self.circles.cur];
  734. curDirec = curCircle.info.direc;
  735. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  736. }
  737. }
  738. // When finish all circles (final position)
  739. if (
  740. self.circles.cur === self.circles.list.length ||
  741. curCircle.alpha === 0
  742. ) {
  743. self.animation.animateKid = false;
  744. self.control.checkAnswer = true;
  745. }
  746. },
  747. checkAnswerHandler: function () {
  748. game.timer.stop();
  749. game.animation.stop(self.kid.animation[0]);
  750. self.control.isCorrect = game.math.isOverlap(self.basket, self.kid);
  751. const x = self.utils.renderOperationUI();
  752. if (self.control.isCorrect) {
  753. completedLevels++;
  754. self.kid.curFrame = self.kid.curFrame < 12 ? 24 : 25;
  755. if (audioStatus) game.audio.okSound.play();
  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.counter = 0;
  769. self.animation.animateBalloon = true;
  770. },
  771. animateBalloonHandler: function () {
  772. self.animation.counter++;
  773. self.balloon.y -= 2;
  774. self.basket.y -= 2;
  775. if (self.control.isCorrect) self.kid.y -= 2;
  776. if (self.animation.counter === 100) {
  777. self.utils.renderEndUI();
  778. self.control.showEndInfo = true;
  779. if (self.control.isCorrect) canGoToNextMapPosition = true;
  780. else canGoToNextMapPosition = false;
  781. }
  782. },
  783. endLevel: function () {
  784. game.state.start('map');
  785. },
  786. // INFORMATION
  787. /**
  788. * Show correct answer
  789. */
  790. showAnswer: function () {
  791. if (!self.control.hasClicked) {
  792. // On gameMode (a)
  793. if (gameMode === 'a') {
  794. self.ui.help.x = self.control.correctX - 20;
  795. self.ui.help.y = self.road.y;
  796. // On gameMode (b)
  797. } else {
  798. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  799. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  800. }
  801. self.ui.help.alpha = 1;
  802. }
  803. },
  804. // HANDLERS
  805. /**
  806. * (in gameMode 'b') Function called when player clicked over a valid circle
  807. *
  808. * @param {number|object} cur clicked circle
  809. */
  810. clickCircleHandler: function (cur) {
  811. if (!self.control.hasClicked) {
  812. // On gameMode (a)
  813. if (gameMode === 'a') {
  814. self.balloon.x = cur;
  815. self.basket.x = cur;
  816. }
  817. // On gameMode (b)
  818. if (gameMode === 'b') {
  819. document.body.style.cursor = 'auto';
  820. for (let i in self.circles.list) {
  821. if (i <= cur.index) {
  822. self.circles.list[i].alpha = 1; // Keep selected circle
  823. self.control.selectedIndex = cur.index;
  824. } else {
  825. self.circles.list[i].alpha = 0; // Hide unselected circle
  826. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  827. }
  828. }
  829. }
  830. if (audioStatus) game.audio.popSound.play();
  831. // Hide fractions
  832. if (showFractions) {
  833. self.circles.list.forEach((circle) => {
  834. circle.info.fraction.labels.forEach((labelPart) => {
  835. if (labelPart) labelPart.alpha = 0;
  836. });
  837. });
  838. }
  839. // Hide solution pointer
  840. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  841. self.ui.message[0].alpha = 0;
  842. navigation.disableIcon(navigation.showAnswerIcon);
  843. self.balloon.alpha = 1;
  844. self.basket.alpha = 1;
  845. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  846. self.control.hasClicked = true;
  847. self.animation.animateKid = true;
  848. game.animation.play(self.kid.animation[0]);
  849. }
  850. },
  851. /**
  852. * (in gameMode 'b') Function called when cursor is over a valid circle
  853. *
  854. * @param {object} cur circle the cursor is over
  855. */
  856. overCircleHandler: function (cur) {
  857. if (!self.control.hasClicked) {
  858. document.body.style.cursor = 'pointer';
  859. for (let i in self.circles.list) {
  860. const alpha = i <= cur.index ? 1 : 0.4;
  861. self.circles.list[i].alpha = alpha;
  862. if (showFractions) {
  863. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  864. if (lbl) lbl.alpha = alpha;
  865. });
  866. }
  867. }
  868. }
  869. },
  870. /**
  871. * (in gameMode 'b') Function called when cursor leaves a valid circle
  872. */
  873. outCircleHandler: function () {
  874. if (!self.control.hasClicked) {
  875. document.body.style.cursor = 'auto';
  876. const alpha = 1;
  877. self.circles.list.forEach((circle) => {
  878. circle.alpha = alpha;
  879. if (showFractions) {
  880. circle.info.fraction.labels.forEach((lbl) => {
  881. if (lbl) lbl.alpha = alpha;
  882. });
  883. }
  884. });
  885. }
  886. },
  887. },
  888. events: {
  889. /**
  890. * Called by mouse click event
  891. *
  892. * @param {object} mouseEvent contains the mouse click coordinates
  893. */
  894. onInputDown: function (mouseEvent) {
  895. const x = game.math.getMouse(mouseEvent).x;
  896. const y = game.math.getMouse(mouseEvent).y;
  897. // GAME MODE A : click road
  898. if (gameMode === 'a') {
  899. const isValid =
  900. y > 150 && x >= self.road.x && x <= self.road.x + self.road.width;
  901. if (isValid) self.utils.clickCircleHandler(x);
  902. }
  903. // GAME MODE B : click circle
  904. if (gameMode === 'b') {
  905. self.circles.list.forEach((circle) => {
  906. const isValid =
  907. game.math.distanceToPointer(
  908. x,
  909. circle.xWithAnchor,
  910. y,
  911. circle.yWithAnchor
  912. ) <=
  913. (circle.diameter / 2) * circle.scale;
  914. if (isValid) self.utils.clickCircleHandler(circle);
  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: function (mouseEvent) {
  933. const x = game.math.getMouse(mouseEvent).x;
  934. const y = game.math.getMouse(mouseEvent).y;
  935. let isOverCircle = false;
  936. // GAME MODE A : balloon follow mouse
  937. if (gameMode === 'a' && !self.control.hasClicked) {
  938. if (
  939. game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8
  940. ) {
  941. self.balloon.x = x;
  942. self.basket.x = x;
  943. }
  944. document.body.style.cursor = 'auto';
  945. }
  946. // GAME MODE B : hover circle
  947. if (gameMode === 'b' && !self.control.hasClicked) {
  948. self.circles.list.forEach((circle) => {
  949. const isValid =
  950. game.math.distanceToPointer(
  951. x,
  952. circle.xWithAnchor,
  953. y,
  954. circle.yWithAnchor
  955. ) <=
  956. (circle.diameter / 2) * circle.scale;
  957. if (isValid) {
  958. self.utils.overCircleHandler(circle);
  959. isOverCircle = true;
  960. }
  961. });
  962. if (!isOverCircle) self.utils.outCircleHandler();
  963. }
  964. // Continue button
  965. if (self.control.showEndInfo) {
  966. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  967. // If pointer is over icon
  968. document.body.style.cursor = 'pointer';
  969. self.ui.continue.button.scale =
  970. self.ui.continue.button.initialScale * 1.1;
  971. self.ui.continue.text.style = textStyles.btnLg;
  972. } else {
  973. // If pointer is not over icon
  974. document.body.style.cursor = 'auto';
  975. self.ui.continue.button.scale =
  976. self.ui.continue.button.initialScale * 1;
  977. self.ui.continue.text.style = textStyles.btn;
  978. }
  979. }
  980. navigation.onInputOver(x, y);
  981. game.render.all();
  982. },
  983. },
  984. fetch: {
  985. /**
  986. * Saves players data after level ends - to be sent to database <br>
  987. *
  988. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  989. *
  990. * @see /php/squareOne.js
  991. */
  992. postScore: function () {
  993. // Creates string that is going to be sent to db
  994. const data =
  995. '&line_game=' +
  996. gameShape +
  997. '&line_mode=' +
  998. gameMode +
  999. '&line_oper=' +
  1000. gameOperation +
  1001. '&line_leve=' +
  1002. gameDifficulty +
  1003. '&line_posi=' +
  1004. curMapPosition +
  1005. '&line_resu=' +
  1006. self.control.isCorrect +
  1007. '&line_time=' +
  1008. game.timer.elapsed +
  1009. '&line_deta=' +
  1010. 'numCircles:' +
  1011. self.circles.list.length +
  1012. ', valCircles: ' +
  1013. self.control.divisorsList +
  1014. ' balloonX: ' +
  1015. self.basket.x +
  1016. ', selIndex: ' +
  1017. self.control.selectedIndex;
  1018. // FOR MOODLE
  1019. sendToDatabase(data);
  1020. },
  1021. },
  1022. };