Class: Moon::StateManager

Inherits:
Object show all
Defined in:
lib/moon/packages/std/state_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(engine) ⇒ StateManager

Returns a new instance of StateManager.


9
10
11
12
13
14
# File 'lib/moon/packages/std/state_manager.rb', line 9

def initialize(engine)
  @engine = engine
  @states = []

  setup_input
end

Instance Attribute Details

#engineMoon::Engine (readonly)

Returns:

  • (Moon::Engine)

4
5
6
# File 'lib/moon/packages/std/state_manager.rb', line 4

def engine
  @engine
end

#statesArray<State> (readonly)

List of all States on the stack

Returns:


7
8
9
# File 'lib/moon/packages/std/state_manager.rb', line 7

def states
  @states
end

Instance Method Details

#change(state) ⇒ Object

Parameters:


76
77
78
79
80
81
# File 'lib/moon/packages/std/state_manager.rb', line 76

def change(state)
  last_state = eject_last
  debug { puts "[#{self.class}] CHANGE #{last_state.class} >> #{state}" }
  @states.push spawn(state)
  @states.last.invoke
end

#clearObject

Clears all the states


37
38
39
# File 'lib/moon/packages/std/state_manager.rb', line 37

def clear
  @states.clear
end

#currentState

Returns:


32
33
34
# File 'lib/moon/packages/std/state_manager.rb', line 32

def current
  @states.last
end

#debugObject

Is the State in debug mode?


22
23
24
# File 'lib/moon/packages/std/state_manager.rb', line 22

def debug
  yield
end

#empty?Boolean

Is the state manager empty?

Returns:


27
28
29
# File 'lib/moon/packages/std/state_manager.rb', line 27

def empty?
  @states.empty?
end

#popObject


85
86
87
88
89
90
91
92
# File 'lib/moon/packages/std/state_manager.rb', line 85

def pop
  @states.last.terminate
  last_state = @states.pop

  debug { puts "[#{self.class}] POP #{last_state.class} > #{@states.last.class}" }
  @states.last.resume if !@states.empty?
  debug { puts "--#{self.class} now empty--" }
end

#push(state) ⇒ Object

Parameters:


96
97
98
99
100
101
102
# File 'lib/moon/packages/std/state_manager.rb', line 96

def push(state)
  last_state = @states.last
  @states.last.pause unless @states.empty?
  debug { puts "[#{self.class}] PUSH #{last_state.class} > #{state}" }
  @states.push spawn(state)
  @states.last.invoke
end

#setup_inputObject


16
17
18
19
# File 'lib/moon/packages/std/state_manager.rb', line 16

def setup_input
  callback = ->(event) { current.input.trigger event if current }
  @engine.input.register(callback)
end

#spawn(klass) ⇒ State

Returns instance of class.

Parameters:

Returns:

  • (State)

    instance of class


58
59
60
61
62
# File 'lib/moon/packages/std/state_manager.rb', line 58

def spawn(klass)
  state = klass.new @engine
  on_spawn state
  state
end

#step(delta) ⇒ Object

Steps the current state

Parameters:


44
45
46
47
# File 'lib/moon/packages/std/state_manager.rb', line 44

def step(delta)
  return unless current
  current.step(delta)
end