Create Mastermind Game in Python – Code a code-breaking game

Mastermind is a two-player code-breaking game, in which one player hides a code consisting of colors, while the other player has to guess it using clues given by the former player for each turn.

In this tutorial, we will be creating our own Mastermind Game using Python Language. In our version of Mastermind, the computer will randomly select a secret code and the user tries to guess it, based on the deterministic clues given by the computer.


Mastermind Game in Python – Demo

Mastermind Game Demo

Without any further ado, let us get into the design part of the game.

Mastermind Game Design

The original mastermind board is shown below.

Mastermind
Mastermind Board

The shielded end of the board hides the secret code, whereas the entirety of the board is based on guesses made by the code-breaker. The game ends as soon as the user identifies the hidden code.

The right side of the board in the figure contains a series of white and red pegs, which are used to denote the clues related to each try.

  • Red – One of the chosen colors is in the right position as in the secret code
  • White – One of the chosen colors is present in the code, but the position is incorrect.

The implementation of the board in the terminal looks like:

Mastermind Game Design
Game Design on Terminal

The top end of the board hides the secret code and is revealed when the player is out of chances or breaks the code. Until that moment, “UNK” for “unknown” is shown.

Each section of the board denotes a turn made by the player. The game supports six colors, RED, GREEN, YELLOW, BLUE, BLACK, ORANGE. The leftmost panel denotes the clues based on each turn. ‘W’ for WHITE and ‘R’ for RED are used with the original meaning behind them

In the figure displayed above, three of the four colors selected by the user are correct, but neither of them is the correct position according to the secret code, hence three ‘W’s in the clues.

# Function to print the mastermind board
def print_mastermind_board(passcode, guess_codes, guess_flags):

	print("-----------------------------------------")
	print("\t      MASTERMIND")
	print("-----------------------------------------")

	print("    |", end="")
	for x in passcode:
		print("\t" + x[:3], end="")
	print()	

	for i in reversed(range(len(guess_codes))):
		print("-----------------------------------------")
		print(guess_flags[i][0], guess_flags[i][1], "|")
		

		print(guess_flags[i][2], guess_flags[i][3], end=" |")
		for x in guess_codes[i]:
			print("\t" + x[:3], end="")

		print()	
	print("-----------------------------------------")

The above code snippet is responsible for displaying the mastermind board on the Terminal.


Data Structures – Game variables