The Wayback Machine - https://web.archive.org/web/20241001221339/https://www.geeksforgeeks.org/mastermind-game-using-python/
Open In App

Mastermind Game using Python

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given the present generation’s acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil. 

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:

We shall not be using any of the Pygame Libraries, to aid us with additional graphics, and therefore shall be dealing only with the framework and concept. Furthermore, we are going to be playing against the Computer i.e, the Computer would generate the number to be guessed. Below is the implementation of the above idea. 

Python3




import random
 
 
# the .randrange() function generates a
# random number within the specified range.
num = random.randrange(1000, 10000)
 
n = int(input("Guess the 4 digit number:"))
 
# condition to test equality of the
# guess made. Program terminates if true.
if (n == num):
    print("Great! You guessed the number in just 1 try! You're a Mastermind!")
else:
    # ctr variable initialized. It will keep count of
    # the number of tries the Player takes to guess the number.
    ctr = 0
 
    # while loop repeats as long as the
    # Player fails to guess the number correctly.
    while (n != num):
        # variable increments every time the loop
        # is executed, giving an idea of how many
        # guesses were made.
        ctr += 1
 
        count = 0
 
        # explicit type conversion of an integer to
        # a string in order to ease extraction of digits
        n = str(n)
 
        # explicit type conversion of a string to an integer
        num = str(num)
 
        # correct[] list stores digits which are correct
        correct = ['X']*4
 
        # for loop runs 4 times since the number has 4 digits.
        for i in range(0, 4):
 
            # checking for equality of digits
            if (n[i] == num[i]):
                # number of digits guessed correctly increments
                count += 1
                # hence, the digit is stored in correct[].
                correct[i] = n[i]
            else:
                continue
 
        # when not all the digits are guessed correctly.
        # if (count < 4) and (count != 0): - this condition is not needed as we are starting with the condition, n!=num, which is, count<4
         print("Not quite the number. But you did get ",
                  count, " digit(s) correct!")
          # second code is not supposed to print the guessed numbers, from the sample output, here I get we are not recording the position of the guess,but count. But as per the explanation, the code should not print the guessed numbers, rather give their count.
            # print("Also these numbers in your input were correct.")
            # for k in correct:
            #    print(k, end=' ')
          print('\n')
          print('\n')
          n = int(input("Enter your next choice of numbers: "))
 
        # when none of the digits are guessed correctly.
        elif (count == 0):
            print("None of the numbers in your input match.")
            n = int(input("Enter your next choice of numbers: "))
 
    # condition for equality.
    if n == num:
    # ctr must be incremented when the n==num gets executed as we have the other incrmentation in the n!=num condition
        ctr+=1
          print("You've become a Mastermind!")
        print("It took you only", ctr, "tries.")


Let’s suppose the number set by computer is 1564 

Output:

Guess the 4 digit number: 1564

Great! You guessed the number in just 1 try! You're a Mastermind!

If the number is not guessed in one chance. 

Output: 

Guess the 4 digit number: 2164    

Not quite the number. But you did get 2 digit(s) correct!
Also these numbers in your input were correct.
X X 6 4

Enter your next choice of numbers: 3564
Not quite the number. But you did get 2 digit(s) correct!
Also these numbers in your input were correct.
X 5 6 4

Enter your next choice of numbers: 1564
You've become a Mastermind.
It took you only 3 tries.

You can make the game harder by either increasing the number of digits of the input or by not disclosing which numbers in the input were correctly placed. This has been explained in the code below. 

Python3




import random
 
# the .randrange() function generates
# a random number within the specified range.
num = random.randrange(1000, 10000)
 
n = int(input("Guess the 4 digit number:"))
 
# condition to test equality of the
# guess made. Program terminates if true.
if(n == num):
    print("Great! You guessed the number in just 1 try! You're a Mastermind!")
else:
    # ctr variable initialized. It will keep count of
    # the number of tries the Player takes to guess the number.
    ctr = 0
 
    # while loop repeats as long as the Player
    # fails to guess the number correctly.
    while(n != num):
        # variable increments every time the loop
        # is executed, giving an idea of how many
        # guesses were made.
        ctr += 1
 
        count = 0
 
        # explicit type conversion of an integer to
        # a string in order to ease extraction of digits
        n = str(n)
 
        # explicit type conversion of a string to an integer
        num = str(num)
 
        # correct[] list stores digits which are correct
        correct = []
 
        # for loop runs 4 times since the number has 4 digits.
        for i in range(0, 4):
            # checking for equality of digits
            if(n[i] == num[i]):
                # number of digits guessed correctly increments
                count += 1
                # hence, the digit is stored in correct[].
                correct.append(n[i])
            else:
                continue
 
        # when not all the digits are guessed correctly.
        if (count < 4) and (count != 0):
            print("Not quite the number. But you did get ",
                  count, " digit(s) correct!")
            print("Also these numbers in your input were correct.")
 
            for k in correct:
                print(k, end=' ')
 
            print('\n')
            print('\n')
            n = int(input("Enter your next choice of numbers: "))
 
        # when none of the digits are guessed correctly.
        elif(count == 0):
            print("None of the numbers in your input match.")
            n = int(input("Enter your next choice of numbers: "))
 
    if n == num:
        print("You've become a Mastermind!")
        print("It took you only", ctr, "tries.")


Output:

Guess the 5 digit number: 38476

Not quite the number. But you did get 2 digit(s) correct! 
Enter your next choice of numbers: 41876

Not quite the number. But you did get 4 digit(s) correct!
Enter the next choice of numbers: 54876

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

Full Code Explanation:

  1. The code starts by initializing a variable, ctr, to 0.
  2. This will keep track of the number of tries the player makes to guess the number.
  3. Next, the code creates a random number within the range of 1000 and 10000.
  4. The .randrange() function generates this random number.
  5. The next line assigns this random number to num.
  6. Next, the code tests whether num is equal to the randomly generated number, num.
  7. If they are equal, then the program terminates and prints “Great!
  8. You guessed the number in just 1 try!
  9. You’re a Mastermind!”
  10. Otherwise, it continues with the while loop.
  11. The while loop runs as long as n!=num (which means that n cannot be equal to num).
  12. Every time execution of this loop occurs, ctr++ increments which gives an idea of how many guesses were made.
  13. The for loop also runs 4 times since there are 4 digits in n (0-3).
  14. For each iteration of this loop, i in range(0,4) checks if n[i]==num[i].
  15. If they are equal then count++; else continue is executed and k is stored in correct[] (an empty list), which will store all digits that
  16. The code initializes a variable called ctr which will keep track of how many times the player guesses the number.
  17. The code also creates a while loop that will repeat as long as the player fails to guess the number correctly.
  18. In each iteration of the while loop, the code increments a variable called ctr and stores this value in a variable called count.
  19. The code also creates a list called correct which will store digits which are correct.
  20. Finally, the code prints out some information about what was entered into the input field and terminates if n==num.

Note: Suppose the number set by the computer is 54876. 

The entire scope of modifying this code is massive. The idea here is to get a sense of what the concept is. There are plenty of games such as this one which relies on similar basic code. By utilizing this code, developing it further while incorporating libraries from Pygame, would make it more like the real deal, not to mention much more involving!



Previous Article
Next Article

Similar Reads

Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this
4 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
Tic Tac Toe Game using PyQt5 in Python
In this article , we will see how we can create a Tic Tac Toe game using PyQt5. Tic-tac-toe, noughts, and crosses, or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Below
5 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red & Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
Python - MCQ Quiz Game using Tkinter
Prerequisite: Python GUI – tkinter Python provides a standard GUI framework Tkinter which is used to develop fast and easy GUI applications. Here we will be developing a simple multiple-choice quiz in python with GUI. We will be creating a multiple choice quiz in Python with Tkinter. First, we will create a library named Quiz in the directory of yo
6 min read
KBC game using Python
In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python. Features of the game:Random questions every timeFour lifelinesAudience Poll50:50Double dipFlip the questionMade with the help of Matplotlib and NumPy libraries of python.Bar graph for audience poll lifelineRules to play the game:T
15 min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Dice game using Turtle in Python
Dice Roll Game using python turtleThe simple python program implements the rolling of dice using the turtle library and random module of python. The turtle library is used to draw graphics and animations on the screen, while the random library is used to generate random numbers and random selections that can be used to control the behavior of the t
3 min read
Automate Chrome Dino Game using Python
For this article, we will be building a Python bot that can play the "Chrome Dino Offline Game". Chrome dino is a dinosaur game that launches itself on your web browser when there is no internet connection. For the introduction of the game, the dinosaur has to jump to avoid the approaching cactus or duck to avoid the bird. The first fundamental ste
7 min read
Blackjack console game using Python
Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One. In this article, we
6 min read
Create Bingo Game Using Python
A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a simple bingo game in this lesson. The following i
9 min read
Number Guessing Game Using Python Tkinter Module
Number Guessing Game using the Python Tkinter module is a simple game that involves guessing a randomly generated number. The game is developed using the Tkinter module, which provides a graphical user interface for the game. The game has a start button that starts the game and a text entry field where the user can enter their guess. The game also
5 min read
Number Guessing Game Using Python Streamlit Library
The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the number like (2+2=?, 3*3=?) to guess the number. In
5 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer s
15+ min read
Dodger Game using Pygame in Python
A Dodger game is a type of game in which a player has access to control an object or any character to dodge (to avoid) upcoming obstacles and earn points according to the number of items dodged if the player is not able to dodge the object the game will be over and final score will be displayed in the console. After certain points or times the spee
5 min read
Create Breakout Game using Python
In this article we will build a clone of a famous game, 'Breakout'. We will build this game using one of Python's in-built libraries, Turtle. RequirementsAn IDE like PyCharm.Basics of PythonBasic knowledge of Python-Turtle.Willingness to learn.Project StructureWe want to keep the programming simple. The best way to do that is to break down the prob
15+ min read
Create pong game using Python - Turtle
Pong is one of the most famous arcade games, simulating table tennis. Each player controls a paddle in the game by dragging it vertically across the screen's left or right side. Players use their paddles to strike back and forth on the ball. Turtle is an inbuilt graphic module in Python. It uses a panel and pen to depict illustrations. Below are th
3 min read
Create a Snake-Game using Turtle in Python
A snake game is an arcade maze game which has been developed by Gremlin Industries and published by Sega in October 1976. It is considered to be a skillful game and has been popularized among people for generations. The snake in the Snake game is controlled using the four direction buttons relative to the direction it is headed in. The player's obj
8 min read
Turtle Race Game Using Python - Turtle Graphics Library
Turtle graphics is a popular way to introduce programming concepts to beginners. It's a fun and interactive module in Python that lets you create simple drawings and animations using a "turtle" that moves around the screen. In this tutorial, we'll create an exciting turtle race game where you can bet on the color of a turtle and watch as they race
4 min read
Flipping Tiles (memory game) using Python3
Flipping tiles game can be played to test our memory. In this, we have a certain even number of tiles, in which each number/figure has a pair. The tiles are facing downwards, and we have to flip them to see them. In a turn, one flips 2 tiles, if the tiles match then they are removed. If not then they are flipped and placed back in the position. We
3 min read
Rock Paper and Scissor Game Using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Prerequisite: Tkinter, random In this articl
7 min read
Stimulate bouncing game using Pygame
In this article, we will learn to make a bouncing game using Pygame. Pygame is a set of Python modules designed for writing video games. It adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the Python language. It is free and runs on nearly every platform and operating
4 min read
Angry Bird Game Using PyGame
Let's discuss the angry bird game using Pygame, I hope this article will be very interesting as it provides a holistic gaming experience at the end. We begin by describing the modules necessary to develop this game. Angry Birds Game Using PyGame The objective of the game is to hit as many enemy birds as possible to score points. Your score increase
14 min read
AI Driven Snake Game using Deep Q Learning
Content has been removed from this Article
1 min read
Create a Memory Puzzle Game Using Pygame
Playing memory puzzle games provides entertainment and boosts mental abilities such as focus and memory recall. This article guides you through the steps to create a straightforward memory puzzle game using the Python Pygame Library. After completing the article, you will have a fully functioning game where players try to match pairs of game pieces
10 min read
Article Tags :
Practice Tags :