#include <iostream>
using namespace std;
// Function to initialize the board
void initializeBoard(char board[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
}
// Function to display the board
void displayBoard(char board[3][3]) {
cout << " 1 2 3" << endl;
for (int i = 0; i < 3; i++) {
cout << i + 1 << " ";
for (int j = 0; j < 3; j++) {
cout << board[i][j];
if (j < 2) cout << "|";
}
cout << endl;
if (i < 2) cout << " -+-+-" << endl;
}
}
// Function to check for a win
bool checkWin(char board[3][3], char player) {
// Check rows and columns
for (int i = 0; i < 3; i++) {
if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) ||
(board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
return true;
}
}
// Check diagonals
if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) ||
(board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
return true;
}
return false;
}
// Function to check for a tie
bool checkTie(char board[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') return false;
}
}
return true;
}
// Function to handle player input
bool makeMove(char board[3][3], char player) {
int row, col;
cout << "Player " << player << ", enter your move (row and column): ";
cin >> row >> col;
if (row < 1 || row > 3 || col < 1 || col > 3 || board[row-1][col-1] != ' ') {
cout << "Invalid move. Try again." << endl;
return false;
}
board[row-1][col-1] = player;
return true;
}
int main() {
char board[3][3];
char currentPlayer = 'X';
bool gameWon = false;
initializeBoard(board);
while (true) {
displayBoard(board);
if (makeMove(board, currentPlayer)) {
if (checkWin(board, currentPlayer)) {
displayBoard(board);
cout << "Player " << currentPlayer << " wins!" << endl;
gameWon = true;
break;
} else if (checkTie(board)) {
displayBoard(board);
cout << "It's a tie!" << endl;
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; // Switch player
}
}
return 0;
}