Yet another state system
Posted: Sat Jul 02, 2016 4:10 am
Here simple state-system, working like average state automaton.
States can be required from files, returns a table with the methods.
Each state has its own local field, which does not affect the global variables and other states.
Example:
Full list of callbacks here: https://love2d.org/wiki/love.
Easy example attached.
Upd: autotracker handlers.
States can be required from files, returns a table with the methods.
Each state has its own local field, which does not affect the global variables and other states.
Example:
Code: Select all
state = require 'gamestate'
menu = {}
function menu:load(x, y) --method calls every gamestate:set('statename', ...), can be called with any arguments
--'self' is local namespase for that state
self.x = x or 10
self.y = y or 20
end
function menu:unload() --method is called when this state is replaced by another, using gamestate:set('statename', ...).
self.x, self.y = nil, nil
end
function menu:keypressed(key)
if key == 'return' then state:set('game') end
end
function menu:draw()
love.graphics.print('state: menu', self.x, self.y)
end
game = {}
function game:load(...)
self.x = 10
self.y = 20
end
function game:keypressed(key)
if key == 'return' then state:set('menu', math.random(300), math.random(200)) end
end
function game:draw()
love.graphics.print('state: game', self.x, self.y)
end
state:new('menu', menu)
state:new('game', game)
state:set('menu')
--if love[callbackname] is defined, is required to use state:[callbackname] method.
function love.keypressed(key)
if key == 'escape' then love.event.quit() end
state:keypressed(key)
end
Easy example attached.
Upd: autotracker handlers.