local ____exports = __module.env ____exports.StateMachine = __TS__DefineClass("StateMachine", __module) local StateMachine = ____exports.StateMachine StateMachine.name = "StateMachine" function StateMachine.prototype.____constructor(self, ctx) self.states = {} self.transitions = {} self.currentState = nil self.stateElapsed = 0 self.paused = false self.history = {} self.ctx = ctx end function StateMachine.prototype.RegisterState(self, id, handler) self.states[id] = handler end function StateMachine.prototype.AddTransition(self, from, to, condition) self.transitions[#self.transitions + 1] = {from = from, to = to, condition = condition} end function StateMachine.prototype.Start(self, initialState) if self.states[initialState] == nil then return false end self.currentState = initialState self.stateElapsed = 0 self.history[#self.history + 1] = initialState local handler = self.states[initialState] if handler and handler.OnEnter then handler.OnEnter(self.ctx, nil) end return true end function StateMachine.prototype.ChangeState(self, nextState) if self.currentState == nextState or self.states[nextState] == nil then return false end local prev = self.currentState if prev ~= nil then local prevHandler = self.states[prev] if prevHandler and prevHandler.OnExit then prevHandler.OnExit(self.ctx, nextState) end end self.currentState = nextState self.stateElapsed = 0 self.history[#self.history + 1] = nextState local nextHandler = self.states[nextState] if nextHandler and nextHandler.OnEnter then nextHandler.OnEnter(self.ctx, prev) end return true end function StateMachine.prototype.Update(self, dt) if self.paused or self.currentState == nil then return end self.stateElapsed = self.stateElapsed + dt do local i = 0 while i < #self.transitions do local tr = self.transitions[i + 1] if (tr.from == "*" or tr.from == self.currentState) and tr.to ~= self.currentState and tr.condition(self.ctx) then self:ChangeState(tr.to) break end i = i + 1 end end local handler = self.states[self.currentState] if handler and handler.OnUpdate then handler.OnUpdate(self.ctx, dt) end end function StateMachine.prototype.SetPaused(self, paused) self.paused = paused end function StateMachine.prototype.GetCurrentState(self) return self.currentState end function StateMachine.prototype.GetStateElapsed(self) return self.stateElapsed end function StateMachine.prototype.GetHistory(self) return self.history end function __module.UpdateImports() end