Class: TungstenEngine::Core::Game

Inherits:
Object
  • Object
show all
Defined in:
lib/core/game.rb

Overview

Represents the base class for a real game

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fixed_time_step = true, target_frame_rate = 60) ⇒ Game

Returns a new instance of Game.



11
12
13
14
15
# File 'lib/core/game.rb', line 11

def initialize(fixed_time_step = true, target_frame_rate = 60)
  @components = []
  @fixed_time_step = fixed_time_step
  self.target_frame_rate = target_frame_rate
end

Instance Attribute Details

#fixed_time_stepObject

Returns the value of attribute fixed_time_step.



9
10
11
# File 'lib/core/game.rb', line 9

def fixed_time_step
  @fixed_time_step
end

Instance Method Details

#exitObject



68
69
70
# File 'lib/core/game.rb', line 68

def exit
  @running = false
end

#register_component(component) ⇒ Object



21
22
23
24
# File 'lib/core/game.rb', line 21

def register_component(component)
  raise("Cannot register objects that ain't GameComponent instances") \
    unless component.is_a? GameComponent
end

#render(game_time) ⇒ Object



62
63
64
65
66
# File 'lib/core/game.rb', line 62

def render(game_time)
  @components.each do |component|
    component.render(game_time)
  end
end

#runObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/core/game.rb', line 26

def run
  started = Time.now
  last_loop = Time.now
  @running = true

  game_loop = Thread.new do
    while @running
      now = Time.now
      total = TimeSpan.diff(started, now)
      elapsed = TimeSpan.diff(last_loop, now)
      spare = @target_frame_microseconds - elapsed.microseconds
      slow = spare < 0
      if @fixed_time_step && !slow
        sleep(spare / 1_000_000)
        now = Time.now
        total = TimeSpan.diff(started, now)
        elapsed = TimeSpan.diff(last_loop, now)
        # do not re-calculate 'slow' here, since we want to know if we
        # have been to slow when the loop was entered again, not if we maybe
        # are too slow after waiting
      end
      game_time = GameTime.new(total, elapsed, slow)
      update(game_time)
      render(game_time)
      last_loop = now
    end
  end
  game_loop.join
end

#target_frame_rate=(frame_rate) ⇒ Object



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

def target_frame_rate=(frame_rate)
  @target_frame_microseconds = 1_000_000.0 / frame_rate
end

#update(game_time) ⇒ Object



56
57
58
59
60
# File 'lib/core/game.rb', line 56

def update(game_time)
  @components.each do |component|
    component.update(game_time)
  end
end