Page 1 of 1

Connect Four Tutorial Rate Topic: ***** 4 Votes

#1 rs4  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 29
  • View blog
  • Posts: 153
  • Joined: 01-February 09

Post icon  Posted 03 April 2009 - 07:28 PM

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.
Posted Image
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:
void display();

Now write the function
void display(){
	cout<<" 1   2   3   4   5   6   7\n";
	for(int a = 0; a<= 5; a++)
	{
	for(int b =0; b <= 6; b++) cout<<char(218)<<char(196)<<char(191)<<" ";
	cout<<'\n';
	for(int b =0; b <= 6; b++) cout<<char(179)<<place[a][b]<<char(179)<<" ";
	cout<<'\n';
	for(int b =0; b <= 6; b++) cout<<char(192)<<char(196)<<char(217)<<" ";
	cout<<'\n';
	}
}

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
#include<iostream>
using namespace std;
int main(){
	for(int i =0; i <=256;i++)
		cout<<i<<":"<<char(i)<<'\n';
	system(“pause”);
return 0;	
}

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.
int main(){
	for(int a =0;a <= 5; a++){
		for(int b = 0; b<=6; b++)
			place[a][b] = ' ';
	}
}
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 thisPosted Image


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 :D

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
int drop(int b, char player){
	if(b >=0 && b<= 6)
	{
		if(place[0][b] == ' '){
			int i;
			for(i = 0;place[i][b] == ' ';i++)
				if(i == 5){place[i][b] = player;
			return i;}
			i--;
			place[i][b] =player;
			return i;
			
		}
		else{
			return -1;
		}

	}
	else{
		return -1;
	}

}

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.
bool check(int a, int b){
	int vertical = 1;//(|)
	int horizontal = 1;//(-)
	int diagonal1 = 1;//(\)
	int diagonal2 = 1;//(/)
	char player = place[a][b];
	int i;//vertical
	int ii;//horizontal
	//check for vertical(|)
	for(i = a +1;place[i][b] == player && i <= 5;i++,vertical++);//Check down
	for(i = a -1;place[i][b] == player && i >= 0;i--,vertical++);//Check up
	if(vertical >= 4)return true;
	//check for horizontal(-)
	for(ii = b -1;place[a][ii] == player && ii >= 0;ii--,horizontal++);//Check left
	for(ii = b +1;place[a][ii] == player && ii <= 6;ii++,horizontal++);//Check right
	if(horizontal >= 4) return true;
	//check for diagonal 1 (\)
	for(i = a -1, ii= b -1;place[i][ii] == player && i>=0 && ii >=0; diagonal1 ++, i --, ii --);//up and left
	for(i = a +1, ii = b+1;place[i][ii] == player && i<=5 && ii <=6;diagonal1 ++, i ++, ii ++);//down and right
	if(diagonal1 >= 4) return true;
	//check for diagonal 2(/)
	for(i = a -1, ii= b +1;place[i][ii] == player && i>=0 && ii <= 6; diagonal2 ++, i --, ii ++);//up and right
	for(i = a +1, ii= b -1;place[i][ii] == player && i<=5 && ii >=0; diagonal2 ++, i ++, ii --);//up and left
	if(diagonal2 >= 4) return true;
	return false;
}

Arrgh :crazy: ,
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;
 #include<iostream>
using namespace std;
void display();
bool check(int a, int b);
int drop(int b, char player);
char place[6][7];//available for whole program


Now lets link all the functions together in the main function
 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.

So here’s what the final code should look like
#include<iostream>
using namespace std;
void display();
bool check(int a, int b);
int drop(int b, char player);
char place[6][7];//available for whole program

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
}
void display(){
	cout<<" 1   2   3   4   5   6   7\n";
	for(int a = 0; a<= 5; a++)
	{
		for(int b =0; b <= 6; b++) cout<<char(218)<<char(196)<<char(191)<<" ";
		cout<<'\n';
		for(int b =0; b <= 6; b++) cout<<char(179)<<place[a][b]<<char(179)<<" ";
		cout<<'\n';
		for(int b =0; b <= 6; b++) cout<<char(192)<<char(196)<<char(217)<<" ";
		cout<<'\n';
	}
}
bool check(int a, int b){
	int vertical = 1;//(|)
	int horizontal = 1;//(-)
	int diagonal1 = 1;//(\)
	int diagonal2 = 1;//(/)
	char player = place[a][b];
	int i;//vertical
	int ii;//horizontal
	//check for vertical(|)
	for(i = a +1;place[i][b] == player && i <= 5;i++,vertical++);//Check down
	for(i = a -1;place[i][b] == player && i >= 0;i--,vertical++);//Check up
	if(vertical >= 4)return true;
	//check for horizontal(-)
	for(ii = b -1;place[a][ii] == player && ii >= 0;ii--,horizontal++);//Check left
	for(ii = b +1;place[a][ii] == player && ii <= 6;ii++,horizontal++);//Check right
	if(horizontal >= 4) return true;
	//check for diagonal 1 (\)
	for(i = a -1, ii= b -1;place[i][ii] == player && i>=0 && ii >=0; diagonal1 ++, i --, ii --);//up and left
	for(i = a +1, ii = b+1;place[i][ii] == player && i<=5 && ii <=6;diagonal1 ++, i ++, ii ++);//down and right
	if(diagonal1 >= 4) return true;
	//check for diagonal 2(/)
	for(i = a -1, ii= b +1;place[i][ii] == player && i>=0 && ii <= 6; diagonal2 ++, i --, ii ++);//up and right
	for(i = a +1, ii= b -1;place[i][ii] == player && i<=5 && ii >=0; diagonal2 ++, i ++, ii --);//up and left
	if(diagonal2 >= 4) return true;
	return false;
}
int drop(int b, char player){
	if(b >=0 && b<= 6)
	{
		if(place[0][b] == ' '){
			int i;
			for(i = 0;place[i][b] == ' ';i++)
				if(i == 5){place[i][b] = player;
			return i;}
			i--;
			place[i][b] =player;
			return i;

		}
		else{
			return -1;
		}

	}
	else{
		return -1;
	}

}



I hope this tutorial has helped you
Richard

Is This A Good Question/Topic? 3
  • +

Replies To: Connect Four Tutorial

#2 Steeeve  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 58
  • Joined: 03-December 08

Posted 16 June 2009 - 11:32 AM

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.

But otherwise, nice work. 4*
Was This Post Helpful? 0
  • +
  • -

#3 Guest_Joey*


Reputation:

Posted 04 June 2010 - 06:23 AM

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.
Was This Post Helpful? 0

#4 markproctor87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 06-May 11

Posted 12 May 2011 - 09:29 AM

How would you make it possible to let the two players enter their own names?
How would you change the playing pieces?
Was This Post Helpful? 0
  • +
  • -

#5 zircle  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 17-June 11

Posted 17 June 2011 - 01:42 AM

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:

View Postmarkproctor87, 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.

#include<iostream>
using namespace std;
int main(){
	for(int i =0; i <=256;i++)
		cout<<i<<":"<<char(i)<<'\n';
	system(“pause”);
return 0;	
}


Was This Post Helpful? 0
  • +
  • -

#6 NovruzeliH  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 04-January 12

Posted 05 January 2012 - 07:10 PM

thanks for the tutorial :)...I am new but learned couple of stuff from this.
Was This Post Helpful? 0
  • +
  • -

#7 hamzamirza22  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 30-May 12

Posted 30 May 2012 - 10:21 AM

[YOUNG WILL HAVE ITS DAY, IT ALWAYS DOES. BUT THE DAY ONCE BELONGED TO THOSE NOW OLD AND SOMETIMES, OFTEN WHEN IT IS MOST NEEDED, THEY WILL OWN IT JUST TO SHOW US THEY STILL CAN]

Where did you make your program 2 players and can you please make and example, that's one player and plays against an AI. (for Connect Four)
Was This Post Helpful? 0
  • +
  • -

#8 axnjxn  Icon User is offline

  • D.I.C Head

Reputation: 14
  • View blog
  • Posts: 144
  • Joined: 04-February 12

Posted 27 June 2012 - 05:58 AM

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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1