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
--电脑生成四个不重复数字
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
相关文章推荐
- lua中Sprite读取图片,缓存问题,会读取到上次保存的图片
- ubuntu lua安装
- luajit stack traceback() 显示不全
- Lua,Lua API,配置文件
- 最简单的Mac xcode下搭建lua
- Lua upvalue
- lua中的require机制
- Lua学习笔记-9.3章-协同用做迭代器
- Lua学习笔记-9.2章-管道和过滤器
- 快速掌握Lua 5.3 —— "table"库
- Lua学习笔记-9.1章-协同程序
- Lua学习笔记
- 灵光乍现,lua数据绑定
- java常用算法之逆波兰表达式(Evaluate Reverse Polish Notation)
- Lua C API 遍历 table
- mac上安装lua
- lua语言介绍
- windows平台编译Lua
- Lua table用法
- Lua学习笔记-迭代器和泛型for