Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Last active November 16, 2015 20:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@mattantonelli
Copy link
Author

Try it out here!

Sample play:

You have 10 guesses.
The code is 4 digits between 1 and 6.
o: A digit matches  x: A digit matches, but is in the wrong place)

Can you guess the code?

Enter your guess: 1111
o---
Enter your guess: 1222
x---
Enter your guess: 3133
ox--
Enter your guess: 4314
xx--
Enter your guess: 5531
ox--
Enter your guess: 6613
oxxx
Enter your guess: 6136
xxxx
Enter your guess: 1366
oxxx
Enter your guess: 1663
ooxx
Enter your guess: 3661

You win!
Press enter to play again.

@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