Posted By

slmnwise on 04/23/12


Tagged

ruby game


Versions (?)

CodeBreaker


 / Published in: Ruby
 

The "Mastermind" Game, Digitized

  1. #!/usr/bin/env ruby
  2. # Codebreaker by Solomon Wise is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.
  3. # http://creativecommons.org/licenses/by-nc-sa/3.0/us/
  4. # Details:
  5. # Text Editors Used:
  6. # cmd edit
  7. # Komodo Edit
  8. # Languages Used:
  9. # Ruby 1.9.3
  10. # 1.9.3-p125
  11. # Operating Systems Used:
  12. # Windows 7
  13. # Mac OS X Lion
  14. # Date First Build Finished:
  15. # April 22, 2012
  16. # 3:55 P.M.
  17. # Base class for the sequence
  18. begin
  19. system("clear")
  20. rescue
  21. system("cls")
  22. end
  23. class Sequence
  24. def exc code, str
  25. puts str, code
  26. exit code
  27. end
  28. def initialize
  29. # Logs difficulty level
  30. puts "Type the difficulty level you would like: 1, 2, 3, 4, or 5"
  31. @level = gets; @level = @level.to_i
  32. # Exits if level is more than 6
  33. if @level > 6
  34. sexit 1, "Invalid Difficulty"
  35. end
  36. end
  37. def create_code
  38. # Creates the code randomly
  39. rnum = Random.new
  40. @code = rnum.rand(1000...@level*2000).to_s
  41. if @level == 5
  42. # Adds an extra digit to make it more difficult
  43. @code += "#{rand(10)}"
  44. end
  45. # Exits program if @level is a string
  46. if @code.length > 5
  47. sexit 1, "Invalid Difficulty"
  48. end
  49. end
  50. def prompt
  51. @retstring = ""
  52. # Sets number of guesses
  53. guesses = 0
  54. while guesses < 4
  55. print "Enter a guess: "
  56. @guess = gets
  57. # Iterates over the code, matching it with the guess
  58. @code.length.times do |x|
  59. if @code[x] == @guess[x]
  60. @retstring += "+"
  61. else
  62. @retstring += "-"
  63. end
  64. puts @retstring
  65. sleep(1)
  66. x += 1
  67. end
  68. # Prompts user for hint
  69. puts "Would you like a hint? Type 'hint' to get a hint"
  70. hint = gets
  71. # Matches hint to RegEx
  72. match = hint =~ /(h|H)(i|I)(n|N)\w/
  73. unless match == nil
  74. # Gives hint if the match is true
  75. j = rand(@level*2)
  76. puts "#{@code[j]} is in the code"
  77. end
  78. guesses += 1
  79. # Prints correct if the user gets the code right
  80. if @retstring == "++++"
  81. puts "Correct!"
  82. break
  83. end
  84. @retstring = ""
  85. end
  86. end
  87. def print_code
  88. # Prints the code
  89. print "#{@code} was the code"
  90. end
  91. end
  92. seq = Sequence.new
  93. seq.create_code
  94. seq.prompt
  95. seq.print_code

Report this snippet  

You need to login to post a comment.