Search code examples
c++incrementdo-whiletic-tac-toe

Error in Tic-Tac-Toe Game


I'm having trouble with this C++ code when creating a program that simulates a tic-tac-toe game. The game runs "fine", displays the winner, validates input, etc., but if the player 'X' wins, the player 'O' is still allowed to make another move before the winner is announced.

do
{
    int turn = 0;

    if (turn % 2 == 0)
    {
        cout << "Player X, Row and Column: ";
        cin >> row >> column;

        while (array[(row-1)][(column-1)] != '*')
        {
            cout << "Invalid move try again \n";
            cout << "Player X, Row and Column: ";
            cin >> row >> column;
        }

        array[row-1][column-1] = 'X';
        showArray(array);
        results = checkWin(array);
    }

    if (turn % 2 != 0)
    {
        cout << "Player O, Row and Column: ";
        cin >> row >> column;

        while (array[row-1][column-1] != '*')
        {
            cout << "Invalid move try again \n";
            cout << "Player O, Row and Column: ";
            cin >> row >> column;
        }
        array[row-1][column-1] = 'O';
        showArray(array);
        results = checkWin(array);
    }
    turn++;
}while (results == 0);

I am using a do-while loop that alternates between two players. When I place the incrementing 'turn++;' statement outside both if blocks, the program only allows the player 'X' to move. When I place the 'turn++;' statement within the player 'X' if block, it alternates, but I run into the problem described above. If you have any suggestions please give them. Thanks.


Solution

  • Every time your loop iterates the turn value gets initialize to 0, that is why every time player 'X' get the chance.

    So place int turn = 0, outside the loop.