Site icon DataFlair

C++ Project – Tic Tac Toe Game

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

#include <iostream>
using namespace std;

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

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

bool checkWin(char player) {
    // Check rows and columns
    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;
            }
    }

    // Check diagonals
    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;
}

int main()
 {
    char currentPlayer = 'X';
    int row, col;
    cout << "Welcome to Tic Tac Toe!\n";
    printBoard();

    while (1) 
    {
        cout << "Player " << currentPlayer << ", enter your move (row and column: 1-3): ";
        cin >> row >> col;

        row--; col--; // Adjust for 0-based index

        if (row < 0 || row > 2 || col < 0 || col > 2) 
        {
            cout << "Invalid input. Try again.\n";
            continue;
        }

        if (board[row][col] != ' ') 
        {
            cout << "Cell already taken. Try again.\n";
            continue;
        }

        board[row][col] = currentPlayer;
        printBoard();

        if (checkWin(currentPlayer)) 
        {
            cout << "Congrats Player " << currentPlayer << " wins!\n";
            break;
        } 
        else if (isBoardFull()) 
         {
            cout << "It's a draw!\n";
            break;
        }
         else 
         {
            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        }
    }

    return 0;
}

 

Exit mobile version