Mastermind Game using Python

Last Updated : 8 Jun, 2026

Mastermind is a code-breaking game in which a player attempts to guess a secret number generated by the computer. After each guess, the program provides feedback about how many digits are correctly placed, helping the player gradually identify the complete number.

Prerequisite: Random Numbers in Python

Rules of the game

Two players play the game against each other; let's assume Player 1 and Player 2.

  • Player 1 plays first by setting a multi-digit number.
  • Player 2 now tries his first attempt at guessing the number.
  • If Player 2 succeeds in his first attempt (despite odds which are highly unlikely) he wins the game and is crowned Mastermind! If not, then Player 1 hints by revealing which digits or numbers Player 2 got correct.
  • The game continues till Player 2 eventually is able to guess the number entirely.
  • Now, Player 2 gets to set the number and Player 1 plays the part of guessing the number.
  • If Player 1 is able to guess the number within a lesser number of tries than Player 2 took, then Player 1 wins the game and is crowned Mastermind.
  • If not, then Player 2 wins the game.
  • The real game, however, has proved aesthetics since the numbers are represented by color-coded buttons.

For example: 

Input:

Player 1, set the number: 5672
Player 2, guess the number: 1472

Output:

Not quite the number. You did get 2 digits correct.
X X 7 2

Enter your next choice of numbers:

Implementation

The following program generates a random 4-digit number and asks the user to guess it. After each guess, the program displays the digits that are correctly placed. The game continues until the player successfully guesses the secret number.

Python
import random

# Generate a random 4-digit number
secret_num = random.randrange(1000, 10000)

attempts = 0

print("Welcome to Mastermind!")
print("Try to guess the 4-digit number.\n")

while True:

    try:
        guess = int(input("Guess the 4-digit number: "))

        if guess < 1000 or guess > 9999:
            print("Please enter a valid 4-digit number.\n")
            continue

    except ValueError:
        print("Please enter numeric digits only.\n")
        continue

    attempts += 1

    # Correct guess
    if guess == secret_num:
        print("\nYou've become a Mastermind!")
        print(f"It took you only {attempts} tries.")
        break

    # Convert numbers to strings for digit comparison
    guess_str = str(guess)
    secret_str = str(secret_num)

    count = 0
    correct = ['X'] * 4

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

    print(f"\nNot quite the number. You did get {count} digit(s) correct.")

    if count > 0:
        print("Correctly placed digits:")
        print(" ".join(correct))

    print()

Output

Welcome to Mastermind!
Try to guess the 4-digit number.

Guess the 4-digit number: 2164

Not quite the number. You did get 2 digit(s) correct.

Correctly placed digits:
X X 6 4

Guess the 4-digit number: 3564

Not quite the number. You did get 3 digit(s) correct.
Correctly placed digits:
X 5 6 4

Guess the 4-digit number: 1564

You've become a Mastermind!
It took you only 3 tries.

Explanation:

  • Initialize Variables: The program generates a random 4-digit number and initializes the attempts counter.
  • Read User Input: A while loop continuously accepts guesses until the correct number is entered.
  • Validate Input: The try-except block handles invalid inputs, while conditional checks ensure a valid 4-digit number is entered.
  • Convert Numbers to Strings: The guessed number and secret number are converted to strings to enable digit-by-digit comparison.
  • Compare Digits: A for loop checks each position and counts matching digits.
  • Store Matches: The correct list stores correctly placed digits, while unmatched positions remain marked as X.
  • Display Results: The program prints the number of matching digits and the contents of the correct list after each guess.

Making the Game More Challenging

Instead of revealing which digits are correctly placed, we can display only the number of correct digits. This increases the difficulty because the player receives less information after each guess.

Python
import random

secret_num = random.randrange(1000, 10000)

attempts = 0

print("Welcome to Mastermind!")
print("Try to guess the 4-digit number.\n")

while True:

    try:
        guess = int(input("Guess the 4-digit number: "))

        if guess < 1000 or guess > 9999:
            print("Please enter a valid 4-digit number.\n")
            continue

    except ValueError:
        print("Please enter numeric digits only.\n")
        continue

    attempts += 1

    if guess == secret_num:
        print("\nYou've become a Mastermind!")
        print(f"It took you only {attempts} tries.")
        break

    guess_str = str(guess)
    secret_str = str(secret_num)

    count = 0

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

    print(
        f"\nNot quite the number. "
        f"You got {count} digit(s) correct.\n"
    )

Output

Guess the 4-digit number: 2164

Not quite the number. You got 2 digit(s) correct.

Guess the 4-digit number: 3564

Not quite the number. You got 3 digit(s) correct.

Guess the 4-digit number: 1564

You've become a Mastermind!
It took you only 3 tries.

Explanation:

  • The program uses random.randrange() to create a random 4-digit number.
  • A while loop repeatedly takes guesses and validates that the input is a valid 4-digit number.
  • The attempts variable counts the number of guesses made by the player.
  • Both numbers are converted to strings and compared position by position using a for loop.
  • The count variable stores the number of digits that match in the correct position.
  • Instead of showing the matching positions, the program displays only the value of count, making the game more challenging.

Possible Enhancements

  • Allow the user to choose the number of digits in the secret code.
  • Limit the number of guessing attempts.
  • Provide hints for correct digits appearing in incorrect positions.
  • Add difficulty levels with larger secret numbers.
  • Build a graphical version of the game using Pygame.

Time Complexity Analysis

  • Time Complexity: O(1) because the game always compares a fixed number of digits.
  • Space Complexity: O(1) since only a few variables and small lists are used.
Comment