您的位置:首页 > 编程语言 > Lua

lua实现的状态机

2014-01-06 20:41 1541 查看
状态机就是管理在不同状态下的操作实现,这里我简单的提一下,大家看代码就懂了。最近学完了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 脚本 管理 游戏