Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- 用于获取棋子图像 -->
<base href="https://cdn.jsdelivr.net/gh/yanranxiaoxi/Minimax-with-Alpha-Beta-Pruning-Chess-AI@main/" />
<h3 class="board">
    α-β 剪枝优化
</h3>
<div id="board" class="board"></div>
<br>
<div class="info">
    计算深度:
    <select id="search-depth">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3" selected>3</option>
        <option value="4">4</option>
        <option value="5">5</option>
    </select>

    <br>
    <span>计算位置:<span id="position-count"></span></span>
    <br>
    <span>用时:<span id="time"></span></span>
    <br>
    <span>位置/秒:<span id="positions-per-s"></span> </span>
    <br>
    <br>
    <div id="move-history" class="move-history">
    </div>
</div>
              
            
!

CSS

              
                .board {
    width: 400px;
    margin: auto;
}

.info {
    width: 400px;
    margin: auto;
}

.move-history {
    max-height: 100px;
    overflow-y: scroll;
}

/*!
 * chessboard.js $version$
 *
 * Copyright 2013 Chris Oakman
 * Released under the MIT license
 * https://github.com/oakmac/chessboardjs/blob/master/LICENSE
 *
 * Date: $date$
 */

/* clearfix */
.clearfix-7da63 {
    clear: both;
}

/* board */
.board-b72b1 {
    border: 2px solid #404040;
    -moz-box-sizing: content-box;
    box-sizing: content-box;
}

/* square */
.square-55d63 {
    float: left;
    position: relative;

    /* disable any native browser highlighting */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* white square */
.white-1e1d7 {
    background-color: #f0d9b5;
    color: #b58863;
}

/* black square */
.black-3c85d {
    background-color: #b58863;
    color: #f0d9b5;
}

/* highlighted square */
.highlight1-32417,
.highlight2-9c5d2 {
    -webkit-box-shadow: inset 0 0 3px 3px yellow;
    -moz-box-shadow: inset 0 0 3px 3px yellow;
    box-shadow: inset 0 0 3px 3px yellow;
}

/* notation */
.notation-322f9 {
    cursor: default;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    position: absolute;
}
.alpha-d2270 {
    bottom: 1px;
    right: 3px;
}
.numeric-fc462 {
    top: 2px;
    left: 2px;
}

              
            
!

JS

              
                var board,
    game = new Chess();

/* AI */

var minimaxRoot = function (depth, game, isMaximisingPlayer) {
    var newGameMoves = game.ugly_moves();
    var bestMove = -9999;
    var bestMoveFound;

    for (var i = 0; i < newGameMoves.length; i++) {
        var newGameMove = newGameMoves[i];
        game.ugly_move(newGameMove);
        var value = minimax(
            depth - 1,
            game,
            -10000,
            10000,
            !isMaximisingPlayer
        );
        game.undo();
        if (value >= bestMove) {
            bestMove = value;
            bestMoveFound = newGameMove;
        }
    }
    return bestMoveFound;
};

var minimax = function (depth, game, alpha, beta, isMaximisingPlayer) {
    positionCount++;
    if (depth === 0) {
        return -evaluateBoard(game.board());
    }

    var newGameMoves = game.ugly_moves();

    if (isMaximisingPlayer) {
        var bestMove = -9999;
        for (var i = 0; i < newGameMoves.length; i++) {
            game.ugly_move(newGameMoves[i]);
            bestMove = Math.max(
                bestMove,
                minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer)
            );
            game.undo();
            alpha = Math.max(alpha, bestMove);
            if (beta <= alpha) {
                return bestMove;
            }
        }
        return bestMove;
    } else {
        var bestMove = 9999;
        for (var i = 0; i < newGameMoves.length; i++) {
            game.ugly_move(newGameMoves[i]);
            bestMove = Math.min(
                bestMove,
                minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer)
            );
            game.undo();
            beta = Math.min(beta, bestMove);
            if (beta <= alpha) {
                return bestMove;
            }
        }
        return bestMove;
    }
};

var evaluateBoard = function (board) {
    var totalEvaluation = 0;
    for (var i = 0; i < 8; i++) {
        for (var j = 0; j < 8; j++) {
            totalEvaluation =
                totalEvaluation + getPieceValue(board[i][j], i, j);
        }
    }
    return totalEvaluation;
};

var getPieceValue = function (piece, x, y) {
    if (piece === null) {
        return 0;
    }
    var getAbsoluteValue = function (piece) {
        if (piece.type === "p") {
            return 10;
        } else if (piece.type === "r") {
            return 50;
        } else if (piece.type === "n") {
            return 30;
        } else if (piece.type === "b") {
            return 30;
        } else if (piece.type === "q") {
            return 90;
        } else if (piece.type === "k") {
            return 900;
        }
        throw "未知的棋子类型:" + piece.type;
    };

    var absoluteValue = getAbsoluteValue(piece);
    return piece.color === "w" ? absoluteValue : -absoluteValue;
};

/* 棋盘可视化和游戏状态处理 */

var onDragStart = function (source, piece, position, orientation) {
    if (
        game.in_checkmate() === true ||
        game.in_draw() === true ||
        piece.search(/^b/) !== -1
    ) {
        return false;
    }
};

var makeBestMove = function () {
    var bestMove = getBestMove(game);
    game.ugly_move(bestMove);
    board.position(game.fen());
    renderMoveHistory(game.history());
    if (game.game_over()) {
        alert("游戏结束");
    }
};

var positionCount;
var getBestMove = function (game) {
    if (game.game_over()) {
        alert("游戏结束");
    }

    positionCount = 0;
    var depth = parseInt($("#search-depth").find(":selected").text());

    var d = new Date().getTime();
    var bestMove = minimaxRoot(depth, game, true);
    var d2 = new Date().getTime();
    var moveTime = d2 - d;
    var positionsPerS = (positionCount * 1000) / moveTime;

    $("#position-count").text(positionCount);
    $("#time").text(moveTime / 1000 + "s");
    $("#positions-per-s").text(positionsPerS);
    return bestMove;
};

var renderMoveHistory = function (moves) {
    var historyElement = $("#move-history").empty();
    historyElement.empty();
    for (var i = 0; i < moves.length; i = i + 2) {
        historyElement.append(
            "<span>" +
                moves[i] +
                " " +
                (moves[i + 1] ? moves[i + 1] : " ") +
                "</span><br>"
        );
    }
    historyElement.scrollTop(historyElement[0].scrollHeight);
};

var onDrop = function (source, target) {
    var move = game.move({
        from: source,
        to: target,
        promotion: "q"
    });

    removeGreySquares();
    if (move === null) {
        return "snapback";
    }

    renderMoveHistory(game.history());
    window.setTimeout(makeBestMove, 250);
};

var onSnapEnd = function () {
    board.position(game.fen());
};

var onMouseoverSquare = function (square, piece) {
    var moves = game.moves({
        square: square,
        verbose: true
    });

    if (moves.length === 0) return;

    greySquare(square);

    for (var i = 0; i < moves.length; i++) {
        greySquare(moves[i].to);
    }
};

var onMouseoutSquare = function (square, piece) {
    removeGreySquares();
};

var removeGreySquares = function () {
    $("#board .square-55d63").css("background", "");
};

var greySquare = function (square) {
    var squareEl = $("#board .square-" + square);

    var background = "#a9a9a9";
    if (squareEl.hasClass("black-3c85d") === true) {
        background = "#696969";
    }

    squareEl.css("background", background);
};

var cfg = {
    draggable: true,
    position: "start",
    onDragStart: onDragStart,
    onDrop: onDrop,
    onMouseoutSquare: onMouseoutSquare,
    onMouseoverSquare: onMouseoverSquare,
    onSnapEnd: onSnapEnd
};
board = ChessBoard("board", cfg);

              
            
!
999px

Console