Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Last active November 16, 2015 20:47
Show Gist options
  • Save mattantonelli/17797ffc1e08378f6973 to your computer and use it in GitHub Desktop.
Save mattantonelli/17797ffc1e08378f6973 to your computer and use it in GitHub Desktop.
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
@TrevorS
Copy link

TrevorS commented Nov 12, 2015

@mattantonelli, dude your code looks great.

@mattantonelli
Copy link
Author

@TrevorS Thanks, dude!

The only thing I'm really unhappy with is this. I would really like to find a cleaner way of clearing out the guess each round. @code_digits.dup didn't seem to work like I wanted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment