Timer.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. initSignals()
  63. {
  64. this.addSignal("timeout");
  65. this._initSignals();
  66. }
  67. onFinish()
  68. {
  69. if (this.oneShot) this.paused = true
  70. this.timeLeft = this.duration;
  71. this._onFinish();
  72. this.emitSignal("timeout");
  73. }
  74. _onFinish()
  75. {
  76. console.log("doneskis");
  77. }
  78. }