Mastermind Game using Python

Share your love

Let’s create a step-by-step guide for building the classic Mastermind game in Python. Mastermind is a code-breaking game where one player sets a secret code, and the other player tries to guess it using clues provided by the first player. We’ll implement a simplified version of this game where the computer generates the secret code, and you’ll play against it.

Mastermind Game Rules

  1. Two players play the game: Player 1 (setter) and Player 2 (guesser).
  2. Player 1 sets a multi-digit number (our secret code).
  3. Player 2 guesses the number.
  4. If Player 2 guesses the number correctly in the first attempt, they win and become the “Mastermind.”
  5. Otherwise, Player 1 provides hints by revealing which digits Player 2 got correct.
  6. The game continues until Player 2 guesses the entire number.

Implementation Steps

Step 1: Generate the Secret Code

We’ll have the computer generate a random 4-digit number for Player 2 to guess.


import random

def generate_secret_code():
    return random.randrange(1000, 10000)

secret_code = generate_secret_code()

AI-generated code. Review and use carefully. More info on FAQ.

Step 2: Player 2’s Guesses

Player 2 (you) will input guesses until they guess the correct code or run out of attempts. We’ll keep track of the number of attempts.


def main():
    attempts = 0
    while True:
        guess = int(input("Guess the 4-digit number: "))
        attempts += 1

        if guess == secret_code:
            print(f"Great! You guessed the number in just 1 try! You're a Mastermind!")

def check_guess(guess):
    count = 0
    guess_str = str(guess)
    secret_str = str(secret_code)
    correct = ['X'] * 4

    for i in range(4):
        if guess_str[i] == secret_str[i]:
            count += 1
            correct[i] = guess_str[i]

    print(f"Not quite the number. But you did get {count} digit(s) correct!")
    print("Digits in correct position:", ' '.join(correct))

if __name__ == "__main__":

AI-generated code. Review and use carefully. More info on FAQ.

Step 3: Player 1’s Turn

Now, the computer (Player 1) will guess your secret code. You can modify the game to switch roles and play against the computer.


You’ve created a simple Mastermind game in Python! Feel free to enhance it by adding more features, such as limiting the number of attempts or using color-coded buttons for a more aesthetic experience.

Written by: Piyush Patil

Happy coding! 😊

Share your love