circleOne.js 18 KB

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