C++ · Module 19 · Lesson 51 min read

Project: Tic-Tac-Toe with an Unbeatable AI

Features checklist

  1. Board class: 3×3 cells, place a mark, check winner/draw, print
  2. Player abstract class with virtual int choose_move(const Board&)
  3. HumanPlayer reads moves from std::cin and validates them
  4. AIPlayer uses minimax to pick the best move
  5. Game class runs turns until win or draw, announces the result
  6. Play several rounds and keep a scoreboard

Minimax in one paragraph

Try every free cell. For each, recursively imagine the opponent's best reply, and so on to the end of the game. Score final positions: win = +10, loss = −10, draw = 0 (subtract depth to prefer quicker wins). The AI picks the move with the maximum score assuming the opponent always picks the minimum. Tic-tac-toe has at most 9! ≈ 362,880 move sequences, so a full search is instant.

Design

perl
class Board { std::array<char, 9> cells_; place(), winner(), full(), free_cells(), print() };
class Player { virtual ~Player(); virtual int choose_move(const Board&) = 0; char mark; };
class HumanPlayer : public Player { ... };
class AIPlayer : public Player { int minimax(Board&, bool maximizing, int depth); };
class Game { std::unique_ptr<Player> x_, o_; play(); };

Concepts practised

std::array, abstract classes and override, std::unique_ptr<Player>, recursion and backtracking (place, recurse, undo), input validation loops, constexpr win-line table.

Extensions

Alpha-beta pruning, difficulty levels (random moves sometimes), Connect Four (bigger board → depth-limited minimax), saving statistics to a file, colours with ANSI codes.

Example

SQL
#include <array>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>

class Board {
public:
    Board() { cells_.fill(' '); }
    bool place(int cell, char mark) {
        if (cell < 0 || cell > 8 || cells_[cell] != ' ') return false;
        cells_[cell] = mark;
        return true;
    }
    void clear(int cell) { cells_[cell] = ' '; }
    char winner() const {
        static constexpr int LINES[8][3] = { {0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6} };
        for (const auto& l : LINES)
            if (cells_[l[0]] != ' ' && cells_[l[0]] == cells_[l[1]] && cells_[l[1]] == cells_[l[2]]) return cells_[l[0]];
        return ' ';
    }
    bool full() const { for (char c : cells_) if (c == ' ') return false; return true; }
    std::vector<int> free_cells() const {
        std::vector<int> v;
        for (int i = 0; i < 9; ++i) if (cells_[i] == ' ') v.push_back(i);
        return v;
    }
    void print() const {
        for (int r = 0; r < 3; ++r) {
            std::cout << ' ' << cells_[r * 3] << " | " << cells_[r * 3 + 1] << " | " << cells_[r * 3 + 2] << '\n';
            if (r < 2) std::cout << "---+---+---\n";
        }
    }
private:
    std::array<char, 9> cells_;
};

class Player {
public:
    explicit Player(char mark) : mark_(mark) {}
    virtual ~Player() = default;
    virtual int choose_move(const Board& b) = 0;
    virtual std::string name() const = 0;
    char mark() const { return mark_; }
protected:
    char mark_;
};

class HumanPlayer : public Player {
public:
    using Player::Player;
    std::string name() const override { return "You"; }
    int choose_move(const Board& b) override {
        int cell;
        while (true) {
            std::cout << "Your move (1-9): ";
            if (!(std::cin >> cell)) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cell = 0; }
            std::cout << cell << '\n';
            Board copy = b;
            if (copy.place(cell - 1, mark_)) return cell - 1;
            std::cout << "Invalid move, try again\n";
        }
    }
};

class AIPlayer : public Player {
public:
    using Player::Player;
    std::string name() const override { return "Computer"; }
    int choose_move(const Board& b) override {
        Board work = b;
        int best_score = std::numeric_limits<int>::min(), best = -1;
        for (int cell : work.free_cells()) {
            work.place(cell, mark_);
            int score = minimax(work, false, 1);
            work.clear(cell);
            if (score > best_score) { best_score = score; best = cell; }
        }
        std::cout << "Computer plays " << best + 1 << '\n';
        return best;
    }
private:
    char opponent() const { return mark_ == 'X' ? 'O' : 'X'; }
    int minimax(Board& b, bool maximizing, int depth) {
        char w = b.winner();
        if (w == mark_) return 10 - depth;               // prefer faster wins
        if (w == opponent()) return depth - 10;          // prefer slower losses
        if (b.full()) return 0;
        int best = maximizing ? std::numeric_limits<int>::min() : std::numeric_limits<int>::max();
        for (int cell : b.free_cells()) {
            b.place(cell, maximizing ? mark_ : opponent());   // try
            int score = minimax(b, !maximizing, depth + 1);   // recurse
            b.clear(cell);                                    // undo (backtracking)
            best = maximizing ? std::max(best, score) : std::min(best, score);
        }
        return best;
    }
};

class Game {
public:
    Game(std::unique_ptr<Player> first, std::unique_ptr<Player> second)
        : players_{ std::move(first), std::move(second) } {}
    char play() {
        Board board;
        for (int turn = 0; ; ++turn) {
            Player& p = *players_[turn % 2];
            board.place(p.choose_move(board), p.mark());
            if (char w = board.winner(); w != ' ') { board.print(); std::cout << p.name() << " won!\n"; return w; }
            if (board.full()) { board.print(); std::cout << "It's a draw!\n"; return ' '; }
        }
    }
private:
    std::array<std::unique_ptr<Player>, 2> players_;
};

int main() {
    std::cout << "== Round 1: you (X) vs computer (O) ==\n";
    Game g1(std::make_unique<HumanPlayer>('X'), std::make_unique<AIPlayer>('O'));
    g1.play();

    std::cout << "== Round 2: computer vs computer ==\n";
    Game g2(std::make_unique<AIPlayer>('X'), std::make_unique<AIPlayer>('O'));
    char result = g2.play();
    std::cout << "Perfect play from both sides ends in " << (result == ' ' ? "a draw" : "a win") << '\n';
    return 0;
}

/* Output:
== Round 1: you (X) vs computer (O) ==
Your move (1-9): 1
Computer plays 5
Your move (1-9): 5
Invalid move, try again
Your move (1-9): 2
Computer plays 3
Your move (1-9): 9
Computer plays 7
 X | X | O
---+---+---
   | O |
---+---+---
 O |   | X
Computer won!
== Round 2: computer vs computer ==
Computer plays 1
Computer plays 5
Computer plays 2
Computer plays 3
Computer plays 7
Computer plays 4
Computer plays 6
Computer plays 8
Computer plays 9
 X | X | O
---+---+---
 O | O | X
---+---+---
 X | O | X
It's a draw!
Perfect play from both sides ends in a draw
*/