Skip to content

Instantly share code, notes, and snippets.

@lukaspili
Created November 9, 2012 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaspili/4046191 to your computer and use it in GitHub Desktop.
Save lukaspili/4046191 to your computer and use it in GitHub Desktop.
Minor program 1 : Guess the number
# Guess the number, minor program written in Ruby by Lukasz Piliszczuk (12007707)
MAX_TRIES = 10 # We define the max number of tries in a constant
puts "Welcome to the game Guess the number, written in ruby"
puts "Guess the number between 0 et 100, and you have #{MAX_TRIES} tries to do that"
guess_number = rand(0..100) # We use the rand() function to generate a pseudo-random number between 0 and 100 (both included)
guess_tries = 1 # The number of tries for the user, initialized at 1 because at the beginning it will be the first try
# Main game loop which will stop after the user found the number or exceed the max allowed tries
while guess_tries <= MAX_TRIES do
puts "This is your #{guess_tries} try, guess the number"
# Get the user input with gets.chomp, which returns the input in a String format
# If the user enters a valid integer then the Integer() method will convert the string to the associated Integer
# If not, the Integer() method will throw an exception which will be catched in the rescue block
begin
number = Integer(gets.chomp)
rescue
puts "You must enter a valid number between 1 and 100, try again"
next # We use the next function to return to the beginning of the loop, to ask the user to enter a new valid number
end
# If the user's number is the same than the number to guess, we exit the main loop
break if number == guess_number
# If not we tell the user if his number is too high or too low than the number to guess
if number > guess_number
puts "Too high, try again"
else
puts "Too low, try again"
end
# Finally we increment the number of tries for the user
guess_tries += 1
end
# At this point the game is finished because the user exceeded the max number of attempts or because he found the number
if number == guess_number
puts "Congrats, you found the number #{guess_number} in #{guess_tries} try"
else
puts "Sorry the number to find was #{guess_number}, maybe next time"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment