Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

game-controller.js 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * -------------------------------------------
  3. * Magic AR Basketball
  4. * A demo game of the encantar.js WebAR engine
  5. * -------------------------------------------
  6. * @fileoverview The Game Controller manages the state of the game
  7. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  8. */
  9. import { Entity } from './entity.js';
  10. import { GameEvent } from '../core/events.js';
  11. import { NUMBER_OF_BALLS, RANK_TABLE } from '../core/globals.js';
  12. /**
  13. * The Game Controller manages the state of the game
  14. */
  15. export class GameController extends Entity
  16. {
  17. /**
  18. * Constructor
  19. * @param {BasketballGame} game
  20. */
  21. constructor(game)
  22. {
  23. super(game);
  24. this._ballsLeft = NUMBER_OF_BALLS;
  25. this._score = 0;
  26. }
  27. /**
  28. * Initialize the entity
  29. * @returns {void}
  30. */
  31. init()
  32. {
  33. this._broadcast(new GameEvent('newball', { ballsLeft: this._ballsLeft }));
  34. this._broadcast(new GameEvent('newscore', { score: this._score }));
  35. }
  36. /**
  37. * Handle an event
  38. * @param {GameEvent} event
  39. * @returns {void}
  40. */
  41. handleEvent(event)
  42. {
  43. switch(event.type) {
  44. case 'scored':
  45. this._score += event.detail.score;
  46. this._broadcast(new GameEvent('newscore', { score: this._score }));
  47. break;
  48. case 'lostball':
  49. if(--this._ballsLeft <= 0) {
  50. const rank = this._computeRank(this._score);
  51. this._broadcast(new GameEvent('newball', { ballsLeft: 0 }));
  52. this._broadcast(new GameEvent('gameover', { rank }));
  53. }
  54. else
  55. this._broadcast(new GameEvent('newball', { ballsLeft: this._ballsLeft }));
  56. break;
  57. case 'restarted':
  58. this._score = 0;
  59. this._ballsLeft = NUMBER_OF_BALLS;
  60. this._broadcast(new GameEvent('newscore', { score: this._score }));
  61. this._broadcast(new GameEvent('newball', { ballsLeft: this._ballsLeft }));
  62. break;
  63. case 'targetlost':
  64. this._broadcast(new GameEvent('restarted'));
  65. break;
  66. }
  67. }
  68. /**
  69. * Compute the rank based on the score of the player
  70. * @param {number} score
  71. * @returns {string}
  72. */
  73. _computeRank(score)
  74. {
  75. const entries = Object.entries(RANK_TABLE).sort((a, b) => b[1] - a[1]);
  76. for(const [rank, minScore] of entries) {
  77. if(score >= minScore)
  78. return rank;
  79. }
  80. return '?';
  81. }
  82. }