Here's a simple console-based C++ code for a two-player Tic Tac Toe game:
cpp
Copy code
#include <iostream>
using namespace std;
char board[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
char currentPlayer = 'X';
void drawBoard() {
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;
}
}
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 checkWin() {
// Check rows, columns, and diagonals for a win
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;
}
int main() {
int row, col;
int moves = 0;
cout << "Welcome to Tic Tac Toe!" << endl;
while (true) {
drawBoard();
cout << "Player " << currentPlayer << ", enter row (1-3) and column (1-3): ";
cin >> row >> col;
row--;
col--;
if (makeMove(row, col)) {
moves++;
if (checkWin()) {
drawBoard();
cout << "Player " << currentPlayer << " wins!" << endl;
break;
} else if (moves == 9) {
drawBoard();
cout << "It's a draw!" << endl;
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
} else {
cout << "Invalid move. Try again." << endl;
}
}
return 0;
}
This code provides a basic implementation of a two-player Tic Tac Toe game in the console. Players take turns making moves by entering the row and column where they want to place their symbol ('X' or 'O'). The game checks for a win or a draw condition after each move. You can further enhance the code by adding input validation and improving the user interface.
Post a Comment