Connect Four Final Report
Members of Team Connect Four
This project consisted of creating a MATLAB script for the game Connect Four. We created code that set up a 6 by 7 board. The rules for the game are exactly the same as any Connect Four game. Two players play against each other: black versus red. The player hovers the mouse over the board and then clicks on any column and their chip will fall to the appropriate row. This means that if there are no chips in that column, it will fall to the bottom, but if there are already chips in that column, it will fall to the row directly above it. The code detects if you try and place a chip in an already taken spot, and it does not allow you to do that. We also made code that determines when there is four in a row and someone has won the game.
The goal of this project was to make a computer game using MATLAB, and Connect Four seemed like the most fun. We wanted our MATLAB version of Connect Four to be as realistic to the actual board game as possible. We wanted all the same rules to apply. The motivation for this project came from the desire to give Professor Cheever a fun game to play over winter break, and from the aspiration to make a game people can really play on the computer. This project is interesting because the code involves some complicated nested for loops and if then statements. This project took a lot of problem solving, but with lots of trial and error we were successful with creating Connect Four on MATLAB.
In order to understand this project, you need to be at least somewhat acquainted with MATLAB. The code has three parts: setting up the board, playing, and checking for four in a row. The latter two parts are repeated for the second player. MATLAB statements that we use include for loops, if then else statements, ginput, round, and patch. The patch statement sets up the 6 by 7 board with yellow circles. The ginput statement allows the player to add their chip to the board, and the round function rounds the x and y positions of where they clicked to a round number, so that their chip falls directly in the column. We set up a matrix called bval, which is composed of zeros. Wherever the red player plays, the matrix value is changed to one, and wherever the black player plays the matrix value is changed to negative one. This is so that MATLAB knows where all the black and red chips are. The nested for loops along with the if then statements help guide the chip to the correct position. Once the chip is settled, the “break” statement at the end of the if statement terminated the turn.
Note: The columns in the matrix appear as rows on the board.
Completed Project Design
For our project we wanted to create a MATLAB version of the game connect four. There ended up being three main sections of our code: graphics, gameplay, and recognizing four in a row.
For the graphics of the game, we created 42 yellow circles, each representing a space that someone can insert a chip. We chose the color yellow because the original connect four board is yellow colored.
for y=1:N, board(x,y)=patch(x+xc,y+yc,[1 1 0]); % Creates patch graphic of yellow % circles centered at increasing zeroes according to N & W end
To set up the board itself, we had to create a 7 by 6 matrix (the actual dimensions of the board of connect four). Our first step in creating each circle is to calculate fifty points around the circumference of a circle, centered about each point in the matrix. The radius of the circle is .4 units (since each point is spaced 1 unit apart, we wanted to leave a little space between each circle). The yellow circles were then created by using the patch command that we used in some of our previous labs. To create 42 circles, we ran a nested four loop (the outer limit representing the number of columns, the inner representing the number of rows) of the patch command. To make the board look more visually appealing, we squared the axes, got rid of any extra space on the graph and removed the tick marks.
The first thing we needed to code for was alternating red and black turns. To do this we set up a for loop that ran 42 times (the maximum number of turns in a game because it is the number of available spaces on a board). When it is red’s turn, we programmed MATLAB to take the coordinates of where someone clicked, rounded those coordinates to the nearest integer, and then changed the original patch function of the yellow circle to the color red. When it black’s turn, the code does the exact same thing except it changes the patch function to create a black circle instead of a red circle.
set(board(i,j),'FaceColor',[1 0 0]); % set the clicked spot to red
set(board(i,j),'FaceColor',[0 0 0]); % set the clicked spot to black
We also assigned the red circles a value of +1 and the black circles a value of -1. These values were stored in the matrix that we used in creating our board.
When you play the real version of connect four, if you slide a chip into the top row, it falls all the way down due to gravity. We wanted our software version to do the exact same thing. To achieve this we had to set up several if… then statements to test for certain conditions. For starters, we had MATLAB test whether the space below was empty by determining if the value of that space was 0, in which case it was empty or -1/+1 in which case it was already filled. If it was already filled, we had MATLAB change the color of the circle you clicked on to the color of whichever turn it was. If it wasn’t filled, we had MATLAB change the color of the circle below, change the color of the circle you clicked on back to yellow, and then test once more whether or not the circle below that was filled.
if bval(i,j-p)==0, % if spot below click iterated by p is yellow set(board(i,j-p),'FaceColor',[1 0 0]); % turn spot red bval(i,j-p+1)=0; % resets bval above to zero set(board(i,j-p+1),'FaceColor',[1 1 0]); % resets spot above to yellow bval(i,j-p)=1; % Identifies red circle in the array as a 1
elseif bval(i,j-p)<0, % if the spot below is below is black set(board(i,(j-p)+1),'FaceColor',[1 0 0]); % set clicked spot to red bval(i,j-p+1)=1; % Identifies red circle in the array as a 1 end
We also changed the values of the matrix accordingly as the chip “fell” down each column.
One last thing we had to code for was making sure that if you clicked on a space that was already taken, you couldn’t change the color of the circle. Once again we used an if… then statement to test if that space had already been assigned a non-zero value; if it had then nothing would happen and the user would have another chance to go again.
for p=1:j-1 % Creates a for... loop for value p of 1 to one below place you clicked if bval(i,j)~=0, % if you click on a already colored spot, then turn is skipped disp ('You are cheating. Go again.'); break, end % terminates turn
Recognizing Four in a Row
The last thing we wanted our code to do was to recognize when there is a winner. In the game of connect four, someone wins by having putting four of their pieces in a row.
Our first step in getting MATLAB to recognize four in a row, was to set up four different for loops, each iterating through all the possible combinations of four in a row horizontally, vertically, diagonally left to right going upwards and diagonally right to left going upwards respectively. For each combination of four, each of the four values of the matrix that represents the board are summed. Remember that we assigned a value of 1 to each red circle and a value of -1 to each black circle. So if the sum of the four values equaled four, MATLAB declared red the winner (by changing the axis title to ‘Red Wins’) and if the sum equaled negative four MATLAB declared black the winner (by changing the axis title to ‘Black Wins’).
We succeeded in achieving the goals we set out for ourselves, namely: to make playable software for Connect Four using MATLAB that provides realistic graphics and gameplay, and accurately determines the winner. In terms of graphics, with Professor Cheever’s help we coded for an image that mostly matches the shape, color, and arrangement of the actual game board. The only difference comes in that rather than have a yellow board with circular spaces, our graphics provide for yellow circles that act as spaces. For gameplay, users are able to direct a cursor in order to select a single circle to insert a chip. Like the real game, a player cannot place their chip in a space already occupied. Additionally, even though the user selects a space anywhere on the board, the chip falls from the top of that column and rests in the space selected. Finally, a large section of our code is devoted to recognizing whether four chips of the same color form a line, successfully stopping the game and informing the users of a winner. In this aspect, our MATLAB version actually surpasses real-life play by taking the responsibility of ending the game from the players, and ensures that a four-in-a-row connection is not overlooked. The only aspect we have failed to make realistic has been clearing the board, but this was nonessential.
MATLAB is well suited to support software for simple games such as Connect Four, and the project was manageable given the tools we’ve accrued throughout the semester. Understanding patch graphics, matrices, ginput, for loops, and if/else statements was essential for creating this game. Debugging was necessary throughout the coding process, but often the problems we encountered required only logic to understand how our code had room for misinterpretation, and with trial we made it hermetic. We could further improve the game by replacing redundant code for each turn with a function, and creating a method for clearing the board and playing again without re-running the script. However, the skills we gained in graphics and loops could support further work in creating game software using MATLAB, and perhaps for making visual models of processes relating to science and engineering.