Ruby 红宝石猜谜游戏w';循环Do';

Ruby 红宝石猜谜游戏w';循环Do';,ruby,terminal,atom-editor,Ruby,Terminal,Atom Editor,我通过Ruby创建了一个猜谜游戏,我相信我的代码结构是错的。输入“作弊”时,系统会给你随机数,然后要求你再次输入。当再次输入时,它会显示随机数不正确,并且在第45行中总是默认为my'elseif' puts "Hey! I'm Sam. What's your name?" name = gets puts "Welcome #{name}. Thanks for playing the guessing game. I've chosen a number between 1-100. You

我通过Ruby创建了一个猜谜游戏,我相信我的代码结构是错的。输入“作弊”时,系统会给你随机数,然后要求你再次输入。当再次输入时,它会显示随机数不正确,并且在第45行中总是默认为my'elseif'

puts "Hey! I'm Sam. What's your name?"
name = gets
puts "Welcome #{name}. Thanks for playing the guessing game.
I've chosen a number between 1-100.
You'll have 10 tries to guess the correct number.
You'll also recieve a hint when you're guess is wrong.
If you feel like being a big ol cheater, type 'Cheat'.
Let's get started..."

random_number = rand(1...100)
Cheat = random_number
counter = 10

loop do
 break if counter == 0
 divisor = rand(2...10)
 guess = gets.chomp
  break if guess.to_i == random_number
 counter -= 1
 if
   guess == random_number
   puts 'You guessed the right number! You win!'
 end
 if counter < 4
   puts "You can go ahead and cheat by typing 'Cheat'..."
 end
  if guess.to_s.downcase.eql? "cheat"
    puts "The random number is #{random_number} you CHEATER!! Go ahead and type it in..."
    guess = gets.chomp
    puts = "You win cheater!"
  end
 if
     guess.to_i < random_number
     puts 'Ah shucks, guess again!'
     guess = gets.chomp
 elsif
     guess.to_i > random_number
     puts 'Too high, guess again!'
     guess = gets.chomp
 end

 if random_number % divisor == 0
   puts "Thats not it.\n #{guess} is #{guess.to_i > random_number ? 'less' : 'greater'} than the random number.
   The random number is divisible by #{divisor}.\nTry again: "
 elsif
   puts "That's not the random number.\n #{guess} is #{guess.to_i > random_number ? 'less' : 'greater'} than the random number.
   The random number is NOT divisible by #{divisor}.\nTry again: "
 end
end

if counter > 0
  puts "The number is #{random_number}! You win!"
else
  puts "You lose! Better luck another time."
end
问题在于:

puts = "You win cheater!"
您正在将字符串
“youwin cheater!”
分配给名为
put
的局部变量。将其更改为此可修复此问题:

puts "You win cheater!"
您可能还需要在该行后面加一个
分隔符


另一方面,这种模式:

loop do
  break if counter == 0
  # ...
end
…最好表述为:

while counter > 0
  # ...
end
…或:

until counter == 0
  # ...
end

此外,您应该始终将
if
/
elsif
/whathaveyou的条件与
if
等放在同一行。为什么?因为如果你不这样做,你会得到这样的错误:

if random_number % divisor == 0
  # ...
elsif
  puts "..."
end
你能发现虫子吗?您忘记在
elsif
之后添加条件,或者在打算使用
else
时使用了
elsif
,这意味着
put
(始终为
nil
)的返回值被用作条件,就像您编写了
elsif-put“…”


如果你养成习惯,总是把条件放在与
If
/
elsif
相同的行上,你的眼睛会习惯的,这样的错误会跳出来的。

谢谢!多亏了你,我注意到了一些错误。谢谢你的帮助!