Skip to content

Instantly share code, notes, and snippets.

@FrancoB411
Created May 26, 2011 14:21
Show Gist options
  • Select an option

  • Save FrancoB411/993237 to your computer and use it in GitHub Desktop.

Select an option

Save FrancoB411/993237 to your computer and use it in GitHub Desktop.
number_guesser.rb
MAX_NUMBER = 50
MIN_NUMBER = 0
GUESS_LIMIT = 5
@computers_number = rand(MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER
def over_guess_limit?
if @guess_count > GUESS_LIMIT
puts "You're over the guess limit!"
true
end
end
def guess_valid?
!over_guess_limit? && !quit?
end
def quit? #checks to see if player has commanded game to quit.
@command == "quit" || @name == "quit"
end
def abort #aborts the game
puts "bye, see ya later"
end
def game #tells you if your guess it too low, too high
loop do
puts "What is your guess?"
@command = gets.chomp
@guess_count += 1
if guess_valid?
guess = @command.to_i
else
abort
break
end
if guess < @computers_number
puts "Your guess was too low!"
elsif guess > @computers_number
puts "Your guess was too high!"
else
success
break
end
end
end
def start_game #starts the game, game timer, & guess_count
if quit?
abort
return
end
puts "Hello #{@name}. I'm guessing a number between #{MIN_NUMBER} and #{MAX_NUMBER}."
puts "You need to guess the number. I will tell you if you are too low or too high."
@start_time = Time.now
@guess_count = 0
game
end
def greeter #Gets player's name, calls start_game
puts "Hello player. What is your name?"
@name = gets.chomp
start_game
end
def success #success message
puts "You got the number right! It was #{@computers_number}."
game_length
abort
end
def game_length #times the duration of the game
game_duration= (Time.now - @start_time).to_i
puts "It took you #{game_duration} seconds to guess!"
end
greeter
@charissa

charissa commented May 26, 2011 via email

Copy link
Copy Markdown

@FrancoB411

Copy link
Copy Markdown
Author

Added Pascal Levy-Garboua's timer to give you the duration of the time it took you to guess the numbers.

@FrancoB411

Copy link
Copy Markdown
Author

Re-factored for clarity. Added the ability to limit the number of player's guesses.

@FrancoB411

Copy link
Copy Markdown
Author

Removed a good number of code lines thanks to Peter Cooper's suggestions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment