我遇到了让游戏重启的问题:
你没有更多的猜测了 你赢了比赛
我使用了while循环,但是通过函数/方法访问它有麻烦。
编辑:
所以基本上玩家有3次尝试猜测秘密号码。如果他们赢了,他们会被问到是否要重新开始比赛。如果他们输了,他们也会被问到是否要重试。
这是代码:
先谢谢你们
def get_input
gets.chomp
end
puts "Welcome to the Secret Number Game! Please tell me your name"
player_name = get_input
puts "Welcome #{player_name}!"
puts "Guess a number between 1 - 10. You only have 3 attempts!"
secret_number = 1 + rand(10)
restart = true
while restart
def playAgain ( restart )
puts "Would you like to play again? (y/n)"
answer = get_input
if answer == "n"
restart = false
end
end
def guess_check ( player_input, secret_number )
if player_input > secret_number
puts "Wrong, sorry! Too high!"
elsif player_input < secret_number
puts "Wrong, sorry! Too low!"
else
puts "Congratulations, you've guessed the secret number! #{[secret_number]}"
playAgain ( restart )
end
end
############################## START GAME ###########################################
guesses = []
attempts = 3
while attempts
attempts = attempts - 1
if attempts == -1
puts "Sorry, you have no more tries"
playAgain ( restart )
else
puts "Guess the secret number (You have #{attempts} tries left):"
end
player_input = get_input.to_i
guesses.push ( player_input )
guess_check( player_input, secret_number )
puts "You've guessed - #{guesses}"
end
playAgain ( restart )
end
答案 0 :(得分:1)
0
是真实的,而不是虚假的,与大多数语言相矛盾。要打破while循环,应该明确检查它是否大于零:
- while attempts
+ while attempts > 0
或更多rubyish:
3.downto(0) do |attempts|
...
end
<强> UPD 强>
重启的部分。您将获得playAgain
中定义的本地重新启动变量。谷歌用于ruby范围,简而言之:函数中的局部变量在这个函数的范围之外是不可见的;参数按值传递给函数。也就是说,在restart = false
内定义playAgain
根本没有任何意义,因为局部变量在函数范围内死亡。可能的解决方案是声明实例变量@restart
。在这种情况下,您不需要将其作为参数传递。但是,完成任务的最合理方法是从playAgain
返回一个布尔值:
def playAgain
puts "Would you like to play again? (y/n)"
answer = get_input
answer != "n" # return a boolean from the function in last statement
end
然后整个范围看起来像:
def playAgain
puts "Would you like to play again? (y/n)"
answer = get_input
answer != "n" # return a boolean from the function in last statement
end
def guess_check ( player_input, secret_number )
if player_input > secret_number
puts "Wrong, sorry! Too high!"
elsif player_input < secret_number
puts "Wrong, sorry! Too low!"
else
puts "Congratulations! Result: #{secret_number}"
end
player_input == secret_number # return true on success
end
# let’s go!
loop do # main loop
guesses = []
3.downto(1) |attempts| # 3 attemts
puts "Guess the secret number (You have #{attempts} tries left):"
player_input = get_input.to_i
guesses.push(player_input)
# you have to return true/false from guess check
# and rerun the topmost loop if success
# see the trick with logical and below:
# on normal execution the loop will return it’s initial
# (3 in this particular case)
# on successful guess is will break, returning false
break false if guess_check(player_input, secret_number)
puts "You've guessed - #{guesses}"
end && puts "Sorry, you have no more tries"
break unless playAgain # will break a topmost loop unless `y` input
end