cplusplus
cplusplus

 

Introduction

Tic-Tac-Toe is a classic two-player game where players take turns marking a 3×3 grid with ‘X’ and ‘O’.
The objective is to get three of your marks in a row, either horizontally, vertically, or diagonally.
This C++ program enhances the traditional game by introducing a simple AI opponent that plays against the user.
The AI opponent will make moves based on a basic strategy to challenge the player.

Objective

The goal of this project is to create an interactive Tic-Tac-Toe game where one player plays against the computer.
The AI will play optimally to either win or draw, ensuring that the player will have to think strategically to win.

Code

#include 
#include 

using namespace std;

char board[3][3] = {{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
char currentPlayer = 'X';

void printBoard() {
    cout << "-------------\n";
    for (int i = 0; i < 3; i++) {
        cout << "| ";
        for (int j = 0; j < 3; j++) {
            cout << board[i][j] << " | ";
        }
        cout << endl;
        cout << "-------------\n";
    }
}

bool checkWin(char player) {
    for (int i = 0; i < 3; i++) {
        if ((board[i][0] == player && board[i][1] == player && board[i][2] == player) || 
            (board[0][i] == player && board[1][i] == player && board[2][i] == player)) {
            return true;
        }
    }
    if ((board[0][0] == player && board[1][1] == player && board[2][2] == player) || 
        (board[0][2] == player && board[1][1] == player && board[2][0] == player)) {
        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 playerMove() {
    int row, col;
    cout << "Enter row and column (0-2) for your move: "; cin >> row >> col;
    if (board[row][col] == ' ') {
        board[row][col] = 'X';
    } else {
        cout << "Cell already taken. Try again." << endl;
        playerMove();
    }
}

int minimax(int depth, bool isMaximizing) {
    if (checkWin('O')) return 1;
    if (checkWin('X')) return -1;
    if (isBoardFull()) return 0;

    if (isMaximizing) {
        int best = -1000;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = 'O';
                    best = max(best, minimax(depth + 1, false));
                    board[i][j] = ' ';
                }
            }
        }
        return best;
    } else {
        int best = 1000;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (board[i][j] == ' ') {
                    board[i][j] = 'X';
                    best = min(best, minimax(depth + 1, true));
                    board[i][j] = ' ';
                }
            }
        }
        return best;
    }
}

void aiMove() {
    int bestVal = -1000;
    int row = -1, col = -1;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) { if (board[i][j] == ' ') { board[i][j] = 'O'; int moveVal = minimax(0, false); board[i][j] = ' '; if (moveVal > bestVal) {
                    row = i;
                    col = j;
                    bestVal = moveVal;
                }
            }
        }
    }
    board[row][col] = 'O';
}

int main() {
    cout << "Welcome to Tic-Tac-Toe! You are 'X' and the AI is 'O'.\n";
    printBoard();
    while (true) {
        playerMove();
        printBoard();
        if (checkWin('X')) {
            cout << "You win!" << endl;
            break;
        }
        if (isBoardFull()) {
            cout << "It's a draw!" << endl;
            break;
        }
        aiMove();
        printBoard();
        if (checkWin('O')) {
            cout << "AI wins!" << endl;
            break;
        }
        if (isBoardFull()) {
            cout << "It's a draw!" << endl;
            break;
        }
    }
    return 0;
}

Explanation of the Program

The program simulates a Tic-Tac-Toe game where the player competes against a simple AI opponent. The main components of the program are:

  • Board Representation: A 3×3 array `board` is used to store the state of the game grid. Each cell in the array holds either ‘X’, ‘O’, or a space character representing an empty spot.
  • Player and AI Move: The player makes a move by entering a row and column. The AI uses the minimax algorithm to calculate the optimal move based on the current board state.
  • Minimax Algorithm: This algorithm recursively evaluates the possible future moves and selects the one that maximizes the AI’s chances of winning, while minimizing the player’s chances.
  • Game Flow: The game alternates between the player’s move and the AI’s move until one player wins or the board is full (draw).

How to Run the Program

To run the program, follow these steps:

  1. Make sure you have a C++ compiler installed on your system (e.g., GCC).
  2. Create a new file called tic_tac_toe.cpp and copy the provided code into this file.
  3. Open a terminal or command prompt and navigate to the directory where your file is saved.
  4. Compile the program using the following command:
    g++ -o tic_tac_toe tic_tac_toe.cpp
  5. Run the program with:
    ./tic_tac_toe
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)