circleOne.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. /**
  509. * if game mode A:
  510. * - left: selected balloon position (user selection)
  511. * - right: line created from the stack of arcs (pre-set)
  512. *
  513. * if game mode B:
  514. * - left: line created from the stack of arcs (user selection)
  515. * - right: baloon position (pre-set)
  516. */
  517. let validCircles = self.circles.list;
  518. if (gameMode === 'b') {
  519. validCircles = [];
  520. for (let i = 0; i <= self.control.selectedIndex; i++) {
  521. validCircles.push(self.circles.list[i]);
  522. }
  523. }
  524. const font = textStyles.fraction;
  525. font.fill = colors.green;
  526. const nominators = [];
  527. const denominators = [];
  528. const renderList = [];
  529. const padding = 100;
  530. const offsetX = 100;
  531. const widthOfChar = 35;
  532. const x0 = padding;
  533. const y0 = context.canvas.height / 3;
  534. let nextX = x0;
  535. const cardHeight = 400;
  536. const cardX = x0 - padding;
  537. const cardY = y0;
  538. // Card
  539. const card = game.add.geom.rect(
  540. cardX,
  541. cardY,
  542. 0,
  543. cardHeight,
  544. colors.blueLight,
  545. 0.5,
  546. colors.blueDark,
  547. 8
  548. );
  549. card.id = 'card';
  550. card.anchor(0, 0.5);
  551. renderList.push(card);
  552. // Fraction list
  553. for (let i in validCircles) {
  554. const curFraction = validCircles[i].info.fraction;
  555. const curFractionString = curFraction.labels[0].name;
  556. let curFractionSign = i !== '0' ? '+' : '';
  557. if (curFraction.labels[1].name === '-') {
  558. curFractionSign = '-';
  559. font.fill = colors.red;
  560. }
  561. const fractionText = game.add.text(
  562. x0 + i * offsetX + offsetX / 2,
  563. curFractionString === '1' ? y0 + 40 : y0,
  564. curFractionString,
  565. font
  566. );
  567. fractionText.lineHeight = 70;
  568. renderList.push(
  569. game.add.text(x0 + i * offsetX, y0 + 35, curFractionSign, font)
  570. );
  571. renderList.push(fractionText);
  572. renderList.push(
  573. game.add.text(
  574. x0 + offsetX / 2 + i * offsetX,
  575. y0,
  576. curFractionString === '1' ? '' : '_',
  577. font
  578. )
  579. );
  580. nominators.push(curFraction.nominator);
  581. denominators.push(curFraction.denominator);
  582. }
  583. // Setup for fraction operation with least common multiple
  584. font.fill = colors.black;
  585. const updatedNominators = [];
  586. const mmc = game.math.mmcArray(denominators);
  587. let resultNominator = 0;
  588. for (let i in nominators) {
  589. const temp = nominators[i] * (mmc / denominators[i]);
  590. updatedNominators.push(temp);
  591. resultNominator += temp;
  592. }
  593. const resultNominatorUnsigned =
  594. resultNominator < 0 ? -resultNominator : resultNominator;
  595. const resultAux = resultNominator / mmc;
  596. const result =
  597. ('' + resultAux).length > 4 ? resultAux.toFixed(2) : resultAux;
  598. // Fraction operation with least common multiple
  599. nextX = x0 + validCircles.length * offsetX + 20;
  600. // Fraction result
  601. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  602. font.align = 'center';
  603. nextX += offsetX;
  604. if (result < 0) {
  605. nextX -= 30;
  606. renderList.push(game.add.text(nextX, y0 + 35, '-', font));
  607. nextX += 60;
  608. }
  609. const fractionResult = game.add.text(
  610. nextX,
  611. mmc === 1 || resultNominatorUnsigned === 0 ? y0 + 40 : y0,
  612. mmc === 1 || resultNominatorUnsigned === 0
  613. ? resultNominatorUnsigned
  614. : resultNominatorUnsigned + '\n' + mmc,
  615. font
  616. );
  617. fractionResult.lineHeight = 70;
  618. renderList.push(fractionResult);
  619. const fractionLine = game.add.geom.line(
  620. nextX,
  621. y0 + 15,
  622. nextX + 60,
  623. y0 + 15,
  624. 4,
  625. colors.black,
  626. mmc === 1 || resultNominatorUnsigned === 0 ? 0 : 1
  627. );
  628. fractionLine.anchor(0.5, 0);
  629. renderList.push(fractionLine);
  630. // Fraction result simplified setup
  631. const mdcAux = game.math.mdc(resultNominator, mmc);
  632. const mdc = mdcAux < 0 ? -mdcAux : mdcAux;
  633. if (mdc !== 1 && resultNominatorUnsigned !== 0) {
  634. // alert(mdc + ' ' + resultNominatorUnsigned);
  635. nextX += offsetX;
  636. renderList.push(game.add.text(nextX, y0 + 35, '=', font));
  637. nextX += offsetX;
  638. renderList.push(
  639. game.add.text(nextX - 50, y0 + 35, result > 0 ? '' : '-', font)
  640. );
  641. renderList.push(
  642. game.add.text(nextX, y0, resultNominatorUnsigned / mdc, font)
  643. );
  644. renderList.push(game.add.text(nextX, y0 + 70, mmc / mdc, font));
  645. const fractionLine = game.add.geom.line(
  646. nextX,
  647. y0 + 15,
  648. nextX + 60,
  649. y0 + 15,
  650. 4,
  651. colors.black
  652. );
  653. fractionLine.anchor(0.5, 0);
  654. renderList.push(fractionLine);
  655. }
  656. // Decimal result
  657. let resultWidth = '_'.length * widthOfChar;
  658. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  659. card.width = cardWidth;
  660. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  661. // Center Card
  662. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  663. self.fractionOperationUI = renderList;
  664. return endSignX;
  665. },
  666. renderEndUI: () => {
  667. let btnColor = colors.green;
  668. let btnText = game.lang.continue;
  669. if (!self.control.isCorrect) {
  670. btnColor = colors.red;
  671. btnText = game.lang.retry;
  672. }
  673. // continue button
  674. self.ui.continue.button = game.add.geom.rect(
  675. context.canvas.width / 2,
  676. context.canvas.height / 2 + 100,
  677. 450,
  678. 100,
  679. btnColor
  680. );
  681. self.ui.continue.button.anchor(0.5, 0.5);
  682. self.ui.continue.text = game.add.text(
  683. context.canvas.width / 2,
  684. context.canvas.height / 2 + 16 + 100,
  685. btnText,
  686. textStyles.btn
  687. );
  688. },
  689. // UPDATE
  690. animateKidHandler: function () {
  691. let canLowerCircles = undefined;
  692. let curCircle = self.circles.list[self.circles.cur];
  693. let curDirec = curCircle.info.direc;
  694. // Move
  695. self.circles.list.forEach((circle) => {
  696. circle.x += self.animation.walkOffsetX * curDirec;
  697. });
  698. self.kid.x += self.animation.walkOffsetX * curDirec;
  699. self.walkedPath[self.control.curWalkedPath].width +=
  700. self.animation.walkOffsetX * curDirec;
  701. // Update arc
  702. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  703. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  704. // When finish current circle
  705. if (curCircle.info.direction === 'right') {
  706. canLowerCircles = curCircle.x >= self.control.nextX;
  707. } else if (curCircle.info.direction === 'left') {
  708. canLowerCircles = curCircle.x <= self.control.nextX;
  709. // If just changed from 'right' to 'left' inform to change direction of kid animation
  710. if (
  711. self.animation.invertDirection === undefined &&
  712. self.circles.cur > 0 &&
  713. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  714. ) {
  715. self.animation.invertDirection = true;
  716. }
  717. }
  718. // Change direction of kid animation
  719. if (self.animation.invertDirection) {
  720. self.animation.invertDirection = false;
  721. game.animation.stop(self.kid.animation[0]);
  722. self.kid.animation = self.animation.list.left;
  723. self.kid.curFrame = 23;
  724. game.animation.play('left');
  725. self.control.curWalkedPath = 1;
  726. self.utils.renderWalkedPath(
  727. curCircle.x,
  728. self.walkedPath[0].y + 8,
  729. colors.red
  730. );
  731. }
  732. if (canLowerCircles) {
  733. // Hide current circle
  734. curCircle.alpha = 0;
  735. // Lowers kid and other circles
  736. self.circles.list.forEach((circle) => {
  737. circle.y += self.circles.diameter;
  738. });
  739. self.kid.y += self.circles.diameter;
  740. self.circles.cur++; // Update index of current circle
  741. if (self.circles.list[self.circles.cur]) {
  742. curCircle = self.circles.list[self.circles.cur];
  743. curDirec = curCircle.info.direc;
  744. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  745. }
  746. }
  747. // When finish all circles (final position)
  748. if (
  749. self.circles.cur === self.circles.list.length ||
  750. curCircle.alpha === 0
  751. ) {
  752. self.animation.animateKid = false;
  753. self.control.checkAnswer = true;
  754. }
  755. },
  756. checkAnswerHandler: function () {
  757. game.timer.stop();
  758. game.animation.stop(self.kid.animation[0]);
  759. self.control.isCorrect = game.math.isOverlap(self.basket, self.kid);
  760. const x = self.utils.renderOperationUI();
  761. if (self.control.isCorrect) {
  762. completedLevels++;
  763. self.kid.curFrame = self.kid.curFrame < 12 ? 24 : 25;
  764. if (audioStatus) game.audio.okSound.play();
  765. game.add
  766. .image(x + 50, context.canvas.height / 3, 'answer_correct')
  767. .anchor(0.5, 0.5);
  768. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  769. } else {
  770. if (audioStatus) game.audio.errorSound.play();
  771. game.add
  772. .image(x, context.canvas.height / 3, 'answer_wrong')
  773. .anchor(0.5, 0.5);
  774. }
  775. self.fetch.postScore();
  776. self.control.checkAnswer = false;
  777. self.animation.counter = 0;
  778. self.animation.animateBalloon = true;
  779. },
  780. animateBalloonHandler: function () {
  781. self.animation.counter++;
  782. self.balloon.y -= 2;
  783. self.basket.y -= 2;
  784. if (self.control.isCorrect) self.kid.y -= 2;
  785. if (self.animation.counter === 100) {
  786. self.utils.renderEndUI();
  787. self.control.showEndInfo = true;
  788. if (self.control.isCorrect) canGoToNextMapPosition = true;
  789. else canGoToNextMapPosition = false;
  790. }
  791. },
  792. endLevel: function () {
  793. game.state.start('map');
  794. },
  795. // INFORMATION
  796. /**
  797. * Show correct answer
  798. */
  799. showAnswer: function () {
  800. if (!self.control.hasClicked) {
  801. // On gameMode (a)
  802. if (gameMode === 'a') {
  803. self.ui.help.x = self.control.correctX - 20;
  804. self.ui.help.y = self.road.y;
  805. // On gameMode (b)
  806. } else {
  807. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  808. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  809. }
  810. self.ui.help.alpha = 1;
  811. }
  812. },
  813. // HANDLERS
  814. /**
  815. * (in gameMode 'b') Function called when player clicked over a valid circle
  816. *
  817. * @param {number|object} cur clicked circle
  818. */
  819. clickCircleHandler: function (cur) {
  820. if (!self.control.hasClicked) {
  821. // On gameMode (a)
  822. if (gameMode === 'a') {
  823. self.balloon.x = cur;
  824. self.basket.x = cur;
  825. }
  826. // On gameMode (b)
  827. if (gameMode === 'b') {
  828. document.body.style.cursor = 'auto';
  829. for (let i in self.circles.list) {
  830. if (i <= cur.index) {
  831. self.circles.list[i].alpha = 1; // Keep selected circle
  832. self.control.selectedIndex = cur.index;
  833. } else {
  834. self.circles.list[i].alpha = 0; // Hide unselected circle
  835. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  836. }
  837. }
  838. }
  839. if (audioStatus) game.audio.popSound.play();
  840. // Hide fractions
  841. if (showFractions) {
  842. self.circles.list.forEach((circle) => {
  843. circle.info.fraction.labels.forEach((labelPart) => {
  844. if (labelPart) labelPart.alpha = 0;
  845. });
  846. });
  847. }
  848. // Hide solution pointer
  849. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  850. self.ui.message[0].alpha = 0;
  851. navigation.disableIcon(navigation.showAnswerIcon);
  852. self.balloon.alpha = 1;
  853. self.basket.alpha = 1;
  854. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  855. self.control.hasClicked = true;
  856. self.animation.animateKid = true;
  857. game.animation.play(self.kid.animation[0]);
  858. }
  859. },
  860. /**
  861. * (in gameMode 'b') Function called when cursor is over a valid circle
  862. *
  863. * @param {object} cur circle the cursor is over
  864. */
  865. overCircleHandler: function (cur) {
  866. if (!self.control.hasClicked) {
  867. document.body.style.cursor = 'pointer';
  868. for (let i in self.circles.list) {
  869. const alpha = i <= cur.index ? 1 : 0.4;
  870. self.circles.list[i].alpha = alpha;
  871. if (showFractions) {
  872. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  873. if (lbl) lbl.alpha = alpha;
  874. });
  875. }
  876. }
  877. }
  878. },
  879. /**
  880. * (in gameMode 'b') Function called when cursor leaves a valid circle
  881. */
  882. outCircleHandler: function () {
  883. if (!self.control.hasClicked) {
  884. document.body.style.cursor = 'auto';
  885. const alpha = 1;
  886. self.circles.list.forEach((circle) => {
  887. circle.alpha = alpha;
  888. if (showFractions) {
  889. circle.info.fraction.labels.forEach((lbl) => {
  890. if (lbl) lbl.alpha = alpha;
  891. });
  892. }
  893. });
  894. }
  895. },
  896. },
  897. events: {
  898. /**
  899. * Called by mouse click event
  900. *
  901. * @param {object} mouseEvent contains the mouse click coordinates
  902. */
  903. onInputDown: function (mouseEvent) {
  904. const x = game.math.getMouse(mouseEvent).x;
  905. const y = game.math.getMouse(mouseEvent).y;
  906. // GAME MODE A : click road
  907. if (gameMode === 'a') {
  908. const isValid =
  909. y > 150 && x >= self.road.x && x <= self.road.x + self.road.width;
  910. if (isValid) self.utils.clickCircleHandler(x);
  911. }
  912. // GAME MODE B : click circle
  913. if (gameMode === 'b') {
  914. self.circles.list.forEach((circle) => {
  915. const isValid =
  916. game.math.distanceToPointer(
  917. x,
  918. circle.xWithAnchor,
  919. y,
  920. circle.yWithAnchor
  921. ) <=
  922. (circle.diameter / 2) * circle.scale;
  923. if (isValid) self.utils.clickCircleHandler(circle);
  924. });
  925. }
  926. // Continue button
  927. if (self.control.showEndInfo) {
  928. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  929. if (audioStatus) game.audio.popSound.play();
  930. self.utils.endLevel();
  931. }
  932. }
  933. navigation.onInputDown(x, y);
  934. game.render.all();
  935. },
  936. /**
  937. * Called by mouse move event
  938. *
  939. * @param {object} mouseEvent contains the mouse move coordinates
  940. */
  941. onInputOver: function (mouseEvent) {
  942. const x = game.math.getMouse(mouseEvent).x;
  943. const y = game.math.getMouse(mouseEvent).y;
  944. let isOverCircle = false;
  945. // GAME MODE A : balloon follow mouse
  946. if (gameMode === 'a' && !self.control.hasClicked) {
  947. if (
  948. game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8
  949. ) {
  950. self.balloon.x = x;
  951. self.basket.x = x;
  952. }
  953. document.body.style.cursor = 'auto';
  954. }
  955. // GAME MODE B : hover circle
  956. if (gameMode === 'b' && !self.control.hasClicked) {
  957. self.circles.list.forEach((circle) => {
  958. const isValid =
  959. game.math.distanceToPointer(
  960. x,
  961. circle.xWithAnchor,
  962. y,
  963. circle.yWithAnchor
  964. ) <=
  965. (circle.diameter / 2) * circle.scale;
  966. if (isValid) {
  967. self.utils.overCircleHandler(circle);
  968. isOverCircle = true;
  969. }
  970. });
  971. if (!isOverCircle) self.utils.outCircleHandler();
  972. }
  973. // Continue button
  974. if (self.control.showEndInfo) {
  975. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  976. // If pointer is over icon
  977. document.body.style.cursor = 'pointer';
  978. self.ui.continue.button.scale =
  979. self.ui.continue.button.initialScale * 1.1;
  980. self.ui.continue.text.style = textStyles.btnLg;
  981. } else {
  982. // If pointer is not over icon
  983. document.body.style.cursor = 'auto';
  984. self.ui.continue.button.scale =
  985. self.ui.continue.button.initialScale * 1;
  986. self.ui.continue.text.style = textStyles.btn;
  987. }
  988. }
  989. navigation.onInputOver(x, y);
  990. game.render.all();
  991. },
  992. },
  993. fetch: {
  994. /**
  995. * Saves players data after level ends - to be sent to database <br>
  996. *
  997. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  998. *
  999. * @see /php/squareOne.js
  1000. */
  1001. postScore: function () {
  1002. // Creates string that is going to be sent to db
  1003. const data =
  1004. '&line_game=' +
  1005. gameShape +
  1006. '&line_mode=' +
  1007. gameMode +
  1008. '&line_oper=' +
  1009. gameOperation +
  1010. '&line_leve=' +
  1011. gameDifficulty +
  1012. '&line_posi=' +
  1013. curMapPosition +
  1014. '&line_resu=' +
  1015. self.control.isCorrect +
  1016. '&line_time=' +
  1017. game.timer.elapsed +
  1018. '&line_deta=' +
  1019. 'numCircles:' +
  1020. self.circles.list.length +
  1021. ', valCircles: ' +
  1022. self.control.divisorsList +
  1023. ' balloonX: ' +
  1024. self.basket.x +
  1025. ', selIndex: ' +
  1026. self.control.selectedIndex;
  1027. // FOR MOODLE
  1028. sendToDatabase(data);
  1029. },
  1030. },
  1031. };