Python Mastermind – A Game of Strategy, Logic, and Skill!

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

Mastermind is a two-player game in which one player hides a color code while the other attempts to guess the code. In this case, we build a four-color code using the colors red, blue, green, and yellow, with the computer device acting as a player and the user acting as the second player.

About Python Mastermind Game

To make this game, we used the tkinter module to create the GUI and the random module to generate a random set of code.

Rules:

  1. Player1, which is a computer, sets the random four colors code.
  2. Player 2 attempts to predict the code.
  3. If Player 2 correctly guesses on his first try, he wins the game and is declared Mastermind!
  4. The game continues until either Player 2 correctly guesses the number or the number of chances runs out.

Prerequisites for Mastermind Game using Python

  • Basic knowledge of the Python programming language and how functions are defined in it.
  • How the window is made in Tkinter GUI and how the frame is made in it
  • How to work with the random library

Download Python Mastermind Game Project

Please download the source code of Python Mastermind Game Project from the following link: Python Mastermind Game Project Code

Steps to Create Mastermind Game using Python

Following are the steps for developing the Python Mastermind Game Project:

Step 1: Importing the necessary modules

Step 2: Making a window for our project

Step 3.1: Function to check guessed code

Step 3.2: Function to create the game window

Step 4: Making Labels and Mapping the Buttons to Their Functionalities

Step 1: Importing the necessary modules

To use Tkinter, we need to import the Tkinter module. We are also going to import the random module and messagebox to show popup messages.

Code

# Importing modules
from tkinter import *
import random
import tkinter.messagebox

Step 2: Making a window for our project

This code sets the title of the window as ‘ProjectGurukul’, and sets the dimensions ‘width x length’.

Code

# Creating the window
window = Tk()
window.title("ProjectGurukul")
window.geometry('300x200')
window.config(bg='#eabeb4')

Step 3.1: Function to check guessed code

Here, we write a function that checks how many of the four guesses are accurate and displays the number of correct guesses on the screen, reducing the odds by one. If all of the answers are accurate, a pop-up message congratulating the player appears. And if the chances are completed, the correct answer is displayed.

Code

def checkcode():
   global ans, col1, col2, col3, col4, n, correct
   count = 0
   count = (col1.get() == ans[0]) + (col2.get() == ans[1]) + (col3.get() == ans[2]) + (
           col4.get() == ans[3])
   chances = n.get()
   print(col1.get(), ',', col2.get(), ",", col3.get(), ",", col4.get())
   print(count)
   if chances > 0:
       if count == 0:
           correct.set(0)
       elif count == 1:
           correct.set(1)
       elif count == 2:
           correct.set(2)
       elif count == 3:
           correct.set(3)
       elif count == 4:
           n = 0
           tkinter.messagebox.showinfo("ProjectGurukul", "Congratulations, your guess is correct!")
           return
       chances -= 1
       n.set(chances)


   else:
       chances -= 1
       print(n.get())
       if (chances <= 0):
           list = ['red', 'blue', 'green', 'yellow']
           ans = list[ans[0] - 1] + "," + list[ans[1] - 1] + "," + list[ans[2] - 1] + "," + list[ans[3] - 1]
           tkinter.messagebox.showinfo("ProjectGurukul","The correct ans is " + ans + ".Better luck for the next time!")
           return
       n.set(chances)
   return 0

Explanation:

We use .get() function to get the values
We use .set() function to mark that the value is correct or not

Step 3.2: Function to create the game window

In this stage, we will create the game window with all of the necessary widgets. Also included are variables for storing user inputs and outputs. In this widget, we have four Radiobuttons, one for each of the four number codes. The user selects one of the four buttons for each digit and clicks the check button to determine the number of correct predictions.

Code

def game():
   global ans, col1, col2, col3, col4, n, correct
   root = Tk()
   root.title("ProjectGurukul")
   root.geometry('800x650')
   root.config(bg='#f5deb3')
   ans = []
   for i in range(0, 4):
       ans.append(random.randint(1, 4))
   print(ans)
   n = IntVar(root)
   n.set(10)
   correct = IntVar(root)
   correct.set(0)
   col1 = IntVar(root)
   col2 = IntVar(root)
   col3 = IntVar(root)
   col4 = IntVar(root)
   # Getting the input of word from the user
   frame = Frame(root)
   frame.pack(pady=20)
   Label(frame, text='Please make your choice', font=('Arial', 15,'bold'), relief="ridge").pack()


   frame1 = Frame(root, bg='#f5deb3')
   frame1.pack(pady=20)
   red1 = Radiobutton(frame1, text="Red", value=1, bg='white', fg='red', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue1 = Radiobutton(frame1, text="Blue", value=2, bg='white', fg='blue', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green1 = Radiobutton(frame1, text="Green", value=3, bg='white', fg='green', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow1 = Radiobutton(frame1, text="Yellow", value=4, bg='white', fg='yellow', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame2 = Frame(root, bg='#f5deb3')
   frame2.pack(pady=20)
   red2 = Radiobutton(frame2, text="Red", value=1, bg='white', fg='red', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue2 = Radiobutton(frame2, text="Blue", value=2, bg='white', fg='blue', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green2 = Radiobutton(frame2, text="Green", value=3, bg='white', fg='green', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow2 = Radiobutton(frame2, text="Yellow", value=4, bg='white', fg='yellow', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame3 = Frame(root, bg='#f5deb3')
   frame3.pack(pady=20)
   red3 = Radiobutton(frame3, text="Red", value=1, bg='white', fg='red', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue3 = Radiobutton(frame3, text="Blue", value=2, bg='white', fg='blue', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green3 = Radiobutton(frame3, text="Green", value=3, bg='white', fg='green', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow3 = Radiobutton(frame3, text="Yellow", value=4, bg='white', fg='yellow', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame4 = Frame(root, bg='#f5deb3')
   frame4.pack(pady=20)
   red4 = Radiobutton(frame4, text="Red", value=1, bg='white', fg='red', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue4 = Radiobutton(frame4, text="Blue", value=2, bg='white', fg='blue', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green4 = Radiobutton(frame4, text="Green", value=3, bg='white', fg='green', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow4 = Radiobutton(frame4, text="Yellow", value=4, bg='white', fg='yellow', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)


   frame5 = Frame(root, bg='#f5deb3')
   frame5.pack(pady=20)
   Label(frame5, text='No of chances left', bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack()
   Label(frame5, textvariable=n, bg='#f5deb3', font=('Arial', 15,'normal'), anchor="e",relief="ridge").pack()


   frame6 = Frame(root, bg='#f5deb3')
   frame6.pack(pady=20)
   Label(frame6, text='No of correct choices', bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack()
   # Button to do the spell check
   Label(frame6, textvariable=correct, bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack(pady=20)


   Button(frame6, text="Check", bg='#f5deb3', command=checkcode, font=('Arial', 15,'bold'), relief="ridge").pack(pady=20)
   # Runs the window till it is closed by the user
   root.mainloop()

Explanation:

.title() sets the title of the window as ‘ProjectGurukul’, and .geometry() sets the dimensions as ‘width x length’.
ans.append(random.randint(1, 4)) Through this, we create a random four color code.
We make frames, labels, and assign buttons to their functionalities.
We make 16 buttons, four for each color (red, blue, green, and yellow), assign their respective columns to them, and give them their value when clicked: 1 for red, 2 for blue, 3 for green, and 4 for yellow

Step 4: Making Labels and Mapping the Buttons to Their Functionalities

Now we add the required widgets for our GUI. We make a label to give the heading “ Mastermind Game”, and we create a button widget and assign the game() function to it.

Code

ans = []
# Creating the variables to get the word and set the correct word
n = IntVar(window)
correct = IntVar(window)
n.set(10)
correct.set(0)
col1 = IntVar(window)
col2 = IntVar(window)
col3 = IntVar(window)
col4 = IntVar(window)
Label(window, text="Mastermind Game", font=('Arial', 15,'bold'), relief="ridge").place(x=70, y=50)
Button(window, text="Start Game", bg='#eabeb4', font=('Arial', 12),command=game).place(x=100, y=100)
window.mainloop()

Full Code

from tkinter import *
import random
import tkinter.messagebox




def checkcode():
   global ans, col1, col2, col3, col4, n, correct
   count = 0
   count = (col1.get() == ans[0]) + (col2.get() == ans[1]) + (col3.get() == ans[2]) + (
           col4.get() == ans[3])
   chances = n.get()
   print(col1.get(), ',', col2.get(), ",", col3.get(), ",", col4.get())
   print(count)
   if chances > 0:
       if count == 0:
           correct.set(0)
       elif count == 1:
           correct.set(1)
       elif count == 2:
           correct.set(2)
       elif count == 3:
           correct.set(3)
       elif count == 4:
           n = 0
           tkinter.messagebox.showinfo("ProjectGurukul", "Congratulations, your guess is correct!")
           return
       chances -= 1
       n.set(chances)


   else:
       chances -= 1
       print(n.get())
       if (chances <= 0):
           list = ['red', 'blue', 'green', 'yellow']
           ans = list[ans[0] - 1] + "," + list[ans[1] - 1] + "," + list[ans[2] - 1] + "," + list[ans[3] - 1]
           tkinter.messagebox.showinfo("ProjectGurukul","The correct ans is " + ans + ".Better luck for the next time!")
           return
       n.set(chances)
   return 0




def game():
   global ans, col1, col2, col3, col4, n, correct
   root = Tk()
   root.title("ProjectGurukul")
   root.geometry('800x650')
   root.config(bg='#f5deb3')
   ans = []
   for i in range(0, 4):
       ans.append(random.randint(1, 4))
   print(ans)
   n = IntVar(root)
   n.set(10)
   correct = IntVar(root)
   correct.set(0)
   col1 = IntVar(root)
   col2 = IntVar(root)
   col3 = IntVar(root)
   col4 = IntVar(root)
   # Getting the input of word from the user
   frame = Frame(root)
   frame.pack(pady=20)
   Label(frame, text='Please make your choice', font=('Arial', 15,'bold'), relief="ridge").pack()


   frame1 = Frame(root, bg='#f5deb3')
   frame1.pack(pady=20)
   red1 = Radiobutton(frame1, text="Red", value=1, bg='white', fg='red', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue1 = Radiobutton(frame1, text="Blue", value=2, bg='white', fg='blue', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green1 = Radiobutton(frame1, text="Green", value=3, bg='white', fg='green', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow1 = Radiobutton(frame1, text="Yellow", value=4, bg='white', fg='yellow', variable=col1, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame2 = Frame(root, bg='#f5deb3')
   frame2.pack(pady=20)
   red2 = Radiobutton(frame2, text="Red", value=1, bg='white', fg='red', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue2 = Radiobutton(frame2, text="Blue", value=2, bg='white', fg='blue', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green2 = Radiobutton(frame2, text="Green", value=3, bg='white', fg='green', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow2 = Radiobutton(frame2, text="Yellow", value=4, bg='white', fg='yellow', variable=col2, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame3 = Frame(root, bg='#f5deb3')
   frame3.pack(pady=20)
   red3 = Radiobutton(frame3, text="Red", value=1, bg='white', fg='red', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue3 = Radiobutton(frame3, text="Blue", value=2, bg='white', fg='blue', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green3 = Radiobutton(frame3, text="Green", value=3, bg='white', fg='green', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow3 = Radiobutton(frame3, text="Yellow", value=4, bg='white', fg='yellow', variable=col3, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   frame4 = Frame(root, bg='#f5deb3')
   frame4.pack(pady=20)
   red4 = Radiobutton(frame4, text="Red", value=1, bg='white', fg='red', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   blue4 = Radiobutton(frame4, text="Blue", value=2, bg='white', fg='blue', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   green4 = Radiobutton(frame4, text="Green", value=3, bg='white', fg='green', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)
   yellow4 = Radiobutton(frame4, text="Yellow", value=4, bg='white', fg='yellow', variable=col4, font=('Arial', 12), relief="groove").pack(side="left",padx=10)


   frame5 = Frame(root, bg='#f5deb3')
   frame5.pack(pady=20)
   Label(frame5, text='No of chances left', bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack()
   Label(frame5, textvariable=n, bg='#f5deb3', font=('Arial', 15,'normal'), anchor="e",relief="ridge").pack()


   frame6 = Frame(root, bg='#f5deb3')
   frame6.pack(pady=20)
   Label(frame6, text='No of correct choices', bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack()
   # Button to do the spell check
   Label(frame6, textvariable=correct, bg='#f5deb3',font=('Arial', 15,'bold'), relief="ridge").pack(pady=20)


   Button(frame6, text="Check", bg='#f5deb3', command=checkcode, font=('Arial', 15,'bold'), relief="ridge").pack(pady=20)
   # Runs the window till it is closed by the user
   root.mainloop()




# Creating the window
window = Tk()
window.title("ProjectGurukul")
window.geometry('300x200')
window.config(bg='#eabeb4')


ans = []
# Creating the variables to get the word and set the correct word
n = IntVar(window)
correct = IntVar(window)
n.set(10)
correct.set(0)
col1 = IntVar(window)
col2 = IntVar(window)
col3 = IntVar(window)
col4 = IntVar(window)
Label(window, text="Mastermind Game", font=('Arial', 15,'bold'), relief="ridge").place(x=70, y=50)
Button(window, text="Start Game", bg='#eabeb4', font=('Arial', 12),command=game).place(x=100, y=100)
window.mainloop()

Python Mastermind Game Output

mastermind game output

python mastermind game output

Summary

Using the Tkinter and random Python libraries, The mastermind project has been successfully completed! We hope you had fun constructing with us. Try to include more alternatives, such as altering the number of chances or providing hints, etc. You can also make the game difficult by including more colours and hence having more numbers to guess. Have fun coding!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook

1 Response

  1. Mounika says:

    You done a great job , the way you explained each and everything was perfect.i enjoyed by doing this project.

Leave a Reply

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