红宝石猜谜游戏 w 'Loop Do'



我通过Ruby创建了一个猜测游戏,我相信我的代码结构已经关闭。输入"作弊"时,您将获得随机数,然后要求再次输入。再次键入时,它说随机数不正确,并且始终默认为我的" elseif"第45行。

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

这是我在终端中得到的响应

Let's get started...
Cheat
The random number is 96 you CHEATER!! Go ahead and type it in...
96
Thats not it.
 96 is greater than the random number.
   The random number is divisible by 8.
Try again: 

问题在这里:

puts = "You win cheater!"

您将字符串"You win cheater!"分配给了名为puts的本地变量。将其更改为解决问题:

puts "You win cheater!"

您可能还想在该行之后放置break


顺便说一句,此模式:

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,这意味着puts的返回值(始终是nil(被用作条件,就像您已经写了elsif puts "..."一样。p>如果您习惯始终将条件与if/elsif相同的线上,那么您的眼睛会习惯它,并且这样的错误会跳出来。

最新更新