circleOne.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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. // Shift question up to leave room for equation below
  594. const qOffsetY = qLines >= 3 ? -80 : -65;
  595. self.ui.challenge.question = game.add.text(
  596. cardX, cardY + qOffsetY,
  597. questionWrapped,
  598. { ...textStyles.h3_, fill: colors.blueDark, font: `bold ${qFontSize}px ${font.families.default}` },
  599. qLineH
  600. );
  601. self.ui.challenge.question.anchor(0.5, 0.5);
  602. {
  603. // Builds equation string
  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;
  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. const challengeCircles = gameMode === 'b'
  614. ? self.circles.list.slice(0, self.control.correctIndex)
  615. : self.circles.list;
  616. const circleScale = 0.20;
  617. const circleR = 35;
  618. const gap = 10;
  619. const eqStyle = { ...textStyles.h3_, fill: colors.blueDark };
  620. const maxW = cardW - 80;
  621. const n = challengeCircles.length;
  622. context.save();
  623. context.font = '38px Arial, sans-serif';
  624. const fullStr = buildEqStr(challengeCircles, 0) + ' =';
  625. const fullW = context.measureText(fullStr).width;
  626. if (fullW + gap + circleR * 2 <= maxW) {
  627. const eqY = cardY + 42;
  628. const textX = cardX - gap / 2 - circleR;
  629. const circleX = cardX + fullW / 2 + gap / 2;
  630. self.ui.challenge.equation = game.add.text(textX, eqY, fullStr, eqStyle);
  631. self.ui.challenge.equationCircle = game.add.image(circleX, eqY - 14, 'circular-question', circleScale, 1);
  632. self.ui.challenge.equationCircle.anchor(0.5, 0.5);
  633. } else {
  634. const mid = Math.ceil(n / 2);
  635. const nextNom = challengeCircles[mid].info.fraction.nominator;
  636. const connector = nextNom < 0 ? ' -' : ' +';
  637. const line1Str = buildEqStr(challengeCircles.slice(0, mid), 0) + connector;
  638. const line2Str = challengeCircles.slice(mid).map((circle, i) => {
  639. const den = circle.info.fraction.denominator;
  640. const nom = circle.info.fraction.nominator;
  641. const frac = FRAC_UNICODE[den] ?? `1/${den}`;
  642. if (i === 0) return frac;
  643. return (nom < 0 ? ' - ' : ' + ') + frac;
  644. }).join('') + ' =';
  645. const line2W = context.measureText(line2Str).width;
  646. const line1Y = cardY + 28;
  647. const line2Y = cardY + 68;
  648. self.ui.challenge.equation = game.add.text(cardX, line1Y, line1Str, eqStyle);
  649. self.ui.challenge.equationLine2 = game.add.text(cardX, line2Y, line2Str, eqStyle);
  650. const line2CircleX = cardX + line2W / 2 + gap + circleR;
  651. self.ui.challenge.equationCircle = game.add.image(line2CircleX, line2Y - 14, 'circular-question', circleScale, 1);
  652. self.ui.challenge.equationCircle.anchor(0.5, 0.5);
  653. }
  654. context.restore();
  655. }
  656. // Decorative kite rendered AFTER the card so it appears in front of it
  657. // Positioned to the right of the card, same scale/anchor as the game kite
  658. const kiteImg = gameOperation === 'minus' ? 'kite_reverse' : 'kite';
  659. // kite_reverse extends leftward from its anchor, so needs more offset to clear the card
  660. const kiteOffset = gameOperation === 'minus' ? 250 : 80;
  661. const decorX = cardX + cardW / 2 + kiteOffset;
  662. const decorLineY = self.road.defaultY - 10;
  663. const decorKiteY = self.road.defaultY - 275;
  664. self.ui.challenge.kiteLineDecor = game.add.image(decorX, decorLineY, 'kite_line', 2, 1);
  665. self.ui.challenge.kiteLineDecor.anchor(0.5, 0);
  666. self.ui.challenge.kiteDecor = game.add.image(decorX, decorKiteY, kiteImg, 1.8, 1);
  667. // kite_reverse attaches at its right edge; regular kite attaches at left edge
  668. self.ui.challenge.kiteDecor.anchor(gameOperation === 'minus' ? 1 : 0, 0.5);
  669. const btnW = cardW; const btnH = 90;
  670. const btnY = cardY + cardH / 2 + 65;
  671. self.ui.challenge.button = game.add.geom.rect(cardX, btnY, btnW, btnH, '#e09800', 1);
  672. self.ui.challenge.button.anchor(0.5, 0.5);
  673. self.ui.challenge.buttonText = game.add.text(
  674. cardX, btnY + 14,
  675. withNewlines(game.lang.c1_challenge_accept),
  676. textStyles.btn
  677. );
  678. self.ui.challenge.buttonText.anchor(0.5, 0.5);
  679. self.control.showChallenge = true;
  680. },
  681. acceptChallenge: function () {
  682. self.control.challengeAnsweredYes = true;
  683. Object.values(self.ui.challenge).forEach(el => {
  684. if (el && typeof el.alpha !== 'undefined') el.alpha = 0;
  685. });
  686. // Restore game kite and line
  687. self.kite_line.alpha = gameMode === 'b' ? 1 : 0.8;
  688. self.kite.alpha = gameMode === 'b' ? 1 : 0.5;
  689. self.control.showChallenge = false;
  690. self.utils.renderMainUI();
  691. if (!self.restart) game.timer.start();
  692. },
  693. renderMainUI: function () {
  694. // Help pointer
  695. self.ui.help = game.add.image(0, 0, 'pointer', 2, 0);
  696. // Intro text
  697. const correctMessage =
  698. gameMode === 'a'
  699. ? game.lang.circleOne_intro_a
  700. : game.lang.circleOne_intro_b;
  701. const treatedMessage = correctMessage.split('\\n');
  702. self.ui.message = [];
  703. self.ui.message.push(
  704. game.add.text(
  705. context.canvas.width / 2,
  706. 170,
  707. treatedMessage[0] + '\n' + treatedMessage[1],
  708. textStyles.h1_
  709. )
  710. );
  711. },
  712. renderOperationUI: function () {
  713. /**
  714. * if game mode A:
  715. * - left: selected kite position (user selection)
  716. * - right: correct sum of stack of arcs (pre-set)
  717. *
  718. * if game mode B:
  719. * - left: line created from the stack of arcs (user selection)
  720. * - right: baloon position (pre-set)
  721. */
  722. const renderFloorFractions = (lastIndex) => {
  723. const divisor = gameDifficulty == 3 ? 4 : gameDifficulty;
  724. const operator = gameOperation === 'minus' ? '-' : '+';
  725. const index = lastIndex;
  726. const blocks = index + 1;
  727. const valueReal = blocks / divisor;
  728. const valueFloor = Math.floor(valueReal);
  729. const valueRest = valueReal - valueFloor;
  730. let fracNomin = (fracDenomin = fracLine = '');
  731. // Adds sign on the left of the equation
  732. if (gameOperation === 'minus') {
  733. fracNomin += ' ';
  734. fracDenomin += ' ';
  735. fracLine += operator;
  736. }
  737. // 1 _ _
  738. if (valueFloor) {
  739. fracNomin += ' ';
  740. fracDenomin += ' ';
  741. fracLine += valueFloor;
  742. }
  743. // _ + _
  744. if (valueFloor && valueRest) {
  745. fracNomin += ' ';
  746. fracDenomin += ' ';
  747. fracLine += operator;
  748. }
  749. // _ _ 1/5
  750. if (valueRest) {
  751. fracNomin += `${valueRest * divisor}`;
  752. fracDenomin += `${divisor}`;
  753. fracLine += '-';
  754. }
  755. return [fracNomin, fracDenomin, fracLine, valueReal];
  756. };
  757. const renderStackFractions = (lastIndex) => {
  758. const index = lastIndex;
  759. const blocks = index + 1;
  760. const nominators = [];
  761. const denominators = [];
  762. const values = [];
  763. let valueReal = 0;
  764. let fracNomin = (fracDenomin = fracLine = '');
  765. for (let i = 0; i < blocks; i++) {
  766. const m = self.circles.list[i].info.fraction.denominator || 1;
  767. const temp = self.circles.list[i].info.fraction.nominator || 0;
  768. const n = temp < 0 ? -temp : +temp;
  769. const nm = n / m;
  770. nominators[i] = n + 0;
  771. denominators[i] = m + 0;
  772. values[i] = nm;
  773. if (gameOperation === 'mixed')
  774. valueReal = temp < 0 ? valueReal - nm : valueReal + nm;
  775. else valueReal += nm;
  776. }
  777. for (let i = 0; i < blocks; i++) {
  778. const valueReal = values[i];
  779. const valueFloor = Math.floor(valueReal);
  780. const valueRest = valueReal - valueFloor;
  781. const operator =
  782. self.circles.list[i].info.fraction.nominator < 0 ? '-' : '+';
  783. if (i > 0 || gameOperation === 'minus') {
  784. fracNomin += ' ';
  785. fracDenomin += ' ';
  786. fracLine += operator;
  787. }
  788. if (valueFloor && !valueRest) {
  789. fracNomin += ' ';
  790. fracDenomin += ' ';
  791. fracLine += valueFloor;
  792. }
  793. if (valueRest) {
  794. fracNomin += `${nominators[i]}`;
  795. fracDenomin += `${denominators[i]}`;
  796. fracLine += '-';
  797. }
  798. }
  799. return [fracNomin, fracDenomin, fracLine, valueReal];
  800. };
  801. // Initial setup
  802. const font = textStyles.fraction;
  803. font.fill = colors.black;
  804. const padding = 100;
  805. const offsetX = 100;
  806. const widthOfChar = 35;
  807. const x0 = padding;
  808. const y0 = context.canvas.height / 3;
  809. let nextX = x0;
  810. const cardHeight = 400;
  811. const cardX = x0 - padding;
  812. const cardY = y0;
  813. const renderList = [];
  814. // Render Card
  815. const card = game.add.geom.rect(
  816. cardX,
  817. cardY,
  818. 0,
  819. cardHeight,
  820. colors.blueLight,
  821. 0.5,
  822. colors.blueDark,
  823. 8
  824. );
  825. card.id = 'card';
  826. card.anchor(0, 0.5);
  827. renderList.push(card);
  828. // Fraction setup
  829. const [floorNominators, floorDenominators, floorLines, floorValue] =
  830. renderFloorFractions(self.blocks.cur.info.index);
  831. const [stackNominators, stackDenominators, stackLines, stackValue] =
  832. renderStackFractions(self.circles.cur - 1);
  833. const renderFloorOperationLine = (x) => {
  834. font.fill = colors.black;
  835. const floorNom = game.add.text(
  836. x + offsetX / 2,
  837. y0,
  838. floorNominators,
  839. font,
  840. 60
  841. );
  842. const floorDenom = game.add.text(
  843. x + offsetX / 2,
  844. y0 + 70,
  845. floorDenominators,
  846. font,
  847. 60
  848. );
  849. const floorLin = game.add.text(
  850. x + offsetX / 2,
  851. y0 + 35,
  852. floorLines,
  853. font,
  854. 60
  855. );
  856. renderList.push(floorNom);
  857. renderList.push(floorDenom);
  858. renderList.push(floorLin);
  859. };
  860. const renderStackOperationLine = (x) => {
  861. font.fill = colors.black;
  862. const stackNom = game.add.text(
  863. x + offsetX / 2,
  864. y0,
  865. stackNominators,
  866. font,
  867. 60
  868. );
  869. const stackDenom = game.add.text(
  870. x + offsetX / 2,
  871. y0 + 70,
  872. stackDenominators,
  873. font,
  874. 60
  875. );
  876. const stackLin = game.add.text(
  877. x + offsetX / 2,
  878. y0 + 35,
  879. stackLines,
  880. font,
  881. 60
  882. );
  883. renderList.push(stackNom);
  884. renderList.push(stackDenom);
  885. renderList.push(stackLin);
  886. };
  887. // Render LEFT part of the operation
  888. if (gameMode === 'a') renderFloorOperationLine(x0);
  889. else renderStackOperationLine(x0);
  890. let curNominators = gameMode === 'a' ? floorNominators : stackNominators;
  891. nextX = x0 + (curNominators.length + 2) * widthOfChar;
  892. // Render middle sign - equal by default
  893. font.fill = colors.green;
  894. let comparisonSign = '=';
  895. // Render middle sign - if not equal
  896. if (floorValue != stackValue) {
  897. font.fill = colors.red;
  898. let leftSideIsLarger = floorValue > stackValue;
  899. if (gameMode === 'b') leftSideIsLarger = !leftSideIsLarger;
  900. if (gameOperation === 'minus') leftSideIsLarger = !leftSideIsLarger;
  901. comparisonSign = leftSideIsLarger ? '>' : '<';
  902. }
  903. renderList.push(game.add.text(nextX, y0 + 35, comparisonSign, font));
  904. // Render RIGHT part of the operationf
  905. if (gameMode === 'a') renderStackOperationLine(nextX);
  906. else renderFloorOperationLine(nextX);
  907. curNominators = gameMode === 'a' ? stackNominators : floorNominators;
  908. const resultWidth = (curNominators.length + 2) * widthOfChar;
  909. const cardWidth = nextX - x0 + resultWidth + padding * 2;
  910. card.width = cardWidth;
  911. const endSignX = (context.canvas.width - cardWidth) / 2 + cardWidth;
  912. // Center Card
  913. moveList(renderList, (context.canvas.width - cardWidth) / 2, 0);
  914. self.fractionOperationUI = renderList;
  915. return endSignX;
  916. },
  917. renderExplanationUI: function () {
  918. const cx = context.canvas.width / 2;
  919. const cy = context.canvas.height / 2;
  920. const withNewlines = (s) => (s == null ? '' : String(s).replace(/\\n/g, '\n'));
  921. const FRAC_UNICODE = { 1: '1', 2: '\u00BD', 4: '\u00BC' };
  922. // Reuse end-tractor-game background image (globally loaded)
  923. const naturalW = game.image['end-tractor-game'].width;
  924. const naturalH = game.image['end-tractor-game'].height;
  925. const imgScale = Math.min((context.canvas.width * 0.92) / naturalW, (context.canvas.height * 0.92) / naturalH);
  926. const imgW = naturalW * imgScale;
  927. const imgH = naturalH * imgScale;
  928. const cardTop = cy - imgH / 2;
  929. const cardBottom = cy + imgH / 2;
  930. const cardLeft = cx - imgW / 2;
  931. const bgImg = game.add.image(cx, cy, 'end-tractor-game');
  932. bgImg.anchor(0.5, 0.5);
  933. bgImg.scale = imgScale;
  934. // Mask over the tractor scene area of the background image
  935. const vizMask = game.add.geom.rect(cx, cardTop + imgH * 0.575, imgW * 0.9, imgH * 0.36, colors.white, 1);
  936. vizMask.anchor(0.5, 0.5);
  937. // Title — move up and reduce font when 2 lines to avoid overlapping steps
  938. const titleText = withNewlines(game.lang.c1_explain_title);
  939. const titleIsMultiline = titleText.includes('\n');
  940. const titleFontSize = titleIsMultiline ? 24 : parseInt(textStyles.h3_.font);
  941. const titleY = cardTop + imgH * (titleIsMultiline ? 0.04 : 0.07);
  942. game.add.text(cx + imgW * 0.04, titleY, titleText,
  943. { ...textStyles.h3_, fill: colors.white, font: `bold ${titleFontSize}px ${font.families.default}` }
  944. );
  945. // Step labels (same positions as squareOne explanation)
  946. const stepFont = `24px ${font.families.default}`;
  947. const stepStyle = { ...textStyles.p_, fill: colors.blueDark, font: stepFont };
  948. const stepsLine1Y = cardTop + imgH * 0.245;
  949. const stepsLine2Y = stepsLine1Y + 26;
  950. const stepCenters = [cardLeft + imgW * 0.28, cardLeft + imgW * 0.50, cardLeft + imgW * 0.75];
  951. [game.lang.c1_explain_step1, game.lang.c1_explain_step2, game.lang.c1_explain_step3]
  952. .map(withNewlines)
  953. .forEach((txt, idx) => {
  954. const lines = txt.split('\n');
  955. game.add.text(stepCenters[idx], stepsLine1Y, lines[0] || '', stepStyle);
  956. if (lines[1]) game.add.text(stepCenters[idx], stepsLine2Y, lines[1], stepStyle);
  957. });
  958. // Mode B: use the circles the player actually selected (not the pre-set correctIndex)
  959. const explainCircles = gameMode === 'b'
  960. ? self.circles.list.slice(0, self.control.selectedIndex + 1)
  961. : self.circles.list;
  962. // Compute final position
  963. let totalDistance = 0;
  964. explainCircles.forEach(c => {
  965. totalDistance += c.info.fraction.nominator / c.info.fraction.denominator;
  966. });
  967. const startPos = gameOperation === 'minus' ? 5 : 0;
  968. const finalPos = startPos + totalDistance;
  969. const formatLabel = (n) => {
  970. if (n < 0) return '-' + formatLabel(-n);
  971. if (Number.isInteger(n)) return String(n);
  972. const whole = Math.floor(n);
  973. const frac = n - whole;
  974. const FM = { 0.25: '\u00BC', 0.5: '\u00BD', 0.75: '\u00BE' };
  975. const f = FM[Math.round(frac * 4) / 4];
  976. return f ? (whole ? String(whole) + f : f) : n.toFixed(2).replace('.', ',');
  977. };
  978. const buildEqStr = (list) => list.map((c, i) => {
  979. const frac = FRAC_UNICODE[c.info.fraction.denominator] ?? `1/${c.info.fraction.denominator}`;
  980. if (i === 0) return c.info.fraction.nominator < 0 ? '-' + frac : frac;
  981. return (c.info.fraction.nominator < 0 ? ' - ' : ' + ') + frac;
  982. }).join('');
  983. // For minus: equation shows the displacement (totalDistance, negative)
  984. // For plus/mixed: equation shows final position
  985. const eqResult = gameOperation === 'minus' ? totalDistance : finalPos;
  986. // Equation in image's equation box area
  987. const eqFontSize = explainCircles.length <= 4 ? 38 : 30;
  988. game.add.text(cx, cardTop + imgH * 0.355,
  989. buildEqStr(explainCircles) + ' = ' + formatLabel(eqResult),
  990. { ...textStyles.h3_, fill: colors.blueDark, font: `bold ${eqFontSize}px ${font.families.default}` }
  991. );
  992. // Number line
  993. const lineY = cardTop + imgH * 0.58;
  994. const lineLeft = cardLeft + imgW * 0.08;
  995. const lineRight = cardLeft + imgW * 0.92;
  996. const lineW = lineRight - lineLeft;
  997. const pointStep = lineW / 5;
  998. const barH = 20;
  999. // Base bar
  1000. game.add.geom.rect(lineLeft, lineY - barH / 2, lineW, barH, '#d4c080', 0.5);
  1001. // Colored segment showing the walked path
  1002. // For minus: 0 is at lineRight, segment goes leftward by |totalDistance|
  1003. // For plus/mixed: 0 is at lineLeft, segment goes rightward to finalPos
  1004. const fillColor = gameOperation === 'minus' ? colors.redLight : colors.greenLight;
  1005. const borderColor = gameOperation === 'minus' ? colors.red : colors.green;
  1006. const barStartX = gameOperation === 'minus' ? lineRight : lineLeft + startPos * pointStep;
  1007. const barEndX = gameOperation === 'minus' ? lineRight + totalDistance * pointStep : lineLeft + finalPos * pointStep;
  1008. game.add.geom.rect(
  1009. Math.min(barStartX, barEndX), lineY - barH / 2,
  1010. Math.abs(barEndX - barStartX), barH,
  1011. fillColor, 0.9, borderColor, 2
  1012. );
  1013. // Integer position markers
  1014. // For minus: shows -5,-4,-3,-2,-1,0 (0 at right)
  1015. // For plus/mixed: shows 0,1,2,3,4,5
  1016. for (let i = 0; i <= 5; i++) {
  1017. const px = lineLeft + i * pointStep;
  1018. const markerCX = px + 18;
  1019. const markerCY = lineY + barH / 2 + 16;
  1020. game.add.geom.circle(markerCX, markerCY, 44, colors.blueDark, 2, colors.white, 1).anchor(0.5, 0.5);
  1021. const displayVal = gameOperation === 'minus' ? (i - 5) : i;
  1022. game.add.text(markerCX - 20, markerCY - 11, String(displayVal),
  1023. { ...textStyles.p_, fill: colors.blueDark, font: `bold 22px ${font.families.default}` }
  1024. ).anchor(0.5, 0.5);
  1025. }
  1026. // Orange label at answer position
  1027. // For minus: answer is at totalDistance from the right (0)
  1028. // For plus/mixed: answer is at finalPos from the left (0)
  1029. const answerX = gameOperation === 'minus' ? lineRight + totalDistance * pointStep : lineLeft + finalPos * pointStep;
  1030. const marker = game.add.geom.rect(answerX, lineY - barH / 2 - 26, 80, 32, '#e09800', 1);
  1031. marker.anchor(0.5, 0.5);
  1032. game.add.text(answerX, lineY - barH / 2 - 17, formatLabel(eqResult),
  1033. { ...textStyles.p_, fill: colors.white, font: `bold 24px ${font.families.default}` }
  1034. );
  1035. game.add.geom.line(answerX, lineY - barH / 2 - 9, answerX, lineY - barH / 2, 2, '#e09800');
  1036. // Body text
  1037. const bodyY1 = cardTop + imgH * 0.825;
  1038. const bodyY2 = bodyY1 + 34;
  1039. const bodyPrefix = gameMode === 'b'
  1040. ? (game.lang.c1_explain_body_prefix_b || game.lang.c1_explain_body_prefix)
  1041. : game.lang.c1_explain_body_prefix;
  1042. game.add.text(cx, bodyY1,
  1043. withNewlines(bodyPrefix) + ' ' +
  1044. buildEqStr(explainCircles) +
  1045. withNewlines(game.lang.c1_explain_body_suffix),
  1046. { ...textStyles.p_, fill: colors.blueDark }
  1047. );
  1048. game.add.text(cx, bodyY2, withNewlines(game.lang.c1_explain_body_line2),
  1049. { ...textStyles.p_, fill: colors.blue }
  1050. );
  1051. // Checkmark top-right
  1052. const checkScale = imgH * 0.13 / 256;
  1053. const checkImg = game.add.image(cardLeft + imgW - 16, cardTop + 16, 'answer_correct', checkScale);
  1054. checkImg.anchor(1, 0);
  1055. // Continue button
  1056. const btnW = imgW * 0.38; const btnH = 62;
  1057. const btnCY = cardBottom - imgH * 0.07;
  1058. self.ui.continue.button = game.add.geom.rect(cx, btnCY, btnW, btnH, colors.green);
  1059. self.ui.continue.button.anchor(0.5, 0.5);
  1060. self.ui.continue.text = game.add.text(cx, btnCY + 14, game.lang.continue, textStyles.btn);
  1061. },
  1062. renderEndUI: function () {
  1063. let btnColor = colors.green;
  1064. let btnText = game.lang.continue;
  1065. if (!self.control.isCorrect) {
  1066. btnColor = colors.red;
  1067. btnText = game.lang.retry;
  1068. }
  1069. // continue button
  1070. self.ui.continue.button = game.add.geom.rect(
  1071. context.canvas.width / 2,
  1072. context.canvas.height / 2 + 100,
  1073. 450,
  1074. 100,
  1075. btnColor
  1076. );
  1077. self.ui.continue.button.anchor(0.5, 0.5);
  1078. self.ui.continue.text = game.add.text(
  1079. context.canvas.width / 2,
  1080. context.canvas.height / 2 + 16 + 100,
  1081. btnText,
  1082. textStyles.btn
  1083. );
  1084. },
  1085. // UPDATE
  1086. animateKidHandler: function () {
  1087. let canLowerCircles = undefined;
  1088. let curCircle = self.circles.list[self.circles.cur];
  1089. let curDirec = curCircle.info.direc;
  1090. // Move
  1091. self.circles.list.forEach((circle) => {
  1092. circle.x += self.animation.walkOffsetX * curDirec;
  1093. });
  1094. self.kid.x += self.animation.walkOffsetX * curDirec;
  1095. self.walkedPath[self.control.curWalkedPath].width +=
  1096. self.animation.walkOffsetX * curDirec;
  1097. // Update arc
  1098. curCircle.info.angleDegree += self.animation.angleOffset * curDirec;
  1099. curCircle.angleEnd = game.math.degreeToRad(curCircle.info.angleDegree);
  1100. // When finish current circle
  1101. if (curCircle.info.direction === 'right') {
  1102. canLowerCircles = curCircle.x >= self.control.nextX;
  1103. } else if (curCircle.info.direction === 'left') {
  1104. canLowerCircles = curCircle.x <= self.control.nextX;
  1105. // If just changed from 'right' to 'left' inform to change direction of kid animation
  1106. if (
  1107. self.animation.invertDirection === undefined &&
  1108. self.circles.cur > 0 &&
  1109. self.circles.list[self.circles.cur - 1].info.direction === 'right'
  1110. ) {
  1111. self.animation.invertDirection = true;
  1112. }
  1113. }
  1114. // Change direction of kid animation
  1115. if (self.animation.invertDirection) {
  1116. self.animation.invertDirection = false;
  1117. game.animation.stop(self.kid.animation[0]);
  1118. self.kid.animation = self.animation.list.left;
  1119. self.kid.curFrame = 23;
  1120. game.animation.play('left');
  1121. self.control.curWalkedPath = 1;
  1122. self.utils.renderWalkedPath(
  1123. curCircle.x,
  1124. self.walkedPath[0].y + 8,
  1125. colors.red
  1126. );
  1127. }
  1128. if (canLowerCircles) {
  1129. // Hide current circle
  1130. curCircle.alpha = 0;
  1131. // Lowers kid and other circles
  1132. self.circles.list.forEach((circle) => {
  1133. circle.y += self.circles.diameter;
  1134. });
  1135. self.kid.y += self.circles.diameter;
  1136. self.circles.cur++; // Update index of current circle
  1137. if (self.circles.list[self.circles.cur]) {
  1138. curCircle = self.circles.list[self.circles.cur];
  1139. curDirec = curCircle.info.direc;
  1140. self.control.nextX += curCircle.info.distance * curDirec; // Update next position
  1141. }
  1142. }
  1143. // When finish all circles (final position)
  1144. if (
  1145. self.circles.cur === self.circles.list.length ||
  1146. curCircle.alpha === 0
  1147. ) {
  1148. self.animation.animateKid = false;
  1149. self.control.checkAnswer = true;
  1150. }
  1151. },
  1152. checkAnswerHandler: function () {
  1153. game.timer.stop();
  1154. game.animation.stop(self.kid.animation[0]);
  1155. self.control.isCorrect = game.math.isOverlap(self.kite_line, self.kid);
  1156. if (self.control.isCorrect) {
  1157. completedLevels++;
  1158. self.kid.alpha = 0;
  1159. const kidStanding = game.add.sprite(
  1160. self.kid.x,
  1161. self.kid.y,
  1162. 'kid_standing',
  1163. 5,
  1164. 1.2
  1165. );
  1166. kidStanding.anchor(0.5, 0.8);
  1167. self.kid = kidStanding;
  1168. self.kid.alpha = 1;
  1169. self.kite_line.alpha = 0;
  1170. self.kite.x += 25;
  1171. self.kite.y -= 40;
  1172. if (audioStatus) game.audio.okSound.play();
  1173. if (isDebugMode) console.log('Completed Levels: ' + completedLevels);
  1174. self.fetch.postScore();
  1175. self.control.checkAnswer = false;
  1176. self.animation.counter = 0;
  1177. self.utils.renderExplanationUI();
  1178. self.control.showEndInfo = true;
  1179. canGoToNextMapPosition = true;
  1180. } else {
  1181. const x = self.utils.renderOperationUI();
  1182. if (audioStatus) game.audio.errorSound.play();
  1183. game.add
  1184. .image(x, context.canvas.height / 3, 'answer_wrong')
  1185. .anchor(0.5, 0.5);
  1186. self.fetch.postScore();
  1187. self.control.checkAnswer = false;
  1188. self.animation.counter = 0;
  1189. self.animation.animateKite = true;
  1190. }
  1191. },
  1192. animateKiteHandler: function () {
  1193. self.animation.counter++;
  1194. if (!self.control.isCorrect) {
  1195. self.kite.y -= 2;
  1196. self.kite_line.y -= 2;
  1197. }
  1198. if (self.animation.counter % 40 === 0) {
  1199. const kiteMovement = self.animation.counter % 80 === 0 ? -3 : 3;
  1200. self.kite.y += kiteMovement;
  1201. }
  1202. if (self.animation.counter === 100) {
  1203. self.utils.renderEndUI();
  1204. self.control.showEndInfo = true;
  1205. canGoToNextMapPosition = false;
  1206. }
  1207. },
  1208. endLevel: function () {
  1209. game.state.start('map');
  1210. },
  1211. // INFORMATION
  1212. /**
  1213. * Show correct answer
  1214. */
  1215. showAnswer: function () {
  1216. if (!self.control.hasClicked) {
  1217. // On gameMode (a)
  1218. if (gameMode === 'a') {
  1219. self.ui.help.x = self.control.correctX - 20;
  1220. self.ui.help.y = self.road.defaultY;
  1221. // On gameMode (b)
  1222. } else {
  1223. self.ui.help.x = self.circles.list[self.control.correctIndex - 1].x;
  1224. self.ui.help.y = self.circles.list[self.control.correctIndex - 1].y; // - self.circles.diameter / 2;
  1225. }
  1226. self.ui.help.alpha = 1;
  1227. }
  1228. },
  1229. // HANDLERS
  1230. /**
  1231. * (in gameMode 'b') Function called when player clicked over a valid circle
  1232. *
  1233. * @param {number|object} cur clicked circle
  1234. */
  1235. clickCircleHandler: function (cur) {
  1236. if (!self.control.hasClicked) {
  1237. // On gameMode (a)
  1238. if (gameMode === 'a') {
  1239. self.kite.x = cur;
  1240. self.kite_line.x = cur;
  1241. }
  1242. // On gameMode (b)
  1243. if (gameMode === 'b') {
  1244. document.body.style.cursor = 'auto';
  1245. for (let i in self.circles.list) {
  1246. if (i <= cur.index) {
  1247. self.circles.list[i].alpha = 1; // Keep selected circle
  1248. self.control.selectedIndex = cur.index;
  1249. } else {
  1250. self.circles.list[i].alpha = 0; // Hide unselected circle
  1251. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  1252. }
  1253. }
  1254. }
  1255. if (audioStatus) game.audio.popSound.play();
  1256. // Hide fractions
  1257. if (showFractions) {
  1258. self.circles.list.forEach((circle) => {
  1259. circle.info.fraction.labels.forEach((labelPart) => {
  1260. if (labelPart) labelPart.alpha = 0;
  1261. });
  1262. });
  1263. }
  1264. // Hide solution pointer
  1265. if (self.ui.help != undefined) self.ui.help.alpha = 0;
  1266. self.ui.message[0].alpha = 0;
  1267. navigation.disableIcon(navigation.showAnswerIcon);
  1268. self.kite.alpha = 1;
  1269. self.kite_line.alpha = 1;
  1270. self.walkedPath[self.control.curWalkedPath].alpha = 1;
  1271. self.control.hasClicked = true;
  1272. self.animation.animateKid = true;
  1273. game.animation.play(self.kid.animation[0]);
  1274. }
  1275. },
  1276. /**
  1277. * (in gameMode 'b') Function called when cursor is over a valid circle
  1278. *
  1279. * @param {object} cur circle the cursor is over
  1280. */
  1281. overCircleHandler: function (cur) {
  1282. if (!self.control.hasClicked) {
  1283. document.body.style.cursor = 'pointer';
  1284. for (let i in self.circles.list) {
  1285. const alpha = i <= cur.index ? 1 : 0.4;
  1286. self.circles.list[i].alpha = alpha;
  1287. if (showFractions) {
  1288. self.circles.list[i].info.fraction.labels.forEach((lbl) => {
  1289. if (lbl) lbl.alpha = alpha;
  1290. });
  1291. }
  1292. }
  1293. }
  1294. },
  1295. /**
  1296. * (in gameMode 'b') Function called when cursor leaves a valid circle
  1297. */
  1298. outCircleHandler: function () {
  1299. if (!self.control.hasClicked) {
  1300. document.body.style.cursor = 'auto';
  1301. const alpha = 1;
  1302. self.circles.list.forEach((circle) => {
  1303. circle.alpha = alpha;
  1304. if (showFractions) {
  1305. circle.info.fraction.labels.forEach((lbl) => {
  1306. if (lbl) lbl.alpha = alpha;
  1307. });
  1308. }
  1309. });
  1310. }
  1311. },
  1312. /** TODO */
  1313. isOverBlock: function (x, blockX, blockWidth) {
  1314. if (
  1315. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1316. x >= blockX &&
  1317. x < blockX + blockWidth) ||
  1318. (gameOperation === 'minus' && x <= blockX && x > blockX + blockWidth)
  1319. )
  1320. return true;
  1321. return false;
  1322. },
  1323. /** TODO */
  1324. isOverRoad: function (x, y, roadX, roadWidth) {
  1325. if (y > 150) {
  1326. if (
  1327. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1328. x >= roadX &&
  1329. x < roadX + roadWidth) ||
  1330. (gameOperation === 'minus' &&
  1331. x <= roadX &&
  1332. x > roadX + roadWidth * self.control.directionModifier)
  1333. )
  1334. return true;
  1335. }
  1336. return false;
  1337. },
  1338. /** TODO */
  1339. fillCurrentBlock: function (x, blockX, block) {
  1340. block.fillColor =
  1341. ((gameOperation === 'plus' || gameOperation === 'mixed') &&
  1342. x > blockX) ||
  1343. (gameOperation === 'minus' && x < blockX)
  1344. ? colors.red
  1345. : 'transparent';
  1346. },
  1347. },
  1348. events: {
  1349. /**
  1350. * Called by mouse click event
  1351. *
  1352. * @param {object} mouseEvent contains the mouse click coordinates
  1353. */
  1354. onInputDown: function (mouseEvent) {
  1355. const x = game.math.getMouse(mouseEvent).x;
  1356. const y = game.math.getMouse(mouseEvent).y;
  1357. if (self.control.showChallenge) {
  1358. if (game.math.isOverIcon(x, y, self.ui.challenge.button)) {
  1359. if (audioStatus) game.audio.popSound.play();
  1360. self.utils.acceptChallenge();
  1361. }
  1362. navigation.onInputDown(x, y);
  1363. game.render.all();
  1364. return;
  1365. }
  1366. // GAME MODE A : click road
  1367. if (gameMode === 'a') {
  1368. const isValidX = self.utils.isOverRoad(
  1369. x,
  1370. y,
  1371. self.road.x,
  1372. self.road.width
  1373. );
  1374. if (isValidX) {
  1375. self.utils.clickCircleHandler(
  1376. self.blocks.cur.x + self.blocks.cur.width
  1377. );
  1378. document.body.style.cursor = 'auto';
  1379. }
  1380. }
  1381. // GAME MODE B : click circle
  1382. if (gameMode === 'b') {
  1383. self.circles.list.forEach((circle) => {
  1384. const isValid =
  1385. game.math.distanceToPointer(
  1386. x,
  1387. circle.xWithAnchor,
  1388. y,
  1389. circle.yWithAnchor
  1390. ) <=
  1391. (circle.diameter / 2) * circle.scale;
  1392. if (isValid) self.utils.clickCircleHandler(circle);
  1393. });
  1394. }
  1395. // Continue button
  1396. if (self.control.showEndInfo) {
  1397. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1398. if (audioStatus) game.audio.popSound.play();
  1399. self.utils.endLevel();
  1400. }
  1401. }
  1402. navigation.onInputDown(x, y);
  1403. game.render.all();
  1404. },
  1405. /**
  1406. * Called by mouse move event
  1407. *
  1408. * @param {object} mouseEvent contains the mouse move coordinates
  1409. */
  1410. onInputOver: function (mouseEvent) {
  1411. const x = game.math.getMouse(mouseEvent).x;
  1412. const y = game.math.getMouse(mouseEvent).y;
  1413. let isOverCircle = false;
  1414. if (self.control.showChallenge && self.ui.challenge.button) {
  1415. if (game.math.isOverIcon(x, y, self.ui.challenge.button)) {
  1416. self.ui.challenge.button.scale = self.ui.challenge.button.initialScale * 1.1;
  1417. self.ui.challenge.buttonText.style = textStyles.btnLg;
  1418. document.body.style.cursor = 'pointer';
  1419. } else {
  1420. self.ui.challenge.button.scale = self.ui.challenge.button.initialScale * 1;
  1421. self.ui.challenge.buttonText.style = textStyles.btn;
  1422. document.body.style.cursor = 'auto';
  1423. }
  1424. game.render.all();
  1425. return;
  1426. }
  1427. if (gameMode === 'a' && !self.control.hasClicked) {
  1428. const isValidX = self.utils.isOverRoad(
  1429. x,
  1430. y,
  1431. self.road.x,
  1432. self.road.width
  1433. );
  1434. if (isValidX) {
  1435. // GAME MODE A : kite follow mouse
  1436. self.blocks.cur = self.blocks.list[0];
  1437. self.blocks.list.forEach((cur) => {
  1438. self.utils.fillCurrentBlock(x, cur.x, cur);
  1439. if (self.utils.isOverBlock(x, cur.x, cur.width, cur))
  1440. self.blocks.cur = cur;
  1441. });
  1442. const newX = self.blocks.cur.x + self.blocks.cur.width;
  1443. self.kite.x = newX;
  1444. self.kite_line.x = newX;
  1445. document.body.style.cursor = 'pointer';
  1446. } else {
  1447. document.body.style.cursor = 'auto';
  1448. }
  1449. }
  1450. // GAME MODE B : hover circle
  1451. if (gameMode === 'b' && !self.control.hasClicked) {
  1452. self.circles.list.forEach((circle) => {
  1453. const isValid =
  1454. game.math.distanceToPointer(
  1455. x,
  1456. circle.xWithAnchor,
  1457. y,
  1458. circle.yWithAnchor
  1459. ) <=
  1460. (circle.diameter / 2) * circle.scale;
  1461. if (isValid) {
  1462. self.utils.overCircleHandler(circle);
  1463. isOverCircle = true;
  1464. }
  1465. });
  1466. if (!isOverCircle) self.utils.outCircleHandler();
  1467. }
  1468. // Continue button
  1469. if (self.control.showEndInfo) {
  1470. if (game.math.isOverIcon(x, y, self.ui.continue.button)) {
  1471. // If pointer is over icon
  1472. document.body.style.cursor = 'pointer';
  1473. self.ui.continue.button.scale =
  1474. self.ui.continue.button.initialScale * 1.1;
  1475. self.ui.continue.text.style = textStyles.btnLg;
  1476. } else {
  1477. // If pointer is not over icon
  1478. document.body.style.cursor = 'auto';
  1479. self.ui.continue.button.scale =
  1480. self.ui.continue.button.initialScale * 1;
  1481. self.ui.continue.text.style = textStyles.btn;
  1482. }
  1483. }
  1484. navigation.onInputOver(x, y);
  1485. game.render.all();
  1486. },
  1487. },
  1488. fetch: {
  1489. /**
  1490. * Saves players data after level ends - to be sent to database <br>
  1491. *
  1492. * Attention: the 'line_' prefix data table must be compatible to data table fields (MySQL server)
  1493. *
  1494. * @see /php/squareOne.js
  1495. */
  1496. postScore: function () {
  1497. // Creates string that is going to be sent to db
  1498. const data =
  1499. '&line_game=' +
  1500. gameShape +
  1501. '&line_mode=' +
  1502. gameMode +
  1503. '&line_oper=' +
  1504. gameOperation +
  1505. '&line_leve=' +
  1506. gameDifficulty +
  1507. '&line_posi=' +
  1508. curMapPosition +
  1509. '&line_resu=' +
  1510. self.control.isCorrect +
  1511. '&line_time=' +
  1512. game.timer.elapsed +
  1513. '&line_deta=' +
  1514. 'numCircles:' +
  1515. self.circles.list.length +
  1516. ', valCircles: ' +
  1517. self.control.divisorsList +
  1518. ' kiteX: ' +
  1519. self.kite_line.x +
  1520. ', selIndex: ' +
  1521. self.control.selectedIndex;
  1522. // FOR MOODLE
  1523. sendToDatabase(data);
  1524. },
  1525. },
  1526. };