当用户写停止时,如何使以下循环结束;否则,如果他们正确回答,如何再次调用该方法以使猜测的数字不同? 游戏的想法是用户试图从类中获取数字,如果他们正确地得到它,那么游戏会询问他们是否想要猜测该类产生的新数字或者他们是否想要停止;如果是这样,他们会写停下来,游戏结束。 在此先感谢您的帮助
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
答案 0 :(得分:-2)
这是我为此问题制作的代码解决方案。试一试,看看是否符合你的喜好:
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类的责任。
希望这会有所帮助。