【发布时间】:2017-06-14 05:24:50
【问题描述】:
当用户写停止时,如何使以下循环结束,否则如果他们回答正确,如何再次调用该方法以使要猜测的数字不同? 游戏的想法是用户尝试从班级中获取数字,如果他们得到正确,那么游戏会询问他们是否想猜测班级生成的新数字或者他们是否想停止;如果是,他们会写停下来,游戏就结束了。 提前感谢您的帮助
class NumberGuessingGame
#clase NumberGuessingGame
def initialize
#metodo que inicia
@number= rand(0..9)
#number es igual a un numero random entre 0 y 9
end
def guess(numer)
#metodo guess que dice que hay una condicion dada por el usuario, si no se da entonces se pide que el usuario la escriba manualmente
if numer<@number
#si el numero es mas pequeño que el numero entonces "Too low"
"Too low"
elsif numer>@number
#si el numero es mayor a el numero entonces "too high"
"Too high"
elsif numer == @number
#si el numero es igual al numero random que pone la computadora entonces "you got it!"
"you got it!"
end
end
end
game = NumberGuessingGame.new
# Pruebas
a = ""
p "Welcome to Guess the Number"
p "Human VS Machine"
while a != "Stop"
x = ""
while x != "you got it!"
p"Write a number between 0 and 9"
y = gets.chomp.to_i
p x = game.guess(y)
end
p "WOOOOW!! Very Impresive. Want to defeat the machine again? If not write
stop or guess the new number"
NumberGuessingGame
a = gets.chomp
end
【问题讨论】:
-
查看stackoverflow.com/questions/1402757/…。谈论打破循环。
-
正常的方法是使用
loop do <your code> end,如果一切正常,然后跳出循环(break或break x)。换句话说,假设你必须重复,除非没有必要这样做。
标签: ruby