Timer.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /************************************************************************
  2. * Timer.js
  3. ************************************************************************
  4. * Copyright (c) 2021 Pedro Tonini Rosenberg Schneider.
  5. *
  6. * This file is part of Pandora.
  7. *
  8. * Pandora is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * Pandora is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with Pandora. If not, see <https://www.gnu.org/licenses/>.
  20. *************************************************************************/
  21. class Timer extends GameObject
  22. {
  23. constructor(name, duration = 1, autostart = false, oneShot = false)
  24. {
  25. super(name);
  26. this.duration = duration;
  27. this.timeLeft = this.duration;
  28. this.paused = !autostart;
  29. this.autostart = autostart;
  30. this.oneShot = oneShot;
  31. }
  32. start(timeSec = this.duration)
  33. {
  34. if (!this.paused) return;
  35. this.duration = timeSec;
  36. this.paused = false;
  37. this.timeLeft = this.duration;
  38. }
  39. stop()
  40. {
  41. this.paused = true;
  42. }
  43. resume()
  44. {
  45. this.paused = false;
  46. }
  47. isStopped()
  48. {
  49. return this.paused;
  50. }
  51. update(delta)
  52. {
  53. if (!this.paused)
  54. {
  55. this.timeLeft -= delta;
  56. if (this.timeLeft <= 0) this.onFinish();
  57. }
  58. this._update(delta);
  59. for (let i = 0; i < this.children.length; i++)
  60. this.children[i].update(delta);
  61. }
  62. onFinish()
  63. {
  64. if (this.oneShot) this.paused = true
  65. this.timeLeft = this.duration;
  66. this._onFinish();
  67. }
  68. _onFinish()
  69. {
  70. console.log("doneskis");
  71. }
  72. }