lua实现的有限状态机

来源:互联网 发布:steam免费mac游戏推荐 编辑:程序博客网 时间:2024/05/20 05:54

       在做的一个项目,由于人物的状态较多,切换比较麻烦不便管理,所以打算引入状态机,方便管理。下面是fsm的简易版本,还有些待完善的地方。

      

local inspect = require "inspect"local FSMState = {}function FSMState:new(super)local obj = super or {}obj.super = selfreturn setmetatable(obj, {__index = self})endfunction FSMState:enter()print(string.format("%s enter", self.name))endfunction FSMState:exit()print(string.format("%s exit", self.name))endlocal FSMStateMachine = {}function FSMStateMachine:new()local obj = {idle = FSMState:new{name="idle"},walk = FSMState:new{name="walk"},attack = FSMState:new{name="attack"},event = {idle = {},walk = {},attack = {},},_curState = "idle",}return setmetatable(obj, {__index = self})endfunction FSMStateMachine:addTransition(before, input, after)if self.event[before] thenif self.event[before][input] then assert("event already be added")elseself.event[before][input] = afterendendendfunction FSMStateMachine:stateTransition(event)assert(self._curState)print(self._curState)local out = self.event[self._curState][event]if out thenprint(string.format("reponse to event:%s", event))-- respond to this eventself[self._curState]:exit()self._curState = outself[self._curState]:enter()else-- no related eventprint(string.format("no reponse to event:%s", event))endend----------------------------------------------------------------------test------------------------------------------------------------------local sm = FSMStateMachine:new()--print(inspect(sm))sm:addTransition("idle", "seen player", "walk")sm:addTransition("idle", "player attack", "attack")sm:addTransition("walk", "player go away", "idle")sm:addTransition("attack", "player die", "idle")--print(inspect(sm))sm:stateTransition("player attack")sm:stateTransition("seen player")

     输出的结果:

     

原创粉丝点击