function Work3
    % 主函数入口，启动五子棋游戏
    Board(); % 初始化并绘制棋盘
end

function Board()
    % 创建和绘制棋盘界面

    % 定义全局变量记录状态
    global vis turn moveHistory

    vis = zeros(15, 15);       % 棋盘状态矩阵（0: 空，1: 白子，2: 黑子）
    turn = 'black';            % 当前轮到的棋子颜色
    moveHistory = [];          % 存储所有落子记录

    % 查找是否已有名为“五子棋”的窗口
    f = findall(0, 'Type', 'figure', 'Name', '五子棋');
    if isempty(f)
        % 如果没有，创建新窗口
        figure('Name', '五子棋', 'NumberTitle', 'off', ...
               'MenuBar', 'none', 'Resize', 'off');
    else
        % 如果已有，清空旧内容，激活窗口
        figure(f);
        clf;
    end

    % 设置坐标轴参数
    axis([0.5 15.5 0.5 15.5]);
    axis equal;
    axis off;

    % 绘制棋盘网格
    for i = 1:15
        line([i, i], [1, 15], 'Color', 'k');
        line([1, 15], [i, i], 'Color', 'k');
    end

    % 绘制坐标数字
    for i = 1:15
        text(-0.5, i, num2str(i), 'HorizontalAlignment', 'right', 'FontSize', 8);
        text(i, -0.5, num2str(i), 'HorizontalAlignment', 'center', 'FontSize', 8);
    end

    % 设置点击落子事件
    set(gcf, 'WindowButtonDownFcn', @Place);

    % 添加“悔棋”按钮
    uicontrol('Style', 'pushbutton', 'String', '悔棋', ...
              'Position', [20, 20, 60, 30], ...
              'Callback', @(src, event) Undo());

    % 添加“重新开始”按钮
    uicontrol('Style', 'pushbutton', 'String', '重新开始', ...
              'Position', [100, 20, 80, 30], ...
              'Callback', @(src, event) Reset());
end

function Place(~, ~)
    % 响应点击事件，处理落子逻辑
    global vis turn moveHistory

    pt = get(gca, 'CurrentPoint');       % 获取鼠标点击坐标
    x = round(pt(1, 1));                 % 四舍五入为棋盘格点
    y = round(pt(1, 2));

    % 越界或位置已占，忽略
    if x < 1 || x > 15 || y < 1 || y > 15 || vis(x, y) ~= 0
        return;
    end

    % 根据当前轮次落子
    if strcmp(turn, 'black')
        vis(x, y) = 2;                  % 黑子编码为 2
        drawPiece(x, y, 'k');           % 绘制黑子
        moveHistory(end+1, :) = [x, y, 2];
        turn = 'white';                 % 下回合轮到白子
    else
        vis(x, y) = 1;                  % 白子编码为 1
        drawPiece(x, y, 'w');           % 绘制白子
        moveHistory(end+1, :) = [x, y, 1];
        turn = 'black';
    end

    drawnow;                            % 刷新图形

    % 检查是否胜利
    if CheckWin(x, y)
        if vis(x, y) == 2
            text(7.5, 16, '黑子获胜', 'HorizontalAlignment', 'center', 'FontSize', 14, 'Color', 'k');
        else
            text(7.5, 16, '白子获胜', 'HorizontalAlignment', 'center', 'FontSize', 14, 'Color', 'k');
        end
        set(gcf, 'WindowButtonDownFcn', []); % 禁止继续落子
    end
end

function drawPiece(x, y, color)
    % 在坐标 (x,y) 处绘制棋子，color: 'k'或'w'
    if strcmp(color, 'k')
        rectangle('Position', [x-0.5, y-0.5, 1, 1], ...
                  'Curvature', [1, 1], 'FaceColor', 'k', 'EdgeColor', 'none');
    else
        rectangle('Position', [x-0.5, y-0.5, 1, 1], ...
                  'Curvature', [1, 1], 'FaceColor', 'w', 'EdgeColor', 'k');
    end
end

function win = CheckWin(x, y)
    % 判断当前落子是否形成五连珠
    global vis
    color = vis(x, y);
    directions = [1 0; 0 1; 1 1; 1 -1];  % 横、竖、正斜、反斜

    for i = 1:4
        dx = directions(i, 1);
        dy = directions(i, 2);
        count = 1;

        % 向正方向搜索
        for d = 1:4
            nx = x + d*dx;
            ny = y + d*dy;
            if nx >= 1 && nx <= 15 && ny >= 1 && ny <= 15 && vis(nx, ny) == color
                count = count + 1;
            else
                break;
            end
        end

        % 向负方向搜索
        for d = 1:4
            nx = x - d*dx;
            ny = y - d*dy;
            if nx >= 1 && nx <= 15 && ny >= 1 && ny <= 15 && vis(nx, ny) == color
                count = count + 1;
            else
                break;
            end
        end

        if count >= 5
            win = true;
            return;
        end
    end

    win = false; % 未形成五子连珠
end

function Undo()
    % 悔棋操作：撤销上一步落子
    global vis turn moveHistory

    if isempty(moveHistory)
        return;
    end

    % 移除最后一步
    last = moveHistory(end, :);
    x = last(1);
    y = last(2);
    vis(x, y) = 0;
    moveHistory(end, :) = [];

    % 恢复当前轮次
    if last(3) == 1
        turn = 'white';
    else
        turn = 'black';
    end

    % 重新绘制棋盘和棋子
    redrawBoard();

    % 重新启用点击功能（即使之前因胜利而禁用）
    set(gcf, 'WindowButtonDownFcn', @Place);
end

function Reset()
    % 重新开始游戏：关闭当前窗口并重启游戏
    close(gcf);
    Work3();
end

function redrawBoard()
    % 清除当前坐标区并重新绘制棋盘和棋子
    global vis

    cla; % 清空坐标区

    % 重新绘制棋盘网格和坐标
    axis([0.5 15.5 0.5 15.5]);
    axis equal; axis off;

    for i = 1:15
        line([i, i], [1, 15], 'Color', 'k');
        line([1, 15], [i, i], 'Color', 'k');
    end

    for i = 1:15
        text(-0.5, i, num2str(i), 'HorizontalAlignment', 'right', 'FontSize', 8);
        text(i, -0.5, num2str(i), 'HorizontalAlignment', 'center', 'FontSize', 8);
    end

    % 绘制所有已有棋子
    hold on;
    for x = 1:15
        for y = 1:15
            if vis(x, y) == 1
                drawPiece(x, y, 'w');
            elseif vis(x, y) == 2
                drawPiece(x, y, 'k');
            end
        end
    end
    hold off;
end
