circleOne.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /**
  2. * GAME STATE
  3. *
  4. * LEVELS - CIRCLE I & II: balloon level
  5. *
  6. * Name of game state : 'circleOne'
  7. * Shape : circle
  8. * Character : kid/balloon
  9. * Theme : flying 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 for each level : 5
  14. *
  15. * Levels can be : 'A' or 'B' (in variable 'levelType')
  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. * Sublevels can be : 'Plus', 'Minus' or 'Mixed' (in variable 'sublevelType')
  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 = (sublevelType == '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 = (sublevelType == 'Mixed' || levelType == 'B') ? 6 : mapPosition + 1;
  91. const min = (sublevelType == '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. // LevelType '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 = (sublevelType == '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 (sublevelType) {
  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 (levelType == '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 (levelType == '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 (sublevelType == '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. } else if (self.circles.direction[cur] == 'Left') {
  235. lowerCircles = self.circles.all[cur].x <= self.nextX;
  236. // If just changed from 'right' to 'left' inform to change direction of kid animation
  237. if (self.changeAnimationFrames == undefined && cur > 0 && self.circles.direction[cur - 1] == 'Right') {
  238. self.changeAnimationFrames = true;
  239. }
  240. }
  241. // Change direction of kid animation
  242. if (self.changeAnimationFrames) {
  243. self.changeAnimationFrames = false;
  244. game.animation.stop(self.kid.animation[0]);
  245. self.kid.animation = self.availableAnimations['Left'];
  246. self.kid.curFrame = 23;
  247. game.animation.play(self.kid.animation[0]);
  248. }
  249. if (lowerCircles) {
  250. self.circles.all[cur].alpha = 0; // Cicle disappear
  251. self.circles.all.forEach(cur => {
  252. cur.y += self.circles.diameter; // Lower circles
  253. });
  254. self.kid.y += self.circles.diameter; // Lower kid
  255. self.circles.cur++; // Update current circle
  256. cur = self.circles.cur;
  257. DIREC = self.circles.direc[cur];
  258. self.nextX += self.circles.distance[cur] * DIREC; // Update next position
  259. }
  260. // When finish all circles (final position)
  261. if (cur == self.circles.all.length || self.circles.all[cur].alpha == 0) {
  262. self.animate = false;
  263. self.checkAnswer = true;
  264. }
  265. }
  266. }
  267. // Check if kid is inside the basket
  268. if (self.checkAnswer) {
  269. game.timer.stop();
  270. game.animation.stop(self.kid.animation[0]);
  271. if (self.func_checkOverlap(self.basket, self.kid)) {
  272. self.result = true; // Answer is correct
  273. self.kid.curFrame = (self.kid.curFrame < 12) ? 24 : 25;
  274. if (audioStatus) game.audio.okSound.play();
  275. game.add.image(defaultWidth / 2, defaultHeight / 2, 'ok').anchor(0.5, 0.5);
  276. completedLevels++;
  277. if (debugMode) console.log('completedLevels = ' + completedLevels);
  278. } else {
  279. self.result = false; // Answer is incorrect
  280. if (audioStatus) game.audio.errorSound.play();
  281. game.add.image(defaultWidth / 2, defaultHeight / 2, 'error').anchor(0.5, 0.5);
  282. }
  283. self.postScore();
  284. self.animateEnding = true;
  285. self.checkAnswer = false;
  286. self.count = 0;
  287. }
  288. // Balloon flying animation
  289. if (self.animateEnding) {
  290. self.balloon.y -= 2;
  291. self.basket.y -= 2;
  292. if (self.result) self.kid.y -= 2;
  293. if (self.count >= 140) {
  294. if (self.result) mapMove = true;
  295. else mapMove = false;
  296. game.state.start('map');
  297. }
  298. }
  299. game.render.all();
  300. },
  301. /* EVENT HANDLER */
  302. /**
  303. * Called by mouse click event
  304. *
  305. * @param {object} mouseEvent contains the mouse click coordinates
  306. */
  307. func_onInputDown: function (mouseEvent) {
  308. const x = mouseEvent.offsetX;
  309. const y = mouseEvent.offsetY;
  310. // LEVEL A : click road
  311. if (levelType == 'A') {
  312. const cur = self.road;
  313. const valid = y > 60 && (x >= cur.xWithAnchor && x <= (cur.xWithAnchor + cur.width * cur.scale));
  314. if (valid) self.func_clicked(x);
  315. }
  316. // LEVEL B : click circle
  317. if (levelType == 'B') {
  318. self.circles.all.forEach(cur => {
  319. const valid = game.math.distanceToPointer(x, cur.xWithAnchor, y, cur.yWithAnchor) <= (cur.diameter / 2) * cur.scale;
  320. if (valid) self.func_clicked(cur);
  321. });
  322. }
  323. navigationIcons.func_onInputDown(x, y);
  324. game.render.all();
  325. },
  326. /**
  327. * Called by mouse move event
  328. *
  329. * @param {object} mouseEvent contains the mouse move coordinates
  330. */
  331. func_onInputOver: function (mouseEvent) {
  332. const x = mouseEvent.offsetX;
  333. const y = mouseEvent.offsetY;
  334. let flag = false;
  335. // LEVEL A : balloon follow mouse
  336. if (levelType == 'A' && !self.hasClicked) {
  337. if (game.math.distanceToPointer(x, self.balloon.x, y, self.balloon.y) > 8) {
  338. self.balloon.x = x;
  339. self.basket.x = x;
  340. }
  341. document.body.style.cursor = 'auto';
  342. }
  343. // LEVEL B : hover circle
  344. if (levelType == 'B' && !self.hasClicked) {
  345. self.circles.all.forEach(cur => {
  346. const valid = game.math.distanceToPointer(x, cur.xWithAnchor, y, cur.yWithAnchor) <= (cur.diameter / 2) * cur.scale;
  347. if (valid) {
  348. self.func_overCircle(cur);
  349. flag = true;
  350. }
  351. });
  352. if (!flag) self.func_outCircle();
  353. }
  354. navigationIcons.func_onInputOver(x, y);
  355. game.render.all();
  356. },
  357. /* CALLED BY EVENT HANDLER */
  358. /**
  359. * (in levelType 'B')
  360. *
  361. * Function called when cursor is over a valid circle
  362. *
  363. * @param {object} cur circle the cursor is over
  364. */
  365. func_overCircle: function (cur) {
  366. if (!self.hasClicked) {
  367. document.body.style.cursor = 'pointer';
  368. for (let i in self.circles.all) {
  369. self.circles.all[i].alpha = (i <= cur.index) ? 1 : 0.5;
  370. }
  371. }
  372. },
  373. /**
  374. * (in levelType 'B')
  375. *
  376. * Function called when cursor is out of a valid circle
  377. */
  378. func_outCircle: function () {
  379. if (!self.hasClicked) {
  380. document.body.style.cursor = 'auto';
  381. self.circles.all.forEach(cur => {
  382. cur.alpha = 0.5;
  383. });
  384. }
  385. },
  386. /**
  387. * (in levelType 'B')
  388. *
  389. * Function called when player clicked over a valid circle
  390. *
  391. * @param {number|object} cur clicked circle
  392. */
  393. func_clicked: function (cur) {
  394. if (!self.hasClicked) {
  395. // On levelType A
  396. if (levelType == 'A') {
  397. self.balloon.x = cur;
  398. self.basket.x = cur;
  399. // On levelType B
  400. } else if (levelType == 'B') {
  401. document.body.style.cursor = 'auto';
  402. for (let i in self.circles.all) {
  403. if (i <= cur.index) {
  404. self.circles.all[i].alpha = 1; // Keep selected circle
  405. self.fractionIndex = cur.index;
  406. } else {
  407. self.circles.all[i].alpha = 0; // Hide unselected circle
  408. self.kid.y += self.circles.diameter; // Lower kid to selected circle
  409. }
  410. }
  411. }
  412. if (audioStatus) game.audio.beepSound.play();
  413. // Hide fractions
  414. if (fractionLabel) {
  415. self.circles.label.forEach(cur => {
  416. cur.forEach(cur => {
  417. cur.alpha = 0;
  418. });
  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 levelType A
  451. if (levelType == 'A') {
  452. self.help.x = self.correctX;
  453. self.help.y = 490;
  454. // On levelType 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
  465. */
  466. postScore: function () {
  467. // Saves player data to send to the database
  468. const data = '&s_game=' + gameShape
  469. + '&s_mode=' + levelType
  470. + '&s_oper=' + sublevelType
  471. + '&s_leve=' + gameDifficulty
  472. + '&s_posi=' + mapPosition
  473. + '&s_resu=' + self.result
  474. + '&s_time=' + game.timer.elapsed
  475. + '&s_deta='
  476. + 'numCircles:' + self.circles.all.length
  477. + ', valCircles: ' + self.divisorsList
  478. + ' balloonX: ' + self.basket.x
  479. + ', selIndex: ' + self.fractionIndex;
  480. postScore(data);
  481. }
  482. };