Last active
November 16, 2015 20:47
-
-
Save mattantonelli/17797ffc1e08378f6973 to your computer and use it in GitHub Desktop.
This file contains 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
class Mind | |
def initialize | |
@random = Random.new | |
generate_code | |
end | |
def play | |
puts "Can you guess the code?\n\n" | |
10.times do | |
print 'Enter your guess: ' | |
guess = gets.chomp | |
if guess.match(/exit|quit/) | |
puts 'Oh, okay then...' | |
return | |
end | |
while !guess.match(/^[1-6]{4}$/) | |
puts "Your guess should be 4 digits between 1 and 6. Try again." | |
guess = gets.chomp | |
end | |
if guess == @code | |
puts "\nYou win!" | |
return | |
else | |
response = guess_code(guess) | |
puts response | |
end | |
end | |
puts "\nYou lose!" | |
puts "The code was #{@code}." | |
end | |
private | |
def generate_code | |
@code = '' | |
@code_digits = Array.new(7) | |
7.times do |i| | |
@code_digits[i] = Hash.new(0) | |
end | |
4.times do | |
digit = @random.rand(1..6) | |
@code_digits[digit][:count] += 1 | |
@code << digit.to_s | |
end | |
end | |
def guess_code(guess) | |
correct = misplaced = 0 | |
guess.split('').each_with_index do |digit, i| | |
if @code[i] == digit | |
@code_digits[digit.to_i][:correct] += 1 | |
elsif @code.match(digit) | |
@code_digits[digit.to_i][:present] += 1 | |
end | |
end | |
@code_digits.each do |h| | |
correct += h[:correct] | |
misplaced += [h[:count] - h[:correct], h[:present]].min | |
h[:correct] = h[:present] = 0 | |
end | |
"#{'o' * correct + 'x' * misplaced}".ljust(4, '-') | |
end | |
end | |
puts "You have 10 guesses.\nThe code is 4 digits between 1 and 6.\n" + | |
"o: A digit matches x: A digit matches, but is in the wrong place)\n\n" | |
while true | |
mastermind = Mind.new | |
mastermind.play | |
puts "Press enter to play again.\n" | |
gets | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try it out here!
Sample play: