from itertools import product class MasterMindAI(object): #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def calcPossibleValues(possibleValueString, repeatTime): return [''.join(p) for p in product(possibleValueString, repeat=repeatTime)] #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def calcResultValues(pegListSize): return [(right, wrong) for right in range(pegListSize+1) for wrong in range((pegListSize + 1) - right) if not (right == (pegListSize - 1) and wrong == 1)] #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def attempt(S, pegList, stringPegList, results, possible, first=False): if first: if (len(pegList) % 2) == 0: a = pegList[0] * int(len(pegList)/2) + pegList[1] * int(len(pegList)/2) else: a = pegList[0] * int((len(pegList)+1) / 2) + pegList[1] * int((len(pegList)-1) / 2) elif len(S) == 1: a = S.pop() else: a = max(possible, key=lambda x: min(sum(1 for p in S if MasterMindAI.score(p, x, stringPegList) != res) for res in results)) return a #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def score(secret, other, stringPegList): first = len([speg for speg, opeg in zip(secret, other) if speg == opeg]) return first, sum([min(secret.count(j), other.count(j)) for j in stringPegList]) - first #---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def updatePossibilties(possibleValues, blacksAndWhites, userGuess, stringPegList): possibleValues.difference_update(set(p for p in possibleValues if MasterMindAI.score(p, userGuess, stringPegList) != blacksAndWhites))