C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C++ Expert!

Join 307,099 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,031 people online right now. Registration is fast and FREE... Join Now!




Connect Four Tutorial

 
Reply to this topicStart new topic

> Connect Four Tutorial

Rating  5
rs4
Group Icon



post 3 Apr, 2009 - 06:28 PM
Post #1


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.
IPB 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
CODE

#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
CODE
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:
CODE
void display();

Now write the function
CODE

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
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.
CODE
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 thisIPB 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 biggrin.gif

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
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
CODE
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.
CODE
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.gif ,
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[i][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 place.

Now we have made all of our functions we need to declare them so our declarations will look like this;
CODE
#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
CODE
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
CODE

#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
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Steeeve
**



post 16 Jun, 2009 - 10:32 AM
Post #2
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*
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 12:11PM

Live C++ Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month