2种语言 AI五子棋

作者应该是原创

第一个是Python

import tkinter as tk
import random
# 棋盘大小
BOARD_SIZE = 15
# 棋盘单元格大小
CELL_SIZE = 40
# 棋盘边界大小
BORDER_SIZE = 20
# AI玩家标记
AI_PLAYER = "X"
# 人类玩家标记
HUMAN_PLAYER = "O"
# 创建棋盘
board = [[None] * BOARD_SIZE for _ in range(BOARD_SIZE)]
# 创建主窗口
window = tk.Tk()
window.title("AI五子棋")
window.geometry(f"{BOARD_SIZE * CELL_SIZE + 2 * BORDER_SIZE}x{BOARD_SIZE * CELL_SIZE + 2 * BORDER_SIZE}")
# 创建画布
canvas = tk.Canvas(window, width=BOARD_SIZE * CELL_SIZE + 2 * BORDER_SIZE,
                   height=BOARD_SIZE * CELL_SIZE + 2 * BORDER_SIZE, bg="darkgoldenrod")
canvas.pack()
def draw_board():
    """绘制棋盘"""
    for i in range(BOARD_SIZE):
        canvas.create_line(BORDER_SIZE, BORDER_SIZE + i * CELL_SIZE,
                           BORDER_SIZE + (BOARD_SIZE - 1) * CELL_SIZE, BORDER_SIZE + i * CELL_SIZE)
        canvas.create_line(BORDER_SIZE + i * CELL_SIZE, BORDER_SIZE,
                           BORDER_SIZE + i * CELL_SIZE, BORDER_SIZE + (BOARD_SIZE - 1) * CELL_SIZE)
def draw_stone(x, y, player):
    """绘制棋子"""
    if player == AI_PLAYER:
        color = "black"
    else:
        color = "white"
    canvas.create_oval(BORDER_SIZE + x * CELL_SIZE - CELL_SIZE // 2,
                       BORDER_SIZE + y * CELL_SIZE - CELL_SIZE // 2,
                       BORDER_SIZE + x * CELL_SIZE + CELL_SIZE // 2,
                       BORDER_SIZE + y * CELL_SIZE + CELL_SIZE // 2,
                       fill=color)
def is_valid_move(x, y):
    """判断落子是否合法"""
    return x >= 0 and x < BOARD_SIZE and y >= 0 and y < BOARD_SIZE and board[x][y] is None
def is_winner(x, y, player):
    """判断当前玩家是否获胜"""
    directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
    for dx, dy in directions:
        count = 1
        tx, ty = x, y
        while count < 5:
            tx += dx
            ty += dy
            if tx < 0 or tx >= BOARD_SIZE or ty < 0 or ty >= BOARD_SIZE or board[tx][ty] != player:
                break
            count += 1
        tx, ty = x, y
        while count < 5:
            tx -= dx
            ty -= dy
            if tx < 0 or tx >= BOARD_SIZE or ty < 0 or ty >= BOARD_SIZE or board[tx][ty] != player:
                break
            count += 1
        if count >= 5:
            return True
    return False
def is_board_full():
    """判断棋盘是否已满"""
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if board[i][j] is None:
                return False
    return True
def ai_move():
    """AI自动下棋"""
    if is_board_full():
        return
    while True:
        x = random.randint(0, BOARD_SIZE - 1)
        y = random.randint(0, BOARD_SIZE - 1)
        if is_valid_move(x, y):
            board[x][y] = AI_PLAYER
            draw_stone(x, y, AI_PLAYER)
            if is_winner(x, y, AI_PLAYER):
                print("AI获胜!")
            elif is_board_full():
                print("平局!")
            break
def click_handler(event):
    """点击事件处理"""
    if is_board_full():
        return
    x = (event.x - BORDER_SIZE) // CELL_SIZE
    y = (event.y - BORDER_SIZE) // CELL_SIZE
    if is_valid_move(x, y):
        board[x][y] = HUMAN_PLAYER
        draw_stone(x, y, HUMAN_PLAYER)
        if is_winner(x, y, HUMAN_PLAYER):
            print("玩家获胜!")
        elif is_board_full():
            print("平局!")
        else:
            ai_move()
draw_board()
canvas.bind("<Button-1>", click_handler)
window.mainloop()

第二个是C++

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
const int BOARD_SIZE = 15; // 棋盘大小
const char EMPTY = '_'; // 空格
const char BLACK = 'B'; // 黑棋
const char WHITE = 'W'; // 白棋
// 棋盘类
class Board {
private:
    vector<vector<char> > board; // 二维向量表示棋盘
public:
    Board() {
        board.resize(BOARD_SIZE, vector<char>(BOARD_SIZE, EMPTY)); // 初始化棋盘为空
    }
    // 打印棋盘
    void printBoard() {
        cout << " ";
        for (int i = 0; i < BOARD_SIZE; i++) {
            cout << " " << i;
        }
        cout << endl;
        for (int i = 0; i < BOARD_SIZE; i++) {
            cout << i;
            for (int j = 0; j < BOARD_SIZE; j++) {
                cout << " " << board[i][j];
            }
            cout << endl;
        }
    }
    // 检查某个位置是否合法
    bool isValidMove(int row, int col) {
        if (row < 0 || row >= BOARD_SIZE || col < 0 || col >= BOARD_SIZE) {
            return false;
        }
        if (board[row][col] != EMPTY) {
            return false;
        }
        return true;
    }
    // 下棋
    void makeMove(int row, int col, char player) {
        board[row][col] = player;
    }
    // AI下棋
    void makeAIMove() {
        srand(time(NULL));
        int row, col;
        do {
            row = rand() % BOARD_SIZE;
            col = rand() % BOARD_SIZE;
        } while (!isValidMove(row, col));
        makeMove(row, col, WHITE);
    }
    // 检查是否有玩家获胜
    bool hasWon(char player) {
        // 检查行
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE - 4; j++) {
                bool win = true;
                for (int k = 0; k < 5; k++) {
                    if (board[i][j + k] != player) {
                        win = false;
                        break;
                    }
                }
                if (win) {
                    return true;
                }
            }
        }
        // 检查列
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE - 4; j++) {
                bool win = true;
                for (int k = 0; k < 5; k++) {
                    if (board[j + k][i] != player) {
                        win = false;
                        break;
                    }
                }
                if (win) {
                    return true;
                }
            }
        }
        // 检查对角线
        for (int i = 0; i < BOARD_SIZE - 4; i++) {
            for (int j = 0; j < BOARD_SIZE - 4; j++) {
                bool win1 = true, win2 = true;
                for (int k = 0; k < 5; k++) {
                    if (board[i + k][j + k] != player) {
                        win1 = false;
                    }
                    if (board[i + k][j + 4 - k] != player) {
                        win2 = false;
                    }
                }
                if (win1 || win2) {
                    return true;
                }
            }
        }
        return false;
    }
    // 检查棋盘是否已满
    bool isBoardFull() {
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (board[i][j] == EMPTY) {
                    return false;
                }
            }
        }
        return true;
    }
};
int main() {
    Board board;
    char currentPlayer = BLACK;
    while (true) {
        board.printBoard();
        if (currentPlayer == BLACK) {
            int row, col;
            cout << "请玩家下棋(行 列):";
            cin >> row >> col;
            if (board.isValidMove(row, col)) {
                board.makeMove(row, col, currentPlayer);
                if (board.hasWon(currentPlayer)) {
                    cout << "黑棋获胜!" << endl;
                    break;
                }
                currentPlayer = WHITE;
            } else {
                cout << "无效的位置,请重新下棋。" << endl;
            }
        } else {
            cout << "AI下棋:" << endl;
            board.makeAIMove();
            if (board.hasWon(currentPlayer)) {
                cout << "白棋获胜!" << endl;
                break;
            }
            currentPlayer = BLACK;
        }
        if (board.isBoardFull()) {
            cout << "平局!" << endl;
            break;
        }
    }
    return 0;
}

喜欢作者可以支持一下

点击这里打赏作者

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值