Refactored state machine to use stack

This commit is contained in:
2024-11-29 17:47:42 -06:00
parent 738baa3d69
commit e3000e3364
2 changed files with 32 additions and 16 deletions

View File

@@ -10,37 +10,53 @@ function GameCore.new()
setmetatable(GameCore, { __index = LoveNode })
local self = setmetatable(LoveNode.new(), GameCore)
self.stateStack = {}
self.states = {
mainmenu = MainMenu.new(self),
game = Game.new(self),
game = Game.new(self, 8, 10),
pausemenu = PauseMenu.new(self)
}
self:switchState(self.states.mainmenu)
self:pushState(self.states.mainmenu)
return self
end
function GameCore:update(dt)
self.states.current:update(dt)
local current = self.stateStack[#self.stateStack]
if current then
current:update(dt)
end
end
function GameCore:draw()
self.states.current:draw()
local current = self.stateStack[#self.stateStack]
if current then
current:draw()
end
end
function GameCore:resize(w, h)
self.states.current:resize(w, h)
local current = self.stateStack[#self.stateStack]
if current then
current:resize(w, h)
end
end
function GameCore:switchState(newState)
if self.states.current then
self.states.current:exit()
self:popState()
self:pushState(newState)
end
function GameCore:pushState(newState)
table.insert(self.stateStack, newState)
newState:enter()
end
function GameCore:popState()
local current = self.stateStack[#self.stateStack]
if current then
current:exit()
end
self.states.prev = self.states.current
self.states.current = newState
self.states.current:enter()
end
return GameCore

View File

@@ -46,9 +46,7 @@ function Player:update(dt)
futurePosX + futureVelX,
futurePosY + futureVelY,
function(item, other)
if other.isExit then
return 'cross'
elseif other.isEnemy then
if other.isExit or other.isEnemy then
return 'cross'
end
return 'slide'
@@ -59,7 +57,9 @@ function Player:update(dt)
for i = 1, len do
local other = cols[i].other
if other.isExit then
self.game.core:switchState(self.game.core.states.game)
self.game:nextLevel()
elseif other.isEnemy then
self.game:failLevel()
end
end
end