A Beginners First Tic-Tac-Toe

I would like to post my first real program.

First of all, I'd like to say, that this may not be the best way to write this program, or the most efficient way of writing it. It is merely a summary of what I have learned over the last 7 - 10 days of C++. I know I have a long way to go yet, and I haven't read up on things like 2d arrays.

I have had some general guidance for TheIdeasMan, but no actual "you do it this way". Everything I did I have researched myself.

The goals for this project I set my selfe are:

1) No Global variables
2) As modular as I could get it, so (hopefully) no complete code rewrites to fix bugs, or add features.
3) As few If statements as possible
4) No Do / While loops
5) No Compiler warnings or errors ( I used QT (Windows and Linux) and then C4Droid to check )

Without further ado, I present, for your amusement ( and probably total laughter ) , my Solution for Tic-Tac-Toe for you to pick over and rip apart (go easy on me).



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include <iostream>
#include <string>


int ClearConsole ()
// Function to clear console without using a system command. NOT printer friendly though
// If you happen to pipe output to a printer instead of a terminal console.
// Not sure why you would do that though.
    {
        for ( int line_count = 0; line_count < 500; line_count++) 	// Ansii Clear Screen
            {							// Feed 500 New lines
                std::cout << "\n";			// To the console
            }							//
    return 0;
    }


int BoardDisplay(char* GameBoard)
// Display the Game Board
{
    ClearConsole(); // Celar The console.

    //Basic game board output to the console
    std::cout << "+-----+          ";
    std::cout << "+-----+\n";
    std::cout << "|"<<GameBoard[0] << "|" <<GameBoard[1]<<"|"<<GameBoard[2]<<"|          ";
    std::cout << "|1|2|3|  Enter the Box \n";
    std::cout << "|-+-+-|          ";
    std::cout << "|-+-+-|  Number\n";
    std::cout << "|"<<GameBoard[3] << "|" <<GameBoard[4]<<"|"<<GameBoard[5]<<"|          ";
    std::cout << "|4|5|6|  You want to\n";
    std::cout << "|-+-+-|          ";
    std::cout << "|-+-+-|  Fill\n";
    std::cout << "|"<<GameBoard[6] << "|" <<GameBoard[7]<<"|"<<GameBoard[8]<<"|          ";
    std::cout << "|7|8|9|\n";
    std::cout << "+-----+          ";
    std::cout << "+-----+\n";
    return 0;
}


int PlayerMove(int DeterminePlayer)
// Function that controls player move
{
    int ValidInput =0;
    char BoxSelect;

    do {
    std::cout << "Player " << DeterminePlayer << " Move \n";
    std::cout << "Enter Box number 1-9\n";

    //Make sure only 1 - 9 is pressed !SMALL BUG TO FIX
    // Enter a string of random charecters. the game board gets pushed up
    std::cin >> BoxSelect;
    ValidInput = BoxSelect - '0';
    } while ( (ValidInput < 1) || (ValidInput > 9) );
    return ValidInput;
}


int GameLogic(int* LogicBoard)
// In game logic. Determines weather the game is won or drawn
{
    int GameWon = 0;
    int Row[3] = {0,0,0}; //3 Rows
    int Col[3] = {0,0,0}; //3 Columns
    int Diag[2] = {0,0}; //2 Diagonals

    Row[0]= ( LogicBoard[0]+LogicBoard[1]+LogicBoard[2] ); // add up the 3 Rows
    Row[1]= ( LogicBoard[3]+LogicBoard[4]+LogicBoard[5] ); // If there were more
    Row[2]= ( LogicBoard[6]+LogicBoard[7]+LogicBoard[8] ); // I would use a for/next loop

    Col[0]= ( LogicBoard[0]+LogicBoard[3]+LogicBoard[6] ); // add up the 3 Colums
    Col[1]= ( LogicBoard[1]+LogicBoard[4]+LogicBoard[7] ); // If there were more
    Col[2]= ( LogicBoard[2]+LogicBoard[5]+LogicBoard[8] ); // I would use a for/next loop

    Diag[0]= ( LogicBoard[0]+LogicBoard[4]+LogicBoard[8] ); // add up the 2
    Diag[1]= ( LogicBoard[2]+LogicBoard[4]+LogicBoard[6] ); // Diagonals

    // First we check for a winner, before we check for a Draw

    //Check Rows and Columns *****************************************


    for (int RCnumber =0;RCnumber <3; RCnumber++){
        if (  (Row[RCnumber] == 36 || Row[RCnumber] == 69) || (Col[RCnumber] == 36 || Col[RCnumber] == 69)){
         GameWon = 1;
         return GameWon;
        }
    }

    //Check Diagonals *************************************************
    for (int DiagNumber =0;DiagNumber <2; DiagNumber++){
        if (  (Diag[DiagNumber] == 36 || Diag[DiagNumber] == 69) ){
         GameWon = 1;
         return GameWon;
        }
    }


    //Check for A draw ************************************************
    for (int DrawCheck =0;DrawCheck <10; DrawCheck++){
         if  ( LogicBoard[DrawCheck]  == 0  ){
          GameWon = 0; // A game draw is checked by checking the logic
          return GameWon;// Board for any empty spaces.
         } // Only if none are found, is a game a draw
     }

    // Default is a Draw, Unless any of the above are true
     GameWon = 3;

    return GameWon;
}


int MoveCheck( int* LogicBoard, int PlayerSelectedBox)
// To check weather the move is a legal move, ie, a square has already been taken
{
    int ValidMove = 0;
    int PlayerSelectedRealBox = --PlayerSelectedBox;

    if (LogicBoard[PlayerSelectedRealBox] != 0){
        ValidMove = 0;
    }
    else {
        ValidMove = 1;
    }

    return ValidMove;
}


int UpdateBoard(char* GameBoard, int* LogicBoard)
// Function to Synchronise the Visual game board to the one
// That performs the game logic that determines the winner or a draw
{

    for (int BoardPeice=0; BoardPeice < 9; ++BoardPeice)
    {
        if ( LogicBoard[BoardPeice] == 12 ) { // Player 1 uses the value 12 for peices
            GameBoard[BoardPeice] = 'O';
        }
        if ( LogicBoard[BoardPeice] == 23 ) { // Player 2 uses the value 23 for peices
            GameBoard[BoardPeice] = 'X';
        }
    }

    return 0;
}


// Main Program
int main()
{

    //Initialise Game Variables
    int SelectedBox=0;
    int Player=2; // Set the first player to 2 Because the game will swap the player on first run
    int Nextplayer=1; // Set the next player to 1. See above
    int TempPlayer=0; // A Temp variable, used when changing players
    int Winner=0; // Variable to hold a "winner"
    int LegalMove=0; // Used to check if a move is legal


    // Set up the Game Boards for play
    int LogicBoard[9] = {0,0,0,0,0,0,0,0,0}; // Set up the Logical game board. used to apply game logic to.
    char GameBoard[10] = "         "; // Set up the Visible Game Board
    BoardDisplay(GameBoard);        // Show the Game Board for first time



    do {
         // Swap the Active Player. Iv done it this way to avoid a couple of long If Statements
        TempPlayer = Player;
        Player = Nextplayer;
        Nextplayer = TempPlayer;
        // *************


        do {


        std::cout << "\n\n\n Please enter a valid move\n\n\n\n"; // Ask Player to move
        SelectedBox = PlayerMove(Player); // Get The Playe to make a Move
        LegalMove= ( MoveCheck(LogicBoard , SelectedBox)) ; // Check that the move is Legal


            } while (LegalMove==0); // If not, ask again for a legal move


    LogicBoard[SelectedBox-1] = (Player*10)+(Player+1); // Place the move on the Logic Board
        // I used (Player*10)+(Player+1) as the formula to enter onto the board,
        // so there is no problem deciding a winner. There can be no confusion of the
        // clear winner, as only one player can make the winning value in a row of 3

    UpdateBoard(GameBoard, LogicBoard); // Sync The Logic Board with the Game Board
    BoardDisplay(GameBoard);            //Display the Game Board after a legal Move
    Winner=GameLogic(LogicBoard);       // Apply Game logic to see if there is a winner or a draw


            } while (Winner==0); // Stop when a winner or draw is detected


    if (Winner != 3){
    std::cout <<"\n\nWinner is Player " << Player <<" \n\n";
    }
    else {
        std::cout <<"\n\nDraw!\n\n"; // Unless there is a specific winner,
                                     // The game will be a draw
    }

    return 0;                        // End Game
}


All ideas / Comments / Pointers are gratefully received.

Regards,
Dave
Last edited on
Pretty cool man. Without spending time dissecting your code I would suggest making it so you can play against an AI instead of making the user control both players.

Maybe you can try and encapsulate it into several reusable classes and house the AI into one or more classes.

EDIT - if you do decide to attempt writing AI, you will need to not worry so much about rule 3. AI involves a ridiculous amount of if statements.
Last edited on
It is merely a summary of what I have learned over the last 7 - 10 days of C++.

Ai is another issue. Study into real AI. The only other way is to write the game in a Pseudo AI, where the computer always forces a draw.

While perfectly possible, is beyond the scope of what I intended for this. Remember, Iv only been coding in C++ for about 7-10 days. but an advanced project, later on, yes.

I have to walk before I can run, and I'm just taking my first baby steps :)

The 1983 film Wargames springs to mind. http://www.imdb.com/title/tt0086567/
Not quite ready to start WWIII ;)
Last edited on
and I haven't read up on things like 2d arrays.


2d arrays are pretty easy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//declare and initialise 2d array
const unsigned short SIZE = 3;

unsigned short Board[SIZE][SIZE] = {{0,0,0},
                                     {0,0,0},
                                     {0,0,0} };
       
//declare  2d array                                 
unsigned short Board[SIZE][SIZE];
//use for loops to initialise

unsigned short Row;
unsigned short Col;
for(Row = 0;Row < SIZE;Row++)
      for(Col = 0 ;Col < SIZE;Col++ ) {
              Board[Row][Col] = 0;
       }


I think I have said before, this makes it really easy to check rows, cols and diagonals. It also scalable to larger boards.

The use can still choose a spot with numbers from 1 to 9. Use integer division and remainder to get the row and col. Subtract 1 from the user input, then divide by 3 answer is the row, remainder is the col.

Now some file structure stuff.

Normally, one declares functions before main, then put the function definitions after main. This makes it more readable because we don't have scroll all the way down to see what main does.

Another thing to do (It is more of a C approach) is to put the function definitions in a separate file, there are details of how to do that in the C Programming book link I sent a while back.

The C++ approach is to use classes - that is a little bit of a different concept.

With the ClearConsole function, 500 newlines seems a bit much - would 100 be OK? This function could be void - there is no need to return a value. Same for the BoardDisplay function.

With the function PlayerMove, I would prefer to test the validty, instead of making it part of a loop condition, and I still have a "bee in my bonnet" about do loops:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Function that controls player move
unsigned PlayerMove(int DeterminePlayer)

{
    bool ValidInput = true;
    unsigned Input = 1;
    char BoxSelect;

    while (ValidInput) {

       if (!ValidInput ) {
             std::cout  << "Invalid Input - Try again"
       }

        std::cout << "Player " << DeterminePlayer << " Move \n";
        std::cout << "Enter Box number 1-9\n";

        std::cin >> Input;

      //Make sure only 1 - 9 is pressed !
         if (cin.fail || Input < 1 || Input >9) { //braces not needed but I do it in case I add more code later
                ValidInput = false;
         }
         else {
                 ValidInput = true;
         }
    } 
    return Input;
}


I have made use of bool variables and removed the do loops, which are things you could do through the rest of the program if you want.

Good Luck !!


Last edited on
Topic archived. No new replies allowed.