lamchau
1/5/2015 - 2:08 AM

guessing-game.rb

def message(message, tries)
  if tries > 0
    puts message + " Please try again. You have #{tries} tries remaining."
  else
    puts "Game over! :("
  end
end

min = 1
max = 100
guess = rand(min..max)
tries = 30

#Welcome the player to the game.  Let them know who created the game.
print "Welcome to the Secret Number game, created by [redacted]!\n\n"

#Ask for the player's name then personally greet them by printing to the screen, "Hi player_name!"
print "What is your name? "
$stdout.flush
player_name = gets.strip

print "Hi #{player_name}!\n"

#Let the player know they must guess a number between 1 and 10 and that they only have 3 tries to do so.
print "Please guess a number between #{min} and #{max}.  You only have #{tries} tries to do so.\n"

(tries - 1).downto(0) do |tries|
  input = Integer(gets.strip) rescue -1
  if input > guess
    message("Sorry, you've guessed too high! ", tries)
  elsif input < guess
    message("Sorry, you've guessed too low! ", tries)
  elsif input == guess
    puts "Congratulations! You have won the game!"
    break
  end
end