Log In  


Cart #fsm_boiler-0 | 2021-10-16 | Code ▽ | Embed ▽ | License: CC4-BY-NC-SA


--core
-- finite state machine (game state)
fsm={states={}}

-- make a state for the fsm system
function mk_state(state_name, f_enter, f_exec, f_exit)
s = {}
s.enter = f_enter
s.exec = f_exec
s.exit = f_exit
s.age=0
fsm.states[state_name] = s
return s
end

function set_state(new_state_name)

if(fsm.current ~= nil) then
-- exit old state
fsm.current.exit()
fsm.current.age=0
end

-- setup new state
fsm.current = fsm.states[new_state_name]
fsm.current.age=0
fsm.current.enter()
end

function _init()
-- set initial state to s1
fsm.current = s1
end

function _update60()
fsm.current.age+=1
fsm.current.exec()
end

-->8
--state 1

function s1_enter()
end

function s1_execute()

cls()
print("state_1: " .. s1.age, 10,10,9)
-- leave when s1 is older than 60 frames
if(s1.age>60) then
set_state("s2")
end
end

function s1_exit()
end

s1 = mk_state("s1", s1_enter, s1_execute, s1_exit)
-->8
--state 2

function s2_enter()
end

function s2_execute()

cls()
print("state_2: " .. s2.age, 40,10,8)
-- leave when s1 is older than 120 frames
if(s2.age>120) then
set_state("s1")
end
end

function s2_exit()
end
s2 = mk_state("s2", s2_enter, s2_execute, s2_exit)



Use this to quickly setup a project with multiple game states (Main Menu / Gameloop etc)



[Please log in to post a comment]