寻找失落的红宝石
我的第一个ruby程序【猜数字】
上一篇 /
下一篇 2007-09-03 02:03:32
/ 个人分类:启程之诗
写的很粗糙也很简单,没有仔细判断键盘输入部分,字符串处理掌握的还不够。
用了basic式程序写的代码,以后慢慢的简化成ruby式的。
希望高手指点用ruby简化的代码。
初学者朋友欢迎一起学习探讨。
#教程里面找到随机生成0-n之间m个不重复数字的方法
def sample(n, m)
if m.zero?
[]
else
s = sample(n-1, m-1)
t = rand(n+1)
s.concat s.include?(t) ? [n] : [t]
end
end
puts '猜数字游戏'
puts '游戏方法:每次输入4位 0-9 之间不重复的数字,根据提示猜测电脑的随机数'
puts '提示中,B代表数正确但位置不对的数字个数,而A代表位置与数都正确的数字个数'
puts '提示规则:共有8次机会,每次提示A,B类数字的数量'
puts '作弊方法:输入0000'
$a4=sample(9,4).join("") #生成4位随机数字
puts '#############################################################'
times = 8
while times>0
$A=$B=0
print "您还有#{times}次机会,请输入4位数字: "
STDOUT.flush
num=gets
num.chop!
if num == '0000' then
win=true
break
end
for n in (0..3)
for m in (0..3)
if num[n]==$a4[m] then
if n==m then
$A+=1
next
end
$B+=1
end
end
end
puts "A=#{$A},B=#{$B}"
times-=1
if $A == 4 then
win=true
break
end
end
if win then
puts "恭喜您,只用了#{8-times}次机会猜中。答案#{$a4}"
else
puts "很遗憾您没有猜中,正确答案是#{$a4}!"
end
puts " |GAME|\n |OVER|"
相关阅读:
- 有关Ruby的英文书籍 (drive2me, 2007-8-03)
- Ruby开发专家级人物的社区网站 (drive2me, 2007-8-04)
- Ruby的附加库 (drive2me, 2007-8-04)
- 又建了一个圈子 (drive2me, 2007-8-05)
- 社区开源项目 (skyover, 2007-8-06)
- 累死我了,刚才在Fedora下装了个redmine. (skyover, 2007-8-18)
- C/Ruby data type conversion functions and macros (rushairer, 2007-8-23)
- 用Rails制作Google sitemap (skyover, 2007-8-26)
- 用method_missing来兼容旧数据库 (skyover, 2007-8-26)
- 在Ruby中使用SQLServer (skyover, 2007-8-27)
导入论坛
收藏
分享给好友
推荐到圈子
管理
举报
TAG:
ruby
猜数字