Class: TimerManager

Inherits:
Object show all
Defined in:
lib/gamebox/core/timer_manager.rb

Instance Method Summary collapse

Constructor Details

#initializeTimerManager

Returns a new instance of TimerManager.



3
4
5
6
7
# File 'lib/gamebox/core/timer_manager.rb', line 3

def initialize
  @timers ||= {}
  @dead_timers = []
  @callbacks = []
end

Instance Method Details

#add_timer(name, interval_ms, recurring = true, &block) ⇒ Object

add block to be executed every interval_ms millis



10
11
12
13
14
15
# File 'lib/gamebox/core/timer_manager.rb', line 10

def add_timer(name, interval_ms, recurring = true, &block)
  raise "timer [#{name}] already exists" if @timers[name]
  @timers[name] = {
    count: 0, recurring: recurring,
    interval_ms: interval_ms, callback: block}
end

#pauseObject



44
45
46
47
# File 'lib/gamebox/core/timer_manager.rb', line 44

def pause
  @paused_timers = @timers
  @timers = {}
end

#remove_timer(name) ⇒ Object



17
18
19
# File 'lib/gamebox/core/timer_manager.rb', line 17

def remove_timer(name)
  @timers.delete name
end

#timer(name) ⇒ Object



21
22
23
# File 'lib/gamebox/core/timer_manager.rb', line 21

def timer(name)
  @timers[name]
end

#unpauseObject



49
50
51
52
# File 'lib/gamebox/core/timer_manager.rb', line 49

def unpause
  @timers = @paused_timers
  @paused_timers = {}
end

#update(time_delta) ⇒ Object

update each timers counts, call any blocks that are over their interval



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/gamebox/core/timer_manager.rb', line 26

def update(time_delta)
  @callbacks.clear
  @dead_timers.clear

  @timers.each do |name, timer_hash|
    timer_hash[:count] += time_delta
    if timer_hash[:count] > timer_hash[:interval_ms]
      timer_hash[:count] -= timer_hash[:interval_ms]
      @callbacks << timer_hash[:callback]
      @dead_timers << name unless timer_hash[:recurring]
    end
  end
  @dead_timers.each do |name|
    remove_timer name
  end
  @callbacks.each &:call
end