Created
May 26, 2011 14:21
-
-
Save FrancoB411/993237 to your computer and use it in GitHub Desktop.
number_guesser.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Removed a good number of code lines thanks to Peter Cooper's suggestions.