Quick-cocos2d-x的MVC架构之有限状态机研究

前端之家收集整理的这篇文章主要介绍了Quick-cocos2d-x的MVC架构之有限状态机研究前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所谓状态机机制,就是指
1)按照一定规则设置好所有状态
2)按照一定规则设置好所有操作
3)按照一定规则设置好对象在某种状态下进行某种操作后会变为另外哪种状态
4)按照一定规则定义好对象在进入某种操作前、中、后和某种状态进入前、中、离开时的处理函数
这样当对对象执行某种操作时,该对象的状态就会自动变化并调用进入前、进入中、进入后的函数


例子:假设类A有3种状态state1、state2、state3
2种操作process1、 process2
对象在state1下,执行process1,状态会变为state2
state2下,执行process1,状态会变为state3
state1下,执行process2,状态会变为state3
其余状态下,执行操作,状态不会发生改变


代码如下
--定义状态机变量
self.fsm_ = {}
cc.GameObject.extend(self.fsm_):
addComponent("components.behavior.StateMachine"):exportMethods()


--定义在某种状态下执行各种操作会变为哪种状态
myEvents = {
{name = "process1",from="state1",to="state2"},
{name = "process1",from="state2",to="state3"},
{name = "process2",
}

--定义各种情况下调用函数
myCallbacks = {
onprocess1 = function(event) print("do process1") end,
onprocess2 = function(event) print("do process2") end,
onstate1 = function(event) print("in state1") end,
onstate2 = function(event) print("in state2") end,
onstate3 = function(event) print("in state3") end,
onleavestate1 = function(event) print("leave state1") end,
onleavestate2 = function(event) print("leave state2") end,
onleavestate3 = function(event) print("leave state3") end,
onchangestate = function(event) print("[FSM] CHANGED STATE: " .. event.from .. " to " .. event.to) end,
}

--设置,initial是初始状态
self.fsm_:setupState({
initial = "state1",
events = myEvents,
callbacks = myCallbacks
})

--改变状态,要先判断该状态下是否可以执行某种操作,或者说是否设置过
if self.fsm_:canDoEvent("process1") then

self.fsm_:doEvent("process1")

print("current state is "..self.fsm_:getState())

else
print("Cannt do process1")
end


输出
[LUA-print] leave state1
[LUA-print] in state2
[LUA-print] [FSM] CHANGED STATE: state1 to state2

[LUA-print] do process1

[LUA-print] current state is state2

原文链接:https://www.f2er.com/cocos2dx/344048.html

猜你在找的Cocos2d-x相关文章