这是自己写的一个状态机在UI界面中使用的样例
function PXUITreaChest:addStateMachine()
self.fsm_ = {}
cc(self.fsm_)
:addComponent("components.behavior.StateMachine")
:exportMethods()
self.fsm_:setupState({
--defer 翻译:延迟 状态机初始状态为none 如果这个为false 则状态自动none->normal 反之需setupState结束后 doEvent("normal")
--{name = "startup", from = "none", to = "normal"}, --下面这句可以这么理解
initial = {state = "Normal", event = "Startup", defer = false},
events = {
--{name = "ToGetData", from = {"Normal", "OpenBox"}, to = "GetData"},
{name = "ToGetData", from = "Normal", to = "GetData"},
{name = "ToPanelBase", from = {"GetData", "OpenInfo", "BuyBox", "OpenBox"}, to = "PanelBase"},
{name = "ToOpenInfo", from = "PanelBase", to = "OpenInfo"},
{name = "ToBuyBox", from = "PanelBase", to = "BuyBox"},
{name = "ToOpenBox", from = "BuyBox", to = "OpenBox"},
-- {name = "release", from = "pressed", to = "normal"},
},
callbacks = {
onenterNormal = handler(self, self.InitAll), --初始化一切
onenterGetData = handler(self, self.initPanelData),--初始化数据
onenterPanelBase = handler(self, self.initPanelBase),--保持界面一致
onenterOpenInfo = handler(self, self.openInfo),--查看信息
onenterBuyBox = handler(self, self.buyBox),--购买宝箱界面
onenterOpenBox = handler(self, self.openBox),--打开宝箱界面
},
terminal = "normal" --与to的状态做比较 相关函数 self.fsm_:isFinishedState()是否最终状态
})
end
function PXUITreaChest:SetState(_szState, ...)
assert(self.fsm_, "状态机不存在")
if self.fsm_:canDoEvent(_szState) then
self.fsm_:doEvent(_szState, ...)
else
printf("不能跳转状态, 从状态: %s 跳转到 %s", self.fsm_:getState(), _szState)
end
end