circleOne.js 18 KB

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