.st0{fill:#FFFFFF;}

Play Mastermind game with MATLAB App Designer 

 July 1, 2022

By  Anuradha Viswanathan

Can you come up with a code that cannot be cracked within ten moves? Do you have what it takes to crack the secret code within ten moves or less? It is time to play Mastermind game- codemaker versus codebreaker. Mastermind is a game where there are two players – one is the codemaker who sets the secret code, which is a sequence of four colours, and the other is the codebreaker who tries to crack the code using logic and deduction. This game has a fascinating history and is a re-adapted form of 'Bulls and Cows' old pencil and paper game. The game researchers have discussed several algorithms and strategies for solving the mastermind game colour code solution in very few moves.

How to play Mastermind

The game starts with the code maker, who comes up with a sequence of four colours using the coloured pegs. In the current version of the game with App Designer, duplicates are not allowed in the solution colour code. The four colours are chosen from six available colours. The codebreaker will try to guess the colour code within ten moves or less to win the game. After each guess, the codemaker provides clues to the codebreaker with black and white pegs. A black peg will be given to guess the correct colour, which is also in the proper position. A white peg will be given to guess the right colour in the wrong place. The codebreaker keeps guessing the colour pattern based on the clues he receives. He loses the game if he doesn't arrive at the exact pattern of colours within ten moves.

Mastermind game

Mastermind game

Design of Mastermind game with MATLAB App Designer


The game is designed using MATLAB App Designer, a built-in environment for creating professional apps that anyone can use. It provides an integrated version of the MATLAB Editor and an extensive set of UI components. The apps developed can be distributed by packaging them into installer files, or they can even exist as a standalone web app which requires a MATLAB Compiler.

App Designer

App Designer

The Design View of App Designer allows you to create many interactive features with its extensive library of UI components and rich layout tools to develop professional-looking applications.

App Designer view

App Designer view

Design View

Design View

Different aspects of the code can be managed with the Code view, which consists of the panes – Component Browser, Code Browser and App Layout. The game interface consists of the Decoder Board, six buttons for the six colour options and three buttons – Result, Reset/Reload, and Change Current row. The properties of these components are set with the component tab of the Component browser, and callbacks are created with the Callback tab of the selected component.

App Designer Component Browser

App Designer Component Browser

The Code Browser pane allows you to create and manage private/public properties, private/public functions and manage callbacks. In the code view, the uneditable sections of the code are greyed out since they are generated and managed by App Designer, whereas the white editable parts consist of the functions defined by the user and the custom property definitions. In this app, there are four properties created ( two private and two public). Two variables, ' i' and 'j', are iterators for row and column numbers, respectively. A public struct property 'play' is defined with the game's variables as its fields, and these are initialized during startup and updated as the game progresses. The fields include the total number of colours, number of rows and columns of the board, current colour number, current row number and current row colours. The property 'var' holds the coloured pegs, clue pegs and the ten by four board matrix. The code uses an existing image for the board, which is in the MAT file format, and it gets loaded on the startup function call of the app. It consists of the board matrix, the colour pegs, and the black and white pegs to be loaded as the game progresses. The public function 'UpdateBoard' is created, which updates the current row of the board based on the colours selected by the player. Each colour is assigned a colour number: Red – 1, Blue-2, Green-3, Yellow-4, Pink-5, Orange-6.

Code Browser and App Layout

Code Browser and App Layout

App Designer allows you to create a startup function which gets executed when the app starts up before any UI interaction by the player. In this function 'startupFcn', the public property 'struct' fields for the game's parameters are initialized, and the image of the empty board is loaded. The colour buttons are also visible to the player to begin the game. A random selection of four colours is generated as the secret colour code solution and is sampled without replacement. This implies that each colour chosen can appear at most once in the set of four colours, and there are no duplicates in the solution. For every colour button click, the public function 'UpdateBoard' is executed to set the corresponding row and column of the board with the selected colour. The button 'Change Current Row' is programmed to reset the colours of the current row for the player to be able to change the current row colour pattern selection before confirming his guess. Once he wants to confirm his guess, he must click on the 'Result' button. This button is programmed to display the clues with black and white pegs on the current row as feedback to the guess, and the public properties are updated to reflect the game's current state after each guess. If the player has not filled the entire row before confirming his guess, he is prompted to do so. If the player gets all the colours correct, four black pegs are set on the board, and a 'Winner' message is displayed to the player with the click of the 'Result' Button. If he fails to guess the exact pattern within ten moves, the black and white pegs are displayed along with a 'Loser' message. To begin a new game after completing the previous game or halfway through the current game, the player needs to click on the 'Reset' button, which clears the board. This button is programmed to allow the player to reload a new game after 'Reset'.

Let us analyze a test run as given in the below figure. Suppose the secret code made by the codemaker is Pink, Red, Orange Yellow. Suppose the first guess made by the player is Red, Blue, Green, and Yellow. The player makes this guess by clicking on the colour buttons to fill the columns one to four in order. After clicking on Result, the codemaker gives the clues one Black peg and one white peg. This indicates that one of the colours(Yellow in this case) is guessed with the correct position for which a black peg is given and another colour (red in this case) is the right colour in the wrong place. The player will only be told how many black and white pegs he gets for a particular pattern guess; he won't be told for which colour the clue pegs are given. Then the game goes on, and he makes the second guess as Pink, Yellow, Green, and Red by clicking on the colour buttons and the result button. For this guess, he receives one black peg and two white pegs. The game goes on until he guesses all four correct colours in the correct places: Pink, Red, Orange, and Yellow, for which he is given four black pegs and a winner message. Suppose the player clicks on the Result button without filling the entire row with four colours, then he receives an alert which tells him to fill the entire row. Incase the player wants to change the colours that he guesses on the current row, he must click on Change Current Row button to reset the colours of that row. Then he needs to refill the row with the colours of his choice before clicking on Result button. After clicking on Result, the colours on the current row cannot be changed.

Mastermind game UI

Mastermind game UI

MATLAB App Designer Implementation

This code uses an existing .MAT file for the board image coloured pegs and clue pegs taken from MATLAB Courseware. This eliminates the need to design these UI components.

Get Access to
MATLAB App & Report!

Mastermind is a code-breaking game which is a clever re-adaptation of the old pencil-and-paper game of 'Bulls and Cows'. Game researchers have widely discussed the best algorithms and strategies used by the code-breaker to crack the code within a minimal number of moves; Use our app and play the game yourself; Developed with MATLAB R2022a with App Designer

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author: Anuradha Viswanathan
% Topic : Play Mastermind game with MATLAB App Designer
% Company: MATLAB Helper
% Website: https://MATLABHelper.com
% Date : 02-06-2022

classdef mastermind
properties (Access = public)
(Uneditable code)
end
% This app has been designed for playing the Mastermind game as the
% code-breaker. The colours used are Red-1, Blue-2, Green-3, Yellow-4,
% Pink-5,Orange-6
properties (Access = private)
% Iteration variables
i;
j;
end

properties (Access = public)
% Game variable and board image variable
play = struct();
var;
end

methods (Access = private)

end

methods (Access = public)
% function to update the board with current guess
function results = UpdateBoard(app,colorNum)
app.ChangecurrentrowButton.Visible = "on";
if app.j <= app.play.numCols && app.i <= app.play.numRows
switch colorNum
case 1
(Code ….)
app.play.currentColorNum = colorNum;
(Code ….)
end

function startupFcn(app)
% Initialise the game variables and load the mat file image
app.var = load(“Mastermind.mat”);
(code….)

….

%generate the random solution (sample without replacement)
(code….)

% Display the empty Board
imshow([app.var.Board{1,:};app.var.Board{2,:};app.var.Board{3,:};app.var.Board{4,:};app.var.Board{5,:};app.var.Board{6,:};app.var.Board{7,:};app.var.Board{8,:};app.var.Board{9,:};...
app.var.Board{10,:}],'Parent',app.UIAxes)
end

function RedButton1Pushed(app,event)
UpdateBoard(app,1)
end
function BlueButton2Pushed(app,event)
UpdateBoard(app,2)
end
function GreenButton3Pushed(app,event)
UpdateBoard(app,3)
end
(code….)…….

function ResultButtonPushed(app,event)

% Code for ‘Fill entire row’ prompt
if sum(app.play.rowColors==0)
(code….)…….
else
% Code to find the number of correct colours and number of correct places
(code….)…….
% Code for winner
if nCorrectPlaces == app.play.numCols
(code….)…….

else
% Code to update the current guess's black and white clue pegs
(code….)…….

% Code for loser
if app.play.currentRow == app.play.numRows
uialert(fig,'You lose','Loser');
return;
end

% Code to update the current state of the game
app.play.currentRow = app.play.currentRow + 1;
(code….)…….


end
end

function ResetButtonPushed(app,event)
% Code to reset game and reload the Board
(Code…)
end
function ChangecurrentrowButtonPushed(app,event)
% Code to reset colours on the current row
(Code…)
end

Conclusion

The design and play of the Mastermind game as the codebreaker have been demonstrated in this blog. The computer is the codemaker, and the player is the codebreaker. The rich features of App Designer have been utilized to design this game.

Did you find some helpful content from our video or article and now looking for its code, model, or application? You can purchase the specific Title, if available, and instantly get the download link.

Thank you for reading this blog. Do share this blog if you found it helpful. If you have any queries, post them in the comments or contact us by emailing your questions to [email protected]. Follow us on LinkedIn Facebook, and Subscribe to our YouTube Channel. If you find any bug or error on this or any other page on our website, please inform us & we will correct it.

If you are looking for free help, you can post your comment below & wait for any community member to respond, which is not guaranteed. You can book Expert Help, a paid service, and get assistance in your requirement. If your timeline allows, we recommend you book the Research Assistance plan. If you want to get trained in MATLAB or Simulink, you may join one of our training modules. 

If you are ready for the paid service, share your requirement with necessary attachments & inform us about any Service preference along with the timeline. Once evaluated, we will revert to you with more details and the next suggested step.

Education is our future. MATLAB is our feature. Happy MATLABing!

About the author 

Anuradha Viswanathan

MATLAB Developer at MATLAB Helper,
M.S in Telecommunications and Networking,
M.S in Physics

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Connect with MATLAB Helper ®

Follow: YouTube Channel, LinkedIn Company, Facebook Page, Instagram Page

Join Community of MATLAB Enthusiasts: Facebook Group, Telegram, LinkedIn Group

Use Website Chat or WhatsApp at +91-8104622179

Watch our Latest Video

Meet Industrial Experts & Ask your Questions

Industrial Interaction MATLAB Helper
>