跳到正文

休闲·娱乐

AI五子棋

yu_rui约 18 分钟
原文
文章信息与版本

文章信息

发布
2025年4月15日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 18 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
#include <ctime>

using namespace std;

const int SIZE = 15;
const int WIN = 1000000;
const int LOSE = -1000000;
const int MAX_DEPTH = 4;  // 搜索深度,可调整

enum ChessType { EMPTY, BLACK, WHITE };

class Board {
public:
    ChessType board[SIZE][SIZE];

    Board() {
        for (int i = 0; i < SIZE; ++i)
            for (int j = 0; j < SIZE; ++j)
                board[i][j] = EMPTY;
    }

    bool is_valid(int x, int y) const {
        return x >= 0 && x < SIZE && y >= 0 && y < SIZE;
    }

    bool is_empty(int x, int y) const {
        return is_valid(x, y) && board[x][y] == EMPTY;
    }

    bool check_win(int x, int y, ChessType type) const {
        const int dir[4][2] = {{1,0}, {0,1}, {1,1}, {1,-1}};
        for (int d = 0; d < 4; ++d) {
            int count = 1;
            for (int step = 1; step <= 4; ++step) {
                int nx = x + dir[d][0] * step;
                int ny = y + dir[d][1] * step;
                if (!is_valid(nx, ny) || board[nx][ny] != type) break;
                ++count;
            }
            for (int step = 1; step <= 4; ++step) {
                int nx = x - dir[d][0] * step;
                int ny = y - dir[d][1] * step;
                if (!is_valid(nx, ny) || board[nx][ny] != type) break;
                ++count;
            }
            if (count >= 5) return true;
        }
        return false;
    }
};

class AI {
private:
    ChessType ai_color;

    int evaluate_line(const vector<ChessType>& line) const {
        int score = 0;
        int count = 0;
        ChessType prev = EMPTY;

        for (size_t i = 0; i < line.size(); ++i) {
            if (line[i] == prev && line[i] != EMPTY) {
                ++count;
            } else {
                if (prev != EMPTY) {
                    score += evaluate_pattern(count, prev == ai_color);
                }
                count = 1;
                prev = line[i];
            }
        }
        if (prev != EMPTY) {
            score += evaluate_pattern(count, prev == ai_color);
        }
        return score;
    }

    int evaluate_pattern(int length, bool is_ai) const {
        const int score_table[6] = {0, 1, 10, 100, 1000, 10000};
        if (length >= 5) return is_ai ? WIN : LOSE;
        int score = score_table[length];
        return is_ai ? score : -score;
    }

    int evaluate(const Board& board) const {
        int total = 0;

        // 横向评估
        for (int i = 0; i < SIZE; ++i) {
            vector<ChessType> line;
            for (int j = 0; j < SIZE; ++j)
                line.push_back(board.board[i][j]);
            total += evaluate_line(line);
        }

        // 纵向评估
        for (int j = 0; j < SIZE; ++j) {
            vector<ChessType> line;
            for (int i = 0; i < SIZE; ++i)
                line.push_back(board.board[i][j]);
            total += evaluate_line(line);
        }

        // 对角线评估
        for (int k = 0; k < SIZE*2-1; ++k) {
            vector<ChessType> line;
            for (int i = max(0, k-SIZE+1); i <= min(k, SIZE-1); ++i)
                line.push_back(board.board[i][k-i]);
            total += evaluate_line(line);
        }

        // 反对角线评估
        for (int k = 0; k < SIZE*2-1; ++k) {
            vector<ChessType> line;
            for (int i = max(0, k-SIZE+1); i <= min(k, SIZE-1); ++i)
                line.push_back(board.board[i][SIZE-1-(k-i)]);
            total += evaluate_line(line);
        }

        return total;
    }

    void generate_moves(const Board& board, vector<pair<int, int> >& moves) const {
        for (int i = 0; i < SIZE; ++i) {
            for (int j = 0; j < SIZE; ++j) {
                if (board.board[i][j] != EMPTY) continue;
                bool near = false;
                for (int dx = -1; dx <= 1; ++dx) {
                    for (int dy = -1; dy <= 1; ++dy) {
                        int x = i + dx;
                        int y = j + dy;
                        if (board.is_valid(x, y) && board.board[x][y] != EMPTY) {
                            near = true;
                            break;
                        }
                    }
                    if (near) break;
                }
                if (near) moves.push_back(make_pair(i, j));
            }
        }
    }

    int alpha_beta(Board& board, int depth, int alpha, int beta, bool maximizing) const {
        if (depth == 0) return evaluate(board);

        vector<pair<int, int> > moves;
        generate_moves(board, moves);
        if (moves.empty()) return 0;

        if (maximizing) {
            int value = numeric_limits<int>::min();
            for (size_t i = 0; i < moves.size(); ++i) {
                int x = moves[i].first;
                int y = moves[i].second;
                board.board[x][y] = ai_color;
                if (board.check_win(x, y, ai_color)) {
                    board.board[x][y] = EMPTY;
                    return WIN;
                }
                value = max(value, alpha_beta(board, depth-1, alpha, beta, false));
                board.board[x][y] = EMPTY;
                alpha = max(alpha, value);
                if (alpha >= beta) break;
            }
            return value;
        } else {
            int value = numeric_limits<int>::max();
            for (size_t i = 0; i < moves.size(); ++i) {
                int x = moves[i].first;
                int y = moves[i].second;
                board.board[x][y] = (ai_color == BLACK) ? WHITE : BLACK;
                if (board.check_win(x, y, board.board[x][y])) {
                    board.board[x][y] = EMPTY;
                    return LOSE;
                }
                value = min(value, alpha_beta(board, depth-1, alpha, beta, true));
                board.board[x][y] = EMPTY;
                beta = min(beta, value);
                if (alpha >= beta) break;
            }
            return value;
        }
    }

public:
    AI(ChessType color) : ai_color(color) {}

    void make_move(Board& board) const {
        vector<pair<int, int> > moves;
        generate_moves(board, moves);
        if (moves.empty()) return;

        int best_value = numeric_limits<int>::min();
        pair<int, int> best_move = moves[0];

        for (size_t i = 0; i < moves.size(); ++i) {
            int x = moves[i].first;
            int y = moves[i].second;
            board.board[x][y] = ai_color;
            if (board.check_win(x, y, ai_color)) {
                cout << "AI moves at (" << x << ", " << y << ")\n";
                return;
            }
            int value = alpha_beta(board, MAX_DEPTH-1, numeric_limits<int>::min(),
                                  numeric_limits<int>::max(), false);
            board.board[x][y] = EMPTY;

            if (value > best_value) {
                best_value = value;
                best_move = moves[i];
            }
        }

        board.board[best_move.first][best_move.second] = ai_color;
        cout << "AI moves at (" << best_move.first << ", " << best_move.second << ")\n";
    }
};

int main() {
    Board board;
    AI ai(WHITE);
    bool human_turn = true;

    while (true) {
        if (human_turn) {
            int x, y;
            cout << "Enter your move (x y): ";
            cin >> x >> y;
            if (!board.is_valid(x, y) {
                cout << "Invalid position!\n";
                continue;
            }
            if (!board.is_empty(x, y)) {
                cout << "Position occupied!\n";
                continue;
            }
            board.board[x][y] = BLACK;
            if (board.check_win(x, y, BLACK)) {
                cout << "You win!\n";
                break;
            }
        } else {
            clock_t start = clock();
            ai.make_move(board);
            clock_t end = clock();
            cout << "AI thinking time: " << (double)(end - start)/CLOCKS_PER_SEC << "s\n";
        }

        // 打印棋盘
        cout << "  ";
        for (int j = 0; j < SIZE; ++j) cout << j%10;
        cout << "\n";
        for (int i = 0; i < SIZE; ++i) {
            cout << i%10 << " ";
            for (int j = 0; j < SIZE; ++j) {
                if (board.board[i][j] == BLACK) cout << 'X';
                else if (board.board[i][j] == WHITE) cout << 'O';
                else cout << '.';
            }
            cout << "\n";
        }

        if (!human_turn) {
            for (int i = 0; i < SIZE; ++i) {
                for (int j = 0; j < SIZE; ++j) {
                    if (board.board[i][j] == WHITE && board.check_win(i, j, WHITE)) {
                        cout << "AI wins!\n";
                        return 0;
                    }
                }
            }
        }

        human_turn = !human_turn;
    }

    return 0;
}
原文
存档评论1 条抓取于