跳到正文

科技·工程

国际象棋 Minimax博弈AI(DP搜索)

jinky111约 43 分钟
原文
文章信息与版本

文章信息

发布
2026年7月27日
收录
2026年7月28日
更新
2026年11月16日
篇幅
约 43 分钟

版本

  1. v2当前
  2. v1

国际象棋 Minimax算法AI(支持人机对战)

HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>国际象棋 Minimax算法AI(支持人机对战)</title>
<style>
body {
    font-family: "Microsoft Yahei", sans-serif;
    padding: 24px;
    background: #f4f4f4;
}
.board {
    display: grid;
    grid-template-columns: repeat(8, 52px);
    gap: 0;
    margin: 16px 0;
}
.cell {
    width: 52px;
    height: 52px;
    font-size: 38px;
    text-align: center;
    line-height: 52px;
    border: none;
    cursor: pointer;
    padding: 0;
}
.selected {
    box-shadow: inset 0 0 0 4px #007bff !important;
}
.movable {
    box-shadow: inset 0 0 0 4px #35c735 !important;
}
.capture {
    box-shadow: inset 0 0 0 4px #ff4444 !important;
}
.ctrl-area button {
    padding: 8px 14px;
    font-size: 15px;
    cursor: pointer;
    margin-right: 8px;
}
.info {
    font-size: 19px;
    margin: 10px 0;
}
.modal {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.5);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 99;
}
.modal-box {
    background: white;
    padding: 20px;
    border-radius: 8px;
}
.promote-btn {
    font-size: 36px;
    padding: 6px 12px;
    margin: 4px;
    cursor: pointer;
}
.game-over-modal{
    font-size:24px;
    padding:30px 50px;
    text-align:center;
}
</style>
</head>
<body>
<div class="ctrl-area">
    <button id="btnPVP">双人对战</button>
    <button id="btnAI">人机对战(玩家白棋,AI黑棋)</button>
    <button id="btnReset">重新开局</button>
</div>
<div class="info" id="turnInfo">当前回合:白方</div>
<div class="board" id="board"></div>

<div class="modal" id="promoteModal">
    <div class="modal-box">
        <p>选择升变棋子:</p>
        <button class="promote-btn" data-type="Q">♛</button>
        <button class="promote-btn" data-type="R">♜</button>
        <button class="promote-btn" data-type="B">♝</button>
        <button class="promote-btn" data-type="N">♞</button>
    </div>
</div>

<div class="modal" id="gameOverModal">
    <div class="modal-box game-over-modal">
        <div id="gameOverText"></div>
        <br>
        <button id="closeGameOver" style="padding:6px 16px">确定</button>
    </div>
</div>

<script>
const PIECES = {
    wR:'♖', wN:'♘', wB:'♗', wQ:'♕', wK:'♔', wP:'♙',
    bR:'♜', bN:'♞', bB:'♝', bQ:'♛', bK:'♚', bP:'♟'
};
const VALUE = {P:100, N:320, B:330, R:500, Q:900, K:100000};

const PAWN_TABLE = [
    [0,0,0,0,0,0,0,0],
    [50,50,50,50,50,50,50,50],
    [10,10,20,30,30,20,10,10],
    [5,5,10,25,25,10,5,5],
    [0,0,0,20,20,0,0,0],
    [5,-5,-10,0,0,-10,-5,5],
    [5,10,10,-20,-20,10,10,5],
    [0,0,0,0,0,0,0,0]
];
const KNIGHT_TABLE = [
    [-50,-40,-30,-30,-30,-30,-40,-50],
    [-40,-20,0,0,0,0,-20,-40],
    [-30,0,10,15,15,10,0,-30],
    [-30,5,15,20,20,15,5,-30],
    [-30,0,15,20,20,15,0,-30],
    [-30,5,10,15,15,10,5,-30],
    [-40,-20,0,5,5,0,-20,-40],
    [-50,-40,-30,-30,-30,-30,-40,-50]
];

const initLayout = [
    ['bR','bN','bB','bQ','bK','bB','bN','bR'],
    ['bP','bP','bP','bP','bP','bP','bP','bP'],
    ['','','','','','','',''],
    ['','','','','','','',''],
    ['','','','','','','',''],
    ['','','','','','','',''],
    ['wP','wP','wP','wP','wP','wP','wP','wP'],
    ['wR','wN','wB','wQ','wK','wB','wN','wR'],
];

let board = [];
let selected = null;
let movableList = [];
let whiteTurn = true;
let gameMode = "pvp";
let aiWorking = false;

let castlingRight = {
    wK:true, wQR:true, wKR:true,
    bK:true, bQR:true, bKR:true
};
let enPassantTarget = null;
let promotePending = null;
// 新增:局面历史,用于三次重复检测
let positionHistory = [];

const boardEl = document.getElementById("board");
const turnInfo = document.getElementById("turnInfo");
const promoteModal = document.getElementById("promoteModal");
const gameOverModal = document.getElementById("gameOverModal");
const gameOverText = document.getElementById("gameOverText");

function copyBoard(b){return JSON.parse(JSON.stringify(b));}
function copyCastle(c){return {...c};}

// 将当前完整局面序列化为字符串(判断三次重复核心)
function getPositionKey() {
    const boardStr = board.flat().join(",");
    const castleStr = Object.values(castlingRight).join("");
    const epStr = enPassantTarget ? enPassantTarget.join(",") : "-";
    const turnStr = whiteTurn ? "W" : "B";
    return `${boardStr}|${castleStr}|${epStr}|${turnStr}`;
}

// 检测三次重复局面
function checkThreefoldRepetition() {
    const key = getPositionKey();
    let count = 0;
    for(const k of positionHistory){
        if(k === key) count++;
    }
    if(count >= 2){ // 当前再出现一次就是第三次
        showGameOver("三次重复局面,本局和棋!");
        return true;
    }
    return false;
}

function checkGameOver(){
    const moves = getAllMoves(board, whiteTurn, castlingRight, enPassantTarget);
    if(moves.length === 0){
        if(inCheck(board, whiteTurn)){
            const winner = whiteTurn ? "黑方" : "白方";
            showGameOver(`${winner} 将杀获胜!`);
        }else{
            showGameOver("无子可动,本局和棋(逼和)");
        }
        return;
    }
    // 优先检测三次重复
    checkThreefoldRepetition();
}
function showGameOver(text){
    gameOverText.innerText = text;
    gameOverModal.style.display = "flex";
}

function resetGame(){
    board = copyBoard(initLayout);
    selected = null;
    movableList = [];
    whiteTurn = true;
    castlingRight = {wK:true,wQR:true,wKR:true,bK:true,bQR:true,bKR:true};
    enPassantTarget = null;
    aiWorking = false;
    promotePending = null;
    positionHistory = [];
    promoteModal.style.display = "none";
    gameOverModal.style.display = "none";
    updateTurnText();
    render();
    // 开局存入初始局面
    positionHistory.push(getPositionKey());
}
function updateTurnText(){
    turnInfo.textContent = "当前回合:" + (whiteTurn ? "白方" : "黑方");
}
function isWhite(p){ return p && p[0]==='w'; }
function isBlack(p){ return p && p[0]==='b'; }
function sameSide(p1,p2){
    if(!p1||!p2) return false;
    return p1[0] === p2[0];
}

function findKing(bd, whiteSide){
    const target = whiteSide ? "wK" : "bK";
    for(let r=0;r<8;r++)
        for(let c=0;c<8;c++)
            if(bd[r][c]===target) return [r,c];
    return null;
}

function inCheck(bd, whiteSide){
    const [kr,kc] = findKing(bd, whiteSide);
    for(let r=0;r<8;r++){
        for(let c=0;c<8;c++){
            const pc = bd[r][c];
            if(!pc || sameSide(pc, whiteSide?"wK":"bK")) continue;
            const att = getAttackSquares(bd, r,c);
            for(let [tr,tc] of att){
                if(tr===kr&&tc===kc) return true;
            }
        }
    }
    return false;
}

function getAttackSquares(bd, r,c){
    const res = [];
    const pc = bd[r][c];
    if(!pc) return res;
    const w = isWhite(pc);
    const type = pc[1];
    if(type==='P'){
        const cap = w ? [[-1,-1],[-1,1]] : [[1,-1],[1,1]];
        for(let [dr,dc] of cap){
            const nr=r+dr, nc=c+dc;
            if(nr>=0&&nr<8&&nc>=0&&nc<8) res.push([nr,nc]);
        }
        return res;
    }
    if(type==='N'){
        const dirs = [[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]];
        for(let [dr,dc] of dirs){
            const nr=r+dr, nc=c+dc;
            if(nr>=0&&nr<8&&nc>=0&&nc<8) res.push([nr,nc]);
        }
    }
    if(type==='K'){
        const dirs=[[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]];
        for(let [dr,dc] of dirs){
            const nr=r+dr, nc=c+dc;
            if(nr>=0&&nr<8&&nc>=0&&nc<8) res.push([nr,nc]);
        }
    }
    const lineDirRQ = [[-1,0],[1,0],[0,-1],[0,1]];
    const lineDirBQ = [[-1,-1],[-1,1],[1,-1],[1,1]];
    if(type==='R'||type==='Q'){
        for(let [dr,dc] of lineDirRQ){
            let nr=r+dr, nc=c+dc;
            while(nr>=0&&nr<8&&nc>=0&&nc<8){
                res.push([nr,nc]);
                if(bd[nr][nc]) break;
                nr+=dr; nc+=dc;
            }
        }
    }
    if(type==='B'||type==='Q'){
        for(let [dr,dc] of lineDirBQ){
            let nr=r+dr, nc=c+dc;
            while(nr>=0&&nr<8&&nc>=0&&nc<8){
                res.push([nr,nc]);
                if(bd[nr][nc]) break;
                nr+=dr; nc+=dc;
            }
        }
    }
    return res;
}

function getLegalMoves(bd, r,c, castle, epTarget){
    const pc = bd[r][c];
    const w = isWhite(pc);
    const type = pc[1];
    const moves = [];

    if(type !== "P"){
        const allAtt = getAttackSquares(bd,r,c);
        for(let [tr,tc] of allAtt){
            const tpc = bd[tr][tc];
            if(sameSide(pc,tpc)) continue;
            const sim = copyBoard(bd);
            sim[tr][tc] = pc; sim[r][c] = "";
            if(!inCheck(sim,w)) moves.push([tr,tc]);
        }
    }

    if(type==='P'){
        const step = w ? -1 : 1;
        const startRow = w ? 6 : 1;
        if(!bd[r+step][c]){
            const sim = copyBoard(bd);
            sim[r+step][c]=pc; sim[r][c]="";
            if(!inCheck(sim,w)) moves.push([r+step,c]);
            if(r===startRow && !bd[r+2*step][c]){
                const sim2 = copyBoard(bd);
                sim2[r+2*step][c]=pc; sim2[r][c]="";
                if(!inCheck(sim2,w)) moves.push([r+2*step,c]);
            }
        }
        const pawnAttacks = getAttackSquares(bd, r, c);
        for(let [tr,tc] of pawnAttacks){
            const targetPiece = bd[tr][tc];
            if(targetPiece && !sameSide(pc, targetPiece)){
                const sim = copyBoard(bd);
                sim[tr][tc] = pc; sim[r][c] = "";
                if(!inCheck(sim,w)) moves.push([tr,tc]);
            }
        }
        if(epTarget){
            const [epr,epc]=epTarget;
            if(epr === r + step && Math.abs(epc - c) === 1){
                const sim = copyBoard(bd);
                sim[epr][epc] = pc;
                sim[r][c] = "";
                sim[r][epc] = "";
                if(!inCheck(sim,w)) moves.push([epr,epc]);
            }
        }
    }

    if(type==='K'){
        const homeRow = w ? 7 : 0;
        const kingChar = w ? "wK" : "bK";
        const rookChar = w ? "wR" : "bR";
        if(r === homeRow && ((w && castle.wK) || (!w && castle.bK)) && !inCheck(bd,w)){
            const canShort = w ? castle.wKR : castle.bKR;
            if(canShort && !bd[r][5] && !bd[r][6]){
                let danger = false;
                for(let col = 4; col <= 6; col++){
                    if(squareAttacked(bd, r, col, !w)) danger = true;
                }
                if(!danger){
                    const sim=copyBoard(bd);
                    sim[r][4] = ""; sim[r][6] = kingChar;
                    sim[r][7] = ""; sim[r][5] = rookChar;
                    if(!inCheck(sim,w)) moves.push([r,6]);
                }
            }
            const canLong = w ? castle.wQR : castle.bQR;
            if(canLong && !bd[r][1] && !bd[r][2] && !bd[r][3]){
                let danger = false;
                for(let col = 2; col <= 4; col++){
                    if(squareAttacked(bd, r, col, !w)) danger = true;
                }
                if(!danger){
                    const sim=copyBoard(bd);
                    sim[r][4] = ""; sim[r][2] = kingChar;
                    sim[r][0] = ""; sim[r][3] = rookChar;
                    if(!inCheck(sim,w)) moves.push([r,2]);
                }
            }
        }
    }
    return moves;
}
function squareAttacked(bd,r,c,byWhite){
    for(let i=0;i<8;i++){
        for(let j=0;j<8;j++){
            const p=bd[i][j];
            if(!p) continue;
            if(isWhite(p) !== byWhite) continue;
            const att=getAttackSquares(bd,i,j);
            for(let [tr,tc] of att) if(tr===r&&tc===c) return true;
        }
    }
    return false;
}

function getAllMoves(bd, whiteToMove, castle, ep){
    const list = [];
    for(let r=0;r<8;r++){
        for(let c=0;c<8;c++){
            const p=bd[r][c];
            if(!p) continue;
            if(isWhite(p) !== whiteToMove) continue;
            const moves = getLegalMoves(bd,r,c,castle,ep);
            for(let [tr,tc] of moves) list.push([r,c,tr,tc]);
        }
    }
    return list;
}

const MAX_DEPTH = 3;
function evaluateBoard(bd){
    let score=0;
    for(let r=0;r<8;r++){
        for(let c=0;c<8;c++){
            const p=bd[r][c];
            if(!p) continue;
            const w=isWhite(p);
            const t=p[1];
            let val = VALUE[t];
            if(t==='P') val += w ? PAWN_TABLE[7-r][c] : PAWN_TABLE[r][c];
            if(t==='N') val += w ? KNIGHT_TABLE[7-r][c] : KNIGHT_TABLE[r][c];
            score += w ? val : -val;
        }
    }
    return score;
}

function minimax(bd, castle, ep, depth, alpha, beta, whiteMax){
    if(depth===0) return evaluateBoard(bd);
    const moves = getAllMoves(bd, whiteMax, castle, ep);
    if(moves.length===0){
        if(inCheck(bd, whiteMax)) return whiteMax ? -99999 : 99999;
        return 0;
    }
    if(whiteMax){
        let best = -Infinity;
        for(let [r,c,tr,tc] of moves){
            const simBd = copyBoard(bd);
            const simCast = copyCastle(castle);
            let newEp=null;
            const piece = simBd[r][c];
            if(piece[1] === "P" && ep && tr === ep[0] && tc === ep[1]) simBd[r][tc] = "";
            simBd[tr][tc]=piece; simBd[r][c]="";
            if(piece[1]==='P' && Math.abs(tr-r)===2) newEp=[(r+tr)/2, c];
            if(piece[1]==='K'){
                if(isWhite(piece)) simCast.wK = simCast.wKR = simCast.wQR = false;
                else simCast.bK = simCast.bKR = simCast.bQR = false;
            }
            if(piece[1]==='R'){
                if(r===7&&c===0) simCast.wQR=false;
                if(r===7&&c===7) simCast.wKR=false;
                if(r===0&&c===0) simCast.bQR=false;
                if(r===0&&c===7) simCast.bKR=false;
            }
            if(piece[1]==='P' && (tr===0||tr===7)) simBd[tr][tc] = isWhite(piece) ? "wQ" : "bQ";
            const sc = minimax(simBd, simCast, newEp, depth-1, alpha, beta, false);
            best = Math.max(best, sc);
            alpha = Math.max(alpha, best);
            if(alpha >= beta) break;
        }
        return best;
    }else{
        let best = Infinity;
        for(let [r,c,tr,tc] of moves){
            const simBd = copyBoard(bd);
            const simCast = copyCastle(castle);
            let newEp=null;
            const piece = simBd[r][c];
            if(piece[1] === "P" && ep && tr === ep[0] && tc === ep[1]) simBd[r][tc] = "";
            simBd[tr][tc]=piece; simBd[r][c]="";
            if(piece[1]==='P' && Math.abs(tr-r)===2) newEp=[(r+tr)/2,c];
            if(piece[1]==='K'){
                if(isWhite(piece)) simCast.wK = simCast.wKR = simCast.wQR = false;
                else simCast.bK = simCast.bKR = simCast.bQR = false;
            }
            if(piece[1]==='R'){
                if(r===7&&c===0) simCast.wQR=false;
                if(r===7&&c===7) simCast.wKR=false;
                if(r===0&&c===0) simCast.bQR=false;
                if(r===0&&c===7) simCast.bKR=false;
            }
            if(piece[1]==='P' && (tr===0||tr===7)) simBd[tr][tc]="bQ";
            const sc = minimax(simBd, simCast, newEp, depth-1, alpha, beta, true);
            best = Math.min(best, sc);
            beta = Math.min(beta, best);
            if(alpha >= beta) break;
        }
        return best;
    }
}

function aiSearch(){
    const allMoves = getAllMoves(board, false, castlingRight, enPassantTarget);
    let bestMove=null;
    let bestScore=Infinity;
    for(let [r,c,tr,tc] of allMoves){
        const simBd = copyBoard(board);
        const simCast = copyCastle(castlingRight);
        let newEp=null;
        const piece = simBd[r][c];
        if(piece[1] === "P" && enPassantTarget && tr === enPassantTarget[0] && tc === enPassantTarget[1]) simBd[r][tc] = "";
        simBd[tr][tc]=piece; simBd[r][c]="";
        if(piece[1]==='P' && Math.abs(tr-r)===2) newEp=[(r+tr)/2,c];
        if(piece[1]==='K'){
            if(isWhite(piece)) simCast.wK = simCast.wKR = simCast.wQR = false;
            else simCast.bK = simCast.bKR = simCast.bQR = false;
        }
        if(piece[1]==='R'){
            if(r===7&&c===0) simCast.wQR=false;
            if(r===7&&c===7) simCast.wKR=false;
            if(r===0&&c===0) simCast.bQR=false;
            if(r===0&&c===7) simCast.bKR=false;
        }
        if(piece[1]==='P' && (tr===0||tr===7)) simBd[tr][tc]="bQ";
        const score = minimax(simBd, simCast, newEp, MAX_DEPTH-1, -Infinity, Infinity, true);
        if(score < bestScore){
            bestScore=score;
            bestMove=[r,c,tr,tc];
        }
    }
    return bestMove;
}

function makeMove(r,c,tr,tc){
    const pc = board[r][c];
    if(pc[1]==='P' && enPassantTarget && tr === enPassantTarget[0] && tc === enPassantTarget[1]) board[r][tc] = "";
    if(pc[1]==='K' && Math.abs(tc-c)>1){
        if(tc===6){board[r][5]=board[r][7]; board[r][7]="";}
        else if(tc===2){board[r][3]=board[r][0]; board[r][0]="";}
    }
    board[tr][tc]=pc;
    board[r][c]="";
    if(pc[1]==='K'){
        if(isWhite(pc)) castlingRight.wK=castlingRight.wKR=castlingRight.wQR=false;
        else castlingRight.bK=castlingRight.bKR=castlingRight.bQR=false;
    }
    if(pc[1]==='R'){
        if(r===7&&c===0) castlingRight.wQR=false;
        if(r===7&&c===7) castlingRight.wKR=false;
        if(r===0&&c===0) castlingRight.bQR=false;
        if(r===0&&c===7) castlingRight.bKR=false;
    }
    if(pc[1]==='P' && Math.abs(tr-r)===2) enPassantTarget = [(r+tr)/2, c];
    else enPassantTarget=null;
    if(pc[1]==='P' && (tr===0||tr===7)){
        promotePending=[tr,tc,isWhite(pc)];
        promoteModal.style.display="flex";
        return false;
    }
    return true;
}

function cellClick(r,c){
    if(aiWorking) return;
    if(gameMode==="ai" && !whiteTurn) return;
    const pc = board[r][c];
    if(selected){
        const [sr,sc] = selected;
        const legal = movableList.some(([tr,tc])=>tr===r&&tc===c);
        if(legal){
            const finish = makeMove(sr,sc,r,c);
            selected=null; movableList=[];
            if(finish){
                whiteTurn = !whiteTurn;
                positionHistory.push(getPositionKey());
                updateTurnText();
                render();
                checkGameOver();
                if(gameMode==="ai" && !whiteTurn){
                    aiWorking=true;
                    setTimeout(()=>{
                        const mv = aiSearch();
                        if(mv){
                            const [ar,ac,atr,atc]=mv;
                            makeMove(ar,ac,atr,atc);
                            whiteTurn=true;
                            positionHistory.push(getPositionKey());
                            updateTurnText();
                            checkGameOver();
                        }
                        aiWorking=false;
                        render();
                    },400);
                }
            }else render();
        }else{
            if(pc && isWhite(pc)===whiteTurn){
                selected=[r,c];
                movableList=getLegalMoves(board,r,c,castlingRight,enPassantTarget);
            }else{selected=null; movableList=[];}
            render();
        }
    }else{
        if(pc && isWhite(pc)===whiteTurn){
            selected=[r,c];
            movableList=getLegalMoves(board,r,c,castlingRight,enPassantTarget);
        }
        render();
    }
}

function render(){
    boardEl.innerHTML="";
    for(let r=0;r<8;r++){
        for(let c=0;c<8;c++){
            const btn = document.createElement("button");
            btn.className="cell";
            btn.style.background = (r+c)%2===0 ? "#f0d9b5" : "#b58863";
            const p=board[r][c];
            btn.textContent = p ? PIECES[p] : "";
            if(selected&&selected[0]===r&&selected[1]===c) btn.classList.add("selected");
            for(let [tr,tc] of movableList){
                if(tr===r&&tc===c){
                    if(board[r][c]) btn.classList.add("capture");
                    else btn.classList.add("movable");
                }
            }
            btn.onclick=()=>cellClick(r,c);
            boardEl.appendChild(btn);
        }
    }
}

document.querySelectorAll(".promote-btn").forEach(btn=>{
    btn.onclick=()=>{
        const [r,c,w] = promotePending;
        const t = btn.dataset.type;
        board[r][c] = w ? ("w"+t) : ("b"+t);
        promoteModal.style.display="none";
        promotePending=null;
        whiteTurn = !whiteTurn;
        positionHistory.push(getPositionKey());
        updateTurnText();
        render();
        checkGameOver();
        if(gameMode==="ai" && !whiteTurn){
            aiWorking=true;
            setTimeout(()=>{
                const mv = aiSearch();
                if(mv){
                    const [ar,ac,atr,atc]=mv;
                    makeMove(ar,ac,atr,atc);
                    whiteTurn=true;
                    positionHistory.push(getPositionKey());
                    updateTurnText();
                    checkGameOver();
                }
                aiWorking=false;
                render();
            },400);
        }
    }
});
document.getElementById("closeGameOver").onclick = ()=>gameOverModal.style.display = "none";
document.getElementById("btnPVP").onclick=()=>{gameMode="pvp"; resetGame();};
document.getElementById("btnAI").onclick=()=>{gameMode="ai"; resetGame();};
document.getElementById("btnReset").onclick=resetGame;

resetGame();
</script>
</body>
</html>
原文