Search code examples
c++tic-tac-toegame-loop

Issue Switching Players - Tic Tac Toe


I have an issue where I can't seem to switch players (from X to O) correctly, it just switches randomly between the two. Here is my code so far:

#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

bool gameover = false;
char position[3][3] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
char player = 'X';
char player2 = 'O';
void draw(){
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << position[i][j] << " ";
        }
        cout << endl;
    }
}


void input(){
    if (_kbhit()) {
        switch (_getch())
        {
        case '1':
            position[0][0] = player;
            break;
        case '2':
            position[0][1] = player;
            break;
        case '3':
            position[0][2] = player;
            break;
        case '4':
            position[0][3] = player;
            break;
        case '5':
            position[0][4] = player;
            break;
        case '6':
            position[0][5] = player;
            break;
        case '7':
            position[0][6] = player;
            break;
        case '8':
            position[0][7] = player;
            break;
        case '9':
            position[0][8] = player;
            break;
        }
    }

}

void logic() {
    if (player == 'X') {
        player = 'O';
    }
    else {
        player = 'X';
    }
}

int main (){
    while (!gameover) {
        input();
        draw();
        logic();
        system("cls");
    }
    return 0;
}

I'm sorry if this question has been asked so many times before, but I just can't seem to find a fix. I've tried changing system ('cls') to pause instead but doesn't work either.


Solution

  • Checking _kbhit() function documentation:

    _kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0.
    

    So, if the user is not pressing any key, _kbhit() returns 0.
    input() function exits and while loop is constantly changing player variable when the user does nothing...

    When you fix that, your code should handle the positions already played.
    By the way, do you want to draw that all the time?
    It seems you do not need to do it until a valid movement happens.