circleOne.js 33 KB

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