Ruby中的简单高低游戏

时间:2011-01-31 14:44:54

标签: ruby irb

我正在尝试编写一个简单的高低程序,输出如下:

$ ./highlow.rb 
Please tell me the max value of the random number: 100
Ok. The random number is generated between 1 and 100.  
Make your guess: 50
That's too low.  Guess again: 75
That's too high.  Guess again: 63
That's too low.  Guess again: 68
Correct!  You guessed the answer in 4 tries!
Would you like to play again? no
OK. Goodbye.
$

这是我的代码,但我在某处出错了。它似乎有时工作:


count=0
play = true
while play = true 

print "Please tell me the max value of the random number: "
    max= gets.to_i
    num= rand(max)
puts "Ok. The random number is generated between 1 and " + max.to_s + 
"."
print "Make your guess: "
    guess=gets.to_i

    while guess != num && play != false 
        if guess > num
            print "That's too high. Guess again: "
            guess=gets.to_i
            count+=1
        end

        if guess < num
            print "That's too low. Guess again: "
            guess=gets.to_i
            count+=1
        else
            break
        end
end

puts "Correct! You guessed the answer in " + count.to_s + " tries!" print "Would you like to play again? "

answer=gets.chomp! if answer == 'n' play = false break end

if 
    answer == 'y'
    play = true
end 

end puts "OK. Goodbye"

有什么建议吗?我哪里错了?

1 个答案:

答案 0 :(得分:2)

我认为你的问题(我能看到的问题)是数字检查代码。

如果guess大于num,则第一个if语句将执行,但第二个将重定向到else,从而突破循环。

您需要使用elsif。尝试将其更改为:

    if guess > num
        print "That's too high. Guess again: "
        guess=gets.to_i
        count+=1
    elsif guess < num
        print "That's too low. Guess again: "
        guess=gets.to_i
        count+=1
    else
        break
    end