To test my C++ skills, i tried making a tic tac toe game. There is an error though. Occasionally it will put the X in the wrong spot, or it will put 2 letters on the board. Can you please tell me why itll put 2 letters on or why it doesnt put it in the right spot? Thanks!!!
Code:#include <iostream> using namespace std; class board { char board[2][2]; public: board() { for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { board[i][j] = ' '; } } } void display() { cout << " X \n"; cout << " 0 | 1 | 2\n\n"; for(int i = 0; i < 3; i++) { cout << " " << board[i][0] << " | " << board[i][1] << " | " << board[i][2] << " "; cout << " " << i; if(i == 1) { cout << " Y "; } if(i != 2) { cout << "\n---|---|--- -\n"; } } } void playerMove() { int x, y; cout << "\nEnter x coordinate: "; cin >> x; cout << "\nEnter y coordinate: "; cin >> y; if(board[x][y] != ' ') { cout << "Incorrect coordinate. Please enter again.\n"; playerMove(); } else { board[x][y] = 'X'; } } void computerMove() { if((board[0][0] == board[1][1]) && (board[2][2] == ' ')) { board[2][2] = 'O'; return; } if((board[1][1] == board[2][2]) && (board[0][0] == ' ')) { board[0][0] = 'O'; return; } if((board[0][0] == board[2][2]) && (board[1][1] == ' ')) { board[1][1] = 'O'; return; } if((board[0][2] == board[1][1]) && (board[2][0] == ' ')) { board[2][0] = 'O'; return; } if((board[2][0] == board[1][1]) && (board[0][2] == ' ')) { board[0][2] = 'O'; return; } if((board[2][0] == board[0][2]) && (board[1][1] == ' ')) { board[1][1] = 'O'; return; } for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { if(board[i][j] == ' ') { board[i][j] = 'O'; return; } } } } char checkWinner() { for(int i = 0; i < 3; i++) { if((board[i][0] == board[i][1]) && (board[i][1] == board[i][2])) { return board[i][0]; } if((board[0][i] == board[1][i]) && (board[1][i] == board[2][i])) { return board[0][i]; } } if((board[0][0] == board[1][1]) && (board[1][1] == board[2][2])) { return board[0][0]; } if((board[0][2] == board[1][1]) && (board[1][1] == board[2][0])) { return board[0][2]; } return ' '; } }; int main() { board b; char win; do { b.display(); b.playerMove(); win = b.checkWinner(); if(win != ' ') { break; } b.computerMove(); win = b.checkWinner(); } while(win == ' '); if(win == 'X') { cout << "\nYOU WIN!\n\n"; } else { cout << "\nTHE COMPUTER WINS!\n\n"; } b.display(); return 0; }