It was always interesting to make the finite state machine for game modules in Love2D.
There is the StateManager!
Code: Select all
-- state-manager.lua
local StateManager = {}
StateManager.currentState = nil
function StateManager.switchState(newState)
-- [switches to a new state and initializes it]
if StateManager.currentState and StateManager.currentState.exit then
StateManager.currentState.exit()
end
StateManager.currentState = newState
if StateManager.currentState and StateManager.currentState.enter then
StateManager.currentState.enter()
end
for i, v in pairs (StateManager) do
print ('StateManager', i, v)
end
end
function StateManager.update(dt)
-- [updates the current state]
if StateManager.currentState and StateManager.currentState.update then
StateManager.currentState.update(dt)
end
end
function StateManager.draw()
-- [draws the current state]
if StateManager.currentState and StateManager.currentState.draw then
StateManager.currentState.draw()
end
end
function StateManager.handleEvent(event, ...)
-- [handles events in the current state]
if StateManager.currentState and StateManager.currentState[event] then
StateManager.currentState[event](...)
end
end
return StateManager
Code: Select all
-- main.lua
StateManager = require("state-manager")
Editor = require("editor") -- example state
function love.load()
-- [sets the initial state to editor]
StateManager.switchState(Editor)
end
function love.update(dt)
-- [updates the current state]
StateManager.update(dt)
end
function love.draw()
-- [renders the current state]
StateManager.draw()
end
function love.keypressed(key)
-- [handles keypress events in the current state]
StateManager.handleEvent("keypressed", key)
end
function love.mousepressed(x, y, button)
-- [handles mouse press events in the current state]
StateManager.handleEvent("mousepressed", x, y, button)
end
function love.mousereleased(x, y, button)
-- [handles mouse release events in the current state]
StateManager.handleEvent("mousereleased", x, y, button)
end
function love.mousemoved(x, y, dx, dy)
-- [handles mouse move events in the current state]
StateManager.handleEvent("mousemoved", x, y, dx, dy)
end
function love.wheelmoved(x, y)
-- [handles mouse wheel events]
StateManager.handleEvent("wheelmoved", x, y)
end
Code: Select all
-- editor.lua
function Editor.enter()
-- [initializes editor state]
print("Editor state entered")
end
function Editor.update(dt)
-- [updates editor logic]
end
function Editor.draw()
-- [draws editor]
end
function Editor.exit()
-- [cleans up editor state]
print("Editor state exited")
end
function Editor.keypressed(key, scancode)
end
function Editor.mousepressed(x, y, button)
end
function Editor.mousemoved(x, y, dx, dy)
end
function Editor.wheelmoved(x, y)
end
return Editor -- most important thing in the file!