Skip to content

Instantly share code, notes, and snippets.

@jonboiser
Created April 3, 2015 19:17
Show Gist options
  • Save jonboiser/f042d9f4df08fafc2891 to your computer and use it in GitHub Desktop.
Save jonboiser/f042d9f4df08fafc2891 to your computer and use it in GitHub Desktop.
Beginning of Mastermind project.
# mastermind implementation
from itertools import *
# functions for AI
# 1. calculate the response for a guess, given the true code
def responseToGuess(guess, true_code):
N = len(guess)
assert N == len(true_code), "Guess is not the same length as true code."
correct_pos = 0
correct_col = 0
# Storage for code characters not matched exactly.
true_code_notmatched = []
guess_notmatched = []
# Number of correct color + position. Matches are discarded from copies.
for i in range(N):
if guess[i] == true_code[i]:
correct_pos = correct_pos + 1
else:
true_code_notmatched.append(guess[i])
guess_notmatched.append(true_code[i])
# Examine the remainder for match on color only.
for x in true_code_notmatched:
if x in guess_notmatched:
correct_col = correct_col + 1
return dict(position = correct_pos, color = correct_col)
# 2. Enumerate all possible codes at the beginning of the game as reference.
def allCodes(code_length):
assert code_length > 0, "Codes must have at least 1 symbol."
return list(product(range(code_length), repeat = code_length))
S = allcodes(6)
# 3.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment