Untitled
// Online C++ compiler to run C++ program online #include <iostream> #include <vector> using namespace std; class TicTacToe { private: vector<vector<int>> board; char currentPlayer; public: TicTacToe() { board = vector<vector<int>>(3, vector<int>(3)); int num = 1; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { board[i][j] = num++; } } currentPlayer = 'X'; } void printBoard() { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (board[i][j] == 'X' || board[i][j] == 'O') cout << (char)board[i][j]; else cout << board[i][j]; if (j < 2) cout << " | "; } cout << endl; if (i < 2) cout << "--|---|--" << endl; } } bool makeMove(int choice) { int row = (choice - 1) / 3; int col = (choice - 1) % 3; if (choice < 1 || choice > 9 || board[row][col] == 'X' || board[row][col] == 'O') { cout << "Invalid move. Try again." << endl; return false; } board[row][col] = currentPlayer; return true; } bool checkWin() { for (int i = 0; i < 3; ++i) { if (board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) return true; if (board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer) return true; } if (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) return true; if (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer) return true; return false; } bool isDraw() { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (board[i][j] != 'X' && board[i][j] != 'O') return false; } } return true; } void switchPlayer() { currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; } void playGame() { while (true) { printBoard(); int choice; cout << "Player " << currentPlayer << "'s turn. Enter the number of the cell: "; cin >> choice; if (makeMove(choice)) { if (checkWin()) { printBoard(); cout << "Player " << currentPlayer << " wins!" << endl; break; } else if (isDraw()) { printBoard(); cout << "It's a draw!" << endl; break; } switchPlayer(); } } } }; int main() { TicTacToe game; game.playGame(); return 0; }
Leave a Comment