So I'm trying to create a winning condition for tic tac toe game in an if statement. For now I'm just trying to make it so that if there are 3 crosses in a line then player 2 wins. But for some odd reason what happens is that after 2 turns no matter where X and O are placed, player 2 wins and program exits.
There is no way that all 3 variables from the array have an X value after 2 turns because before the X is assigned to them they've got a value of 1, 2 and 3.
The else statement calls the game function which allows users to place circles and crosses in turns.
void game()
{
int iField; //this variable is responsible for placing circle or a cross in chosen field
if (player == 1) //if it's player's one turn then...
{
cout<<"Player O turn:"<<endl;
}
else //if it's player's two turn...
{
cout<<"Player X turn:"<<endl;
}
cin>>iField; //player choses field where he wants to place circle or a cross
if (abFieldStatus[iField - 1] == true) //if the field has already a circle or cross in it then start game function from the beginning
{
cout<<endl<<"Field already taken, try again"<<endl<<endl;
game();
}
else //if not then program places the circle or a cross in correct field and changes the status of the field to already taken.
{
if(player == 1) //if it's player 1 then place a circle
{
switch(iField)
{
case 1: gameBoard[0][0] = 'O'; abFieldStatus[0] = true; break;
case 2: gameBoard[0][1] = 'O'; abFieldStatus[1] = true; break;
case 3: gameBoard[0][2] = 'O'; abFieldStatus[2] = true; break;
case 4: gameBoard[1][0] = 'O'; abFieldStatus[3] = true; break;
case 5: gameBoard[1][1] = 'O'; abFieldStatus[4] = true; break;
case 6: gameBoard[1][2] = 'O'; abFieldStatus[5] = true; break;
case 7: gameBoard[2][0] = 'O'; abFieldStatus[6] = true; break;
case 8: gameBoard[2][1] = 'O'; abFieldStatus[7] = true; break;
case 9: gameBoard[2][2] = 'O'; abFieldStatus[8] = true; break;
default: cout<<"wrong input, try again"; game();
}
system("cls");
displayBoard(); //displays updated board
player = 2; //changes turn to player 2
}
elseif(player == 2) //if it's player 2 then place a cross
{
switch(iField)
{
case 1: gameBoard[0][0] = 'X'; abFieldStatus[0] = true; break;
case 2: gameBoard[0][1] = 'X'; abFieldStatus[1] = true; break;
case 3: gameBoard[0][2] = 'X'; abFieldStatus[2] = true; break;
case 4: gameBoard[1][0] = 'X'; abFieldStatus[3] = true; break;
case 5: gameBoard[1][1] = 'X'; abFieldStatus[4] = true; break;
case 6: gameBoard[1][2] = 'X'; abFieldStatus[5] = true; break;
case 7: gameBoard[2][0] = 'X'; abFieldStatus[6] = true; break;
case 8: gameBoard[2][1] = 'X'; abFieldStatus[7] = true; break;
case 9: gameBoard[2][2] = 'X'; abFieldStatus[8] = true; break;
default: "wrong input, try again"; game();
}
system("cls");
displayBoard();
player = 1;
}
}
}