circleOne.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /**
  2. * LInE - Free Education, Private Data
  3. *
  4. * iFractions GAME STATE
  5. *
  6. * Name of game state : 'circleOne'
  7. * Shape : circle
  8. * Character : kid/balloon
  9. * Theme : flying in a balloon
  10. * Concept : 'How much the kid has to walk to get to the balloon?'
  11. * Represent fractions as : circles
  12. *
  13. * # of different difficulties : 5
  14. *
  15. * Game modes can be : 'A' or 'B' (in variable 'gameMode')
  16. *
  17. * A : Player can place balloon position
  18. * Place balloon in position (so the kid can get to it)
  19. * B : Player can select # of circles
  20. * Selects number of circles (that represent distance kid needs to walk to get to the balloon)
  21. *
  22. * Operations can be : 'Plus', 'Minus' or 'Mixed' (in variable 'gameOperation')
  23. *
  24. * Plus : addition of fractions
  25. * Represented by : kid going to the right (floor positions 0..5)
  26. * Minus : subtraction of fractions
  27. * Represented by: kid going to the left (floor positions 5..0)
  28. * Mixed : Mix addition and subtraction of fractions in same
  29. * Represented by: kid going to the left (floor positions 0..5)
  30. *
  31. * @namespace
  32. */
  33. const circleOne = {
  34. /**
  35. * Main code
  36. */
  37. create: function () {
  38. // CONTROL VARIABLES
  39. this.availableAnimations = [];
  40. this.changeAnimationFrames = undefined;
  41. this.checkAnswer = false; // Check kid inside ballon's basket
  42. this.animate = false; // Start move animation
  43. this.animateEnding = false; // Start ballon fly animation
  44. this.hasClicked = false; // Air ballon positioned
  45. this.result = false; // Game is correct
  46. this.count = 0;
  47. this.divisorsList = ''; // Used in postScore()
  48. let hasBaseDifficulty = false; // Will validate that level isnt too easy (has at least one '1/difficulty' fraction)
  49. const startX = (gameOperation == 'Minus') ? 66 + 5 * 156 : 66; // Initial 'x' coordinate for the kid and the baloon
  50. this.correctX = startX; // Ending position, accumulative
  51. // BACKGROUND
  52. // Add background image
  53. game.add.image(0, 0, 'bgimage');
  54. // Add clouds
  55. game.add.image(300, 100, 'cloud');
  56. game.add.image(660, 80, 'cloud');
  57. game.add.image(110, 85, 'cloud', 0.8);
  58. // Add floor of grass
  59. for (let i = 0; i < 9; i++) { game.add.image(i * 100, defaultHeight - 100, 'floor'); }
  60. // Road
  61. this.road = game.add.image(47, 515, 'road', 1.01, 0.94);
  62. // Road points
  63. const distanceBetweenPoints = 156; // Distance between road points
  64. for (let i = 0; i <= 5; i++) {
  65. game.add.image(66 + i * distanceBetweenPoints, 526, 'place_off', 0.3).anchor(0.5, 0.5);
  66. game.add.text(66 + i * distanceBetweenPoints, 560, i, textStyles.h2_blue);
  67. }
  68. this.trace = game.add.geom.rect(startX - 1, 526, 1, 1, undefined, 1);
  69. this.trace.alpha = 0;
  70. // Calls function that loads navigation icons
  71. // FOR MOODLE
  72. if (moodle) {
  73. navigationIcons.func_addIcons(
  74. false, false, false, // Left buttons
  75. true, false, // Right buttons
  76. false, false
  77. );
  78. } else {
  79. navigationIcons.func_addIcons(
  80. true, true, true, // Left buttons
  81. true, false, // Right buttons
  82. 'customMenu', this.func_viewHelp
  83. );
  84. }
  85. // CIRCLES AND FRACTIONS
  86. this.circles = {
  87. all: [], // Circles objects of current level
  88. label: [], // Fractions labels
  89. diameter: 60, // (Fixed) diameter for circles
  90. cur: 0, // Current circle index
  91. direction: [], // Circle direction : 'Right' (plus), 'Left' (minus)
  92. distance: [], // Fraction of distance between circles (used in walking animation)
  93. angle: [], // Angle in degrees : 90 / 180 / 270 / 360
  94. lineColor: [], // Circle line colors (also used for tracing on floor)
  95. direc: [], // Can be : 1 or -1 : will be multiplied to values to easily change object direction when needed
  96. };
  97. this.balloonPlace = defaultWidth / 2; // Balloon place
  98. // Number of circles
  99. const max = (gameOperation == 'Mixed' || gameMode == 'B') ? 6 : mapPosition + 1;
  100. const min = (gameOperation == 'Mixed' && mapPosition < 2) ? 2 : mapPosition; // Mixed level has at least 2 fractions
  101. const total = game.math.randomInRange(min, max); // Total number of circles
  102. // gameMode 'B' exclusive variables
  103. this.fractionIndex = -1; // Index of clicked circle (game B)
  104. this.numberOfPlusFractions = game.math.randomInRange(1, total - 1);
  105. // CIRCLES
  106. const levelDirection = (gameOperation == 'Minus') ? -1 : 1;
  107. const x = startX + 65 * levelDirection;
  108. for (let i = 0; i < total; i++) {
  109. const divisor = game.math.randomInRange(1, gameDifficulty); // Set fraction 'divisor' (depends on difficulty)
  110. if (divisor == gameDifficulty) hasBaseDifficulty = true; // True if after for ends has at least 1 '1/difficulty' fraction
  111. this.divisorsList += divisor + ','; // Add this divisor to the list of divisors (for postScore())
  112. // Set each circle direction
  113. let direction;
  114. switch (gameOperation) {
  115. case 'Plus': direction = 'Right'; break;
  116. case 'Minus': direction = 'Left'; break;
  117. case 'Mixed':
  118. if (i < this.numberOfPlusFractions) direction = 'Right';
  119. else direction = 'Left';
  120. break;
  121. }
  122. this.circles.direction[i] = direction;
  123. // Set each circle color
  124. let lineColor, anticlockwise;
  125. if (direction == 'Right') {
  126. lineColor = colors.darkBlue;
  127. this.circles.direc[i] = 1;
  128. anticlockwise = true;
  129. } else {
  130. lineColor = colors.red;
  131. this.circles.direc[i] = -1;
  132. anticlockwise = false;
  133. }
  134. this.circles.lineColor[i] = lineColor;
  135. // Draw circles
  136. let circle, label = [];
  137. if (divisor == 1) {
  138. circle = game.add.geom.circle(startX, 490 - i * this.circles.diameter, this.circles.diameter,
  139. lineColor, 2, colors.white, 1);
  140. circle.anticlockwise = anticlockwise;
  141. this.circles.angle.push(360);
  142. if (fractionLabel) {
  143. label[0] = game.add.text(x, 490 - i * this.circles.diameter, divisor, textStyles.h2_blue);
  144. this.circles.label.push(label);
  145. }
  146. } else {
  147. let degree = 360 / divisor;
  148. if (direction == 'Right') degree = 360 - degree; // Anticlockwise equivalent
  149. circle = game.add.geom.arc(startX, 490 - i * this.circles.diameter, this.circles.diameter,
  150. 0, game.math.degreeToRad(degree), anticlockwise,
  151. lineColor, 2, colors.white, 1);
  152. this.circles.angle.push(degree);
  153. if (fractionLabel) {
  154. label[0] = game.add.text(x, 480 - i * this.circles.diameter + 32, divisor, textStyles.h4_blue);
  155. label[1] = game.add.text(x, 488 - i * this.circles.diameter, '1', textStyles.h4_blue);
  156. label[2] = game.add.text(x, 488 - i * this.circles.diameter, '___', textStyles.h4_blue);
  157. this.circles.label.push(label);
  158. }
  159. }
  160. circle.rotate = 90;
  161. // If game is type B (select fractions)
  162. if (gameMode == 'B') {
  163. circle.alpha = 0.5;
  164. circle.index = i;
  165. }
  166. this.circles.distance.push(Math.floor(distanceBetweenPoints / divisor));
  167. this.circles.all.push(circle);
  168. this.correctX += Math.floor(distanceBetweenPoints / divisor) * this.circles.direc[i];
  169. }
  170. // Calculate next circle
  171. this.nextX = startX + this.circles.distance[0] * this.circles.direc[0];
  172. // Check if need to restart
  173. this.restart = false;
  174. // If top circle position is out of bounds (when on the ground) or game doesnt have base difficulty, restart
  175. if (this.correctX < 66 || this.correctX > 66 + 3 * 260 || !hasBaseDifficulty) {
  176. this.restart = true;
  177. }
  178. // If game is type B, selectiong a random balloon place
  179. if (gameMode == 'B') {
  180. this.balloonPlace = startX;
  181. this.endIndex = game.math.randomInRange(this.numberOfPlusFractions, this.circles.all.length);
  182. for (let i = 0; i < this.endIndex; i++) {
  183. this.balloonPlace += this.circles.distance[i] * this.circles.direc[i];
  184. }
  185. // If balloon position is out of bounds, restart
  186. if (this.balloonPlace < 66 || this.balloonPlace > 66 + 5 * distanceBetweenPoints) {
  187. this.restart = true;
  188. }
  189. }
  190. // KID
  191. this.availableAnimations['Right'] = ['Right', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4];
  192. this.availableAnimations['Left'] = ['Left', [23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12], 4];
  193. this.kid = game.add.sprite(startX, 495 - this.circles.all.length * this.circles.diameter, 'kid_walk', 0, 0.8);
  194. this.kid.anchor(0.5, 0.8);
  195. if (gameOperation == 'Minus') {
  196. this.kid.animation = this.availableAnimations['Left'];
  197. this.kid.curFrame = 23;
  198. } else {
  199. this.kid.animation = this.availableAnimations['Right'];
  200. }
  201. // BALLOON
  202. this.balloon = game.add.image(this.balloonPlace, 350, 'balloon', 1, 0.5);
  203. this.balloon.alpha = 0.5;
  204. this.balloon.anchor(0.5, 0.5);
  205. this.basket = game.add.image(this.balloonPlace, 472, 'balloon_basket');
  206. this.basket.anchor(0.5, 0.5);
  207. // Help pointer
  208. this.help = game.add.image(0, 0, 'help_pointer', 0.5);
  209. this.help.anchor(0.5, 0);
  210. this.help.alpha = 0;
  211. if (!this.restart) {
  212. game.timer.start(); // Set a timer for the current level (used in postScore())
  213. game.event.add('click', this.func_onInputDown);
  214. game.event.add('mousemove', this.func_onInputOver);
  215. }
  216. },
  217. /**
  218. * Game loop
  219. */
  220. update: function () {
  221. self.count++;
  222. // Start animation
  223. if (self.animate) {
  224. let cur = self.circles.cur;
  225. let direc = self.circles.direc[cur];
  226. if (self.count % 2 == 0) { // Lowers animation
  227. // Move kid
  228. self.kid.x += 2 * direc;
  229. // Move circles
  230. for (let i in self.circles.all) {
  231. self.circles.all[i].x += 2 * direc;
  232. }
  233. // Manage line on the floor
  234. self.trace.width += 2 * direc;
  235. self.trace.lineColor = self.circles.all[cur].lineColor;
  236. // Change angle of current arc
  237. self.circles.angle[cur] += 4.6 * direc;
  238. self.circles.all[cur].angleEnd = game.math.degreeToRad(self.circles.angle[cur]);
  239. // When finish current circle
  240. let lowerCircles;
  241. if (self.circles.direction[cur] == 'Right') {
  242. lowerCircles = self.circles.all[cur].x >= self.nextX;
  243. }
  244. else if (self.circles.direction[cur] == 'Left') {
  245. lowerCircles = self.circles.all[cur].x <= self.nextX;
  246. // If just changed from 'right' to 'left' inform to change direction of kid animation
  247. if (self.changeAnimationFrames == undefined && cur > 0 && self.circles.direction[cur - 1] == 'Right') {
  248. self.changeAnimationFrames = true;
  249. }
  250. }
  251. // Change direction of kid animation
  252. if (self.changeAnimationFrames) {
  253. self.changeAnimationFrames = false;
  254. game.animation.stop(self.kid.animation[0]);
  255. self.kid.animation = self.availableAnimations['Left'];
  256. self.kid.curFrame = 23;
  257. game.animation.play(self.kid.animation[0]);
  258. }
  259. if (lowerCircles) {
  260. self.circles.all[cur].alpha = 0; // Cicle disappear
  261. self.circles.all.forEach(cur => {
  262. cur.y += self.circles.diameter; // Lower circles
  263. });
  264. self.kid.y += self.circles.diameter; // Lower kid
  265. self.circles.cur++; // Update current circle
  266. cur = self.circles.cur;
  267. direc = self.circles.direc[cur];
  268. self.nextX += self.circles.distance[cur] * direc; // Update next position
  269. }
  270. // When finish all circles (final position)
  271. if (cur == self.circles.all.length || self.circles.all[cur].alpha == 0) {
  272. self.animate = false;
  273. self.checkAnswer = true;
  274. }
  275. }
  276. }
  277. // Check if kid is inside the basket
  278. if (self.checkAnswer) {
  279. game.timer.stop();
  280. game.animation.stop(self.kid.animation[0]);
  281. if (self.func_checkOverlap(self.basket, self.kid)) {
  282. self.result = true; // Answer is correct
  283. self.kid.curFrame = (self.kid.curFrame < 12) ? 24 : 25;
  284. if (audioStatus) game.audio.okSound.play();
  285. game.add.image(defaultWidth / 2, defaultHeight / 2, 'ok').anchor(0.5, 0.5);
  286. completedLevels++;
  287. if (debugMode) console.log('completedLevels = ' + completedLevels);
  288. } else {
  289. self.result = false; // Answer is incorrect
  290. if (audioStatus) game.audio.errorSound.play();
  291. game.add.image(defaultWidth / 2, defaultHeight / 2, 'error').anchor(0.5, 0.5);
  292. }
  293. self.postScore();
  294. self.animateEnding = true;
  295. self.checkAnswer = false;
  296. self.count = 0;
  297. }
  298. // Balloon flying animation
  299. if (self.animateEnding) {
  300. self.balloon.y -= 2;
  301. self.basket.y -= 2;
  302. if (self.result) self.kid.y -= 2;
  303. if (self.count >= 140) {
  304. if (self.result) mapMove = true;
  305. else mapMove = false;
  306. game.state.start('map');
  307. }
  308. }
  309. game.render.all();
  310. },
  311. /* EVENT HANDLER */
  312. /**
  313. * Called by mouse click event
  314. *
  315. * @param {object} mouseEvent contains the mouse click coordinates
  316. */
  317. func_onInputDown: function (mouseEvent) {
  318. const x = mouseEvent.offsetX;
  319. const y = mouseEvent.offsetY;
  320. // GAME MODE A : click road
  321. if (gameMode == 'A') {
  322. const cur = self.road;
  323. const valid = y > 60 && (x >= cur.xWithAnchor && x <= (cur.xWithAnchor + cur.width * cur.scale));
  324. if (valid) self.func_clicked(x);
  325. }
  326. // GAME MODE B : click circle
  327. if (gameMode == 'B') {
  328. self.circles.all.forEach(cur => {
  329. const valid = game.math.distanceToPointer(x, cur.xWithAnchor, y, cur.yWithAnchor) <= (cur.diameter / 2) * cur.scale;
  330. if (valid) self.func_clicked(cur);
  331. });
  332. }
  333. navigationIcons.func_onInputDown(x, y);
  334. game.render.all();
  335. },
  336. /**
  337. * Called by mouse move event
  338. *
  339. * @param {object} mouseEvent contains the mouse move coordinates
  340. */
  341. func_onInputOver: function (mouseEvent) {
  342. const x = mouseEvent.offsetX;
  343. const y = mouseEvent.offsetY;
  344. let flag = false;
  345. // GAME MODE A : balloon follow mouse
  346. if (gameMode == 'A' && !self.hasClicked) {
  347. if (game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8) {
  348. self.balloon.x = x;
  349. self.basket.x = x;
  350. }
  351. document.body.style.cursor = 'auto';
  352. }
  353. // GAME MODE B : hover circle
  354. if (gameMode == 'B' && !self.hasClicked) {
  355. self.circles.all.forEach(cur => {
  356. const valid = game.math.distanceToPointer(x, cur.xWithAnchor, y, cur.yWithAnchor) <= (cur.diameter / 2) * cur.scale;
  357. if (valid) {
  358. self.func_overCircle(cur);
  359. flag = true;
  360. }
  361. });
  362. if (!flag) self.func_outCircle();
  363. }
  364. navigationIcons.func_onInputOver(x, y);
  365. game.render.all();
  366. },
  367. /* CALLED BY EVENT HANDLER */
  368. /**
  369. * (in gameMode 'B') <br>
  370. *
  371. * Function called when cursor is over a valid circle
  372. *
  373. * @param {object} cur circle the cursor is over
  374. */
  375. func_overCircle: function (cur) {
  376. if (!self.hasClicked) {
  377. document.body.style.cursor = 'pointer';
  378. for (let i in self.circles.all) {
  379. self.circles.all[i].alpha = (i <= cur.index) ? 1 : 0.5;
  380. }
  381. }
  382. },
  383. /**
  384. * (in gameMode 'B') <br>
  385. *
  386. * Function called when cursor is out of a valid circle
  387. */
  388. func_outCircle: function () {
  389. if (!self.hasClicked) {
  390. document.body.style.cursor = 'auto';
  391. self.circles.all.forEach(cur => {
  392. cur.alpha = 0.5;
  393. });
  394. }
  395. },
  396. /**
  397. * (in gameMode 'B') <br>
  398. *
  399. * Function called when player clicked over a valid circle
  400. *
  401. * @param {number|object} cur clicked circle
  402. */
  403. func_clicked: function (cur) {
  404. if (!self.hasClicked) {
  405. // On gameMode A
  406. if (gameMode == 'A') {
  407. self.balloon.x = cur;
  408. self.basket.x = cur;
  409. // On gameMode B
  410. }
  411. else if (gameMode == 'B') {
  412. document.body.style.cursor = 'auto';
  413. for (let i in self.circles.all) {
  414. if (i <= cur.index) {
  415. self.circles.all[i].alpha = 1; // Keep selected circle
  416. self.fractionIndex = cur.index;
  417. } else {
  418. self.circles.all[i].alpha = 0; // Hide unselected circle
  419. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  420. }
  421. }
  422. }
  423. if (audioStatus) game.audio.beepSound.play();
  424. // Hide fractions
  425. if (fractionLabel) {
  426. self.circles.label.forEach(cur => {
  427. cur.forEach(cur => { cur.alpha = 0; });
  428. });
  429. }
  430. // Hide solution pointer
  431. if (self.help != undefined) self.help.alpha = 0;
  432. self.balloon.alpha = 1;
  433. self.trace.alpha = 1;
  434. self.hasClicked = true;
  435. self.animate = true;
  436. game.animation.play(this.kid.animation[0]);
  437. }
  438. },
  439. /* GAME FUNCTIONS */
  440. /**
  441. * Checks if 2 images overlap
  442. *
  443. * @param {object} spriteA image 1
  444. * @param {object} spriteB image 2
  445. * @returns {boolean}
  446. */
  447. func_checkOverlap: function (spriteA, spriteB) {
  448. const xA = spriteA.x;
  449. const xB = spriteB.x;
  450. // Consider it comming from both sides
  451. if (Math.abs(xA - xB) > 14) return false;
  452. else return true;
  453. },
  454. /**
  455. * Display correct answer
  456. */
  457. func_viewHelp: function () {
  458. if (!self.hasClicked) {
  459. // On gameMode A
  460. if (gameMode == 'A') {
  461. self.help.x = self.correctX;
  462. self.help.y = 490;
  463. // On gameMode B
  464. } else {
  465. self.help.x = self.circles.all[self.endIndex - 1].x;
  466. self.help.y = self.circles.all[self.endIndex - 1].y - self.circles.diameter / 2;
  467. }
  468. self.help.alpha = 0.7;
  469. }
  470. },
  471. /* METADATA FOR GAME */
  472. /**
  473. * Saves players data after level ends - to be sent to database <br>
  474. *
  475. * Attention: the "line_" prefix data table must be compatible to data table fields (MySQL server)
  476. * @see /php/squareOne.js
  477. */
  478. postScore: function () {
  479. // Creates string that is going to be sent to db
  480. const data = '&line_game=' + gameShape
  481. + '&line_mode=' + gameMode
  482. + '&line_oper=' + gameOperation
  483. + '&line_leve=' + gameDifficulty
  484. + '&line_posi=' + mapPosition
  485. + '&line_resu=' + self.result
  486. + '&line_time=' + game.timer.elapsed
  487. + '&line_deta='
  488. + 'numCircles:' + self.circles.all.length
  489. + ', valCircles: ' + self.divisorsList
  490. + ' balloonX: ' + self.basket.x
  491. + ', selIndex: ' + self.fractionIndex;
  492. // FOR MOODLE
  493. if (moodle) sendToDB(data, self.result, game.timer.elapsed);
  494. else sendToDB(data);
  495. }
  496. };