.st0{fill:#FFFFFF;}

Connect four with App Designer 

 July 8, 2022

By  Anuradha Viswanathan

Connect-4 is a strategy game for two players played on a computer or a physical board with disks/chips. The board comprises vertical and horizontal columns containing slots, and each player takes turns dropping their coloured chips into the slots. The game's objective is to place four adjacent disks of your colour in a row, column, or diagonal, i.e. connect four horizontally, vertically or diagonally. Researchers have discussed many approaches and strategies to solving this game. Some of them are the brute-force approach, artificial intelligence algorithms such as minimax and negamax, and the knowledge-based approach. The brute-force solution was out of favour when initial solutions were found because of the game's complexity and available computer technology. The game has been played with variations of the rules, such as differing board sizes and pieces which are popular in game theory and artificial intelligence research. The game was first known as "The Captain's Mistress" but was released in its modern-day form by Milton Bradley in 1974. In 1988, the game was solved by Victor Allis, who demonstrated that with the perfect play, the first player can always be the winner if he plays the middle column first, and if he selects another column first, the second player can always make the game a draw.

Some simple and effective winning tactics for a player to know

This game might seem simple, but it needs a lot of strategies and tactics to ensure a winning result; therefore, being aware of these strategies is essential. Let us quickly discuss common strategies before going on to how the game is designed. One of the basic strategies of this game is to place your disks somewhere in the middle since this opens up your win options in any direction. The computer's moves designed by this code use a basic win/block strategy which checks for 3 in a row, column or diagonal by either the player or the computer. Therefore, it would be reasonably straightforward to set up a winning strategy against the computer and simultaneously be aware that the computer has its basic strategy to prevent you from winning.

Strategy- Start in the middle

Strategy- Start in the middle

Another vital approach to use as a player is to plan a couple of different moves in advance to anticipate a reactionary move by the computer to block you in one direction. That will still leave you with other possible winning moves to set yourself up for a win.

Strategy- Plan multiple moves

Strategy- Plan multiple moves

 It's also vital to make moves that don't work in favour of the opponent(computer). The player must be looking for 3-connection moves that the computer could make and try to prevent them. Preventing 3-connections will also prevent the computer from setting up a trap such that a win can be achieved from multiple directions. The difference between winning and losing happens when you take advantage of the computer's mistakes.

Computer wins

Computer wins

Understanding the implications of your moves in advance would help you develop a strong defensive and offensive game plan. A strong offensive game plan is when you try to make winning connect-four formations with your chips by utilizing the chances at doing so. Try to form as many simultaneous horizontal, vertical and diagonal connections by using your disks and the opponent's disks. This will leave you with multiple win options even if one of the win options gets thwarted by the computer. The player must also ensure not to fill a slot below a game-ending move. An empty space next to a three-disk connection sometimes cannot be used due to open slots around it. It is important not to fill up these slots to create an avenue for the opponent to win the game. There are four trillion possible ways that any game of connect-4 can be played, making it impossible to remember the right moves for any given scenario. Therefore it requires practice and patience to develop the skills to win any game. Some advanced strategies can aid you in winning, such as "7" trap and the septuplet attack. The "7" trap is a configuration of your disks such that it forms the number "7" with three horizontal chips connected to two diagonal chips branching off from the last horizontal chip.

The "7"  trap

The "7" trap

 This can be configured in many ways, forwards, backwards and upside-down backwards. The other strategy is the septuplet trap which uses a configuration that enables you to win in seven different directions, the details of which won't be discussed in this blog. The interested reader is encouraged to look this up online.

Design of connect four using MATLAB App Designer

Let us now describe an example of how the game is played. The game is initialized in the 'startupfcn' of the code where the empty board and chips are loaded, the gameboard matrix is initialized with zeros, and the result flag is set to zero. The result variable gets set to 1 for the player's win, 2 for the computer's win and 3 for a draw. The player is assigned the number '1' with red chips, and the computer is designated as '2' with the black chips. The invalid play flag is set to zero initially and gets a value of 1 when the player selects a column that is already full and will be prompted to choose an alternative unfilled column. Suppose the player chooses to start the game with column 3 and clicks on the button on top of column 3 to drop his chip down this column.

Computer's block move

Computer's block move

The 'playerMove' function determines the lowest possible row into which the player's chip will be placed by iterating through the rows until it finds a row just below it filled. If a column is empty, the chip lands right at the bottom, designated as row' 6'. This function is implemented with the click of a column button on top of every corresponding column. After a suitable row is computed, a red chip is placed in that slot, and the result of the move is checked. This is done with the 'checkResult' function, called within the 'playerMove' function with the input argument as the game board variable. The game board property gets set to '1' for the corresponding row and column index for the player's move and as '2' for the slots filled by the computer. The rest of the unfilled slots are zeros until occupied. This public property is declared within the properties section of the code, along with the other properties such as the 'result flag, invalid play flag and playable row as 'row'. A message is displayed to the player whether it is a win/loss/draw/none result. A message is displayed accordingly when it is the player's or the computer's turn. After the player has finished his turn, there is a small pause, after which the computer makes its move. The computer's move is designed to be such that it can identify the basic block and win moves that it keeps track of. The row-wise, column-wise and diagonal-wise win options are computed and stored, and then the computer chooses the win moves before it opts for the next best option of blocking the player's win.

Computer's block moves in all directions

Computer's block moves in all directions

If neither of these is possible, it generates a random column for its play and the bottommost unoccupied slot available is found to drop the computer's black chip into. After this, the result is checked using 'checkResult' just as before, and a message is displayed. The game alternates between the player and the computer until one connects four horizontally, vertically or diagonally. After this, the player can click on 'New Game' to start over again.

Start of a new game

Start of a new game

Implementation of Connect four game using App Designer

Get Access to
App & Report!

Connect four is the classic game you would love to play with friends and family. Put your strategic gaming skills to the test and become the first to connect four horizontally, vertically or diagonally to win the game against the computer; Use our app and play the game yourself; Developed with MATLAB R2022a with App Designer.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Author: Anuradha Viswanathan
% Topic : Connect four with App Designer
% Company: MATLAB Helper
% Website: https://MATLABHelper.com
% MATLAB Version & Toolbox: R2022a
% Date : 07-06-2022

classdef connect4 < matlab.apps.AppBase

% Properties that correspond to app components
properties (Access = public)

(Uneditable code...)

% This app is designed for the connect four game played between the
% player and the computer. The player is assigned the number '1' and
% red chips, the computer is designated as '2' with black chips. The
% graphics for the game are already available for use in this code.

properties (Access = private)
% Description
end

properties (Access = public)
(Editable code..)
end

methods (Access = public)
% Function to check the result of the current play
function checkResult(app,board)
(Editable code..)

% Check for the horizontal connect-4 win

% Check for the vertical connect-4 win

% Check for the diagonal connect-4 win

% Check for the inverse diagonal connect-4 win

% Check for a draw
end

% function to update the player's move to the board
function playerMove(app,col_num)
% Check for play into a full column

% Find the playable row for the selected column

% Place red chip of the player

% Check the result of the move made by the player and display the
% message of the game status

end

% function for finding the available win/block options for the
% computer and make a move by preferring the win over the block
function computerMove(app)

% Horizontal win/block options

% Check each set of four in a row

% Check if there is a win or block(3 in a row by
% the computer or the player)

% Check if the position is a valid choice

% Add the move to the list of
% available options

% Similarly, check for vertical win/block options, two diagonal win/block options and
% add to the list of available win/block options

% Looping through the list, check if it is a win option or if it is the last option
% available

% If there are no win or blocks options, choose a random column

% Find the playable row for the computer's chosen column

% Update the board with a black chip for the computer
% on the playable row and column

% Check the result of the move made by the computer and display the
% message of the game status

end

% Code that executes after component creation
function startupFcn(app)

% Load the board image and the red and black chips used by the
% player and computer

% Initialize the gameboard and result variables

end

% Button pushed function: Col1
function Col1ButtonPushed(app, event)
% Make the move if the game has not ended with a result

% Make the player's move for column 1

end

%(Similarly implement for other columns)

% Button pushed function: NewGameButton
function NewGameButtonPushed(app, event)
startupFcn(app);
end

Conclusion

The Connect four game has been designed using App Designer, and the implementation has been discussed. The strategies and tactics the player needs to use against the computer and the computer's win/block strategies against the player have been explained and designed in 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"}

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

>