-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStateMachine.lua
More file actions
78 lines (71 loc) · 2.06 KB
/
StateMachine.lua
File metadata and controls
78 lines (71 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
--
-- StateMachine - a state machine
--
-- Usage:
--
-- -- States are only created as need, to save memory, reduce clean-up bugs and increase speed
-- -- due to garbage collection taking longer with more data in memory.
-- --
-- -- States are added with a string identifier and an intialisation function.
-- -- It is expect the init function, when called, will return a table with
-- -- Render, Update, Enter and Exit methods.
--
-- gStateMachine = StateMachine {
-- ['MainMenu'] = function()
-- return MainMenu()
-- end,
-- ['InnerGame'] = function()
-- return InnerGame()
-- end,
-- ['GameOver'] = function()
-- return GameOver()
-- end,
-- }
-- gStateMachine:change("MainGame")
--
-- Arguments passed into the Change function after the state name
-- will be forwarded to the Enter function of the state being changed too.
--
-- State identifiers should have the same name as the state table, unless there's a good
-- reason not to. i.e. MainMenu creates a state using the MainMenu table. This keeps things
-- straight forward.
--
-- =Doing Transitions=
--
StateMachine = Class{}
function StateMachine:init(states)
self.empty = {
render = function() end,
update = function() end,
enter = function() end,
exit = function() end,
checking = function (x,y) end,
check_key_released= function (key) end,
check_key_pressed= function (key) end
}
self.states = states or {} -- [name] -> [function that returns states]
self.current = self.empty
end
function StateMachine:change(stateName, enterParams)
assert(self.states[stateName]) -- state must exist!
self.current:exit()
self.g=stateName
self.current = self.states[stateName]()
self.current:enter(enterParams,arg2)
end
function StateMachine:update(dt)
self.current:update(dt)
end
function StateMachine:mouse_pressed(x,y)
self.current:mouse_pressed(x,y)
end
function StateMachine:render()
self.current:render()
-- love.graphics.print(tostring(self.g),400,400)
end
function StateMachine:key_released(key)
self.current:key_released(key)
end
function StateMachine:key_pressed(key)
self.current:key_pressed(key)
end