Search code examples
tic-tac-toe

How to validate player input in tic tac toe?


Hi i am trying to make a tic tac toe game where the player plays against the pc. The only problem is that i cannot validate the move of the player or pc, as in, if the pc places its move on the board the player cannot place their move in that same spot as it will be occupied.The same goes for the pc. My code is down below so have a look at it and let me know how to rectify it.

for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        board[row][col]=' ';
    }
}
cout << endl << endl;
for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        cout << "|" << board[row][col] <<  "|" ;
    }
    cout << endl << "|-||-||-|" ;
    cout << endl;
}
cout << endl << endl << endl;

cout << "Are you player 1 or 2?: ";
cin >> player;
cout << endl << endl << endl;

    if(player==1){
        cout << "Your symbol is 'O'.The computer's is 'X' " << endl;
    }else if(player==2){
        cout << "Your symbol is 'X'.The computer's is 'O' " << endl;
    }
    cout << endl << endl;



while(Gameover==false){

    while(win==false){
    if(player==1){
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;

    srand(time(0));
    x=rand()%3;
    y=rand()%3;

    cout << endl << endl << endl;

    if(board[row][col]!=' '){
    cout << "Invalid move.That spot is already occupied.";
    cout << endl << endl << endl;
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;
    srand(time(0));
    x=rand()%3;
    y=rand()%3;
    }
    board[r][c]='O';
    board[x][y]='X';


}else if(player==2){
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;

    srand(time(0));
    x=rand()%3;
    y=rand()%3;

    if(board[row][col]!=' '){
    cout << "Invalid move.That spot is already occupied.";
    cout << endl << endl << endl;
    cout << "Enter row: ";
    cin >> r;
    cout << "Enter column: ";
    cin >> c;
    srand(time(0));
    x=rand()%3;
    y=rand()%3;
    }
    board[r][c]='X';
    board[x][y]='O';
}
    cout << endl << endl << endl;

for(row=0;row<3;row++){
    for(col=0;col<3;col++){
        cout << "|" << board[row][col]  <<  "|" ;
    }
    cout << endl << "|-||-||-|" ;
    cout << endl;
}
cout << endl << endl << endl;
    }

}

return 0; }


Solution

  • you have a logic problem in the loop ,if(board[row][col]!=' ') sentence should be While(board[r][c]!=' ' then after this loop you have to test the computer player values like While (board[y][x]!=' ') after these to loops, you will put the values, the if clause will test once if the user enter the second time occupied place you will not know.