133 views
Tic-Tac-Toe in C++
Creating a simple console-based Tic-Tac-Toe game in C++ involves designing the game logic and the user interface. Here’s a basic implementation to get you started:
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to print the Tic-Tac-Toe board
void printBoard(const vector<vector<char>>& board) {
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;
}
cout << endl;
}
// Function to check if there's a winner
char checkWinner(const vector<vector<char>>& board) {
// Check rows
for (int i = 0; i < 3; ++i) {
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
return board[i][0];
}
}
// Check columns
for (int j = 0; j < 3; ++j) {
if (board[0][j] == board[1][j] && board[1][j] == board[2][j]) {
return board[0][j];
}
}
// Check diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
return board[0][0];
}
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
return board[0][2];
}
return ' '; // No winner yet
}
int main() {
vector<vector<char>> board(3, vector<char>(3, ' '));
char currentPlayer = 'X';
int row, col;
cout << "Tic-Tac-Toe Game" << endl;
printBoard(board);
int moves = 0;
while (true) {
cout << "Player " << currentPlayer << ", enter row (0-2) and column (0-2): ";
cin >> row >> col;
if (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ') {
cout << "Invalid move! Try again." << endl;
continue;
}
board[row][col] = currentPlayer;
printBoard(board);
char winner = checkWinner(board);
if (winner != ' ') {
cout << "Player " << winner << " wins!" << endl;
break;
}
if (++moves == 9) {
cout << "It's a draw!" << endl;
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
return 0;
}
In this code:
- We create a 3×3 vector to represent the Tic-Tac-Toe board.
- We have functions to print the board, check for a winner, and handle player turns.
- The game loop continues until there’s a winner or a draw.
- Players take turns entering row and column coordinates to make their moves.
- The game announces the winner or declares a draw when the game ends.
This is a basic console-based Tic-Tac-Toe game. You can further enhance it by adding features like input validation, error handling, and a replay option.