Simple Word Game Loop

Proto
# Guessing Game
# 1.0
# by Proto


words = ["cat", "snake", "wolf", "giraffe", "elephant"]

picked = words.sample

puts "Welcome to the guessing game! I'm thinking of an animal. 
It's a #{picked.length} letter word. Can you guess what it is?"

try = gets.chomp

while try != picked 
    puts "Try again."
    try = gets.chomp
    if try == picked
        puts "You win!"
        break
    end
end

It works but only sometimes and I get no errors from running it. The problem is that if I get the guess right on the first try, the game doesn't seem to enter the loop at all (it doesn't tell me "You win!"), it just exits the program. But that result is inconsistent. If i immediately restart and get it right sometimes it will tell me that I won. Sometimes it works, sometimes it doesn't. There seems to be something wrong with my loop or syntax, but I can't see it. Any help appreciated. Thanks.

mu 無

Remove the if block and put the "You win!" statement outside the while statement. Reason being, eventually, in your current logic the player will win, and only then the logic breaks, so you might as well move it out.

while try != picked 
    puts "Try again."
    try = gets.chomp
end

puts "You win!"

The reason the "You win!" is not printed in your existing code is that the loop is never entered when try == picked initially, because that is the condition in the while loop. The above changes take care of that scenario as well.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related