码迷,mamicode.com
首页 > 其他好文 > 详细

Lua中使用状态机FSM简单例子

时间:2017-12-28 16:00:22      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:fun   date()   初始化   pre   根据   切换   smm   turn   简单   

FSM 有限状态机:

一个有限状态机是一个设备,或者是一个设备模型,具有有限数量的状态,它可以在任何给定的时间根据输入进行操作,使得一个状态变换到另一个状态,或者是使一个输入或者一种行为的发生。一个有限状态机在任何瞬间只能处在一种状态。

进入动作
退出动作
更新动作

FsmMachine.lua

FsmMachine = {}

function FsmMachine:New()
    self.__index = self
    o = setmetatable({}, self)
    o.states = {}
    o.curState = nil
    return o
end

-- 添加状态
function FsmMachine:AddState(baseState)
    self.states[baseState.stateName] = baseState
end

-- 初始化默认状态
function FsmMachine:AddInitState(baseState)
    self.curState = baseState
end

-- 更新当前状态
function FsmMachine:Update()
    self.curState:OnUpdate()
end

-- 切换状态
function FsmMachine:Switch(stateName)
    if self.curState.stateName ~= stateName then
        self.curState:OnLeave()
        self.curState = self.states[stateName]
        self.curState:OnEnter()
    end
end

状态机基类
BaseState.lua

BaseState = {}

function BaseState:New(stateName)
    self.__index = self
    o = setmetatable({}, self)
    o.stateName = stateName
    return o
end

-- 进入状态
function BaseState:OnEnter()
end

-- 更新状态
function BaseState:OnUpdate()
end

-- 离开状态
function BaseState:OnLeave()
end

测试类
Main.lua

require("BaseState")
require("FsmMachine")
FsmMachineTest = {}

-----[状态A,覆盖BaseState方法]----------------
aState = BaseState:New("aState")

function  aState:OnEnter()
    print("aState:OnEnter()")
end

function  aState:OnUpdate()
    print("aState:OnUpdate()")
end

function  aState:OnLeave()
    print("aState:OnLeave()")
end

-----[状态B,覆盖BaseState方法]----------------
bState = BaseState:New("bState")

function  bState:OnEnter()
    print("bState:OnEnter()")
end

function  bState:OnUpdate()
    print("bState:OnUpdate()")
end

function  bState:OnLeave()
    print("bState:OnLeave()")
end

-----[测试状态机]-----------------------------
fsm = FsmMachine:New()
fsm:AddState(aState)
fsm:AddState(bState)
fsm:AddInitState(aState)

for i = 1, 10 do
    if i == 5 then
        fsm:Switch("bState")
    end
    fsm.curState:OnUpdate()
end

输出

aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnUpdate()
aState:OnLeave()
bState:OnEnter()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()
bState:OnUpdate()

Lua中使用状态机FSM简单例子

标签:fun   date()   初始化   pre   根据   切换   smm   turn   简单   

原文地址:https://www.cnblogs.com/tangyongle/p/8135722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!