Hi,
I've tried to make this tutorial a simple as I could for people who have just started to learn C++,I recommend that before you attempt this tutorial you know how to use the following.

Using functions

Data types char and int

Creating and using arrays

Using loops

Overview of game

A quick bit of research and you will find that connect four is played on the connect four board which is 7 holes(horizontal) by 6 holes(vertical). It uses a yellow and red piece one for each player.How are we going to manage to game?Key functions
Well because we need to be able to see the game board, we will need a function to display it, we will call this display.
We will also need one that will put the pieces into the board, we will call this drop.
And one to check to see if someone has won, we will call this check.

Managing the data
We need someway to store what is in each slot on the board, for this we will use a 2d array, we will call it place.

Start programming

Create a new empty console project, and add a .cpp file called connectFour.cpp, for simplicity we will only use this one cpp file and no header file.

Add standard declarations

#include<iostream>// allows us to display output and get input for the game
using namespace std;//Puts us in standard namespace so there is no need to fully specify path to iostream functions

lets also add this after that

char place[6][7];

This creates a char 2d array called place where we will store what’s in each slot on the board, we will put it here rather then in main() so all functions can access it. Because the board is 6 by 7 we have used place[6][7] what this does is the same as creating 6 normal arrays of place[7] but all in one. If we want to access the first column we would use place[0][x], second place[1][x] and so on, remember all arrays start at 0 not 1.

Now write our code to display this we don't need to give or receive any values from our display so would will declare it like this:

Its worth noting what cout does, cout a way of display writing on the screen, any characters/words that you want to display need to be enclosed in " ", this is called a string, anything enclosed in ' ' is a character they can only have one character in them. And to display any value within the program use its name it without using " " or ' '. << is used to send what to display to cout, you cannot just keep adding on after << you need to add another << each time another string, value or character is added.

The first row cout<<" 1 2 3 4 5 6 7\n"; puts numbers on the columns so that people using the game know what the columns are. Notice the \n at the end this is like return/enter it moves down a line, this has the same basic effect of cout<<endl;, notice endl is not inside "" but "\n" is.

The next line for(int a = 0; a<= 5; a++){...} loops adding one on to a each time(a++) until i is above five, so the code inside runs 6 times, each time it makes another row down for the six rows of the board.

The code inside makes the six columns each slot is a square which will have the player piece inside,
The first line will loop 7 times once for each column, the combination of char(218), char(196) and char(191) puts the top on the square and the " " at the end places a space between it and the next column.

So what is char(218) doing, its the same as putting in a character like this 'a', every character has a numerical value the value of a is 97 so 'a' is the same as char(97), the char() tells the program to display it as a character not a number. I have had to use char(196) etc. because they are special characters that are not on the keyboard. To see what number associates with what character compile and run this code

The next line puts the edges on the squares and displays the value of place inside.place[a][ b] a is equal to the row and b is equal to the column, because a is taken from the first for loop and b is this for loop, so place[a][ b] is the value in the row and column the square is being drawn for.
The last line puts the bottom on the square.

Now because place has no value the program will either display an error or a unwanted character.
So lets fill place with spaces, these will show up as blanks(no player piece) when we display the program.

As you can see I’ve put this in the main function so its the first thing to run.
This runs in the same way as display() with its for loops but instead of displaying values it is assigning place[a][ b] to ' ', do not use a string " " because place holds characters.

Now if you call display() you should see this

Stop take sometime and make sure you understand how place is being used in the above it is crucial to the rest if this tutorial

Now lets make the drop function, the drop function must put the piece above the first full square or failing that at the bottom. So heres the code

I have made it return a int so that it can tell the rest of the program at what row it stopped at(-1 is error value returned). The if(b >=0 && b<= 6) checks the value b given is a vaild number between 0 and 6(For the 1 to 7 columns, 0 to 6 because arrays start at 0 not 1). The && means and so if b is greater than or equal to zero and b is smaller than or equal to six it will run, if it isn’t the last else statement will run and return a error value of -1.if(place[0][ b] == ' '), row 0 is the top line so this makes sure that the top is empty, i.e there is somewhere for the players piece to go in the column b (the column the piece is being dropped down). If its not the second to last else run and returns a error value -1. This bit of code tells it were to put the piece, i have commented how it works after each line

int i;
for(i = 0;place[i][b] == ' ';i++)//starts i at 0 and adds one each time this effectivly moves down
//the colomn checking to see if it is empty, when it isn't it stops.
if(i == 5){place[i][b] = player;//checks to see if its hit the bottom and runs next line if it has
return i;}//returns 5 i.e row 5
i--;// takes one of i because i++ is run after place[i][b] == ' ' is checked
place[i][b] =player;//puts the players piece(player) in the correct place
return i;//returns the row it ends up in

Now lets write the code to check to see if someones won this is what it looks like.

Arrgh ,
Well its not as bad as it looks firstly it returns a bool i.e has someone won? true or false.
It takes the parameters a and b as integers a is the column b is the row. We will give it the location of the piece just added because only a row of four including the piece just added can possibly be made. Each for loop runs checking what is in the location as commented and adds to how many are in the line. If the line is 4 or above it will return true otherwise move to the next pair of loops, at the end if none are 4 or above it will return false.

i.e for(i = a +1;place[b] == player && i <= 5;i++,vertical++);//Check down

Adds 1 to a each time therefore checking below the piece dropped, if it is equal to player (the piece dropped) It will run again and add 1 to vertical(used to count number of pieces in vertical line) each time. i<= simply stops the loop so it is aways checking within the size of the 2d array [i]place.

Now we have made all of our functions we need to declare them so our declarations will look like this;

int main(){
for(int a =0;a <= 5; a++){ //fill place with whitespace
for(int b = 0; b<=6; b++) //
place[a][b] = ' '; //
} //
display();//Displays for first time so players can see the board
int hold;//Will house user row choice
int hold2 = 0;//will hold drop value
int charsPlaced = 0;//Number of peices dropped so can end game if a draw
bool gamewon = false;//Will be changed to true when game is won and will exit while loop
char player = 15;//start as player 2 will change back 2 player 1
while(!gamewon){//will stop when game is won, ! means NOT makes the oppisite be checked
if(hold2 != -1){//check if there was a error in the last drop
if(player == 15){//if player 2 lasted dropped a piece so its player 1s turn
cout<<"player 1 drop where?";
player = 254;//char of players piece
}
else{
cout<<"player 2 drop where?";
player = 15;//char of player piece
}
}
while(true){//will run untill 'break;'
if(charsPlaced == 42) break;//if draw
cin>>hold;//get user input
hold--;//take off 1 to account for arrays starting at 0 not 1
if(hold <=6 && hold>= 0) break;//if within valid range stop loop
else cout<< "\nplease enter a value between 1 and 7 :";//ask for input and loop again
if (cin.fail()) //catch a non number
{ //
cin.clear(); //Stops cin trying to put its value in to hold
char c; //Try entering a non number without this, 2 see what this does
cin>>c; //
} //Catch a non number
}
if(charsPlaced == 42) break;//if draw
hold2 = drop(hold,player);//drop the player store the row in hold2
if(hold2 == -1) cout<<"Colom is full\nPlease enter anothor number between 1 and 7:";//if error -1 row is full
else{
gamewon = check(hold2,hold);//check if game is run
charsPlaced ++;//another character has been succesfully placed
system("cls");//This clears the screen works with windows, not nesscery to run game
display();//displayed updated board
}
}
system("cls");//this clears the screen
if(charsPlaced == 42){//if draw
cout<<"No winner, Game was draw\n";
system("pause");
return 0;
}
if(player == 15)//if won by player 2
cout<<"gamewon by : player 2\n";
else cout<<"gamewon by : player 1\n";//Else won by player 1
system("pause");//pauses before exit so players can see who won, works with windows
return 0;//Exit application
}

All calls to system() are dependent on operating systems and vary between each, the commands I have used are for windows OS.

Replies To: Connect Four Tutorial

Nice tutorial. Only complaint is that the code and some comments are hard to read because they're very cramped together. Might want to clean it up. Fixing up the grammar and using capital letters, and spacing the code out would go a long way.

I definitely agree with the previous person who commented, really need to clean up the code. The check to see if someone won function was incredibly sloppy and made it 100times more difficult to understand, but the content itself was rather helpful.

rs4:
Very good tutorial. I don't feel like the formatting is enough to you many dock points especially since you are trying to clearly explain your code. Anyone following along with the code (and can see color) should be able to follow your code well since you offer comments as well as detailed explanations.

markproctor87:

markproctor87, on 12 May 2011 - 09:29 AM, said:

How would you make it possible to let the two players enter their own names?
How would you change the playing pieces?

Hello,

I'm necro-ing a thread that you necro-ed, but help is help, eh? (I haven't compiled the code yet, since it is pretty late here so my answers are not gold.)

In order to setup custom player names, one method you can use is convert the static strings "player 1" and "player 2" into variables and then have an option that calls "cin >> player1" and "cin >> player2" (which could be at the start of your program).

Regarding your other question about pieces, I believe characters are used to display players so simply changing the code here will result in a different piece.

player = 254;//char of players piece
player = 15;//char of player piece

If you look at his explanation, he describes how to determine different characters.

Uh, I'm pretty sure this tutorial was meant for beginners (considering the author explains what cout does). Building an AI isn't exactly beginner level stuff. I encourage you to build an AI for this game. I might try. But I would also put it in a different TUTORIAL section.