数码资讯
lua实现的状态机
选购提示
关注价格、性能、续航、售后和真实使用场景,理性比较后再下单。
状态机就是管理在不同状态下的操作实现,这里我简单的提一下,大家看代码就懂了。最近学完了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
声明:本文内容用于数码产品信息整理与选购参考,具体价格、库存、售后政策以官方渠道和电商页面实时信息为准。