Untitled
unknown
plain_text
10 months ago
2.6 kB
4
Indexable
// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
using namespace std;
class TicTacToe {
private:
vector<vector<char>> board;
char currentPlayer;
public:
TicTacToe() {
board = vector<vector<char>>(3, vector<char>(3, ' '));
currentPlayer = 'X';
}
void printBoard() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << board[i][j];
if (j < 2) cout << " | ";
}
cout << endl;
if (i < 2) cout << "---------" << endl;
}
}
bool makeMove(int row, int col) {
if (row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == ' ') {
board[row][col] = currentPlayer;
return true;
}
return false;
}
bool checkWinner() {
// Check rows and columns
for (int i = 0; i < 3; ++i) {
if ((board[i][0] == currentPlayer && board[i][1] == currentPlayer && board[i][2] == currentPlayer) ||
(board[0][i] == currentPlayer && board[1][i] == currentPlayer && board[2][i] == currentPlayer)) {
return true;
}
}
// Check diagonals
if ((board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) ||
(board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)) {
return true;
}
return false;
}
bool isBoardFull() {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i][j] == ' ') return false;
}
}
return true;
}
void switchPlayer() {
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
void playGame() {
int row, col;
while (true) {
printBoard();
cout << "Player " << currentPlayer << ", enter your move (row and column): ";
cin >> row >> col;
if (!makeMove(row - 1, col - 1)) {
cout << "Invalid move. Try again!" << endl;
continue;
}
if (checkWinner()) {
printBoard();
cout << "Player " << currentPlayer << " wins!" << endl;
break;
}
if (isBoardFull()) {
printBoard();
cout << "It's a draw!" << endl;
break;
}
switchPlayer();
}
}
};
int main() {
TicTacToe game;
game.playGame();
return 0;
}Editor is loading...
Leave a Comment