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

lua程序:猜数字

2016-02-18 17:11 405 查看
猜数字游戏的规则是:规则是由电脑和人轮流猜,猜中则游戏停止
--电脑生成四个不重复数字
tb1={0,1,2,3,4,5,6,7,8,9}
i=1 tbn={}
if i<5 then
for i=1,4 do
n=math.random(1,11-i)
g=tb1

table.insert(tbn,g)
tb1[11-i],tb1
=tb1
,tb1[11-i] --交换生成的数和最后一个数的位置
i=i+1

end
end
print(tbn[1],tbn[2],tbn[3],tbn[4])
tbn_number=tbn[1]*1000+tbn[2]*100+tbn[3]*10+tbn[4]

--判断部分
q=1
while true do
a=0 b=0
if q==1 then
print("请输入四个数字")
while true do
p=io.read("*line")
if (not tonumber(p)) or (string.len(p)~=4) then
print("您输入的不是4位数字,请重新输入")
else
p=tonumber(p)
break
end
end

while true do
p1=math.modf(p/1000)
if p1<0 or p1>9 then
print("您输入的数字不是四位,请重新输入")
else break
end
end
p2=math.modf(p/100)-p1*10
p3=math.modf(p/10)-p2*10-p1*100
p4=p-p3*10-p2*100-p1*1000
tbp={p1,p2,p3,p4}
print(p1,p2,p3,p4)
q=0
for i=1,4 do
for j=1,4 do
if tbp[i]==tbn[j] then
if i~=j then
b=b+1
else
a=a+1
end
end

end
end
if a==4 and b==0 then
print("玩家胜利")
break
end
print(a.."A"..b.."B")

else
--缺少电脑生成数不能使用玩家已输入的判断
k=1
while k==1 do
m1=math.random(0,9)
m2=math.random(0,9)
m3=math.random(0,9)
m4=math.random(0,9)
tbm={m1,m2,m3,m4}
if tbm~=tbp then
break
end
end
print(m1,m2,m3,m4)
q=1
for i=1,4 do
for j=1,4 do
if tbm[i]==tbn[j] then
if i~=j then
b=b+1
else
a=a+1
end
end
end
end
if a==4 and b==0 then
print("电脑胜利")
break
end
print(a.."A"..b.."B")
end
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: