当用户写入停止并在循环中启动新号码时,如何使循环结束?
问题描述:
当用户写入停止时,如何让以下循环结束,否则如果它们正确回答,它如何再次调用该方法以便猜测的数字不同? 游戏的想法是用户试图从课程中获得数字,如果他们得到正确的答案,那么游戏会询问他们是否想猜测由课程生成的新数字,或者他们是否想停止;如果是这样,他们写停止,游戏结束。 在此先感谢帮助当用户写入停止并在循环中启动新号码时,如何使循环结束?
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
答
这是我为此问题生成的代码解决方案。试试吧,看看它是否是根据自己的喜好:
https://gist.github.com/BKSpurgeon/1a2346e278836d5b4448424cb93fd0e9
class NumberGuessingGame
def initialize
welcome
end
def welcome
puts "Welcome to Guess the Number \n Human VS Machine"
end
def guess
loop do
@number= rand(0..9)
p "Write a number between 0 and 9"
numer = -1
while numer != @number
numer = gets.chomp.to_i
if numer<@number
p "Too low"
elsif numer>@number
p "Too high"
elsif numer == @number
p "You got it!"
puts "WOOOOW!! Very Impresive. Want to defeat the machine again? If not write stop otherwise press any key."
break
end
end
answer = gets.chomp # The Critical Line to break out of the Loop is here:
break if answer.downcase == "stop"
end
end
end
,你会这样称呼它:
g = NumberGuessingGame.new
g.guess
如果你写的“一站式”逃逸。我对功能做了微小的修改。如果检测到“停止”应答,则循环中断。这是关键线。
我看不到一个很好的理由,客户端代码做这种类型的事情:
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
最好要让一类的所有方法来完成所有的工作 - 你不应该必须从课外写'欢迎游戏等' - 这应该是NumberGuessingGame课程的责任。
希望这有助于。
+0
非常感谢!这完全解决了我的问题 –
检查此https://stackoverflow.com/questions/1402757/how-to-break-out-from-a-ruby-block。谈论打破循环。 – Wax
正常的做法是使用'loop do end',如果一切正常,则跳出循环('break'或'break x')。换句话说,假设你将不得不重复,除非没有必要这样做。 –