circleOne.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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/kite
  18. * Theme : getting the kite on the floor
  19. * Concept : 'How much the kid has to walk to get to the kite?'
  20. * Represent fractions as : circles/arcs
  21. *
  22. * Game modes can be :
  23. *
  24. * a : Player can place kite position
  25. * Place kite 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 kite)
  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. kite: undefined,
  48. kite_line: undefined,
  49. walkedPath: undefined,
  50. /**
  51. * Main code
  52. */
  53. create: function () {
  54. this.ui = {
  55. help: undefined,
  56. message: undefined,
  57. challenge: {},
  58. continue: {
  59. // modal: undefined,
  60. button: undefined,
  61. text: undefined,
  62. },
  63. };
  64. const roadMapper = () => {
  65. const _pointWidth = (game.sprite['map_place'].width / 2) * 0.45;
  66. const defaultX = 150;
  67. const defaultY =
  68. context.canvas.height - game.image['floor_grass'].width * 1.5;
  69. const defaultWidth = 1620;
  70. // Initial 'x' coordinate for the kid and the kite
  71. const x =
  72. gameOperation === 'minus'
  73. ? context.canvas.width - defaultX - _pointWidth / 2
  74. : defaultX + _pointWidth / 2;
  75. const y = defaultY;
  76. const width = defaultWidth - _pointWidth;
  77. const _divisions = 5;
  78. const _subdivisions = gameDifficulty === 3 ? 4 : gameDifficulty;
  79. const numberOfBlocks = _divisions * _subdivisions;
  80. return { x, y, width, numberOfBlocks, defaultX, defaultY, defaultWidth };
  81. };
  82. this.road = roadMapper();
  83. const blocksMapper = () => {
  84. let width = this.road.width / this.road.numberOfBlocks;
  85. if (gameOperation === 'minus') width = -width;
  86. const height = 50;
  87. return { width, height, list: [], cur: undefined };
  88. };
  89. this.blocks = blocksMapper();
  90. this.walkedPath = [];
  91. const pointWidth = (game.sprite['map_place'].width / 2) * 0.45;
  92. const distanceBetweenPoints =
  93. (context.canvas.width - this.road.defaultX * 2 - pointWidth) / 5; // Distance between road points
  94. const y0 = this.road.defaultY + 20;
  95. const x0 = this.road.x;
  96. this.circles = {
  97. diameter: game.math.getRadiusFromCircunference(distanceBetweenPoints) * 2, // (Fixed) Circles Diameter
  98. cur: 0, // Current circle index
  99. list: [], // Circle objects
  100. };
  101. this.control = {
  102. directionModifier: gameOperation === 'minus' ? -1 : 1,
  103. correctX: x0, // Correct position (accumulative)
  104. nextX: undefined, // Next point position
  105. divisorsList: '', // used in postScore (Accumulative)
  106. hasClicked: false, // Checks if user has clicked
  107. checkAnswer: false, // Check kid on top of kiteline
  108. isCorrect: false, // Informs answer is correct
  109. showChallenge: false,
  110. challengeAnsweredYes: null,
  111. showEndInfo: false,
  112. endSignX: undefined,
  113. curWalkedPath: 0,
  114. // mode 'b' exclusive
  115. correctIndex: undefined,
  116. selectedIndex: -1, // Index of clicked circle (game (b))
  117. numberOfPlusFractions: undefined,
  118. };
  119. const walkOffsetX = 2;
  120. const walksPerDistanceBetweenPoints = distanceBetweenPoints / walkOffsetX;
  121. this.animation = {
  122. list: {
  123. left: undefined,
  124. right: undefined,
  125. },
  126. invertDirection: undefined,
  127. animateKid: false,
  128. animateKite: false, // TODO
  129. counter: undefined,
  130. walkOffsetX,
  131. angleOffset: 360 / walksPerDistanceBetweenPoints,
  132. };
  133. renderBackground('farmRoad');
  134. // Calls function that loads navigation icons
  135. // FOR MOODLE
  136. if (moodle) {
  137. navigation.add.right(['audio']);
  138. } else {
  139. navigation.add.left(['back', 'menu', 'show_answer'], 'customMenu');
  140. navigation.add.right(['audio']);
  141. }
  142. const validPath = { x0, y0, distanceBetweenPoints };
  143. this.utils.renderRoadBlocks();
  144. this.utils.renderRoad(validPath);
  145. const [restart, kiteX] = this.utils.renderCircles(validPath);
  146. this.restart = restart;
  147. this.utils.renderCharacters(validPath, kiteX);
  148. this.utils.renderChallengeUI();
  149. if (!this.restart) {
  150. game.event.add('click', this.events.onInputDown);
  151. game.event.add('mousemove', this.events.onInputOver);
  152. }
  153. },
  154. /**
  155. * Game loop
  156. */
  157. update: function () {
  158. // Starts kid animation
  159. if (self.animation.animateKid) {
  160. self.utils.animateKidHandler();
  161. }
  162. // Check if kid is on top of kite line
  163. if (self.control.checkAnswer) {
  164. self.utils.checkAnswerHandler();
  165. }
  166. // Starts kite moving animation
  167. if (self.animation.animateKite) {
  168. self.utils.animateKiteHandler();
  169. }
  170. game.render.all();
  171. },
  172. utils: {
  173. renderRoadBlocks: function () {
  174. for (let i = 0; i < self.road.numberOfBlocks; i++) {
  175. const block = game.add.geom.rect(
  176. self.road.x + i * self.blocks.width,
  177. self.road.y,
  178. self.blocks.width, // If gameOperation is minus, block width is negative
  179. self.blocks.height,
  180. 'transparent',
  181. 0.5,
  182. colors.red,
  183. 2
  184. );
  185. block.info = { index: i };
  186. self.blocks.list.push(block);
  187. }
  188. },
  189. // RENDERS
  190. renderRoad: function (validPath) {
  191. const offset = 40;
  192. for (let i = 0; i <= 5; i++) {
  193. // Gray place
  194. game.add
  195. .sprite(
  196. validPath.x0 +
  197. i *
  198. validPath.distanceBetweenPoints *
  199. self.control.directionModifier,
  200. validPath.y0,
  201. 'map_place',
  202. 0,
  203. 0.45
  204. )
  205. .anchor(0.5, 0.5);
  206. // White circle behind number
  207. const curX =
  208. validPath.x0 +
  209. i * validPath.distanceBetweenPoints * self.control.directionModifier;
  210. game.add.geom
  211. .circle(
  212. curX,
  213. validPath.y0 + 60 + offset,
  214. 60,
  215. undefined,
  216. 0,
  217. colors.white,
  218. 0.8
  219. )
  220. .anchor(0, 0.25);
  221. game.add.geom.rect(
  222. curX,
  223. validPath.y0 + 60 - 28,
  224. 4,
  225. 25,
  226. colors.white,
  227. 0.8,
  228. undefined,
  229. 0
  230. );
  231. // Number
  232. game.add.text(
  233. curX,
  234. validPath.y0 + 60 + offset,
  235. i * self.control.directionModifier,
  236. {
  237. ...textStyles.h2_,
  238. font: 'bold ' + textStyles.h2_.font,
  239. fill: gameOperation === 'minus' ? colors.red : colors.green,
  240. }
  241. );
  242. }
  243. self.utils.renderWalkedPath(
  244. validPath.x0 - 1,
  245. validPath.y0 - 5,
  246. gameOperation === 'minus' ? colors.red : colors.green
  247. );
  248. },
  249. renderWalkedPath: function (x, y, color) {
  250. const path = game.add.geom.rect(x, y, 1, 1, 'transparent', 1, color, 4);
  251. self.walkedPath.push(path);
  252. return path;
  253. },
  254. renderCircles: function (validPath) {
  255. let restart = false;
  256. let hasBaseDifficulty = false;
  257. let kiteX = context.canvas.width / 2;
  258. const fractionX =
  259. validPath.x0 -
  260. (self.circles.diameter - 10) * self.control.directionModifier;
  261. const font = {
  262. ...textStyles.h2_,
  263. font: 'bold ' + textStyles.h2_.font,
  264. };
  265. // Number of circles
  266. const max = gameOperation === 'mixed' ? 6 : curMapPosition + 1;
  267. const min =
  268. curMapPosition === 1 && (gameOperation === 'mixed' || gameMode === 'b')
  269. ? 2
  270. : curMapPosition; // Mixed level has at least 2 fractions
  271. const total = game.math.randomInRange(min, max); // Total number of circles
  272. // For mode 'b'
  273. self.control.numberOfPlusFractions = game.math.randomInRange(
  274. 1,
  275. total - 1
  276. );
  277. for (let i = 0; i < total; i++) {
  278. let curDirection = undefined;
  279. let curLineColor = undefined;
  280. let curFillColor = undefined;
  281. let curAngleDegree = undefined;
  282. let curIsCounterclockwise = undefined;
  283. let curFractionItems = undefined;
  284. let curCircle = undefined;
  285. const curCircleInfo = {
  286. direction: undefined,
  287. direc: undefined,
  288. distance: undefined,
  289. angle: undefined,
  290. fraction: {
  291. labels: [],
  292. nominator: undefined,
  293. denominator: undefined,
  294. },
  295. };
  296. let curDivisor = game.math.randomInRange(1, gameDifficulty); // Set fraction 'divisor' (depends on difficulty)
  297. if (curDivisor === gameDifficulty) hasBaseDifficulty = true; // True if after for ends has at least 1 '1/difficulty' fraction
  298. curDivisor = curDivisor === 3 ? 4 : curDivisor; // Turns 1/3 into 1/4 fractions
  299. self.control.divisorsList += curDivisor + ','; // Add this divisor to the list of divisors (for postScore())
  300. // Set each circle direction
  301. switch (gameOperation) {
  302. case 'plus':
  303. curDirection = 'right';
  304. break;
  305. case 'minus':
  306. curDirection = 'left';
  307. break;
  308. case 'mixed':
  309. curDirection =
  310. i < self.control.numberOfPlusFractions ? 'right' : 'left';
  311. break;
  312. }
  313. curCircleInfo.direction = curDirection;
  314. // Set each circle visual info
  315. if (curDirection === 'right') {
  316. curIsCounterclockwise = true;
  317. curLineColor = colors.green;
  318. curFillColor = colors.greenLight;
  319. curCircleInfo.direc = 1;
  320. } else {
  321. curIsCounterclockwise = false;
  322. curLineColor = colors.red;
  323. curFillColor = colors.redLight;
  324. curCircleInfo.direc = -1;
  325. }
  326. font.fill = curLineColor;
  327. const curCircleY =
  328. validPath.y0 -
  329. 5 -
  330. self.circles.diameter / 2 -
  331. i * self.circles.diameter;
  332. // Draw circles
  333. if (curDivisor === 1) {
  334. curAngleDegree = 360;
  335. curCircle = game.add.geom.circle(
  336. validPath.x0,
  337. curCircleY,
  338. self.circles.diameter,
  339. curLineColor,
  340. 3,
  341. curFillColor,
  342. 1
  343. );
  344. curCircle.counterclockwise = curIsCounterclockwise;
  345. curCircleInfo.angleDegree = curAngleDegree;
  346. curFractionItems = [
  347. {
  348. x: fractionX,
  349. y: curCircleY + 10,
  350. text: '1',
  351. },
  352. {
  353. x: fractionX - 25,
  354. y: curCircleY + 10,
  355. text: curDirection === 'left' ? '-' : '',
  356. },
  357. null,
  358. ];
  359. } else {
  360. curAngleDegree = 360 / curDivisor;
  361. if (curDirection === 'right') curAngleDegree = 360 - curAngleDegree; // counterclockwise equivalent
  362. curCircle = game.add.geom.arc(
  363. validPath.x0,
  364. curCircleY,
  365. self.circles.diameter,
  366. 0,
  367. game.math.degreeToRad(curAngleDegree),
  368. curIsCounterclockwise,
  369. curLineColor,
  370. 3,
  371. curFillColor,
  372. 1
  373. );
  374. curCircleInfo.angleDegree = curAngleDegree;
  375. curFractionItems = [
  376. {
  377. x: fractionX,
  378. y: curCircleY - 2,
  379. text: `1\n${curDivisor}`,
  380. },
  381. {
  382. x: fractionX - 35,
  383. y: curCircleY + 15,
  384. text: curDirection === 'left' ? '-' : '',
  385. },
  386. {
  387. x0: fractionX,
  388. y0: curCircleY + 2,
  389. x1: fractionX + 25,
  390. y1: curCircleY + 2,
  391. lineWidth: 2,
  392. color: curLineColor,
  393. },
  394. ];
  395. }
  396. for (let i = 0; i < 2; i++) {
  397. const item = game.add.text(
  398. curFractionItems[i].x,
  399. curFractionItems[i].y,
  400. curFractionItems[i].text,
  401. font
  402. );
  403. item.lineHeight = 37;
  404. curCircleInfo.fraction.labels.push(item);
  405. }
  406. if (curFractionItems[2]) {
  407. const line = game.add.geom.line(
  408. curFractionItems[2].x0,
  409. curFractionItems[2].y0,
  410. curFractionItems[2].x1,
  411. curFractionItems[2].y1,
  412. curFractionItems[2].lineWidth,
  413. curFractionItems[2].color
  414. );
  415. line.anchor(0.5, 0);
  416. curCircleInfo.fraction.labels.push(line);
  417. } else {
  418. curCircleInfo.fraction.labels.push(null);
  419. }
  420. curCircleInfo.fraction.nominator = curCircleInfo.direc;
  421. curCircleInfo.fraction.denominator = curDivisor;
  422. if (!showFractions) {
  423. curCircleInfo.fraction.labels.forEach((label) => {
  424. if (label) label.alpha = 0;
  425. });
  426. }
  427. curCircle.rotate = 90;
  428. // If game is type (b) (select fractions)
  429. if (gameMode === 'b') {
  430. curCircle.index = i;
  431. }
  432. curCircleInfo.distance = Math.floor(
  433. validPath.distanceBetweenPoints / curDivisor
  434. );
  435. // Add to the list
  436. curCircle.info = curCircleInfo;
  437. self.circles.list.push(curCircle);
  438. self.control.correctX +=
  439. Math.floor(validPath.distanceBetweenPoints / curDivisor) *
  440. curCircle.info.direc;
  441. }
  442. // Restart if
  443. // Does not have at least one fraction of type 1/difficulty
  444. if (!hasBaseDifficulty) {
  445. restart = true;
  446. }
  447. // Calculate next circle
  448. self.control.nextX =
  449. validPath.x0 +
  450. self.circles.list[0].info.distance * self.circles.list[0].info.direc;
  451. let isBeforeMin = (isAfterMax = false);
  452. let finalPosition = Number(self.control.correctX.toFixed(1));
  453. const extraPixels = gameOperation === 'mixed' ? 5 : 0;
  454. // Restart if
  455. // In Game mode 'a' and 'b' : Kite position is out of bounds
  456. if (gameOperation === 'minus') {
  457. isBeforeMin = finalPosition > validPath.x0;
  458. isAfterMax =
  459. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  460. } else {
  461. isBeforeMin = finalPosition - extraPixels <= validPath.x0;
  462. isAfterMax =
  463. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  464. }
  465. if (isBeforeMin || isAfterMax) restart = true;
  466. if (gameMode === 'b') {
  467. // If game is type (b), select a random kite place
  468. kiteX = validPath.x0;
  469. self.control.correctIndex = game.math.randomInRange(
  470. self.control.numberOfPlusFractions,
  471. self.circles.list.length
  472. );
  473. for (let i = 0; i < self.control.correctIndex; i++) {
  474. kiteX +=
  475. self.circles.list[i].info.distance *
  476. self.circles.list[i].info.direc;
  477. }
  478. finalPosition = kiteX;
  479. self.blocks.list.forEach((cur) => {
  480. self.utils.fillCurrentBlock(kiteX, cur.x, cur);
  481. if (self.utils.isOverBlock(kiteX, cur.x, cur.width, cur))
  482. self.blocks.cur = cur;
  483. });
  484. // Restart if
  485. // In Game mode 'b' : Top circle position is out of bounds (when on the ground)
  486. if (gameOperation === 'minus') {
  487. isBeforeMin = finalPosition > validPath.x0;
  488. isAfterMax =
  489. finalPosition < validPath.x0 - 5 * validPath.distanceBetweenPoints;
  490. } else {
  491. isBeforeMin = finalPosition < validPath.x0;
  492. isAfterMax =
  493. finalPosition > validPath.x0 + 5 * validPath.distanceBetweenPoints;
  494. }
  495. if (isBeforeMin || isAfterMax) restart = true;
  496. }
  497. return [restart, kiteX];
  498. },
  499. renderCharacters: function (validPath, kiteX) {
  500. // KID
  501. self.kid = game.add.sprite(
  502. validPath.x0,
  503. validPath.y0 - 32 - self.circles.list.length * self.circles.diameter,
  504. 'kid_walking',
  505. 0,
  506. 1.2
  507. );
  508. self.kid.anchor(0.5, 0.8);
  509. self.animation.list.right = [
  510. 'right',
  511. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
  512. 4,
  513. ];
  514. self.animation.list.left = [
  515. 'left',
  516. [23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12],
  517. 4,
  518. ];
  519. if (gameOperation === 'minus') {
  520. self.kid.animation = self.animation.list.left;
  521. self.kid.curFrame = 23;
  522. } else {
  523. self.kid.animation = self.animation.list.right;
  524. }
  525. // KITE
  526. self.kite = game.add.image(kiteX, validPath.y0 - 295, 'kite', 1.8, 0.5);
  527. self.kite.alpha = 0.5;
  528. self.kite.anchor(0, 0.5);
  529. self.kite_line = game.add.image(kiteX, validPath.y0 - 30, 'kite_line', 2);
  530. self.kite_line.alpha = 0.8;
  531. self.kite_line.anchor(0.5, 0);
  532. if (gameMode === 'b') {
  533. self.kite_line.alpha = 1;
  534. self.kite.alpha = 1;
  535. }
  536. },
  537. renderChallengeUI: function () {
  538. // Hide game kite line during challenge
  539. self.kite_line.alpha = 0;
  540. self.kite.alpha = 0;
  541. const cx = context.canvas.width / 2;
  542. const withNewlines = (s) => (s == null ? '' : String(s).replace(/\\n/g, '\n'));
  543. const FRAC_UNICODE = { 1: '1', 2: '\u00BD', 4: '\u00BC' };
  544. const ribbonScale = 0.87;
  545. const ribbonH = Math.round(166 * ribbonScale);
  546. const ribbonY = 30;
  547. self.ui.challenge.image = game.add.image(cx, ribbonY, 'challenge-card', ribbonScale, 1);
  548. self.ui.challenge.image.anchor(0.5, 0);
  549. const ribbonCenterY = ribbonY + ribbonH / 2 + 2;
  550. self.ui.challenge.title = game.add.text(
  551. cx, ribbonCenterY,
  552. withNewlines(game.lang.c1_challenge_title),
  553. { ...textStyles.h2_, fill: colors.white, font: 'bold ' + textStyles.h2_.font }
  554. );
  555. self.ui.challenge.title.anchor(0.5, 0.5);
  556. const ribbonBottom = ribbonY + ribbonH;
  557. const subtitleLines = withNewlines(game.lang.c1_challenge_subtitle).split('\n');
  558. self.ui.challenge.subtitleTop = game.add.text(
  559. cx, ribbonBottom + 48,
  560. subtitleLines[0] || '',
  561. { ...textStyles.h4_, fill: colors.blueDark, font: 'bold ' + textStyles.h4_.font }
  562. );
  563. self.ui.challenge.subtitleTop.anchor(0.5, 0.5);
  564. self.ui.challenge.subtitleBottom = game.add.text(
  565. cx, ribbonBottom + 100,
  566. subtitleLines.slice(1).join('\n'),
  567. { ...textStyles.h3_, fill: colors.blue }
  568. );
  569. self.ui.challenge.subtitleBottom.anchor(0.5, 0.5);
  570. const topCircleY = self.road.defaultY + 20 - 5 - self.circles.diameter / 2
  571. - (self.circles.list.length - 1) * self.circles.diameter;
  572. const kidHeadY = self.kid ? self.kid.y - 155 : topCircleY;
  573. const labelY = Math.min(topCircleY, kidHeadY) - 30;
  574. self.ui.challenge.circlesLabel = game.add.text(
  575. self.road.x, labelY,
  576. withNewlines(game.lang.c1_circles_label),
  577. { ...textStyles.h4_, fill: colors.blueDark, font: 'bold ' + textStyles.h4_.font }
  578. );
  579. self.ui.challenge.circlesLabel.anchor(0.5, 0.5);
  580. const cardW = 580; const cardH = 260;
  581. const cardX = cx;
  582. const cardY = context.canvas.height / 2 - 80;
  583. self.ui.challenge.card = game.add.geom.rect(
  584. cardX, cardY, cardW, cardH, colors.white, 0.95, colors.blueMenuLine, 4
  585. );
  586. self.ui.challenge.card.anchor(0.5, 0.5);
  587. const questionWrapped = withNewlines(
  588. gameMode === 'b' ? (game.lang.c1_challenge_question_b || game.lang.c1_challenge_question) : game.lang.c1_challenge_question
  589. );
  590. const qLines = questionWrapped.split('\n').length;
  591. const qFontSize = qLines === 3 ? 30 : qLines > 3 ? 26 : 32;
  592. const qLineH = qLines >= 3 ? 34 : 40;
  593. const qOffsetY = qLines >= 3 ? -80 : -65;
  594. self.ui.challenge.question = game.add.text(
  595. cardX, cardY + qOffsetY,
  596. questionWrapped,
  597. { ...textStyles.h3_, fill: colors.blueDark, font: `bold ${qFontSize}px ${font.families.default}` },
  598. qLineH
  599. );
  600. self.ui.challenge.question.anchor(0.5, 0.5);
  601. // Builds equation string for a slice of circles; globalStart tracks
  602. // sign context so the very first circle of the whole equation has no
  603. // leading '+' even when called for a sub-range.
  604. const buildEqStr = (slice, globalStart) => {
  605. return slice.map((circle, i) => {
  606. const den = circle.info.fraction.denominator;
  607. const nom = circle.info.fraction.nominator; // 1 or -1
  608. const frac = FRAC_UNICODE[den] ?? `1/${den}`;
  609. if (globalStart + i === 0) return nom < 0 ? '-' + frac : frac;
  610. return (nom < 0 ? ' - ' : ' + ') + frac;
  611. }).join('');
  612. };
  613. // Mode B: only the first correctIndex circles are the answer
  614. const challengeCircles = gameMode === 'b'
  615. ? self.circles.list.slice(0, self.control.correctIndex)
  616. : self.circles.list;
  617. // Hide extra circles (beyond answer count) so stack matches equation
  618. if (gameMode === 'b') {
  619. self.circles.list.forEach((c, i) => {
  620. if (i >= self.control.correctIndex) {
  621. c.alpha = 0;
  622. c.info.fraction.labels.forEach(l => { if (l) l.alpha = 0; });
  623. }
  624. });
  625. }
  626. const circleScale = 0.20;
  627. const circleR = 35;
  628. const gap = 10;
  629. const eqStyle = { ...textStyles.h3_, fill: colors.blueDark };
  630. const maxW = cardW - 80;
  631. const n = challengeCircles.length;
  632. context.save();
  633. context.font = '38px Arial, sans-serif';
  634. const fullStr = buildEqStr(challengeCircles, 0) + ' =';
  635. const fullW = context.measureText(fullStr).width;
  636. if (fullW + gap + circleR * 2 <= maxW) {
  637. const eqY = cardY + 42;
  638. const textX = cardX - gap / 2 - circleR;
  639. const circleX = cardX + fullW / 2 + gap / 2;
  640. self.ui.challenge.equation = game.add.text(textX, eqY, fullStr, eqStyle);
  641. self.ui.challenge.equationCircle = game.add.image(circleX, eqY - 14, 'circular-question', circleScale, 1);
  642. self.ui.challenge.equationCircle.anchor(0.5, 0.5);
  643. } else {
  644. const mid = Math.ceil(n / 2);
  645. const nextNom = challengeCircles[mid].info.fraction.nominator;
  646. const connector = nextNom < 0 ? ' -' : ' +';
  647. const line1Str = buildEqStr(challengeCircles.slice(0, mid), 0) + connector;
  648. const line2Str = challengeCircles.slice(mid).map((circle, i) => {
  649. const den = circle.info.fraction.denominator;
  650. const nom = circle.info.fraction.nominator;
  651. const frac = FRAC_UNICODE[den] ?? `1/${den}`;
  652. if (i === 0) return frac; // connector already shown at end of line 1
  653. return (nom < 0 ? ' - ' : ' + ') + frac;
  654. }).join('') + ' =';
  655. const line2W = context.measureText(line2Str).width;
  656. const line1Y = cardY + 28;
  657. const line2Y = cardY + 68;
  658. self.ui.challenge.equation = game.add.text(cardX, line1Y, line1Str, eqStyle);
  659. self.ui.challenge.equationLine2 = game.add.text(cardX, line2Y, line2Str, eqStyle);
  660. const line2CircleX = cardX + line2W / 2 + gap + circleR;
  661. self.ui.challenge.equationCircle = game.add.image(line2CircleX, line2Y - 14, 'circular-question', circleScale, 1);
  662. self.ui.challenge.equationCircle.anchor(0.5, 0.5);
  663. }
  664. context.restore();
  665. // Decorative kite rendered AFTER the card so it appears in front of it
  666. // Positioned to the right of the card, same scale/anchor as the game kite
  667. const kiteImg = gameOperation === 'minus' ? 'kite_reverse' : 'kite';
  668. // kite_reverse extends leftward from its anchor, so needs more offset to clear the card
  669. const kiteOffset = gameOperation === 'minus' ? 250 : 80;
  670. const decorX = cardX + cardW / 2 + kiteOffset;
  671. const decorLineY = self.road.defaultY - 10;
  672. const decorKiteY = self.road.defaultY - 275;
  673. self.ui.challenge.kiteLineDecor = game.add.image(decorX, decorLineY, 'kite_line', 2, 1);
  674. self.ui.challenge.kiteLineDecor.anchor(0.5, 0);
  675. self.ui.challenge.kiteDecor = game.add.image(decorX, decorKiteY, kiteImg, 1.8, 1);
  676. // kite_reverse attaches at its right edge; regular kite attaches at left edge
  677. self.ui.challenge.kiteDecor.anchor(gameOperation === 'minus' ? 1 : 0, 0.5);
  678. const btnW = cardW; const btnH = 90;
  679. const btnY = cardY + cardH / 2 + 65;
  680. self.ui.challenge.button = game.add.geom.rect(cardX, btnY, btnW, btnH, '#e09800', 1);
  681. self.ui.challenge.button.anchor(0.5, 0.5);
  682. self.ui.challenge.buttonText = game.add.text(
  683. cardX, btnY + 14,
  684. withNewlines(game.lang.c1_challenge_accept),
  685. textStyles.btn
  686. );
  687. self.ui.challenge.buttonText.anchor(0.5, 0.5);
  688. self.control.showChallenge = true;
  689. },
  690. acceptChallenge: function () {
  691. self.control.challengeAnsweredYes = true;
  692. Object.values(self.ui.challenge).forEach(el => {
  693. if (el && typeof el.alpha !== 'undefined') el.alpha = 0;
  694. });
  695. // Restore extra circles hidden during challenge (mode B)
  696. if (gameMode === 'b') {
  697. self.circles.list.forEach((c, i) => {
  698. if (i >= self.control.correctIndex) {
  699. c.alpha = 1;
  700. if (showFractions) {
  701. c.info.fraction.labels.forEach(l => { if (l) l.alpha = 1; });
  702. }
  703. }
  704. });
  705. }
  706. // Restore game kite and line
  707. self.kite_line.alpha = gameMode === 'b' ? 1 : 0.8;
  708. self.kite.alpha = gameMode === 'b' ? 1 : 0.5;
  709. self.control.showChallenge = false;
  710. self.utils.renderMainUI();
  711. if (!self.restart) game.timer.start();
  712. },
  713. renderMainUI: function () {
  714. // Help pointer
  715. self.ui.help = game.add.image(0, 0, 'pointer', 2, 0);
  716. // Intro text
  717. const correctMessage =
  718. gameMode === 'a'
  719. ? game.lang.circleOne_intro_a
  720. : game.lang.circleOne_intro_b;
  721. const treatedMessage = correctMessage.split('\\n');
  722. self.ui.message = [];
  723. self.ui.message.push(
  724. game.add.text(
  725. context.canvas.width / 2,
  726. 170,
  727. treatedMessage[0] + '\n' + treatedMessage[1],
  728. textStyles.h1_
  729. )
  730. );
  731. },
  732. renderOperationUI: function () {
  733. /**
  734. * if game mode A:
  735. * - left: selected kite position (user selection)
  736. * - right: correct sum of stack of arcs (pre-set)
  737. *
  738. * if game mode B:
  739. * - left: line created from the stack of arcs (user selection)
  740. * - right: baloon position (pre-set)
  741. */
  742. const renderFloorFractions = (lastIndex) => {
  743. const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
  744. const operator = gameOperation === 'minus' ? '-' : '+';
  745. const index = lastIndex;
  746. const blocks = index + 1;
  747. const valueReal = blocks / divisor;
  748. const valueFloor = Math.floor(valueReal);
  749. const valueRest = valueReal - valueFloor;
  750. let fracNomin = (fracDenomin = fracLine = '');
  751. // Adds sign on the left of the equation
  752. if (gameOperation === 'minus') {
  753. fracNomin += ' ';
  754. fracDenomin += ' ';
  755. fracLine += operator;
  756. }
  757. // 1 _ _
  758. if (valueFloor) {
  759. fracNomin += ' ';
  760. fracDenomin += ' ';
  761. fracLine += valueFloor;
  762. }
  763. // _ + _
  764. if (valueFloor && valueRest) {
  765. fracNomin += ' ';
  766. fracDenomin += ' ';
  767. fracLine += operator;
  768. }
  769. // _ _ 1/5
  770. if (valueRest) {
  771. fracNomin += `${valueRest * divisor}`;
  772. fracDenomin += `${divisor}`;
  773. fracLine += '-';
  774. }
  775. return [fracNomin, fracDenomin, fracLine, valueReal];
  776. };
  777. const renderStackFractions = (lastIndex) => {
  778. const index = lastIndex;
  779. const blocks = index + 1;
  780. const nominators = [];
  781. const denominators = [];
  782. const values = [];
  783. let valueReal = 0;
  784. let fracNomin = (fracDenomin = fracLine = '');
  785. for (let i = 0; i < blocks; i++) {
  786. const m = self.circles.list[i].info.fraction.denominator || 1;
  787. const temp = self.circles.list[i].info.fraction.nominator || 0;
  788. const n = temp < 0 ? -temp : +temp;
  789. const nm = n / m;
  790. nominators[i] = n + 0;
  791. denominators[i] = m + 0;
  792. values[i] = nm;
  793. if (gameOperation === 'mixed')
  794. valueReal = temp < 0 ? valueReal - nm : valueReal + nm;
  795. else valueReal += nm;
  796. }
  797. for (let i = 0; i < blocks; i++) {
  798. const valueReal = values[i];
  799. const valueFloor = Math.floor(valueReal);
  800. const valueRest = valueReal - valueFloor;
  801. const operator =
  802. self.circles.list[i].info.fraction.nominator < 0 ? '-' : '+';
  803. if (i > 0 || gameOperation === 'minus') {
  804. fracNomin += ' ';
  805. fracDenomin += ' ';
  806. fracLine += operator;
  807. }
  808. if (valueFloor && !valueRest) {
  809. fracNomin += ' ';
  810. fracDenomin += ' ';
  811. fracLine += valueFloor;
  812. }
  813. if (valueRest) {
  814. fracNomin += `${nominators[i]}`;
  815. fracDenomin += `${denominators[i]}`;
  816. fracLine += '-';
  817. }
  818. }
  819. return [fracNomin, fracDenomin, fracLine, valueReal];
  820. };
  821. // Initial setup
  822. const font = textStyles.fraction;
  823. font.fill = colors.black;
  824. const padding = 100;
  825. const offsetX = 100;
  826. const widthOfChar = 35;
  827. const x0 = padding;
  828. const y0 = context.canvas.height / 3;
  829. let nextX = x0;
  830. const cardHeight = 400;
  831. const cardX = x0 - padding;
  832. const cardY = y0;
  833. const renderList = [];
  834. // Render Card
  835. const card = game.add.geom.rect(
  836. cardX,
  837. cardY,
  838. 0,
  839. cardHeight,
  840. colors.blueLight,
  841. 0.5,
  842. colors.blueDark,
  843. 8
  844. );
  845. card.id = 'card';
  846. card.anchor(0, 0.5);
  847. renderList.push(card);
  848. // Fraction setup
  849. const [floorNominators, floorDenominators, floorLines, floorValue] =
  850. renderFloorFractions(self.blocks.cur.info.index);
  851. const [stackNominators, stackDenominators, stackLines, stackValue] =
  852. renderStackFractions(self.circles.cur - 1);
  853. const renderFloorOperationLine = (x) => {
  854. font.fill = colors.black;
  855. const floorNom = game.add.text(
  856. x + offsetX / 2,
  857. y0,
  858. floorNominators,
  859. font,
  860. 60
  861. );
  862. const floorDenom = game.add.text(
  863. x + offsetX / 2,
  864. y0 + 70,
  865. floorDenominators,
  866. font,
  867. 60
  868. );
  869. const floorLin = game.add.text(
  870. x + offsetX / 2,
  871. y0 + 35,
  872. floorLines,
  873. font,
  874. 60
  875. );
  876. renderList.push(floorNom);
  877. renderList.push(floorDenom);
  878. renderList.push(floorLin);
  879. };
  880. const renderStackOperationLine = (x) => {
  881. font.fill = colors.black;
  882. const stackNom = game.add.text(
  883. x + offsetX / 2,
  884. y0,
  885. stackNominators,
  886. font,
  887. 60
  888. );
  889. const stackDenom = game.add.text(
  890. x + offsetX / 2,
  891. y0 + 70,
  892. stackDenominators,
  893. font,
  894. 60
  895. );
  896. const stackLin = game.add.text(
  897. x + offsetX / 2,
  898. y0 + 35,
  899. stackLines,
  900. font,
  901. 60
  902. );
  903. renderList.push(stackNom);
  904. renderList.push(stackDenom);
  905. renderList.push(stackLin);
  906. };
  907. // Render LEFT part of the operation
  908. if (gameMode === 'a') renderFloorOperationLine(x0);
  909. else renderStackOperationLine(x0);
  910. let curNominators = gameMode === 'a' ? floorNominators : stackNominators;
  911. nextX = x0 + (curNominators.length + 2) * widthOfChar;
  912. // Render middle sign - equal by default
  913. font.fill = colors.green;
  914. let comparisonSign = '=';
  915. // Render middle sign - if not equal
  916. if (floorValue != stackValue) {
  917. font.fill = colors.red;
  918. let leftSideIsLarger = floorValue > stackValue;
  919. if (gameMode === 'b') leftSideIsLarger = !leftSideIsLarger;
  920. if (gameOperation === 'minus') leftSideIsLarger = !leftSideIsLarger;
  921. comparisonSign = leftSideIsLarger ? '>' : '<';
  922. }
  923. renderList.push(game.add.text(nextX, y0 + 35, comparisonSign, font));
  924. // Render RIGHT part of the operationf
  925. if (gameMode === 'a') renderStackOperationLine(nextX);
  926. else renderFloorOperationLine(nextX);
  927. curNominators = gameMode === 'a' ? stackNominators : floorNominators;
  928. const resultWidth = (curNominators.length + 2) * widthOfChar;
  929. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  930. card.width = cardWidth;
  931. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  932. // Center Card
  933. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  934. self.fractionOperationUI = renderList;
  935. return endSignX;
  936. },
  937. renderExplanationUI: function () {
  938. const cx = context.canvas.width / 2;
  939. const cy = context.canvas.height / 2;
  940. const withNewlines = (s) => (s == null ? '' : String(s).replace(/\\n/g, '\n'));
  941. const FRAC_UNICODE = { 1: '1', 2: '\u00BD', 4: '\u00BC' };
  942. // Reuse end-tractor-game background image (globally loaded)
  943. const naturalW = game.image['end-tractor-game'].width;
  944. const naturalH = game.image['end-tractor-game'].height;
  945. const imgScale = Math.min((context.canvas.width * 0.92) / naturalW, (context.canvas.height * 0.92) / naturalH);
  946. const imgW = naturalW * imgScale;
  947. const imgH = naturalH * imgScale;
  948. const cardTop = cy - imgH / 2;
  949. const cardBottom = cy + imgH / 2;
  950. const cardLeft = cx - imgW / 2;
  951. const bgImg = game.add.image(cx, cy, 'end-tractor-game');
  952. bgImg.anchor(0.5, 0.5);
  953. bgImg.scale = imgScale;
  954. // Mask over the tractor scene area of the background image
  955. const vizMask = game.add.geom.rect(cx, cardTop + imgH * 0.575, imgW * 0.9, imgH * 0.36, colors.white, 1);
  956. vizMask.anchor(0.5, 0.5);
  957. // Title — move up and reduce font when 2 lines to avoid overlapping steps
  958. const titleText = withNewlines(game.lang.c1_explain_title);
  959. const titleIsMultiline = titleText.includes('\n');
  960. const titleFontSize = titleIsMultiline ? 24 : parseInt(textStyles.h3_.font);
  961. const titleY = cardTop + imgH * (titleIsMultiline ? 0.04 : 0.07);
  962. game.add.text(cx + imgW * 0.04, titleY, titleText,
  963. { ...textStyles.h3_, fill: colors.white, font: `bold ${titleFontSize}px ${font.families.default}` }
  964. );
  965. // Step labels (same positions as squareOne explanation)
  966. const stepFont = `24px ${font.families.default}`;
  967. const stepStyle = { ...textStyles.p_, fill: colors.blueDark, font: stepFont };
  968. const stepsLine1Y = cardTop + imgH * 0.245;
  969. const stepsLine2Y = stepsLine1Y + 26;
  970. const stepCenters = [cardLeft + imgW * 0.28, cardLeft + imgW * 0.50, cardLeft + imgW * 0.75];
  971. [game.lang.c1_explain_step1, game.lang.c1_explain_step2, game.lang.c1_explain_step3]
  972. .map(withNewlines)
  973. .forEach((txt, idx) => {
  974. const lines = txt.split('\n');
  975. game.add.text(stepCenters[idx], stepsLine1Y, lines[0] || '', stepStyle);
  976. if (lines[1]) game.add.text(stepCenters[idx], stepsLine2Y, lines[1], stepStyle);
  977. });
  978. // Mode B: use the circles the player actually selected (not the pre-set correctIndex)
  979. const explainCircles = gameMode === 'b'
  980. ? self.circles.list.slice(0, self.control.selectedIndex + 1)
  981. : self.circles.list;
  982. // Compute final position
  983. let totalDistance = 0;
  984. explainCircles.forEach(c => {
  985. totalDistance += c.info.fraction.nominator / c.info.fraction.denominator;
  986. });
  987. const startPos = gameOperation === 'minus' ? 5 : 0;
  988. const finalPos = startPos + totalDistance;
  989. const formatLabel = (n) => {
  990. if (n < 0) return '-' + formatLabel(-n);
  991. if (Number.isInteger(n)) return String(n);
  992. const whole = Math.floor(n);
  993. const frac = n - whole;
  994. const FM = { 0.25: '\u00BC', 0.5: '\u00BD', 0.75: '\u00BE' };
  995. const f = FM[Math.round(frac * 4) / 4];
  996. return f ? (whole ? String(whole) + f : f) : n.toFixed(2).replace('.', ',');
  997. };
  998. const buildEqStr = (list) => list.map((c, i) => {
  999. const frac = FRAC_UNICODE[c.info.fraction.denominator] ?? `1/${c.info.fraction.denominator}`;
  1000. if (i === 0) return c.info.fraction.nominator < 0 ? '-' + frac : frac;
  1001. return (c.info.fraction.nominator < 0 ? ' - ' : ' + ') + frac;
  1002. }).join('');
  1003. // For minus: equation shows the displacement (totalDistance, negative)
  1004. // For plus/mixed: equation shows final position
  1005. const eqResult = gameOperation === 'minus' ? totalDistance : finalPos;
  1006. // Equation in image's equation box area
  1007. const eqFontSize = explainCircles.length <= 4 ? 38 : 30;
  1008. game.add.text(cx, cardTop + imgH * 0.355,
  1009. buildEqStr(explainCircles) + ' = ' + formatLabel(eqResult),
  1010. { ...textStyles.h3_, fill: colors.blueDark, font: `bold ${eqFontSize}px ${font.families.default}` }
  1011. );
  1012. // Number line
  1013. const lineY = cardTop + imgH * 0.58;
  1014. const lineLeft = cardLeft + imgW * 0.08;
  1015. const lineRight = cardLeft + imgW * 0.92;
  1016. const lineW = lineRight - lineLeft;
  1017. const pointStep = lineW / 5;
  1018. const barH = 20;
  1019. // Base bar
  1020. game.add.geom.rect(lineLeft, lineY - barH / 2, lineW, barH, '#d4c080', 0.5);
  1021. // Colored segment showing the walked path
  1022. // For minus: 0 is at lineRight, segment goes leftward by |totalDistance|
  1023. // For plus/mixed: 0 is at lineLeft, segment goes rightward to finalPos
  1024. const fillColor = gameOperation === 'minus' ? colors.redLight : colors.greenLight;
  1025. const borderColor = gameOperation === 'minus' ? colors.red : colors.green;
  1026. const barStartX = gameOperation === 'minus' ? lineRight : lineLeft + startPos * pointStep;
  1027. const barEndX = gameOperation === 'minus' ? lineRight + totalDistance * pointStep : lineLeft + finalPos * pointStep;
  1028. game.add.geom.rect(
  1029. Math.min(barStartX, barEndX), lineY - barH / 2,
  1030. Math.abs(barEndX - barStartX), barH,
  1031. fillColor, 0.9, borderColor, 2
  1032. );
  1033. // Integer position markers
  1034. // For minus: shows -5,-4,-3,-2,-1,0 (0 at right)
  1035. // For plus/mixed: shows 0,1,2,3,4,5
  1036. for (let i = 0; i <= 5; i++) {
  1037. const px = lineLeft + i * pointStep;
  1038. const markerCX = px + 18;
  1039. const markerCY = lineY + barH / 2 + 16;
  1040. game.add.geom.circle(markerCX, markerCY, 44, colors.blueDark, 2, colors.white, 1).anchor(0.5, 0.5);
  1041. const displayVal = gameOperation === 'minus' ? (i - 5) : i;
  1042. game.add.text(markerCX - 20, markerCY - 11, String(displayVal),
  1043. { ...textStyles.p_, fill: colors.blueDark, font: `bold 22px ${font.families.default}` }
  1044. ).anchor(0.5, 0.5);
  1045. }
  1046. // Orange label at answer position
  1047. // For minus: answer is at totalDistance from the right (0)
  1048. // For plus/mixed: answer is at finalPos from the left (0)
  1049. const answerX = gameOperation === 'minus' ? lineRight + totalDistance * pointStep : lineLeft + finalPos * pointStep;
  1050. const marker = game.add.geom.rect(answerX, lineY - barH / 2 - 26, 80, 32, '#e09800', 1);
  1051. marker.anchor(0.5, 0.5);
  1052. game.add.text(answerX, lineY - barH / 2 - 17, formatLabel(eqResult),
  1053. { ...textStyles.p_, fill: colors.white, font: `bold 24px ${font.families.default}` }
  1054. );
  1055. game.add.geom.line(answerX, lineY - barH / 2 - 9, answerX, lineY - barH / 2, 2, '#e09800');
  1056. // Body text
  1057. const bodyY1 = cardTop + imgH * 0.825;
  1058. const bodyY2 = bodyY1 + 34;
  1059. const bodyPrefix = gameMode === 'b'
  1060. ? (game.lang.c1_explain_body_prefix_b || game.lang.c1_explain_body_prefix)
  1061. : game.lang.c1_explain_body_prefix;
  1062. game.add.text(cx, bodyY1,
  1063. withNewlines(bodyPrefix) + ' ' +
  1064. buildEqStr(explainCircles) +
  1065. withNewlines(game.lang.c1_explain_body_suffix),
  1066. { ...textStyles.p_, fill: colors.blueDark }
  1067. );
  1068. game.add.text(cx, bodyY2, withNewlines(game.lang.c1_explain_body_line2),
  1069. { ...textStyles.p_, fill: colors.blue }
  1070. );
  1071. // Checkmark top-right
  1072. const checkScale = imgH * 0.13 / 256;
  1073. const checkImg = game.add.image(cardLeft + imgW - 16, cardTop + 16, 'answer_correct', checkScale);
  1074. checkImg.anchor(1, 0);
  1075. // Continue button
  1076. const btnW = imgW * 0.38; const btnH = 62;
  1077. const btnCY = cardBottom - imgH * 0.07;
  1078. self.ui.continue.button = game.add.geom.rect(cx, btnCY, btnW, btnH, colors.green);
  1079. self.ui.continue.button.anchor(0.5, 0.5);
  1080. self.ui.continue.text = game.add.text(cx, btnCY + 14, game.lang.continue, textStyles.btn);
  1081. },
  1082. renderEndUI: function () {
  1083. let btnColor = colors.green;
  1084. let btnText = game.lang.continue;
  1085. if (!self.control.isCorrect) {
  1086. btnColor = colors.red;
  1087. btnText = game.lang.retry;
  1088. }
  1089. // continue button
  1090. self.ui.continue.button = game.add.geom.rect(
  1091. context.canvas.width / 2,
  1092. context.canvas.height / 2 + 100,
  1093. 450,
  1094. 100,
  1095. btnColor
  1096. );
  1097. self.ui.continue.button.anchor(0.5, 0.5);
  1098. self.ui.continue.text = game.add.text(
  1099. context.canvas.width / 2,
  1100. context.canvas.height / 2 + 16 + 100,
  1101. btnText,
  1102. textStyles.btn
  1103. );
  1104. },
  1105. // UPDATE
  1106. animateKidHandler: function () {
  1107. let canLowerCircles = undefined;
  1108. let curCircle = self.circles.list[self.circles.cur];
  1109. let curDirec = curCircle.info.direc;
  1110. // Move
  1111. self.circles.list.forEach((circle) => {
  1112. circle.x += self.animation.walkOffsetX * curDirec;
  1113. });
  1114. self.kid.x += self.animation.walkOffsetX * curDirec;
  1115. self.walkedPath[self.control.curWalkedPath].width +=
  1116. self.animation.walkOffsetX * curDirec;
  1117. // Update arc
  1118. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  1119. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  1120. // When finish current circle
  1121. if (curCircle.info.direction === 'right') {
  1122. canLowerCircles = curCircle.x >= self.control.nextX;
  1123. } else if (curCircle.info.direction === 'left') {
  1124. canLowerCircles = curCircle.x <= self.control.nextX;
  1125. // If just changed from 'right' to 'left' inform to change direction of kid animation
  1126. if (
  1127. self.animation.invertDirection === undefined &&
  1128. self.circles.cur > 0 &&
  1129. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  1130. ) {
  1131. self.animation.invertDirection = true;
  1132. }
  1133. }
  1134. // Change direction of kid animation
  1135. if (self.animation.invertDirection) {
  1136. self.animation.invertDirection = false;
  1137. game.animation.stop(self.kid.animation[0]);
  1138. self.kid.animation = self.animation.list.left;
  1139. self.kid.curFrame = 23;
  1140. game.animation.play('left');
  1141. self.control.curWalkedPath = 1;
  1142. self.utils.renderWalkedPath(
  1143. curCircle.x,
  1144. self.walkedPath[0].y + 8,
  1145. colors.red
  1146. );
  1147. }
  1148. if (canLowerCircles) {
  1149. // Hide current circle
  1150. curCircle.alpha = 0;
  1151. // Lowers kid and other circles
  1152. self.circles.list.forEach((circle) => {
  1153. circle.y += self.circles.diameter;
  1154. });
  1155. self.kid.y += self.circles.diameter;
  1156. self.circles.cur++; // Update index of current circle
  1157. if (self.circles.list[self.circles.cur]) {
  1158. curCircle = self.circles.list[self.circles.cur];
  1159. curDirec = curCircle.info.direc;
  1160. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  1161. }
  1162. }
  1163. // When finish all circles (final position)
  1164. if (
  1165. self.circles.cur === self.circles.list.length ||
  1166. curCircle.alpha === 0
  1167. ) {
  1168. self.animation.animateKid = false;
  1169. self.control.checkAnswer = true;
  1170. }
  1171. },
  1172. checkAnswerHandler: function () {
  1173. game.timer.stop();
  1174. game.animation.stop(self.kid.animation[0]);
  1175. self.control.isCorrect = game.math.isOverlap(self.kite_line, self.kid);
  1176. if (self.control.isCorrect) {
  1177. completedLevels++;
  1178. self.kid.alpha = 0;
  1179. const kidStanding = game.add.sprite(
  1180. self.kid.x,
  1181. self.kid.y,
  1182. 'kid_standing',
  1183. 5,
  1184. 1.2
  1185. );
  1186. kidStanding.anchor(0.5, 0.8);
  1187. self.kid = kidStanding;
  1188. self.kid.alpha = 1;
  1189. self.kite_line.alpha = 0;
  1190. self.kite.x += 25;
  1191. self.kite.y -= 40;
  1192. if (audioStatus) game.audio.okSound.play();
  1193. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  1194. self.fetch.postScore();
  1195. self.control.checkAnswer = false;
  1196. self.animation.counter = 0;
  1197. self.utils.renderExplanationUI();
  1198. self.control.showEndInfo = true;
  1199. canGoToNextMapPosition = true;
  1200. } else {
  1201. const x = self.utils.renderOperationUI();
  1202. if (audioStatus) game.audio.errorSound.play();
  1203. game.add
  1204. .image(x, context.canvas.height / 3, 'answer_wrong')
  1205. .anchor(0.5, 0.5);
  1206. self.fetch.postScore();
  1207. self.control.checkAnswer = false;
  1208. self.animation.counter = 0;
  1209. self.animation.animateKite = true;
  1210. }
  1211. },
  1212. animateKiteHandler: function () {
  1213. self.animation.counter++;
  1214. if (!self.control.isCorrect) {
  1215. self.kite.y -= 2;
  1216. self.kite_line.y -= 2;
  1217. }
  1218. if (self.animation.counter % 40 === 0) {
  1219. const kiteMovement = self.animation.counter % 80 === 0 ? -3 : 3;
  1220. self.kite.y += kiteMovement;
  1221. }
  1222. if (self.animation.counter === 100) {
  1223. self.utils.renderEndUI();
  1224. self.control.showEndInfo = true;
  1225. canGoToNextMapPosition = false;
  1226. }
  1227. },
  1228. endLevel: function () {
  1229. game.state.start('map');
  1230. },
  1231. // INFORMATION
  1232. /**
  1233. * Show correct answer
  1234. */
  1235. showAnswer: function () {
  1236. if (!self.control.hasClicked) {
  1237. // On gameMode (a)
  1238. if (gameMode === 'a') {
  1239. self.ui.help.x = self.control.correctX - 20;
  1240. self.ui.help.y = self.road.defaultY;
  1241. // On gameMode (b)
  1242. } else {
  1243. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  1244. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  1245. }
  1246. self.ui.help.alpha = 1;
  1247. }
  1248. },
  1249. // HANDLERS
  1250. /**
  1251. * (in gameMode 'b') Function called when player clicked over a valid circle
  1252. *
  1253. * @param {number|object} cur clicked circle
  1254. */
  1255. clickCircleHandler: function (cur) {
  1256. if (!self.control.hasClicked) {
  1257. // On gameMode (a)
  1258. if (gameMode === 'a') {
  1259. self.kite.x = cur;
  1260. self.kite_line.x = cur;
  1261. }
  1262. // On gameMode (b)
  1263. if (gameMode === 'b') {
  1264. document.body.style.cursor = 'auto';
  1265. for (let i in self.circles.list) {
  1266. if (i <= cur.index) {
  1267. self.circles.list[i].alpha = 1; // Keep selected circle
  1268. self.control.selectedIndex = cur.index;
  1269. } else {
  1270. self.circles.list[i].alpha = 0; // Hide unselected circle
  1271. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  1272. }
  1273. }
  1274. }
  1275. if (audioStatus) game.audio.popSound.play();
  1276. // Hide fractions
  1277. if (showFractions) {
  1278. self.circles.list.forEach((circle) => {
  1279. circle.info.fraction.labels.forEach((labelPart) => {
  1280. if (labelPart) labelPart.alpha = 0;
  1281. });
  1282. });
  1283. }
  1284. // Hide solution pointer
  1285. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  1286. self.ui.message[0].alpha = 0;
  1287. navigation.disableIcon(navigation.showAnswerIcon);
  1288. self.kite.alpha = 1;
  1289. self.kite_line.alpha = 1;
  1290. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  1291. self.control.hasClicked = true;
  1292. self.animation.animateKid = true;
  1293. game.animation.play(self.kid.animation[0]);
  1294. }
  1295. },
  1296. /**
  1297. * (in gameMode 'b') Function called when cursor is over a valid circle
  1298. *
  1299. * @param {object} cur circle the cursor is over
  1300. */
  1301. overCircleHandler: function (cur) {
  1302. if (!self.control.hasClicked) {
  1303. document.body.style.cursor = 'pointer';
  1304. for (let i in self.circles.list) {
  1305. const alpha = i <= cur.index ? 1 : 0.4;
  1306. self.circles.list[i].alpha = alpha;
  1307. if (showFractions) {
  1308. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  1309. if (lbl) lbl.alpha = alpha;
  1310. });
  1311. }
  1312. }
  1313. }
  1314. },
  1315. /**
  1316. * (in gameMode 'b') Function called when cursor leaves a valid circle
  1317. */
  1318. outCircleHandler: function () {
  1319. if (!self.control.hasClicked) {
  1320. document.body.style.cursor = 'auto';
  1321. const alpha = 1;
  1322. self.circles.list.forEach((circle) => {
  1323. circle.alpha = alpha;
  1324. if (showFractions) {
  1325. circle.info.fraction.labels.forEach((lbl) => {
  1326. if (lbl) lbl.alpha = alpha;
  1327. });
  1328. }
  1329. });
  1330. }
  1331. },
  1332. /** TODO */
  1333. isOverBlock: function (x, blockX, blockWidth) {
  1334. if (
  1335. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1336. x >= blockX &&
  1337. x < blockX + blockWidth) ||
  1338. (gameOperation === 'minus' && x <= blockX && x > blockX + blockWidth)
  1339. )
  1340. return true;
  1341. return false;
  1342. },
  1343. /** TODO */
  1344. isOverRoad: function (x, y, roadX, roadWidth) {
  1345. if (y > 150) {
  1346. if (
  1347. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1348. x >= roadX &&
  1349. x < roadX + roadWidth) ||
  1350. (gameOperation === 'minus' &&
  1351. x <= roadX &&
  1352. x > roadX + roadWidth * self.control.directionModifier)
  1353. )
  1354. return true;
  1355. }
  1356. return false;
  1357. },
  1358. /** TODO */
  1359. fillCurrentBlock: function (x, blockX, block) {
  1360. block.fillColor =
  1361. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1362. x > blockX) ||
  1363. (gameOperation === 'minus' && x < blockX)
  1364. ? colors.red
  1365. : 'transparent';
  1366. },
  1367. },
  1368. events: {
  1369. /**
  1370. * Called by mouse click event
  1371. *
  1372. * @param {object} mouseEvent contains the mouse click coordinates
  1373. */
  1374. onInputDown: function (mouseEvent) {
  1375. const x = game.math.getMouse(mouseEvent).x;
  1376. const y = game.math.getMouse(mouseEvent).y;
  1377. if (self.control.showChallenge) {
  1378. if (game.math.isOverIcon(x, y, self.ui.challenge.button)) {
  1379. if (audioStatus) game.audio.popSound.play();
  1380. self.utils.acceptChallenge();
  1381. }
  1382. navigation.onInputDown(x, y);
  1383. game.render.all();
  1384. return;
  1385. }
  1386. // GAME MODE A : click road
  1387. if (gameMode === 'a') {
  1388. const isValidX = self.utils.isOverRoad(
  1389. x,
  1390. y,
  1391. self.road.x,
  1392. self.road.width
  1393. );
  1394. if (isValidX) {
  1395. self.utils.clickCircleHandler(
  1396. self.blocks.cur.x + self.blocks.cur.width
  1397. );
  1398. document.body.style.cursor = 'auto';
  1399. }
  1400. }
  1401. // GAME MODE B : click circle
  1402. if (gameMode === 'b') {
  1403. self.circles.list.forEach((circle) => {
  1404. const isValid =
  1405. game.math.distanceToPointer(
  1406. x,
  1407. circle.xWithAnchor,
  1408. y,
  1409. circle.yWithAnchor
  1410. ) <=
  1411. (circle.diameter / 2) * circle.scale;
  1412. if (isValid) self.utils.clickCircleHandler(circle);
  1413. });
  1414. }
  1415. // Continue button
  1416. if (self.control.showEndInfo) {
  1417. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1418. if (audioStatus) game.audio.popSound.play();
  1419. self.utils.endLevel();
  1420. }
  1421. }
  1422. navigation.onInputDown(x, y);
  1423. game.render.all();
  1424. },
  1425. /**
  1426. * Called by mouse move event
  1427. *
  1428. * @param {object} mouseEvent contains the mouse move coordinates
  1429. */
  1430. onInputOver: function (mouseEvent) {
  1431. const x = game.math.getMouse(mouseEvent).x;
  1432. const y = game.math.getMouse(mouseEvent).y;
  1433. let isOverCircle = false;
  1434. if (self.control.showChallenge && self.ui.challenge.button) {
  1435. if (game.math.isOverIcon(x, y, self.ui.challenge.button)) {
  1436. self.ui.challenge.button.scale = self.ui.challenge.button.initialScale * 1.1;
  1437. self.ui.challenge.buttonText.style = textStyles.btnLg;
  1438. document.body.style.cursor = 'pointer';
  1439. } else {
  1440. self.ui.challenge.button.scale = self.ui.challenge.button.initialScale * 1;
  1441. self.ui.challenge.buttonText.style = textStyles.btn;
  1442. document.body.style.cursor = 'auto';
  1443. }
  1444. game.render.all();
  1445. return;
  1446. }
  1447. if (gameMode === 'a' && !self.control.hasClicked) {
  1448. const isValidX = self.utils.isOverRoad(
  1449. x,
  1450. y,
  1451. self.road.x,
  1452. self.road.width
  1453. );
  1454. if (isValidX) {
  1455. // GAME MODE A : kite follow mouse
  1456. self.blocks.cur = self.blocks.list[0];
  1457. self.blocks.list.forEach((cur) => {
  1458. self.utils.fillCurrentBlock(x, cur.x, cur);
  1459. if (self.utils.isOverBlock(x, cur.x, cur.width, cur))
  1460. self.blocks.cur = cur;
  1461. });
  1462. const newX = self.blocks.cur.x + self.blocks.cur.width;
  1463. self.kite.x = newX;
  1464. self.kite_line.x = newX;
  1465. document.body.style.cursor = 'pointer';
  1466. } else {
  1467. document.body.style.cursor = 'auto';
  1468. }
  1469. }
  1470. // GAME MODE B : hover circle
  1471. if (gameMode === 'b' && !self.control.hasClicked) {
  1472. self.circles.list.forEach((circle) => {
  1473. const isValid =
  1474. game.math.distanceToPointer(
  1475. x,
  1476. circle.xWithAnchor,
  1477. y,
  1478. circle.yWithAnchor
  1479. ) <=
  1480. (circle.diameter / 2) * circle.scale;
  1481. if (isValid) {
  1482. self.utils.overCircleHandler(circle);
  1483. isOverCircle = true;
  1484. }
  1485. });
  1486. if (!isOverCircle) self.utils.outCircleHandler();
  1487. }
  1488. // Continue button
  1489. if (self.control.showEndInfo) {
  1490. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1491. // If pointer is over icon
  1492. document.body.style.cursor = 'pointer';
  1493. self.ui.continue.button.scale =
  1494. self.ui.continue.button.initialScale * 1.1;
  1495. self.ui.continue.text.style = textStyles.btnLg;
  1496. } else {
  1497. // If pointer is not over icon
  1498. document.body.style.cursor = 'auto';
  1499. self.ui.continue.button.scale =
  1500. self.ui.continue.button.initialScale * 1;
  1501. self.ui.continue.text.style = textStyles.btn;
  1502. }
  1503. }
  1504. navigation.onInputOver(x, y);
  1505. game.render.all();
  1506. },
  1507. },
  1508. fetch: {
  1509. /**
  1510. * Saves players data after level ends - to be sent to database <br>
  1511. *
  1512. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  1513. *
  1514. * @see /php/squareOne.js
  1515. */
  1516. postScore: function () {
  1517. // Creates string that is going to be sent to db
  1518. const data =
  1519. '&line_game=' +
  1520. gameShape +
  1521. '&line_mode=' +
  1522. gameMode +
  1523. '&line_oper=' +
  1524. gameOperation +
  1525. '&line_leve=' +
  1526. gameDifficulty +
  1527. '&line_posi=' +
  1528. curMapPosition +
  1529. '&line_resu=' +
  1530. self.control.isCorrect +
  1531. '&line_time=' +
  1532. game.timer.elapsed +
  1533. '&line_deta=' +
  1534. 'numCircles:' +
  1535. self.circles.list.length +
  1536. ', valCircles: ' +
  1537. self.control.divisorsList +
  1538. ' kiteX: ' +
  1539. self.kite_line.x +
  1540. ', selIndex: ' +
  1541. self.control.selectedIndex;
  1542. // FOR MOODLE
  1543. sendToDatabase(data);
  1544. },
  1545. },
  1546. };