lua实现的状态机

本文介绍如何使用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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值