circleOne.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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. if (self.animation.counter < 130) {
  773. self.animation.counter++;
  774. self.balloon.y -= 2;
  775. self.basket.y -= 2;
  776. if (self.control.isCorrect) self.kid.y -= 2;
  777. }
  778. if (self.animation.counter === 130) {
  779. self.utils.renderEndUI();
  780. self.control.showEndInfo = true;
  781. if (self.control.isCorrect) canGoToNextMapPosition = true;
  782. else canGoToNextMapPosition = false;
  783. }
  784. },
  785. endLevel: function () {
  786. game.state.start('map');
  787. },
  788. // INFORMATION
  789. /**
  790. * Show correct answer
  791. */
  792. showAnswer: function () {
  793. if (!self.control.hasClicked) {
  794. // On gameMode (a)
  795. if (gameMode === 'a') {
  796. self.ui.help.x = self.control.correctX - 20;
  797. self.ui.help.y = self.road.y;
  798. // On gameMode (b)
  799. } else {
  800. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  801. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  802. }
  803. self.ui.help.alpha = 1;
  804. }
  805. },
  806. // HANDLERS
  807. /**
  808. * (in gameMode 'b') Function called when player clicked over a valid circle
  809. *
  810. * @param {number|object} cur clicked circle
  811. */
  812. clickCircleHandler: function (cur) {
  813. if (!self.control.hasClicked) {
  814. // On gameMode (a)
  815. if (gameMode === 'a') {
  816. self.balloon.x = cur;
  817. self.basket.x = cur;
  818. }
  819. // On gameMode (b)
  820. if (gameMode === 'b') {
  821. document.body.style.cursor = 'auto';
  822. for (let i in self.circles.list) {
  823. if (i <= cur.index) {
  824. self.circles.list[i].alpha = 1; // Keep selected circle
  825. self.control.selectedIndex = cur.index;
  826. } else {
  827. self.circles.list[i].alpha = 0; // Hide unselected circle
  828. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  829. }
  830. }
  831. }
  832. if (audioStatus) game.audio.popSound.play();
  833. // Hide fractions
  834. if (showFractions) {
  835. self.circles.list.forEach((circle) => {
  836. circle.info.fraction.labels.forEach((labelPart) => {
  837. if (labelPart) labelPart.alpha = 0;
  838. });
  839. });
  840. }
  841. // Hide solution pointer
  842. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  843. self.ui.message[0].alpha = 0;
  844. navigation.disableIcon(navigation.showAnswerIcon);
  845. self.balloon.alpha = 1;
  846. self.basket.alpha = 1;
  847. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  848. self.control.hasClicked = true;
  849. self.animation.animateKid = true;
  850. game.animation.play(self.kid.animation[0]);
  851. }
  852. },
  853. /**
  854. * (in gameMode 'b') Function called when cursor is over a valid circle
  855. *
  856. * @param {object} cur circle the cursor is over
  857. */
  858. overCircleHandler: function (cur) {
  859. if (!self.control.hasClicked) {
  860. document.body.style.cursor = 'pointer';
  861. for (let i in self.circles.list) {
  862. const alpha = i <= cur.index ? 1 : 0.4;
  863. self.circles.list[i].alpha = alpha;
  864. if (showFractions) {
  865. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  866. if (lbl) lbl.alpha = alpha;
  867. });
  868. }
  869. }
  870. }
  871. },
  872. /**
  873. * (in gameMode 'b') Function called when cursor leaves a valid circle
  874. */
  875. outCircleHandler: function () {
  876. if (!self.control.hasClicked) {
  877. document.body.style.cursor = 'auto';
  878. const alpha = 1;
  879. self.circles.list.forEach((circle) => {
  880. circle.alpha = alpha;
  881. if (showFractions) {
  882. circle.info.fraction.labels.forEach((lbl) => {
  883. if (lbl) lbl.alpha = alpha;
  884. });
  885. }
  886. });
  887. }
  888. },
  889. },
  890. events: {
  891. /**
  892. * Called by mouse click event
  893. *
  894. * @param {object} mouseEvent contains the mouse click coordinates
  895. */
  896. onInputDown: function (mouseEvent) {
  897. const x = game.math.getMouse(mouseEvent).x;
  898. const y = game.math.getMouse(mouseEvent).y;
  899. // GAME MODE A : click road
  900. if (gameMode === 'a') {
  901. const isValid =
  902. y > 150 && x >= self.road.x && x <= self.road.x + self.road.width;
  903. if (isValid) self.utils.clickCircleHandler(x);
  904. }
  905. // GAME MODE B : click circle
  906. if (gameMode === 'b') {
  907. self.circles.list.forEach((circle) => {
  908. const isValid =
  909. game.math.distanceToPointer(
  910. x,
  911. circle.xWithAnchor,
  912. y,
  913. circle.yWithAnchor
  914. ) <=
  915. (circle.diameter / 2) * circle.scale;
  916. if (isValid) self.utils.clickCircleHandler(circle);
  917. });
  918. }
  919. // Continue button
  920. if (self.control.showEndInfo) {
  921. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  922. if (audioStatus) game.audio.popSound.play();
  923. self.utils.endLevel();
  924. }
  925. }
  926. navigation.onInputDown(x, y);
  927. game.render.all();
  928. },
  929. /**
  930. * Called by mouse move event
  931. *
  932. * @param {object} mouseEvent contains the mouse move coordinates
  933. */
  934. onInputOver: function (mouseEvent) {
  935. const x = game.math.getMouse(mouseEvent).x;
  936. const y = game.math.getMouse(mouseEvent).y;
  937. let isOverCircle = false;
  938. // GAME MODE A : balloon follow mouse
  939. if (gameMode === 'a' && !self.control.hasClicked) {
  940. if (
  941. game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8
  942. ) {
  943. self.balloon.x = x;
  944. self.basket.x = x;
  945. }
  946. document.body.style.cursor = 'auto';
  947. }
  948. // GAME MODE B : hover circle
  949. if (gameMode === 'b' && !self.control.hasClicked) {
  950. self.circles.list.forEach((circle) => {
  951. const isValid =
  952. game.math.distanceToPointer(
  953. x,
  954. circle.xWithAnchor,
  955. y,
  956. circle.yWithAnchor
  957. ) <=
  958. (circle.diameter / 2) * circle.scale;
  959. if (isValid) {
  960. self.utils.overCircleHandler(circle);
  961. isOverCircle = true;
  962. }
  963. });
  964. if (!isOverCircle) self.utils.outCircleHandler();
  965. }
  966. // Continue button
  967. if (self.control.showEndInfo) {
  968. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  969. // If pointer is over icon
  970. document.body.style.cursor = 'pointer';
  971. self.ui.continue.button.scale =
  972. self.ui.continue.button.initialScale * 1.1;
  973. self.ui.continue.text.style = textStyles.btnLg;
  974. } else {
  975. // If pointer is not over icon
  976. document.body.style.cursor = 'auto';
  977. self.ui.continue.button.scale =
  978. self.ui.continue.button.initialScale * 1;
  979. self.ui.continue.text.style = textStyles.btn;
  980. }
  981. }
  982. navigation.onInputOver(x, y);
  983. game.render.all();
  984. },
  985. },
  986. fetch: {
  987. /**
  988. * Saves players data after level ends - to be sent to database <br>
  989. *
  990. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  991. *
  992. * @see /php/squareOne.js
  993. */
  994. postScore: function () {
  995. // Creates string that is going to be sent to db
  996. const data =
  997. '&line_game=' +
  998. gameShape +
  999. '&line_mode=' +
  1000. gameMode +
  1001. '&line_oper=' +
  1002. gameOperation +
  1003. '&line_leve=' +
  1004. gameDifficulty +
  1005. '&line_posi=' +
  1006. curMapPosition +
  1007. '&line_resu=' +
  1008. self.control.isCorrect +
  1009. '&line_time=' +
  1010. game.timer.elapsed +
  1011. '&line_deta=' +
  1012. 'numCircles:' +
  1013. self.circles.list.length +
  1014. ', valCircles: ' +
  1015. self.control.divisorsList +
  1016. ' balloonX: ' +
  1017. self.basket.x +
  1018. ', selIndex: ' +
  1019. self.control.selectedIndex;
  1020. // FOR MOODLE
  1021. sendToDatabase(data);
  1022. },
  1023. },
  1024. };