/ Published in: Ruby
The "Mastermind" Game, Digitized
Expand |
Embed | Plain Text
#!/usr/bin/env ruby # Codebreaker by Solomon Wise is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License. # http://creativecommons.org/licenses/by-nc-sa/3.0/us/ # Details: # Text Editors Used: # cmd edit # Komodo Edit # Languages Used: # Ruby 1.9.3 # 1.9.3-p125 # Operating Systems Used: # Windows 7 # Mac OS X Lion # Date First Build Finished: # April 22, 2012 # 3:55 P.M. # Base class for the sequence begin system("clear") rescue system("cls") end class Sequence def exc code, str puts str, code exit code end def initialize # Logs difficulty level puts "Type the difficulty level you would like: 1, 2, 3, 4, or 5" @level = gets; @level = @level.to_i # Exits if level is more than 6 if @level > 6 sexit 1, "Invalid Difficulty" end end def create_code # Creates the code randomly rnum = Random.new @code = rnum.rand(1000...@level*2000).to_s if @level == 5 # Adds an extra digit to make it more difficult @code += "#{rand(10)}" end # Exits program if @level is a string if @code.length > 5 sexit 1, "Invalid Difficulty" end end def prompt @retstring = "" # Sets number of guesses guesses = 0 while guesses < 4 print "Enter a guess: " @guess = gets # Iterates over the code, matching it with the guess @code.length.times do |x| if @code[x] == @guess[x] @retstring += "+" else @retstring += "-" end puts @retstring sleep(1) x += 1 end # Prompts user for hint puts "Would you like a hint? Type 'hint' to get a hint" hint = gets # Matches hint to RegEx match = hint =~ /(h|H)(i|I)(n|N)\w/ unless match == nil # Gives hint if the match is true j = rand(@level*2) puts "#{@code[j]} is in the code" end guesses += 1 # Prints correct if the user gets the code right if @retstring == "++++" puts "Correct!" break end @retstring = "" end end def print_code # Prints the code print "#{@code} was the code" end end seq = Sequence.new seq.create_code seq.prompt seq.print_code
You need to login to post a comment.
