Master Mind - Solution

Taken from Stack Overflow, modified by Jens Hahn

http://stackoverflow.com/questions/15648407/python-mastermind-game-troubles


In [ ]:
import random

def main():
    print('>> New game started.\n>> Good luck!\n')
    answer = generateAnswer()
    while True:
        userGuess = getUserGuess()
        if userGuess == answer:
            print('>> Congratulations, you won!')
            return
        else: 
            print('>> The answer you provided is incorrect.\n>> Perhaps this hint will help you: ')
            giveFeedback(answer, userGuess)

def generateAnswer():
    digits = [str(x) for x in range(10)]
    answer = ''
    for i in range(4):
        digit = random.sample(digits, 1)[0]
        digits.remove(digit)
        answer += digit
    return answer

def getUserGuess():
    while True:
        guess = input('>> Please enter a 4-digit number: ').strip()
        if len(guess) != 4:
            continue
        guessIsValid = True
        for x in guess:
            if guess.count(x) != 1 or ord(x) not in range(48, 58):
                guessIsValid = False
                break
        if guessIsValid:
            return guess
    
def giveFeedback(answer, guess):
    for i in range(4):
        if guess[i] == answer[i]:
            print('X', end='')
            continue
        if guess[i] in answer:
            print('O', end='')
            continue
        print('-', end=''),
    print('\n')

if __name__ == '__main__':
    main()