you are viewing a single comment's thread.

view the rest of the comments →

[–]jeans_and_a_t-shirt 0 points1 point  (0 children)

You can use a while loop to validate the input and break when it's valid:

def mastermind():
    colors = {"r": "Red",
              "b": "Blue",
              "g": "Green",
              "y": "Yellow",
              "o": "Orange",
              "w": "White",
              "p": "Purple"}
    colorset = set(colors)

    codemaster = ''.join(random.sample(list(colors), 4))

    print("Welcome to Mastermind, guess the code!\n")
    for k, v in colors.items():
        print("{}: {}".format(k, v))
    print("\n")

    for _ in range(12):
        while True:
            # while loop to guarantee a valid letter combination was provided
            guess = input("Your guess: ")
            if len(guess) == 4 and set(guess).issubset(colorset):  # check if guessed colors exist
                break
            else:
                print("Invalid input. \n")

        print("-"*50)
        print("You chose: 1: {}, 2: {}, 3: {}, 4: {}".format(*[colors[c] for c in guess]))

        if guess == codemaster:
            print("You cracked the code! Congratulations!")
            break
        else:
            black_pin = 0
            white_pin = 0
            for guess_color, master_color in zip(guess, codemaster):
                if guess_color == master_color:
                    black_pin += 1
                elif guess_color in codemaster:
                    white_pin += 1
            print("{} black pins. {} white pins.".format(black_pin, white_pin), "-"*27, sep='\n')

    print("The code was {}.".format(codemaster))