状态机就是管理在不同状态下的操作实现,这里我简单的提一下,大家看代码就懂了。最近学完了lua打算做点游戏,所有先用lua弄清楚一些常用的状态控制。
------创建状态机制类型三种状态学习,编码,休息
local state = {study="study",code="code",relax="relax"}
bobo={nowstate=state.study} ---默认的是学习状态
-----获取目前状态
function bobo.getstate()
return bobo.nowstate
end
----改变状态
function bobo.exchagestate(var)
bobo.nowstate=var
end
---是否想写代码
function bobo.iswriteabl()
if math.random(0,1) < 0.2 then ----居然只有0.2想写代码。。。
return true
end
end
-----是否想休息
function bobo.istire()
return true ------------这么干脆就说累了?
end
------编码中
function bobo.code()
print("i am codeing")
end
------休息中
function bobo.relax()
print("i am relax")
end
----学习中
function bobo.study()
print("i am study")
end
----模拟状态改变
while true do
if bobo.nowstate==state.study then
if bobo.istire() then
bobo.relax()
bobo.exchagestate(state.relax)
end
elseif bobo.nowstate==state.code then
if bobo.istire() then
bobo.relax()
bobo.exchagestate(state.relax)
end
elseif bobo.nowstate==state.relax then
if bobo.iswriteabl() then
bobo.code()
bobo.exchagestate(state.code)
else
bobo.study()
bobo.exchagestate(state.study)
end
end
end
本文介绍如何使用Lua语言实现状态机,并通过简单的实例展示了如何管理不同状态下的操作,如学习、编码和休息。
1269

被折叠的 条评论
为什么被折叠?



