Sharing is caring!

Best 3 Mastermind Game in Python With Source Code

Table of Contents

Introduction

Have you ever thought about making a traditional code-breaking game as you learn Python? You’re in for a treat! Today, we will be constructing the Mastermind game – an exciting game where you try to crack a secret code with hints given after each attempt. Are you excited to begin? Let’s start!

What is Mastermind?

Mastermind is a challenging code-breaking game where players must guess a secret code within a limited number of tries.

The computer creates the secret code, and players make guesses to crack it. With each guess, the computer gives feedback using black and white pegs—black pegs mean the right color in the right spot, while white pegs mean the right color in the wrong spot.

The goal is to figure out the secret code before running out of attempts.

The Objective of the Mastermind Game in Python

In the Mastermind game coded in Python, the goal is for the computer to come up with a secret code randomly, and for the player to try and guess the code within a set number of tries.

The game will give hints after each guess to assist the player in narrowing down the options and ultimately solving the code.

Let’s Start Coding

First, let’s set up the basic structure of our Mastermind game. We need to generate a random secret code, accept guesses from the player, and provide feedback based on the guess.

Let’s break down and explain the Mastermind game code step by step. This explanation will help you understand how each part works and why it’s there.

Step 1: Importing the Required Libraries

import random

The random module is imported to generate random numbers. We’ll use this to create our secret code.

Step 2: Generating the Secret Code

def generate_code():
    colors = ['R', 'G', 'B', 'Y', 'O', 'P']  # Red, Green, Blue, Yellow, Orange, Purple
    return random.sample(colors, 4)

Here, we define a function generate_code that generates a random sequence of 4 colors from the list of available colors. The random.sample function ensures that the colors in the code are unique.

Step 3: Providing Feedback on the Guess

def get_feedback(secret_code, guess):
    black_pegs = sum([1 for i in range(4) if secret_code[i] == guess[i]])
    white_pegs = sum([min(secret_code.count(j), guess.count(j)) for j in 'RGBYOP']) - black_pegs
    return black_pegs, white_pegs

The get_feedback function compares the player’s guess to the secret code and provides feedback. It counts:

  • black_pegs: The number of correct colors in the correct position.
  • white_pegs: The number of correct colors in the wrong position, adjusted by subtracting the black pegs to avoid double-counting.

Step 4: The Main Game Function

def mastermind():
    secret_code = generate_code()
    attempts = 10
    print("Welcome to Mastermind!")
    print("Colors: R = Red, G = Green, B = Blue, Y = Yellow, O = Orange, P = Purple")
    print("You have 10 attempts to guess the secret code.")

    while attempts > 0:
        guess = input("Enter your guess (e.g., RGBY): ").upper()
        if len(guess) != 4 or any(c not in 'RGBYOP' for c in guess):
            print("Invalid input. Please enter a sequence of 4 colors using the letters RGBYOP.")
            continue

        black_pegs, white_pegs = get_feedback(secret_code, guess)
        print(f"Black Pegs: {black_pegs}, White Pegs: {white_pegs}")

        if black_pegs == 4:
            print("Congratulations! You guessed the secret code.")
            break

        attempts -= 1
        print(f"Attempts remaining: {attempts}")

    if attempts == 0:
        print(f"Game over! The secret code was {''.join(secret_code)}.")

mastermind()

Game Initialization

  • Generate the Code: A secret code is generated using the generate_code function.
  secret_code = generate_code()
  • Set Attempts: The player starts with 10 attempts to guess the secret code.
  attempts = 10
  • Welcome Message: Inform the player about the game rules and available colors.
  print("Welcome to Mastermind!")
  print("Colors: R = Red, G = Green, B = Blue, Y = Yellow, O = Orange, P = Purple")
  print("You have 10 attempts to guess the secret code.")

The Game Loop

  • Input and Validation: The player is prompted to enter their guess. The input is checked for validity (correct length and valid characters). If the input is invalid, the player is asked to enter a valid guess.
  guess = input("Enter your guess (e.g., RGBY): ").upper()
  if len(guess) != 4 or any(c not in 'RGBYOP' for c in guess):
      print("Invalid input. Please enter a sequence of 4 colors using the letters RGBYOP.")
      continue
  • Feedback and Score Calculation: The get_feedback function is used to determine the number of black and white pegs. If the player guesses the code correctly, they are congratulated, and the game ends. If not, the player is informed about the feedback and the remaining attempts.
  black_pegs, white_pegs = get_feedback(secret_code, guess)
  print(f"Black Pegs: {black_pegs}, White Pegs: {white_pegs}")

  if black_pegs == 4:
      print("Congratulations! You guessed the secret code.")
      break

  attempts -= 1
  print(f"Attempts remaining: {attempts}")
  • Game Over: If the player runs out of attempts without guessing the code, the game reveals the secret code.
  if attempts == 0:
      print(f"Game over! The secret code was {''.join(secret_code)}.")

Enhancing the Game

Want to make your Mastermind game even more exciting? Here are a few ideas to spice things up:

Expand the Color List: Add more colors to increase the variety and challenge. You could include colors like ‘C’ for Cyan, ‘M’ for Magenta, and so on.

Visual Representation: Create a simple visual representation of the feedback using symbols or ASCII art to make the game more engaging.

Hint System: Offer hints after a certain number of incorrect guesses to help the player out. For example, reveal one correct color in its position after every three incorrect guesses.

Here is a small enhancement with a hint system:

import random

def generate_code():
    colors = ['R', 'G', 'B', 'Y', 'O', 'P']  # Red, Green, Blue, Yellow, Orange, Purple
    return random.sample(colors, 4)

def get_feedback(secret_code, guess):
    black_pegs = sum([1 for i in range(4) if secret_code[i] == guess[i]])
    white_pegs = sum([min(secret_code.count(j), guess.count(j)) for j in 'RGBYOP']) - black_pegs
    return black_pegs, white_pegs

def mastermind():
    secret_code = generate_code()
    attempts = 10
    print("Welcome to Mastermind!")
    print("Colors: R = Red, G = Green, B = Blue, Y = Yellow, O = Orange, P = Purple")
    print("You have 10 attempts to guess the secret code.")

    while attempts > 0:
        guess = input("Enter your guess (e.g., RGBY): ").upper()
        if len(guess) != 4 or any(c not in 'RGBYOP' for c in guess):
            print("Invalid input. Please enter a sequence of 4 colors using the letters RGBYOP.")
            continue

        black_pegs, white_pegs = get_feedback(secret_code, guess)
        print(f"Black Pegs: {black_pegs}, White Pegs: {white_pegs}")

        if black_pegs == 4:
            print("Congratulations! You guessed the secret code.")
            break

        attempts -= 1
        print(f"Attempts remaining: {attempts}")

        if attempts % 3 == 0:
            hint_index = random.choice([i for i in range(4) if secret_code[i] != guess[i]])
            print(f"Hint: One of the colors in position {hint_index + 1} is {secret_code[hint_index]}.")

    if attempts == 0:
        print(f"Game over! The secret code was {''.join(secret_code)}.")

mastermind()

The Mastermind game offers more than just entertainment – it’s a fantastic chance to hone your Python programming abilities.

Creating this game will help you grasp loops, conditionals, and critical thinking on a deeper level. By adding extra features, you can ramp up the difficulty and fun factor.

Get ready to code, challenge yourself, and experience the excitement of deciphering the hidden code!

Enhance the Mastermind Game

To make the Mastermind game even more engaging, here are some ideas to enhance the gameplay:

Add Difficulty Levels

Introduce different difficulty levels by varying the length of the secret code and the number of attempts. For example, easy mode could have a 4-color code with 12 attempts, while hard mode could have a 6-color code with 8 attempts.

Function to Generate Secret Code

def generate_code(length=4):
    colors = ['R', 'G', 'B', 'Y', 'O', 'P']  # Red, Green, Blue, Yellow, Orange, Purple
    return random.sample(colors, length)

The generate_code function is responsible for creating a secret code that the player has to guess. Here’s how it works:

  • Define Possible Colors: We have a list of colors represented by their first letters: R for Red, G for Green, B for Blue, Y for Yellow, O for Orange, and P for Purple.
  • Generate Code: The function uses random.sample to pick a specified number of unique colors (default is 4) from the list. This ensures that the secret code is made up of different colors and is randomized every time the game starts.

Main Game Function

def mastermind():
    print("Welcome to Mastermind!")
    print("Colors: R = Red, G = Green, B = Blue, Y = Yellow, O = Orange, P = Purple")
    difficulty = input("Choose difficulty (easy, medium, hard): ").lower()

The mastermind function sets up and runs the game.

  • Welcome Message: It starts by welcoming the player and displaying the possible colors they can use in their guesses.
  • Choose Difficulty: The game asks the player to choose a difficulty level. This affects the length of the secret code and the number of attempts the player has.
    if difficulty == 'easy':
        code_length, attempts = 4, 12
    elif difficulty == 'medium':
        code_length, attempts = 5, 10
    else:
        code_length, attempts = 6, 8

Based on the chosen difficulty, the game sets the length of the secret code and the number of attempts allowed:

  • Easy: 4 colors, 12 attempts
  • Medium: 5 colors, 10 attempts
  • Hard: 6 colors, 8 attempts
    secret_code = generate_code(code_length)
    print(f"You have {attempts} attempts to guess the secret code.")

Generate Secret Code: The function then generates the secret code using the generate_code function, passing in the code length based on the difficulty level.

Inform the Player: It informs the player about the number of attempts they have to guess the code.

Game Loop

    while attempts > 0:
        guess = input(f"Enter your guess (e.g., RGBY{'O' * (code_length - 4)}): ").upper()
        if len(guess) != code_length or any(c not in 'RGBYOP' for c in guess):
            print("Invalid input. Please enter a valid guess.")
            continue

Player Guess: The game enters a loop where the player makes guesses until they either run out of attempts or guess the code correctly.

Input Validation: The input is checked for validity. It must be the correct length and contain only the specified color letters. If not, the player is prompted to enter a valid guess.

        black_pegs, white_pegs = get_feedback(secret_code, guess)
        print(f"Black Pegs: {black_pegs}, White Pegs: {white_pegs}")

Feedback: The get_feedback function (assumed to be defined elsewhere) calculates the number of black and white pegs for the guess. Black pegs indicate correct color and position, while white pegs indicate correct color but wrong position. This feedback is printed to help the player adjust their next guess.

        if black_pegs == code_length:
            print("Congratulations! You guessed the secret code.")
            break

        attempts -= 1
        print(f"Attempts remaining: {attempts}")

Check for Win: If the number of black pegs equals the code length, the player has guessed the code correctly, and the game congratulates them and exits the loop.

Reduce Attempts: If the guess was incorrect, the number of remaining attempts is decremented, and the player is informed of how many attempts they have left.

    if attempts == 0:
        print(f"Game over! The secret code was {''.join(secret_code)}.")

Game Over: If the player runs out of attempts without guessing the code, the game ends and reveals the secret code.

mastermind()

Start the Game: Finally, the mastermind function is called to start the game.

By following this explanation, you should now have a clear understanding of how the Mastermind game works in Python and how each part of the code contributes to the game’s functionality.

Implement a Scoring System

Add a scoring system that awards points based on the number of attempts remaining when the player guesses the code correctly. This can add an extra layer of competition and replayability.

Let’s break down the enhanced Mastermind game code, which now includes a scoring system based on the number of remaining attempts.

Main Game Function

The mastermind function sets up and runs the game. The game begins by welcoming the player and showing the possible colors they can use for their guesses. The player then selects a difficulty level which determines the length of the secret code and the number of attempts they get.

Depending on the selected difficulty, the code length and the number of attempts are set. For the easy level, there are 4 colors and 12 attempts. For the medium level, there are 5 colors and 10 attempts. For the hard level, there are 6 colors and 8 attempts.

The game generates the secret code using the generate_code function, which produces a code of the specified length. The player is then informed about the number of attempts they have to guess the code.

Game Loop

The player makes guesses until they either guess the code correctly or run out of attempts. The input is checked for validity. It must be the correct length and contain only the specified color letters. If not, the player is prompted to enter a valid guess.

The get_feedback function (assumed to be defined elsewhere) calculates the number of black and white pegs for the guess. Black pegs indicate correct color and position, while white pegs indicate correct color but wrong position. This feedback helps the player adjust their next guess.

If the number of black pegs equals the code length, the player has guessed the code correctly. The game calculates the player’s score (remaining attempts multiplied by 10) and displays it before exiting the loop. If the guess was incorrect, the number of remaining attempts is decremented, and the player is informed of how many attempts they have left.

If the player runs out of attempts without guessing the code, the game ends and reveals the secret code. Finally, the mastermind function is called to start the game.

Code

def mastermind():
    print("Welcome to Mastermind!")
    print("Colors: R = Red, G = Green, B = Blue, Y = Yellow, O = Orange, P = Purple")
    difficulty = input("Choose difficulty (easy, medium, hard): ").lower()

    if difficulty == 'easy':
        code_length, attempts = 4, 12
    elif difficulty == 'medium':
        code_length, attempts = 5, 10
    else:
        code_length, attempts = 6, 8

    secret_code = generate_code(code_length)
    initial_attempts = attempts
    print(f"You have {attempts} attempts to guess the secret code.")

    while attempts > 0:
        guess = input(f"Enter your guess (e.g., RGBY{'O' * (code_length - 4)}): ").upper()
        if len(guess) != code_length or any(c not in 'RGBYOP' for c in guess):
            print("Invalid input. Please enter a valid guess.")
            continue

        black_pegs, white_pegs = get_feedback(secret_code, guess)
        print(f"Black Pegs: {black_pegs}, White Pegs: {white_pegs}")

        if black_pegs == code_length:
            score = attempts * 10
            print(f"Congratulations! You guessed the secret code. Your score is: {score}")
            break

        attempts -= 1
        print(f"Attempts remaining: {attempts}")

    if attempts == 0:
        print(f"Game over! The secret code was {''.join(secret_code)}.")

mastermind()

By following this explanation, you should now have a clear understanding of how the enhanced Mastermind game works in Python and how each part of the code contributes to the game’s functionality, including the scoring system based on remaining attempts.

Conclusion

The Mastermind game offers a great way to have fun while also improving your Python programming skills. Creating this game will help you grasp loops, conditionals, and strategic thinking better.

You can even add extra features to make the game more exciting and challenging. Get ready to code, crack the secret code, and have a blast!

Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *