我一直在试图弄清楚如何做到这一点,以便用户只能为这个简单的高/低猜谜游戏输入 1 到 100 之间的正整数。我想要它,所以除了 1 到 100 之间的整数之外的任何东西都会通知用户他们不能对所有输入都这样做。有没有一种简单的方法可以做到这一点?
我现在拥有的:
count=0
play = true
while play == true
print "Give me a random number between 1 and 100: "
max= gets.to_i
num= rand(max)
puts "Now guess between 1 and " + max.to_s +
"."
print "What is your guess?: "
guess=gets.to_i
while guess != num && play != false
if guess > num
print "Too high! "
guess=gets.to_i
count+=1
elsif guess < num
print "Too low! "
guess=gets.to_i
count+=1
else
break
end
end
puts "Good Job! You figured it out in " + count.to_s + " attempts!"
print "Want to try again? y/n "
answer=gets.chomp!
if answer == 'n'
play = false
break
end
if
answer == 'y'
play = true
end
end
puts "Maybe next time..."