circleOne.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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,4,5..... = 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. if (showFractions) {
  347. for (let i = 0; i < 2; i++) {
  348. const item = game.add.text(
  349. curFractionItems[i].x,
  350. curFractionItems[i].y,
  351. curFractionItems[i].text,
  352. font
  353. );
  354. item.lineHeight = 37;
  355. curCircleInfo.fraction.labels.push(item);
  356. }
  357. if (curFractionItems[2]) {
  358. const line = game.add.geom.line(
  359. curFractionItems[2].x0,
  360. curFractionItems[2].y0,
  361. curFractionItems[2].x1,
  362. curFractionItems[2].y1,
  363. curFractionItems[2].lineWidth,
  364. curFractionItems[2].color
  365. );
  366. line.anchor(0.5, 0);
  367. curCircleInfo.fraction.labels.push(line);
  368. } else {
  369. curCircleInfo.fraction.labels.push(null);
  370. }
  371. curCircleInfo.fraction.nominator = curCircleInfo.direc;
  372. curCircleInfo.fraction.denominator = curDivisor;
  373. }
  374. curCircle.rotate = 90;
  375. // If game is type (b) (select fractions)
  376. if (gameMode === 'b') {
  377. curCircle.index = i;
  378. }
  379. curCircleInfo.distance = Math.floor(
  380. validPath.distanceBetweenPoints / curDivisor
  381. );
  382. // Add to the list
  383. curCircle.info = curCircleInfo;
  384. self.circles.list.push(curCircle);
  385. self.control.correctX +=
  386. Math.floor(validPath.distanceBetweenPoints / curDivisor) *
  387. curCircle.info.direc;
  388. }
  389. // Restart if
  390. // Does not have at least one fraction of type 1/difficulty
  391. if (!hasBaseDifficulty) {
  392. restart = true;
  393. }
  394. // Calculate next circle
  395. self.control.nextX =
  396. validPath.x0 +
  397. self.circles.list[0].info.distance * self.circles.list[0].info.direc;
  398. let isBeforeMin = (isAfterMax = false);
  399. let finalPosition = self.control.correctX;
  400. // Restart if
  401. // In Game mode 'a' and 'b' : Balloon position is out of bounds
  402. if (gameOperation === 'minus') {
  403. isBeforeMin = finalPosition > validPath.x0;
  404. isAfterMax =
  405. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  406. } else {
  407. isBeforeMin = finalPosition < validPath.x0;
  408. isAfterMax =
  409. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  410. }
  411. if (isBeforeMin || isAfterMax) restart = true;
  412. if (gameMode === 'b') {
  413. // If game is type (b), select a random balloon place
  414. balloonX = validPath.x0;
  415. self.control.correctIndex = game.math.randomInRange(
  416. self.control.numberOfPlusFractions,
  417. self.circles.list.length
  418. );
  419. for (let i = 0; i < self.control.correctIndex; i++) {
  420. balloonX +=
  421. self.circles.list[i].info.distance *
  422. self.circles.list[i].info.direc;
  423. }
  424. finalPosition = balloonX;
  425. // Restart if
  426. // In Game mode 'b' : Top circle position is out of bounds (when on the ground)
  427. if (gameOperation === 'minus') {
  428. isBeforeMin = finalPosition > validPath.x0;
  429. isAfterMax =
  430. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  431. } else {
  432. isBeforeMin = finalPosition < validPath.x0;
  433. isAfterMax =
  434. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  435. }
  436. if (isBeforeMin || isAfterMax) restart = true;
  437. }
  438. return [restart, balloonX];
  439. },
  440. renderCharacters: function (validPath, balloonX) {
  441. // KID
  442. self.kid = game.add.sprite(
  443. validPath.x0,
  444. validPath.y0 - 32 - self.circles.list.length * self.circles.diameter,
  445. 'kid_walking',
  446. 0,
  447. 1.2
  448. );
  449. self.kid.anchor(0.5, 0.8);
  450. self.animation.list.right = [
  451. 'right',
  452. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  453. 4,
  454. ];
  455. self.animation.list.left = [
  456. 'left',
  457. [23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12],
  458. 4,
  459. ];
  460. if (gameOperation === 'minus') {
  461. self.kid.animation = self.animation.list.left;
  462. self.kid.curFrame = 23;
  463. } else {
  464. self.kid.animation = self.animation.list.right;
  465. }
  466. // BALLOON
  467. self.balloon = game.add.image(
  468. balloonX,
  469. validPath.y0 - 295,
  470. 'balloon',
  471. 1.5,
  472. 0.5
  473. );
  474. self.balloon.alpha = 0.5;
  475. self.balloon.anchor(0.5, 0.5);
  476. self.basket = game.add.image(
  477. balloonX,
  478. validPath.y0 - 95,
  479. 'balloon_basket',
  480. 1.5
  481. );
  482. self.basket.alpha = 0.8;
  483. self.basket.anchor(0.5, 0.5);
  484. },
  485. renderMainUI: function () {
  486. // Help pointer
  487. self.ui.help = game.add.image(0, 0, 'pointer', 2, 0);
  488. // Intro text
  489. const correctMessage =
  490. gameMode === 'a'
  491. ? game.lang.circleOne_intro_a
  492. : game.lang.circleOne_intro_b;
  493. const treatedMessage = correctMessage.split('\\n');
  494. self.ui.message = [];
  495. self.ui.message.push(
  496. game.add.text(
  497. context.canvas.width / 2,
  498. 170,
  499. treatedMessage[0] + '\n' + treatedMessage[1],
  500. textStyles.h1_
  501. )
  502. );
  503. },
  504. renderOperationUI: function () {
  505. let validCircles = self.circles.list;
  506. if (gameMode === 'b') {
  507. validCircles = [];
  508. for (let i = 0; i <= self.control.selectedIndex; i++) {
  509. validCircles.push(self.circles.list[i]);
  510. }
  511. }
  512. const font = textStyles.fraction;
  513. font.fill = colors.green;
  514. const nominators = [];
  515. const denominators = [];
  516. const renderList = [];
  517. const padding = 100;
  518. const offsetX = 100;
  519. const widthOfChar = 35;
  520. const x0 = padding;
  521. const y0 = context.canvas.height / 3;
  522. let nextX = x0;
  523. const cardHeight = 400;
  524. const cardX = x0 - padding;
  525. const cardY = y0;
  526. // Card
  527. const card = game.add.geom.rect(
  528. cardX,
  529. cardY,
  530. 0,
  531. cardHeight,
  532. colors.blueLight,
  533. 0.5,
  534. colors.blueDark,
  535. 8
  536. );
  537. card.id = 'card';
  538. card.anchor(0, 0.5);
  539. renderList.push(card);
  540. // Fraction list
  541. for (let i in validCircles) {
  542. const curFraction = validCircles[i].info.fraction;
  543. const curFractionString = curFraction.labels[0].name;
  544. let curFractionSign = i !== '0' ? '+' : '';
  545. if (curFraction.labels[1].name === '-') {
  546. curFractionSign = '-';
  547. font.fill = colors.red;
  548. }
  549. const fractionText = game.add.text(
  550. x0 + i * offsetX + offsetX / 2,
  551. curFractionString === '1' ? y0 + 40 : y0,
  552. curFractionString,
  553. font
  554. );
  555. fractionText.lineHeight = 70;
  556. renderList.push(
  557. game.add.text(x0 + i * offsetX, y0 + 35, curFractionSign, font)
  558. );
  559. renderList.push(fractionText);
  560. renderList.push(
  561. game.add.text(
  562. x0 + offsetX / 2 + i * offsetX,
  563. y0,
  564. curFractionString === '1' ? '' : '_',
  565. font
  566. )
  567. );
  568. nominators.push(curFraction.nominator);
  569. denominators.push(curFraction.denominator);
  570. }
  571. // Setup for fraction operation with least common multiple
  572. font.fill = colors.black;
  573. const updatedNominators = [];
  574. const mmc = game.math.mmcArray(denominators);
  575. let resultNominator = 0;
  576. for (let i in nominators) {
  577. const temp = nominators[i] * (mmc / denominators[i]);
  578. updatedNominators.push(temp);
  579. resultNominator += temp;
  580. }
  581. const resultNominatorUnsigned =
  582. resultNominator < 0 ? -resultNominator : resultNominator;
  583. const resultAux = resultNominator / mmc;
  584. const result =
  585. ('' + resultAux).length > 4 ? resultAux.toFixed(2) : resultAux;
  586. // let fracLine = '';
  587. // const updatedNominatorsString = updatedNominators
  588. // .map((n) => {
  589. // const len = ('' + n).length;
  590. // for (let i = 0; i < len; i++) fracLine += '_';
  591. // fracLine = n < 0 ? fracLine : fracLine + '_';
  592. // return n >= 0 ? '+' + n : n;
  593. // })
  594. // .join('');
  595. // const fractionMiddleX = widthOfChar * (fracLine.length / 2);
  596. // Fraction operation with least common multiple
  597. nextX = x0 + validCircles.length * offsetX + 20;
  598. // renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  599. // nextX += offsetX / 2;
  600. // renderList.push(game.add.text(nextX, y0, updatedNominatorsString, font));
  601. // renderList.push(
  602. // game.add.text(nextX + fractionMiddleX, y0 + 70, mmc, font)
  603. // );
  604. // renderList.push(game.add.text(nextX, y0, fracLine, font));
  605. // Fraction result
  606. //nextX += fractionMiddleX * 2 + 50;
  607. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  608. font.align = 'center';
  609. nextX += offsetX + 40;
  610. renderList.push(
  611. game.add.text(nextX - 80, y0 + 35, result >= 0 ? '' : '-', font)
  612. );
  613. const fractionResult = game.add.text(
  614. nextX,
  615. mmc === 1 || resultNominatorUnsigned === 0 ? y0 + 40 : y0,
  616. mmc === 1 || resultNominatorUnsigned === 0
  617. ? resultNominatorUnsigned
  618. : resultNominatorUnsigned + '\n' + mmc,
  619. font
  620. );
  621. fractionResult.lineHeight = 70;
  622. renderList.push(fractionResult);
  623. const fractionLine = game.add.geom.line(
  624. nextX,
  625. y0 + 15,
  626. nextX + 60,
  627. y0 + 15,
  628. 4,
  629. colors.black,
  630. mmc === 1 || resultNominatorUnsigned === 0 ? 0 : 1
  631. );
  632. fractionLine.anchor(0.5, 0);
  633. renderList.push(fractionLine);
  634. // Fraction result simplified setup
  635. const mdcAux = game.math.mdc(resultNominator, mmc);
  636. const mdc = mdcAux < 0 ? -mdcAux : mdcAux;
  637. if (mdc !== 1 && resultNominatorUnsigned !== 0) {
  638. // alert(mdc + ' ' + resultNominatorUnsigned);
  639. nextX += offsetX;
  640. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  641. nextX += offsetX;
  642. renderList.push(
  643. game.add.text(nextX - 50, y0 + 35, result > 0 ? '' : '-', font)
  644. );
  645. renderList.push(
  646. game.add.text(nextX, y0, resultNominatorUnsigned / mdc, font)
  647. );
  648. renderList.push(game.add.text(nextX, y0 + 70, mmc / mdc, font));
  649. const fractionLine = game.add.geom.line(
  650. nextX,
  651. y0 + 15,
  652. nextX + 60,
  653. y0 + 15,
  654. 4,
  655. colors.black
  656. );
  657. fractionLine.anchor(0.5, 0);
  658. renderList.push(fractionLine);
  659. }
  660. // Decimal result
  661. // nextX += offsetX;
  662. // renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  663. // nextX += offsetX / 2;
  664. // renderList.push(game.add.text(nextX, y0 + 35, result, font));
  665. //let resultWidth = ('' + result).length * widthOfChar;
  666. let resultWidth = '_'.length * widthOfChar;
  667. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  668. card.width = cardWidth;
  669. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  670. // Center Card
  671. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  672. self.fractionOperationUI = renderList;
  673. return endSignX;
  674. },
  675. renderEndUI: () => {
  676. let btnColor = colors.green;
  677. let btnText = game.lang.continue;
  678. if (!self.control.isCorrect) {
  679. btnColor = colors.red;
  680. btnText = game.lang.retry;
  681. }
  682. // continue button
  683. self.ui.continue.button = game.add.geom.rect(
  684. context.canvas.width / 2,
  685. context.canvas.height / 2 + 100,
  686. 450,
  687. 100,
  688. btnColor
  689. );
  690. self.ui.continue.button.anchor(0.5, 0.5);
  691. self.ui.continue.text = game.add.text(
  692. context.canvas.width / 2,
  693. context.canvas.height / 2 + 16 + 100,
  694. btnText,
  695. textStyles.btn
  696. );
  697. },
  698. // UPDATE
  699. animateKidHandler: function () {
  700. let canLowerCircles = undefined;
  701. let curCircle = self.circles.list[self.circles.cur];
  702. let curDirec = curCircle.info.direc;
  703. // Move
  704. self.circles.list.forEach((circle) => {
  705. circle.x += self.animation.walkOffsetX * curDirec;
  706. });
  707. self.kid.x += self.animation.walkOffsetX * curDirec;
  708. self.walkedPath[self.control.curWalkedPath].width +=
  709. self.animation.walkOffsetX * curDirec;
  710. // Update arc
  711. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  712. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  713. // When finish current circle
  714. if (curCircle.info.direction === 'right') {
  715. canLowerCircles = curCircle.x >= self.control.nextX;
  716. } else if (curCircle.info.direction === 'left') {
  717. canLowerCircles = curCircle.x <= self.control.nextX;
  718. // If just changed from 'right' to 'left' inform to change direction of kid animation
  719. if (
  720. self.animation.invertDirection === undefined &&
  721. self.circles.cur > 0 &&
  722. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  723. ) {
  724. self.animation.invertDirection = true;
  725. }
  726. }
  727. // Change direction of kid animation
  728. if (self.animation.invertDirection) {
  729. self.animation.invertDirection = false;
  730. game.animation.stop(self.kid.animation[0]);
  731. self.kid.animation = self.animation.list.left;
  732. self.kid.curFrame = 23;
  733. game.animation.play('left');
  734. self.control.curWalkedPath = 1;
  735. self.utils.renderWalkedPath(
  736. curCircle.x,
  737. self.walkedPath[0].y + 8,
  738. colors.red
  739. );
  740. }
  741. if (canLowerCircles) {
  742. // Hide current circle
  743. curCircle.alpha = 0;
  744. // Lowers kid and other circles
  745. self.circles.list.forEach((circle) => {
  746. circle.y += self.circles.diameter;
  747. });
  748. self.kid.y += self.circles.diameter;
  749. self.circles.cur++; // Update index of current circle
  750. if (self.circles.list[self.circles.cur]) {
  751. curCircle = self.circles.list[self.circles.cur];
  752. curDirec = curCircle.info.direc;
  753. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  754. }
  755. }
  756. // When finish all circles (final position)
  757. if (
  758. self.circles.cur === self.circles.list.length ||
  759. curCircle.alpha === 0
  760. ) {
  761. self.animation.animateKid = false;
  762. self.control.checkAnswer = true;
  763. }
  764. },
  765. checkAnswerHandler: function () {
  766. game.timer.stop();
  767. game.animation.stop(self.kid.animation[0]);
  768. self.control.isCorrect = game.math.isOverlap(self.basket, self.kid);
  769. const x = self.utils.renderOperationUI();
  770. if (self.control.isCorrect) {
  771. completedLevels++;
  772. self.kid.curFrame = self.kid.curFrame < 12 ? 24 : 25;
  773. if (audioStatus) game.audio.okSound.play();
  774. game.add
  775. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  776. .anchor(0.5, 0.5);
  777. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  778. } else {
  779. if (audioStatus) game.audio.errorSound.play();
  780. game.add
  781. .image(x, context.canvas.height / 3, 'answer_wrong')
  782. .anchor(0.5, 0.5);
  783. }
  784. self.fetch.postScore();
  785. self.control.checkAnswer = false;
  786. self.animation.counter = 0;
  787. self.animation.animateBalloon = true;
  788. },
  789. animateBalloonHandler: function () {
  790. self.animation.counter++;
  791. self.balloon.y -= 2;
  792. self.basket.y -= 2;
  793. if (self.control.isCorrect) self.kid.y -= 2;
  794. if (self.animation.counter === 100) {
  795. self.utils.renderEndUI();
  796. self.control.showEndInfo = true;
  797. if (self.control.isCorrect) canGoToNextMapPosition = true;
  798. else canGoToNextMapPosition = false;
  799. }
  800. },
  801. endLevel: function () {
  802. game.state.start('map');
  803. },
  804. // INFORMATION
  805. /**
  806. * Show correct answer
  807. */
  808. showAnswer: function () {
  809. if (!self.control.hasClicked) {
  810. // On gameMode (a)
  811. if (gameMode === 'a') {
  812. self.ui.help.x = self.control.correctX - 20;
  813. self.ui.help.y = self.road.y;
  814. // On gameMode (b)
  815. } else {
  816. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  817. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  818. }
  819. self.ui.help.alpha = 1;
  820. }
  821. },
  822. // HANDLERS
  823. /**
  824. * (in gameMode 'b') Function called when player clicked over a valid circle
  825. *
  826. * @param {number|object} cur clicked circle
  827. */
  828. clickCircleHandler: function (cur) {
  829. if (!self.control.hasClicked) {
  830. // On gameMode (a)
  831. if (gameMode === 'a') {
  832. self.balloon.x = cur;
  833. self.basket.x = cur;
  834. }
  835. // On gameMode (b)
  836. if (gameMode === 'b') {
  837. document.body.style.cursor = 'auto';
  838. for (let i in self.circles.list) {
  839. if (i <= cur.index) {
  840. self.circles.list[i].alpha = 1; // Keep selected circle
  841. self.control.selectedIndex = cur.index;
  842. } else {
  843. self.circles.list[i].alpha = 0; // Hide unselected circle
  844. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  845. }
  846. }
  847. }
  848. if (audioStatus) game.audio.popSound.play();
  849. // Hide fractions
  850. if (showFractions) {
  851. self.circles.list.forEach((circle) => {
  852. circle.info.fraction.labels.forEach((labelPart) => {
  853. if (labelPart) labelPart.alpha = 0;
  854. });
  855. });
  856. }
  857. // Hide solution pointer
  858. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  859. self.ui.message[0].alpha = 0;
  860. navigation.disableIcon(navigation.showAnswerIcon);
  861. self.balloon.alpha = 1;
  862. self.basket.alpha = 1;
  863. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  864. self.control.hasClicked = true;
  865. self.animation.animateKid = true;
  866. game.animation.play(self.kid.animation[0]);
  867. }
  868. },
  869. /**
  870. * (in gameMode 'b') Function called when cursor is over a valid circle
  871. *
  872. * @param {object} cur circle the cursor is over
  873. */
  874. overCircleHandler: function (cur) {
  875. if (!self.control.hasClicked) {
  876. document.body.style.cursor = 'pointer';
  877. for (let i in self.circles.list) {
  878. const alpha = i <= cur.index ? 1 : 0.4;
  879. self.circles.list[i].alpha = alpha;
  880. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  881. if (lbl) lbl.alpha = alpha;
  882. });
  883. }
  884. }
  885. },
  886. /**
  887. * (in gameMode 'b') Function called when cursor leaves a valid circle
  888. */
  889. outCircleHandler: function () {
  890. if (!self.control.hasClicked) {
  891. document.body.style.cursor = 'auto';
  892. const alpha = 1;
  893. self.circles.list.forEach((circle) => {
  894. circle.alpha = alpha;
  895. circle.info.fraction.labels.forEach((lbl) => {
  896. if (lbl) lbl.alpha = alpha;
  897. });
  898. });
  899. }
  900. },
  901. },
  902. events: {
  903. /**
  904. * Called by mouse click event
  905. *
  906. * @param {object} mouseEvent contains the mouse click coordinates
  907. */
  908. onInputDown: function (mouseEvent) {
  909. const x = game.math.getMouse(mouseEvent).x;
  910. const y = game.math.getMouse(mouseEvent).y;
  911. // GAME MODE A : click road
  912. if (gameMode === 'a') {
  913. const isValid =
  914. y > 150 && x >= self.road.x && x <= self.road.x + self.road.width;
  915. if (isValid) self.utils.clickCircleHandler(x);
  916. }
  917. // GAME MODE B : click circle
  918. if (gameMode === 'b') {
  919. self.circles.list.forEach((circle) => {
  920. const isValid =
  921. game.math.distanceToPointer(
  922. x,
  923. circle.xWithAnchor,
  924. y,
  925. circle.yWithAnchor
  926. ) <=
  927. (circle.diameter / 2) * circle.scale;
  928. if (isValid) self.utils.clickCircleHandler(circle);
  929. });
  930. }
  931. // Continue button
  932. if (self.control.showEndInfo) {
  933. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  934. if (audioStatus) game.audio.popSound.play();
  935. self.utils.endLevel();
  936. }
  937. }
  938. navigation.onInputDown(x, y);
  939. game.render.all();
  940. },
  941. /**
  942. * Called by mouse move event
  943. *
  944. * @param {object} mouseEvent contains the mouse move coordinates
  945. */
  946. onInputOver: function (mouseEvent) {
  947. const x = game.math.getMouse(mouseEvent).x;
  948. const y = game.math.getMouse(mouseEvent).y;
  949. let isOverCircle = false;
  950. // GAME MODE A : balloon follow mouse
  951. if (gameMode === 'a' && !self.control.hasClicked) {
  952. if (
  953. game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8
  954. ) {
  955. self.balloon.x = x;
  956. self.basket.x = x;
  957. }
  958. document.body.style.cursor = 'auto';
  959. }
  960. // GAME MODE B : hover circle
  961. if (gameMode === 'b' && !self.control.hasClicked) {
  962. self.circles.list.forEach((circle) => {
  963. const isValid =
  964. game.math.distanceToPointer(
  965. x,
  966. circle.xWithAnchor,
  967. y,
  968. circle.yWithAnchor
  969. ) <=
  970. (circle.diameter / 2) * circle.scale;
  971. if (isValid) {
  972. self.utils.overCircleHandler(circle);
  973. isOverCircle = true;
  974. }
  975. });
  976. if (!isOverCircle) self.utils.outCircleHandler();
  977. }
  978. // Continue button
  979. if (self.control.showEndInfo) {
  980. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  981. // If pointer is over icon
  982. document.body.style.cursor = 'pointer';
  983. self.ui.continue.button.scale =
  984. self.ui.continue.button.initialScale * 1.1;
  985. self.ui.continue.text.style = textStyles.btnLg;
  986. } else {
  987. // If pointer is not over icon
  988. document.body.style.cursor = 'auto';
  989. self.ui.continue.button.scale =
  990. self.ui.continue.button.initialScale * 1;
  991. self.ui.continue.text.style = textStyles.btn;
  992. }
  993. }
  994. navigation.onInputOver(x, y);
  995. game.render.all();
  996. },
  997. },
  998. fetch: {
  999. /**
  1000. * Saves players data after level ends - to be sent to database <br>
  1001. *
  1002. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  1003. *
  1004. * @see /php/squareOne.js
  1005. */
  1006. postScore: function () {
  1007. // Creates string that is going to be sent to db
  1008. const data =
  1009. '&line_game=' +
  1010. gameShape +
  1011. '&line_mode=' +
  1012. gameMode +
  1013. '&line_oper=' +
  1014. gameOperation +
  1015. '&line_leve=' +
  1016. gameDifficulty +
  1017. '&line_posi=' +
  1018. curMapPosition +
  1019. '&line_resu=' +
  1020. self.control.isCorrect +
  1021. '&line_time=' +
  1022. game.timer.elapsed +
  1023. '&line_deta=' +
  1024. 'numCircles:' +
  1025. self.circles.list.length +
  1026. ', valCircles: ' +
  1027. self.control.divisorsList +
  1028. ' balloonX: ' +
  1029. self.basket.x +
  1030. ', selIndex: ' +
  1031. self.control.selectedIndex;
  1032. // FOR MOODLE
  1033. sendToDatabase(data);
  1034. },
  1035. },
  1036. };