Create Mastermind Game using Python

We would have played a lot of games since our childhood. Have you ever played a game that tests your thinking skills? Here we build a similar game that is both fun and let’s to think. So, let’s get started and build mastermind game using python.

What is Mastermind Game?

Mastermind is a two-player game where one player hides a code of colors and the other tries to guess the code. Here we create a 4 combination code with the colors red, blue, green, and yellow with the computer device being a player and the user being the second player.

Rules of the Game

As discussed there will be two Players say, Player 1 and Player 2.

  • Player 1 first sets a multi-digit number.
  • Player 2 now tries to guess the number.
  • If Player 2 succeeds to guess in his first attempt he wins the game and is crowned Mastermind!
  • If not, Player 1 hints by revealing how many digits Player 2 got correct.
  • The game continues till Player 2 guesses the number entirely or the number of chances end.
  • Now, the roles switch.
  • If player 2 guesses in a lesser number of chances than PLayer 1 then Player 2 wins the game, else player1. If none of them guesses then it ends in a draw.
  • The real game, however, the numbers are represented by color-coded buttons.

Building Mastermind Game in Python

To develop this game, we use the tkinter module to build the GUI and use the random module create a random set of code.

Download the Mastermind Game in Python

Please download the source code for Mastermind Game in Python using the link: Mastermind Game Project

Prerequisites

It is recommended for the developer to have prior knowledge of Python and the tkinter module to have an ease and familiarity while building the project. You can install the tkinter module using the command:

pip install tk

Steps to build the Mastermind Game in Python

Here are steps we follow to develop the game:

1. Import the module
2. Create the function to check the guessed code
3. Create the function create the game window
4. Build the main window

1. Import the module

First we start by importing the required modules, tkinter and random. We also import the messagebox from tkinter to show pop up messages.

import tkinter as tk
from tkinter import *
import random
import tkinter.messagebox

2. Create the function to check the guessed code

Here, we create a function to check how many guesses out of the four are correct and show the number of correct guesses on screen and the chances is reduced by 1. If all are correct, then the pop up message is shown congratulating the player. And if the chances are done, then the correct answer is shown.

def check():
    global n, answer,ch1,ch2,ch3,ch4,correct
    cnt=0
    cnt=(ch1.get()==answer[0])+(ch2.get()==answer[1]) + (ch3.get()==answer[2]) + (ch4.get()==answer[3])
    chances=n.get()
    print(ch1.get(),',',ch2.get(),",",ch3.get(),",",ch4.get())
    print(cnt)
    if(chances>0):
        if(cnt==0):
            correct.set(0)
        elif(cnt==1):
            correct.set(1)
        elif(cnt==2):
            correct.set(2)
        elif(cnt==3):
            correct.set(3)
        elif(cnt==4):
            n=0
            tkinter.messagebox.showinfo("TechVidvan Mastermind Game","Congratulations, you have guessed it correct!")
            return
        chances-=1
        n.set(chances)
       
    else:
       
        chances-=1
        print(n.get())
        if(chances<=0):
            l=['red','blue','green','yellow']
            ans=l[answer[0]-1]+","+l[answer[1]-1]+","+l[answer[2]-1]+","+l[answer[3]-1]
            tkinter.messagebox.showinfo("TechVidvan MastermindGame","The correct answer is "+ans+ ".Better luck next time!")
            return
        n.set(chances)


    return 0

Here,

  • get() is used to get the choice made for that set of radio buttons based on the value of respective radiobutton
  • set() is used to show a particular message on the widget
  • showinfo() shows a pop up message

3. Create the function create the game window

In this step, we create the game window with all the required widgets. And also the variables to store the user inputs and the outputs. In this widget, we have a set of four radiobuttons for each of the 4 digit code. The user makes a choice of one of the 4 buttons fo each digit and clicks the check button to know number of correct guesses.

def startGame():
   
    global n, answer,ch1,ch2,ch3,ch4,correct
    wn = Tk()
    wn.title("TechVidvan Mastermind Game")
    wn.geometry('700x500')
    wn.config(bg='SlateGray1')
    n =IntVar(wn)
    n.set(5)
    correct=IntVar(wn)
    correct.set(0)
    ch1=IntVar(wn)
    ch2=IntVar(wn)
    ch3=IntVar(wn)
    ch4=IntVar(wn)
    answer = []
    for i in range(0,4):
        answer.append(random.randint(1,4))
    print(answer)
    #Getting the input of word from the user
    Label(wn, text='Please make your choice',bg='SlateGray1',font=('calibre',10,'normal'), anchor="e",
          justify=LEFT).grid(row=3,column=1,pady= 20)

    red1 = Radiobutton(wn, text="Red", value=1,bg='SlateGray1',fg='red',variable=ch1,
                       font=('calibre',12,'normal')).grid(row=4, column=1,padx=20,sticky = W,pady=10)
    blue1 = Radiobutton(wn, text="Blue",  value=2,bg='SlateGray1',fg='blue',variable=ch1,
                       font=('calibre',12,'normal')).grid(row=4, column=2,sticky = W,pady=10)
    green1 = Radiobutton(wn, text="Green", value=3,bg='SlateGray1',fg='green',variable=ch1,
                       font=('calibre',12,'normal')).grid(row=4, column=3,padx=80,sticky = W,pady=10)
    yellow1 = Radiobutton(wn, text="Yellow", value=4,bg='SlateGray1',fg='yellow',variable=ch1,
                       font=('calibre',12,'normal')).grid(row=4, column=4,padx=20,sticky = W,pady=10)


    red2 = Radiobutton(wn, text="Red",  value=1,bg='SlateGray1',fg='red',variable=ch2,
                       font=('calibre',12,'normal')).grid(row=5, column=1,padx=20,sticky = W,pady=10)
    blue2 = Radiobutton(wn, text="Blue",  value=2,bg='SlateGray1',fg='blue',variable=ch2,
                       font=('calibre',12,'normal')).grid(row=5, column=2,sticky = W,pady=10)
    green2 = Radiobutton(wn, text="Green", value=3,bg='SlateGray1',fg='green',variable=ch2,
                       font=('calibre',12,'normal')).grid(row=5, column=3,padx=80,sticky = W,pady=10)
    yellow2 = Radiobutton(wn, text="Yellow", value=4,bg='SlateGray1',fg='yellow',variable=ch2,
                       font=('calibre',12,'normal')).grid(row=5, column=4,padx=20,sticky = W,pady=10)


    red3 = Radiobutton(wn, text="Red",  value=1,bg='SlateGray1',fg='red',variable=ch3,
                       font=('calibre',12,'normal')).grid(row=6, column=1,padx=20,sticky = W,pady=10)
    blue3 = Radiobutton(wn, text="Blue",value=2,bg='SlateGray1',fg='blue',variable=ch3,
                       font=('calibre',12,'normal')).grid(row=6, column=2,sticky = W,pady=10)
    green3 = Radiobutton(wn, text="Green", value=3,bg='SlateGray1',fg='green',variable=ch3,
                       font=('calibre',12,'normal')).grid(row=6, column=3,padx=80,sticky = W,pady=10)
    yellow3 = Radiobutton(wn, text="Yellow", value=4,bg='SlateGray1',fg='yellow',variable=ch3,
                       font=('calibre',12,'normal')).grid(row=6, column=4,padx=20,sticky = W,pady=10)


    red4 = Radiobutton(wn, text="Red", value=1,bg='SlateGray1',fg='red',variable=ch4,
                       font=('calibre',12,'normal')).grid(row=7, column=1,padx=20,sticky = W,pady=10)
    blue4 = Radiobutton(wn, text="Blue", value=2,bg='SlateGray1',fg='blue',variable=ch4,
                       font=('calibre',12,'normal')).grid(row=7, column=2,sticky = W,pady=10)
    green4 = Radiobutton(wn, text="Green", value=3,bg='SlateGray1',fg='green',variable=ch4,
                       font=('calibre',12,'normal')).grid(row=7, column=3,padx=80,sticky = W,pady=10)
    yellow4 = Radiobutton(wn, text="Yellow", value=4,bg='SlateGray1',fg='yellow',variable=ch4,
                       font=('calibre',12,'normal')).grid(row=7, column=4,padx=20,sticky = W,pady=10)


    Label(wn, text='No of chances left',bg='SlateGray1',font=('calibre',12,'normal'), anchor="e", justify=LEFT).grid(row=8,column=1)

    Label(wn, textvariable=n,bg='SlateGray1',font=('calibre',12,'normal'), anchor="e", justify=LEFT).grid(row=9,column=1,pady= 20)
    Label(wn, text='No of correct choices',bg='SlateGray1',font=('calibre',12,'normal'),anchor="e", justify=LEFT).grid(row=10,column=1,pady= 20)
    #Button to do the spell check
    Label(wn, textvariable=correct,bg='SlateGray1',font=('calibre',12,'normal'),anchor="e", justify=LEFT).grid(row=10,column=2,pady= 20)

    Button(wn, text="Check", bg='SlateGray4',font=('calibre', 13),
       command=check).grid(row=11,column=3)
    #Runs the window till it is closed by the user
    wn.mainloop()

Here,

  • geometry(): It sets the length and width of the window.
  • configure(): It sets the background color of the screen
  • title(): It is used for the title on the top of the window.
  • grid: This places the widgets in a the form of columns and rows
  • Label(): This helps in showing text
  • IntVar(): Creates a integer variable for a widget
  • StringVar(): Creates a string variable for a winget
  • Radiobutton(): Creates a radiobutton of required properties
  • Button(): Creates a button with mentioned properties. The command parameter represents the function that is to be executed/operated on clicking the button
  • mainloop(): runs the GUI till it is manually closed

4. Build the main window

#Creating the window
wn = Tk()
wn.title("TechVidvan Mastermind Game")
wn.geometry('500x300')
wn.config(bg='SlateGray1')

answer = []
#Creating the variables to get the word and set the correct word
n =IntVar(wn)
correct=IntVar(wn)
n.set(5)
correct.set(0)
ch1=IntVar(wn)
ch2=IntVar(wn)
ch3=IntVar(wn)
ch4=IntVar(wn)
Label(wn, text='Please make your choice',bg='SlateGray1',font=('calibre',20,'normal'), anchor="e",
          justify=LEFT).place(x=100,y=20)
Button(wn, text="Start Game", bg='SlateGray4',font=('calibre', 13),
       command=startGame).place(x=180,y=100)
wn.mainloop()

Here,

  • geometry(): It sets the length and width of the window.
  • configure(): It sets the background color of the screen
  • title(): It is used for the title on the top of the window.
  • place: This places the widgets at specified location
  • Label(): This helps in showing text
  • IntVar(): Creates a integer variable for a widget
  • StringVar(): Creates a string variable for a winget
  • Button(): Creates a button with mentioned properties. The command parameter represents the function that is to be executed/operated on clicking the button
  • mainloop(): runs the GUI till it is manually closed

Python Mastermind Game Output

python mastermind game output

Summary

Congratulations, you have successfully completed building the mastermind project! Hope you enjoyed building with us. Do try to add more options like changing the number of chances or giving hints, etc. Happy coding!