timer.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # The Timer module allows timers to be set
  2. module Timer
  3. # Timer class models a normal timer
  4. class Timer
  5. # Start time in ticks since Eruta engine start
  6. attr_reader :start
  7. # Delay of timer
  8. attr_reader :delay
  9. # Total time timer was running
  10. attr_reader :total
  11. # Current cycle start
  12. attr_reader :cycle_start
  13. # Current cycle stop
  14. attr_reader :cycle_stop
  15. # Initializes the timer.
  16. def initialize(delay, &to_call)
  17. @to_call = to_call
  18. @delay = delay
  19. @start = Eruta.time
  20. @cycle_start = @start
  21. @cycle_stop = @cycle_start + delay
  22. @total = 0
  23. @done = false
  24. end
  25. # Updates the timer.
  26. def update()
  27. now = Eruta.time
  28. @total = now - @start
  29. if now >= @cycle_stop
  30. @done = @to_call.call(self)
  31. if !@done
  32. @cycle_start = Eruta.time
  33. @cycle_stop = @cycle_start + @delay
  34. end
  35. end
  36. return @done
  37. end
  38. # Checks if timer is done.
  39. def done?
  40. return @done
  41. end
  42. # Forces timer to done.
  43. def done!
  44. @done = true
  45. end
  46. end
  47. # Makes a new timer
  48. # If the callback terurns true, the timer will not be
  49. # called again. If false it will be called again.
  50. def self.make(delay, &callback)
  51. @timers ||= []
  52. timer = ::Timer::Timer.new(delay, &callback)
  53. @timers << timer
  54. return timer
  55. end
  56. # Updates all timers
  57. def self.update
  58. @timers ||= []
  59. done_timers = []
  60. @timers.each do | timer |
  61. if timer.update
  62. done_timers << timer
  63. end
  64. end
  65. done_timers.each do | timer |
  66. @timers.delete(timer)
  67. end
  68. end
  69. end