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

时间:2017-06-23 16:45:23

标签: ruby terminal atom-editor

我通过Ruby创建了一个猜谜游戏,我相信我的代码结构已经关闭了。输入' Cheat'时,会给您随机编号,然后再要求输入。再次键入时,它表示随机数不正确,并且始终默认为我的' 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: 

1 个答案:

答案 0 :(得分:0)

问题在于:

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之后添加条件,或在您打算使用elsif时使用else,这意味着puts的返回值(始终为{{1} }}被用作条件,就像你写了nil

如果你养成了将条件放在与elsif puts "..." / if相同的行上的习惯,你的眼睛就会习惯它,这样的错误就会跳出来。

相关问题