Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to write the Tic-Tac-Toe game in C++

1 Answer

0 votes
#include <iostream>
#include <array>

/*
    A simple, expressive Tic‑Tac‑Toe game implemented in C++.

    Highlights:
      - The board is represented using std::array<char, 9>.
      - Functions handle board printing, move validation, win checking,
        and turn progression.
      - The game loop is clear and easy to follow.
      - Comments explain the reasoning behind each part of the program.
*/

// Print the board in a human‑friendly 3×3 layout
void printBoard(const std::array<char, 9>& board) {
    std::cout << "\n";
    for (int i = 0; i < 9; i++) {
        std::cout << board[i];
        if ((i + 1) % 3 == 0)
            std::cout << "\n";
        else
            std::cout << " | ";
    }
    std::cout << "\n";
}

// Check if a player has won
bool checkWin(const std::array<char, 9>& board, char player) {
    // All winning combinations
    const int wins[8][3] = {
        {0,1,2}, {3,4,5}, {6,7,8}, // rows
        {0,3,6}, {1,4,7}, {2,5,8}, // columns
        {0,4,8}, {2,4,6}           // diagonals
    };

    for (auto& w : wins) {
        if (board[w[0]] == player &&
            board[w[1]] == player &&
            board[w[2]] == player)
            return true;
    }

    return false;
}

// Check if the board is full (draw)
bool boardFull(const std::array<char, 9>& board) {
    for (char c : board) {
        if (c == ' ')
            return false;
    }

    return true;
}

// Attempt to place a move; return true if successful
bool placeMove(std::array<char, 9>& board, int pos, char player) {
    // Validate position
    if (pos < 0 || pos >= 9)
        return false;

    // Ensure the cell is empty
    if (board[pos] != ' ')
        return false;

    board[pos] = player;

    return true;
}

int main() {
    // Board initialized with spaces
    std::array<char, 9> board{};
    board.fill(' ');

    char currentPlayer = 'X';

    std::cout << "Tic‑Tac‑Toe\n";
    printBoard(board);

    while (true) {
        std::cout << "Player " << currentPlayer << ", enter position (0‑8): ";

        int pos;
        std::cin >> pos;

        // Try to place the move
        if (!placeMove(board, pos, currentPlayer)) {
            std::cout << "Invalid move. Try again.\n";
            continue;
        }

        printBoard(board);

        // Check win
        if (checkWin(board, currentPlayer)) {
            std::cout << "Player " << currentPlayer << " wins!\n";
            break;
        }

        // Check draw
        if (boardFull(board)) {
            std::cout << "It's a draw!\n";
            break;
        }

        // Switch player
        currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
    }
}


/*
run:

Tic‑Tac‑Toe

  |   |  
  |   |  
  |   |  

Player X, enter position (0‑8): 0

X |   |  
  |   |  
  |   |  

Player O, enter position (0‑8): 1

X | O |  
  |   |  
  |   |  

Player X, enter position (0‑8): 8

X | O |  
  |   |  
  |   | X

Player O, enter position (0‑8): 4

X | O |  
  | O |  
  |   | X

Player X, enter position (0‑8): 6

X | O |  
  | O |  
X |   | X

Player O, enter position (0‑8): 7

X | O |  
  | O |  
X | O | X

Player O wins!

*/

 



answered 5 days ago by avibootz
...