Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #---------
- # name: NumberGuess.rb
- # Solution A
- #
- #----------------
- class Screen
- def cls
- puts ("\n" * 30)
- puts "\a"
- end
- def pause
- STDIN.gets
- end
- end
- class Game
- $gameNumber = 0 #class variable to store the no. of games
- def display_instruction
- puts "Instructions:\n\n"
- puts "This game randomly generates a number from 1 to 1000 and "
- puts "challenges you to identify it in as few guesses and possible "
- puts "Numbers between 1 and 1000 are valid inputs only"
- end
- def display_greeting
- Console_Screen.cls
- print "\t\t Welcome to the Ruby Number Guessing Game!"
- print "\n\n\n\n\n\n\n\n\n\n\n\n\ Press Enter to "
- print "continue."
- Console_Screen.pause
- end
- def generate_number
- return randomNo = 1 + rand(1000)
- end
- def play_game
- number = generate_number
- $gameNumber +=1 #Increment the variable by 1 everytime a no. is generated
- $guesses = 0
- loop do
- #Console_Screen.cls
- print "\nEnter your guess and press the enter key: "
- $guesses +=1
- reply = STDIN.gets
- reply.chop!
- reply = reply.to_i
- if reply < 1 or reply > 1000 then
- puts "\n\n\n\n\n\n\n"
- puts "Invalid Input"
- puts "\n\n\n\n"
- puts "Valid inputs are numbers between 1 and 1000 only"
- redo # redo the current iteration of the loop
- end
- if reply == number then
- Console_Screen.cls
- print "You have guessed the number! Press Enter to continue."
- Console_Screen.pause
- break
- elsif reply < number then
- Console_Screen.cls
- print "Your guess is too low! Press enter to continue."
- Console_Screen.pause
- elsif reply > number then
- Console_Screen.cls
- print "Your guess is too high! Press enter to continue."
- Console_Screen.pause
- end
- end
- end
- def display_credits
- Console_Screen.cls
- puts "Thanks you for playing the Number Guessing Game #{$gameNumber} times with #{$guesses} guesses!!" # Display number of times game playedon the screen
- puts "Average guesses per game #{$guesses.to_i/$gameNumber.to_i}"
- end
- $noRight = 0
- Console_Screen = Screen.new
- SQ = Game.new
- SQ.display_greeting
- answer = ""
- loop do
- Console_Screen.cls
- print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
- answer = STDIN.gets
- answer.chop!
- break if answer == "y" || answer == "n"
- end
- if answer == "n"
- Console_Screen.cls
- puts "Perhaps another time.\n\n"
- else
- Console_Screen.cls
- SQ.display_instruction
- print "\n\n\n\n\n"
- Console_Screen.pause
- loop do
- SQ.play_game
- Console_Screen.cls
- print "Would you like to play again? (y/n): "
- playAgain = STDIN.gets
- playAgain.chop!
- break if playAgain == "n"
- end
- SQ.display_credits
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement