circleOne.js 32 KB

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