#include <iostream>
#include <vector>
using namespace std;
// Function prototypes
void displayBoard(const vector<vector<char>>& board);
bool isMoveValid(const vector<vector<char>>& board, int row, int col);
bool isBoardFull(const vector<vector<char>>& board);
char checkForWinner(const vector<vector<char>>& board);
int main() {
const int boardSize = 3;
vector<vector<char>> board(boardSize, vector<char>(boardSize, ' '));
int currentPlayer = 1; // Player 1 starts
int row, col;
do {
// Display the current state of the board
displayBoard(board);
// Get the move from the current player
cout << "Player " << currentPlayer << ", enter your move (row and column): ";
cin >> row >> col;
// Check if the move is valid
if (isMoveValid(board, row, col)) {
// Make the move
board[row][col] = (currentPlayer == 1) ? 'X' : 'O';
// Check for a winner
char winner = checkForWinner(board);
if (winner != ' ') {
displayBoard(board);
cout << "Player " << currentPlayer << " wins!" << endl;
return 0; // End the game
}
// Switch to the other player
currentPlayer = (currentPlayer == 1) ? 2 : 1;
} else {
cout << "Invalid move. Try again." << endl;
}
} while (!isBoardFull(board));
// If the board is full and no winner, it's a tie
displayBoard(board);
cout << "It's a tie!" << endl;
return 0;
}
void displayBoard(const vector<vector<char>>& board) {
cout << " 0 1 2" << endl;
for (int i = 0; i < board.size(); ++i) {
cout << i << " ";
for (int j = 0; j < board[i].size(); ++j) {
cout << board[i][j];
if (j < board[i].size() - 1) {
cout << "|";
}
}
cout << endl;
if (i < board.size() - 1) {
cout << " -----" << endl;
}
}
cout << endl;
}
bool isMoveValid(const vector<vector<char>>& board, int row, int col) {
return (row >= 0 && row < board.size() && col >= 0 && col < board[row].size() && board[row][col] == ' ');
}
bool isBoardFull(const vector<vector<char>>& board) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (board[i][j] == ' ') {
return false; // If any cell is empty, the board is not full
}
}
}
return true; // All cells are filled
}
char checkForWinner(const vector<vector<char>>& board) {
// Check rows and columns
for (int i = 0; i < board.size(); ++i) {
if (board[i][0] != ' ' && board[i][0] == board[i][1] && board[i][0] == board[i][2]) {
return board[i][0]; // Winner in a row
}
if (board[0][i] != ' ' && board[0][i] == board[1][i] && board[0][i] == board[2][i]) {
return board[0][i]; // Winner in a column
}
}
// Check diagonals
if (board[0][0] != ' ' && board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
return board[0][0]; // Winner in the main diagonal
}
if (board[0][2] != ' ' && board[0][2] == board[1][1] && board[0][2] == board[2][0]) {
return board[0][2]; // Winner in the other diagonal
}
return ' '; // No winner yet
}