Thursday 2 May 2024

Tic-Tac-Toe Game in C++

How to Run the Game:
1. Save the C++ code into a file named 'TicTacToe.cpp'.
2. Compile the code using the command: g++ -o TicTacToe TicTacToe.cpp
3. Run the executable in the command line: ./TicTacToe
Game Explanation:
- The game consists of a 3x3 grid where two players take turns marking their spaces (one with 'X'
and the other with 'O').
- The game starts with Player 1 using 'X'.
- Players enter their moves by specifying the row and column numbers where they want to place
their mark.
- The game checks for a win or a draw after every move.
- The game ends when one player has three of their marks in a row, column, or diagonal, or when all
spaces are filled, resulting in a draw.
C++ CODE:
#include <iostream>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
int current_player = 1;
char current_marker;
void drawBoard() {
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 placeMarker(int slot) {
int row = (slot - 1) / 3;
int col = (slot - 1) % 3;
if (board[row][col] != 'X' && board[row][col] != 'O') {
board[row][col] = current_marker;
return true;
}
return false;
}
int winner() {
for (int i = 0; i < 3; i++) {
// Check rows and columns
if (board[i][0] == board[i][1] && board[i][1] == board[i][2]) return current_player;
if (board[0][i] == board[1][i] && board[1][i] == board[2][i]) return current_player;
}
// Check diagonals
if (board[0][0] == board[1][1] && board[1][1] == board[2][2]) return current_player;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0]) return current_player;
return 0;
}
void swap_turns() {
current_player = (current_player == 1) ? 2 : 1;
current_marker = (current_marker == 'X') ? 'O' : 'X';
}
void game() {
cout << "Player one, choose your marker (X or O): ";
cin >> current_marker;
drawBoard();
int player_won;
for (int i = 0; i < 9; i++) {
cout << "It's player " << current_player << "'s turn. Enter your slot: ";
int slot;
cin >> slot;
if (!placeMarker(slot)) {
cout << "That slot is occupied! Try another slot!" << endl;
i--;
continue;
}
drawBoard();
player_won = winner();
if (player_won != 0) break;
swap_turns();
}
if (player_won != 0) cout << "Player " << player_won << " wins!" << endl;
else cout << "The game is a draw!" << endl;
}
int main() {
game();
return 0;
}