I have a tic tac toe game I made, I am not done yet, but I made it so that if I get the first three rows I win the game for X.
But for some reason it doesn’t work. It prints out that I won, BUT it doesn’t end the while loop and break out and finish the game.
What am I missing?
#include <iostream>
using namespace std;
// Initialize Array to 9 elements.
// Set array elements 1 to 9 to specify locations for placement of X and O.
char ticTacBoard[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
// gameState will return 1 to 4. #1. PlayerXhaswon, #2. PlayerYhaswon, #3. Draw, #4. GameNotFinished.
int gameState = 0;
int choosePositionX = 0;
int choosePositionO = 0;
// Functions declared to run game.
// Checks for winners, draw and if game should continue.
int checkGameState (int gameState);
// Takes in users moves.
void makeMove ();
// Resets board when game finished.
void reset ();
// Prints the board to the user.
void printBoard ();
int main()
{
cout << "Welcome to Tic Tac Toe!" << endl << endl
<< "The goal of Tic Tac Toe is to be the first player to get three in a row on the grid." << endl << endl
<< "Please select 1 through 9 to select placement for your turn."<< endl << endl;
int gameState = 4;
while ( gameState == 4)
{
printBoard();
cout << "Player X please choose a position: ";
cin >> choosePositionX; makeMove();
printBoard();
gameState = checkGameState(gameState);
cout << "Player O please choose a position: ";
cin >> choosePositionO;
makeMove();
printBoard();
gameState = checkGameState(gameState);
}
cout << " END";
return 0;
}
int checkGameState(int gameState)
{
// Check Rows
if(ticTacBoard[0] == 'X' && ticTacBoard[1] == 'X' && ticTacBoard[2] == 'X')
{
cout << "YOU WIN!" << endl;
return 1;
}
if(ticTacBoard[3] == 'X' && ticTacBoard[4] == 'X' && ticTacBoard[5] == 'X')
{
cout << "YOU WIN!" << endl;
return gameState = 1;
}
if(ticTacBoard[6] == 'X' && ticTacBoard[7] == 'X' && ticTacBoard[8] == 'X')
{
cout << "YOU WIN!" << endl;
return gameState = 1;
}
else
return gameState = 4;
}
void makeMove()
{
if ( choosePositionX )
{
ticTacBoard[choosePositionX - 1] = 'X';
}
if ( choosePositionO )
{
ticTacBoard[choosePositionO - 1] = 'O';
}
}
void printBoard()
{
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
cout << ticTacBoard[3 * y + x] << " ";
}
cout << endl;
}
cout << endl;
}
You never use the return value of checkGameState. You probably want to either pass gameState by reference and return void, or do gameState = checkGameState(gameState).
If you do the former, then you change them all to
gameState = 1; return;If you do the latter, then you just change them toreturn 1;Version passing by reference: