这是什么算法?
聪明的豆包写了一个国际象棋网页版。复制,写在文本文档里,重命名chess.html双击打开即可。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>洛谷头像国际象棋 难度1‑7</title>
<style>
*{box-sizing: border-box;margin:0;padding:0;font-family:system-ui, sans-serif;}
body{
background:#ffffff;
color:#333;
padding:24px;
display:flex;
flex-direction:column;
align-items:center;
}
.container{
display:flex;
gap:30px;
align-items:flex-start;
}
#boardWrap{
position:relative;
}
#board{
display:grid;
grid-template-columns: repeat(8, 64px);
grid-template-rows: repeat(8, 64px);
border:3px solid #cccccc;
touch-action:none;
user-select:none;
}
.sq{
width:64px;
height:64px;
display:flex;
align-items:center;
justify-content:center;
position:relative;
cursor:pointer;
background:#ffffff;
font-size:42px;
}
.sq.hint-move{background:rgba(80,180,80,0.35);}
.sq.hint-cap{background:rgba(220,60,60,0.35);}
.sq.selected{box-shadow:inset 0 0 0 4px #42a5f5;}
.piece-img{
width:48px;
height:48px;
pointer-events:none;
z-index:1;
object-fit:contain;
}
#killEffectContainer{
position:absolute;
top:0;left:0;
width:calc(8*64px);
height:calc(8*64px);
pointer-events:none;
z-index:200;
}
.kill-effect-item{
position:absolute;
width:72px;
height:72px;
object-fit:contain;
animation: popBlink 0.45s ease-out forwards;
transform: translate(-4px,-4px);
}
@keyframes popBlink {
0% {transform:scale(0.3);opacity:1;filter:brightness(2) drop-shadow(0 0 8px red);}
40% {transform:scale(1.6);opacity:1;filter:brightness(2.5) drop-shadow(0 0 12px red);}
100% {transform:scale(2.0);opacity:0;}
}
#floating{
position:fixed;
pointer-events:none;
z-index:9999;
width:48px;
height:48px;
transform:translate(-50%,-50%);
opacity:0.85;
display:none;
}
#panel{
min-width:260px;
}
button{
padding:9px 16px;
margin:5px 4px;
border:none;
border-radius:6px;
font-size:15px;
cursor:pointer;
background:#3498db;
color:white;
}
button:hover{background:#2980b9;}
button.danger{background:#e74c3c;}
#info{
margin:12px 0;
min-height:42px;
font-size:16px;
}
.desc{
margin-top:16px;
font-size:13px;
opacity:0.85;
line-height:1.6;
}
.row{
margin:8px 4px;
}
select{
padding:6px 8px;
font-size:15px;
border-radius:4px;
}
</style>
</head>
<body>
<h1>洛谷头像国际象棋</h1>
<div class="container">
<div id="boardWrap">
<div id="killEffectContainer"></div>
<div id="board"></div>
<img id="floating" alt="drag piece">
</div>
<div id="panel">
<h3>游戏模式</h3>
<div>
<button id="btnPvP">👥 双人对弈</button>
<button id="btnAI">🤖 对战AI</button>
</div>
<div class="row">
<label>AI难度(1‑7):</label>
<select id="diffSelect">
<option value="1">1‑新手</option>
<option value="2">2‑简单</option>
<option value="3">3‑初级</option>
<option value="4" selected>4‑中等</option>
<option value="5">5‑进阶</option>
<option value="6">6‑较强</option>
<option value="7">7‑最强</option>
</select>
</div>
<div id="info">请先选择游戏模式</div>
<div><button id="resetBtn" class="danger">重新开局</button></div>
<div class="desc">
<p>【点击操作】点棋子选中 → 再点目标格子走棋</p>
<p>绿色=移动,红色=吃子,吃子弹出封禁特效</p>
<p>难度7=原版强AI;难度越低越容易犯错误</p>
</div>
</div>
</div>
<script>
// ============棋子头像配置区============
const PIECE_ICONS = {
'K':null,
'Q': "https://cdn.luogu.com.cn/upload/usericon/8457.png",
'B': "https://cdn.luogu.com.cn/upload/usericon/10703.png",
'N': "https://cdn.luogu.com.cn/upload/usericon/22030.png",
'R': "https://cdn.luogu.com.cn/upload/usericon/2674.png",
'P': "https://cdn.luogu.com.cn/upload/usericon/90693.png",
'k':null,
'q': "https://cdn.luogu.com.cn/upload/usericon/65363.png",
'b': "https://cdn.luogu.com.cn/upload/usericon/1.png",
'n': "https://cdn.luogu.com.cn/upload/usericon/28910.png",
'r': "https://cdn.luogu.com.cn/upload/usericon/253738.png",
'p': "https://cdn.luogu.com.cn/upload/usericon/943582.png"
};
const KILL_EFFECT_SRC = "https://cdn.luogu.com.cn/upload/image_hosting/v2eqpdgl.png?x-oss-process=image/resize,m_lfit,h_170,w_225";
const EFFECT_DURATION = 450;
// 难度配置:[搜索深度, 允许选取的候选前N个走法,随机权重]
// level:1~7;最高深度限制为5避免浏览器卡死
const DIFFICULTY_CFG = [
null,
{depth:1, topN:6}, //1
{depth:2, topN:5}, //2
{depth:2, topN:4}, //3
{depth:3, topN:3}, //4
{depth:3, topN:2}, //5
{depth:4, topN:2}, //6
{depth:5, topN:1} //7最强,只选最优
];
let board=[];
let turn='w';
let gameMode=null;
let aiThinking=false;
let gameOver=false;
let castling={wK:true,wQ:true,bK:true,bQ:true};
let enPassant=null;
let selectState=null;
let dragState=null;
function isWhite(p){return p&&p===p.toUpperCase();}
function isBlack(p){return p&&p===p.toLowerCase();}
function getColor(p){if(!p)return null;return isWhite(p)?'w':'b';}
function initBoard(){
board=[
['r','n','b','q','k','b','n','r'],
['p','p','p','p','p','p','p','p'],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
[null,null,null,null,null,null,null,null],
['P','P','P','P','P','P','P','P'],
['R','N','B','Q','K','B','N','R']
];
turn='w';
gameOver=false;
aiThinking=false;
dragState=null;
selectState=null;
castling={wK:true,wQ:true,bK:true,bQ:true};
enPassant=null;
document.getElementById("killEffectContainer").innerHTML = "";
renderBoard();
setInfo(gameMode==='pvp'?"白方回合":"你(白方)回合");
}
function playKillEffect(r,c){
const sqSize = 64;
const effX = c * sqSize;
const effY = r * sqSize;
const container = document.getElementById("killEffectContainer");
const effectImg = document.createElement("img");
effectImg.className = "kill-effect-item";
effectImg.src = KILL_EFFECT_SRC;
effectImg.style.left = effX + "px";
effectImg.style.top = effY + "px";
container.appendChild(effectImg);
setTimeout(()=>{effectImg.remove();},EFFECT_DURATION);
}
function generatePieceRawMoves(r,c,includeCastle,bd){
const pc=bd[r][c];
const col=getColor(pc);
const moves=[];
const type=pc.toUpperCase();
const dirs={
N:[[-2,-1],[-2,1],[-1,-2],[-1,2],[1,-2],[1,2],[2,-1],[2,1]],
B:[[-1,-1],[-1,1],[1,-1],[1,1]],
R:[[-1,0],[1,0],[0,-1],[0,1]],
Q:[[-1,-1],[-1,1],[1,-1],[1,1],[-1,0],[1,0],[0,-1],[0,1]]
};
function addSlide(dlist){
for(const [dr,dc] of dlist){
let nr=r+dr,nc=c+dc;
while(nr>=0&&nr<8&&nc>=0&&nc<8){
const t=bd[nr][nc];
if(!t){moves.push({r:nr,c:nc});}
else{ if(getColor(t)!==col) moves.push({r:nr,c:nc}); break; }
nr+=dr; nc+=dc;
}
}
}
if(type==='N'){
for(const [dr,dc] of dirs.N){
const nr=r+dr,nc=c+dc;
if(nr>=0&&nr<8&&nc>=0&&nc<8){
const t=bd[nr][nc];
if(!t||getColor(t)!==col) moves.push({r:nr,c:nc});
}
}
}else if(type==='B') addSlide(dirs.B);
else if(type==='R') addSlide(dirs.R);
else if(type==='Q') addSlide(dirs.Q);
else if(type==='K'){
for(let dr=-1;dr<=1;dr++){
for(let dc=-1;dc<=1;dc++){
if(dr===0&&dc===0) continue;
const nr=r+dr,nc=c+dc;
if(nr>=0&&nr<8&&nc>=0&&nc<8){
const t=bd[nr][nc];
if(!t||getColor(t)!==col) moves.push({r:nr,c:nc});
}
}
}
if(includeCastle){
if(col==='w'&&r===7&&c===4){
if(castling.wK&&!bd[7][5]&&!bd[7][6]){
if(!isSquareAttackedLocal(7,4,'b',bd)&&!isSquareAttackedLocal(7,5,'b',bd)&&!isSquareAttackedLocal(7,6,'b',bd)){
moves.push({r:7,c:6,castle:'K'});
}
}
if(castling.wQ&&!bd[7][3]&&!bd[7][2]&&!bd[7][1]){
if(!isSquareAttackedLocal(7,4,'b',bd)&&!isSquareAttackedLocal(7,3,'b',bd)&&!isSquareAttackedLocal(7,2,'b',bd)){
moves.push({r:7,c:2,castle:'Q'});
}
}
}
if(col==='b'&&r===0&&c===4){
if(castling.bK&&!bd[0][5]&&!bd[0][6]){
if(!isSquareAttackedLocal(0,4,'w',bd)&&!isSquareAttackedLocal(0,5,'w',bd)&&!isSquareAttackedLocal(0,6,'w',bd)){
moves.push({r:0,c:6,castle:'K'});
}
}
if(castling.bQ&&!bd[0][3]&&!bd[0][2]&&!bd[0][1]){
if(!isSquareAttackedLocal(0,4,'w',bd)&&!isSquareAttackedLocal(0,3,'w',bd)&&!isSquareAttackedLocal(0,2,'w',bd)){
moves.push({r:0,c:2,castle:'Q'});
}
}
}
}
}else if(type==='P'){
const dr=col==='w'?-1:1;
const startRow=col==='w'?6:1;
const nr1=r+dr;
if(nr1>=0&&nr1<8&&!bd[nr1][c]){
moves.push({r:nr1,c});
if(r===startRow&&!bd[r+2*dr][c]) moves.push({r:r+2*dr,c});
}
for(const dc of [-1,1]){
const nc=c+dc;
if(nc>=0&&nc<8){
const nt=bd[r+dr][nc];
if(nt&&getColor(nt)!==col) moves.push({r:r+dr,c:nc});
if(enPassant&&enPassant.r===r+dr&&enPassant.c===nc) moves.push({r:r+dr,c:nc,ep:true});
}
}
}
return moves;
}
function isSquareAttacked(r,c,byColor){
return isSquareAttackedLocal(r,c,byColor,board);
}
function isSquareAttackedLocal(r,c,byColor,bd){
for(let i=0;i<8;i++){
for(let j=0;j<8;j++){
const p=bd[i][j];
if(!p||getColor(p)!==byColor) continue;
const ms=generatePieceRawMoves(i,j,false,bd);
for(const m of ms) if(m.r===r&&m.c===c) return true;
}
}
return false;
}
function findKing(color,bd){
const k=color==='w'?'K':'k';
for(let r=0;r<8;r++) for(let c=0;c<8;c++) if(bd[r][c]===k) return {r,c};
return null;
}
function inCheckLocal(color,bd){
const kp=findKing(color,bd);
if(!kp) return false;
const enemy=color==='w'?'b':'w';
return isSquareAttackedLocal(kp.r,kp.c,enemy,bd);
}
function inCheck(color){
return inCheckLocal(color,board);
}
function makeMoveSnapshot(fromR,fromC,to,moveMeta,oldBoard,oldCastle,oldEP){
const nb=oldBoard.map(row=>[...row]);
const ncCastle={...oldCastle};
const oldEPval=oldEP?{...oldEP}:null;
const piece=nb[fromR][fromC];
nb[to.r][to.c]=piece;
nb[fromR][fromC]=null;
let newEP=null;
if(moveMeta.castle){
if(moveMeta.castle==='K'){
if(piece==='K'){ nb[7][5]=nb[7][7]; nb[7][7]=null; }
else { nb[0][5]=nb[0][7]; nb[0][7]=null; }
}else{
if(piece==='K'){ nb[7][3]=nb[7][0]; nb[7][0]=null; }
else { nb[0][3]=nb[0][0]; nb[0][0]=null; }
}
}
if(moveMeta.ep){
const capR=piece==='P'?to.r+1:to.r-1;
nb[capR][to.c]=null;
}
const pt=piece.toUpperCase();
if(pt==='P'&&(to.r===0||to.r===7)) nb[to.r][to.c]=getColor(piece)==='w'?'Q':'q';
if(pt==='P'&&Math.abs(to.r-fromR)===2) newEP={r:(fromR+to.r)/2,c:fromC};
if(piece==='K'){ ncCastle.wK=false; ncCastle.wQ=false; }
if(piece==='k'){ ncCastle.bK=false; ncCastle.bQ=false; }
if(piece==='R'){
if(fromR===7&&fromC===0) ncCastle.wQ=false;
if(fromR===7&&fromC===7) ncCastle.wK=false;
}
if(piece==='r'){
if(fromR===0&&fromC===0) ncCastle.bQ=false;
if(fromR===0&&fromC===7) ncCastle.bK=false;
}
return {board:nb,castling:ncCastle,enPassant:newEP};
}
function getLegalMovesForPiece(r,c){
const pc=board[r][c];
const col=getColor(pc);
const raw=generatePieceRawMoves(r,c,true,board);
const legal=[];
for(const mvTo of raw){
const snap=makeMoveSnapshot(r,c,mvTo,mvTo,board,castling,enPassant);
if(!inCheckLocal(col,snap.board)) legal.push(mvTo);
}
return legal;
}
function generateAllLegalMovesLocal(color,bd,castle,ep){
const out=[];
const origBd=board;
const origCast=castling;
const origEP=enPassant;
board=bd;castling=castle;enPassant=ep;
for(let r=0;r<8;r++){
for(let c=0;c<8;c++){
const p=bd[r][c];
if(!p||getColor(p)!==color) continue;
const ms=getLegalMovesForPiece(r,c);
for(const m of ms) out.push({from:{r,c},to:m});
}
}
board=origBd;castling=origCast;enPassant=origEP;
return out;
}
function doRealMove(fromR,fromC,to,meta){
const piece=board[fromR][fromC];
const capturedPiece = board[to.r][to.c];
if(capturedPiece){
playKillEffect(to.r,to.c);
}
if(meta.ep){
const capR=piece==='P'?to.r+1:to.r-1;
playKillEffect(capR,to.c);
board[capR][to.c]=null;
}
board[to.r][to.c]=piece;
board[fromR][fromC]=null;
if(meta.castle){
if(meta.castle==='K'){
if(piece==='K'){board[7][5]=board[7][7];board[7][7]=null;}
else{board[0][5]=board[0][7];board[0][7]=null;}
}else{
if(piece==='K'){board[7][3]=board[7][0];board[7][0]=null;}
else{board[0][3]=board[0][0];board[0][0]=null;}
}
}
enPassant=null;
if(piece.toUpperCase()==='P'&&Math.abs(to.r-fromR)===2){
enPassant={r:(fromR+to.r)/2,c:fromC};
}
if(piece.toUpperCase()==='P'&&(to.r===0||to.r===7)){
board[to.r][to.c]=getColor(piece)==='w'?'Q':'q';
}
if(piece==='K'){castling.wK=false;castling.wQ=false;}
if(piece==='k'){castling.bK=false;castling.bQ=false;}
if(piece==='R'){
if(fromR===7&&fromC===0) castling.wQ=false;
if(fromR===7&&fromC===7) castling.wK=false;
}
if(piece==='r'){
if(fromR===0&&fromC===0) castling.bQ=false;
if(fromR===0&&fromC===7) castling.bK=false;
}
}
const pieceValue={P:100,N:320,B:330,R:500,Q:900,K:20000};
const pstWhite={
P:[[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]],
N:[[-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]],
B:[[-20,-10,-10,-10,-10,-10,-10,-20],[-10,0,0,0,0,0,0,-10],[-10,0,5,10,10,5,0,-10],[-10,5,5,10,10,5,5,-10],[-10,0,10,10,10,10,0,-10],[-10,10,10,10,10,10,10,-10],[-10,5,0,0,0,0,5,-10],[-20,-10,-10,-10,-10,-10,-10,-20]],
R:[[0,0,0,0,0,0,0,0],[5,10,10,10,10,10,10,5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[-5,0,0,0,0,0,0,-5],[0,0,0,5,5,0,0,0]],
Q:[[-20,-10,-10,-5,-5,-10,-10,-20],[-10,0,0,0,0,0,0,-10],[-10,0,5,5,5,5,0,-10],[-5,0,5,5,5,5,0,-5],[0,0,5,5,5,5,0,-5],[-10,5,5,5,5,5,0,-10],[-10,0,5,0,0,0,0,-10],[-20,-10,-10,-5,-5,-10,-10,-20]],
K:[[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-30,-40,-40,-50,-50,-40,-40,-30],[-20,-30,-30,-40,-40,-30,-30,-20],[-10,-20,-20,-20,-20,-20,-20,-10],[20,20,0,0,0,0,20,20],[20,30,10,0,0,10,30,20]]
};
function evaluateLocal(bd){
let s=0;
for(let r=0;r<8;r++)for(let c=0;c<8;c++){
const p=bd[r][c];if(!p)continue;
const up=p.toUpperCase();
const pv=pieceValue[up];
const pos=isWhite(p)?pstWhite[up][r][c]:pstWhite[up][7-r][c];
s+= isWhite(p)?(pv+pos):-(pv+pos);
}
return s;
}
/**
* Alpha‑Beta剪枝,不污染全局状态
* @param {*} bd 棋盘副本
* @param {*} cst 王车权限副本
* @param {*} epd 吃过路兵副本
* @param {number} depth 剩余深度
* @param {number} alpha
* @param {number} beta
* @param {boolean} isMax true=w极大,false=b极小
* @returns {{score:number,bestMove:any|null}}
*/
function alphaBeta(bd,cst,epd,depth,alpha,beta,isMax){
if(depth===0){
return {score:evaluateLocal(bd),bestMove:null};
}
const side = isMax ? 'w' : 'b';
const moves = generateAllLegalMovesLocal(side,bd,cst,epd);
if(moves.length===0){
if(inCheckLocal(side,bd)){
return {score: isMax ? -100000 : 100000, bestMove:null};
}else{
return {score:0,bestMove:null};
}
}
// 走法排序:吃子优先,加速剪枝
moves.sort((ma,mb)=>{
const capA = bd[ma.to.r][ma.to.c] ? 1000 : 0;
const capB = bd[mb.to.r][mb.to.c] ? 1000 : 0;
return capB - capA;
});
let bestMove=null;
if(isMax){
let bestVal = -Infinity;
for(const mv of moves){
const snap = makeMoveSnapshot(mv.from.r,mv.from.c,mv.to,mv.to,bd,cst,epd);
const res = alphaBeta(snap.board,snap.castling,snap.enPassant,depth-1,alpha,beta,false);
if(res.score > bestVal){
bestVal = res.score;
bestMove = mv;
}
alpha = Math.max(alpha,res.score);
if(alpha >= beta){
return {score:beta,bestMove};
}
}
return {score:bestVal,bestMove};
}else{
let bestVal = Infinity;
for(const mv of moves){
const snap = makeMoveSnapshot(mv.from.r,mv.from.c,mv.to,mv.to,bd,cst,epd);
const res = alphaBeta(snap.board,snap.castling,snap.enPassant,depth-1,alpha,beta,true);
if(res.score < bestVal){
bestVal = res.score;
bestMove = mv;
}
beta = Math.min(beta,res.score);
if(alpha >= beta){
return {score:alpha,bestMove};
}
}
return {score:bestVal,bestMove};
}
}
function aiTurn(){
if(gameOver||aiThinking)return;
aiThinking=true;
setInfo("AI思考中…");
const level = Number(document.getElementById("diffSelect").value);
const cfg = DIFFICULTY_CFG[level];
setTimeout(()=>{
// AI黑方,极小玩家
const rootBoard = board.map(r=>[...r]);
const rootCast = {...castling};
const rootEp = enPassant ? {...enPassant} : null;
const rootMoves = generateAllLegalMovesLocal('b',rootBoard,rootCast,rootEp);
if(rootMoves.length===0){
aiThinking=false;
checkEnd();renderBoard();
return;
}
// 全部走法打分
const scored=[];
for(const mv of rootMoves){
const snap=makeMoveSnapshot(mv.from.r,mv.from.c,mv.to,mv.to,rootBoard,rootCast,rootEp);
const abRes = alphaBeta(snap.board,snap.castling,snap.enPassant,cfg.depth-1,-Infinity,Infinity,true);
scored.push({move:mv,score:abRes.score});
}
//黑方分数升序:分数越小对黑越好
scored.sort((a,b)=>a.score - b.score);
const candidates = scored.slice(0,cfg.topN);
const pickIdx = Math.floor(Math.random()*candidates.length);
const selectedMove = candidates[pickIdx].move;
doRealMove(selectedMove.from.r,selectedMove.from.c,selectedMove.to,selectedMove.to);
turn='w';
aiThinking=false;
selectState=null;
checkEnd();
renderBoard();
},180);
}
function checkEnd(){
const ms=generateAllLegalMoves(turn);
if(ms.length===0){
gameOver=true;
if(inCheck(turn)){
const win=turn==='w'?"黑方(AI)":"白方";
setInfo(`将死!${win}获胜`);
}else{
setInfo("逼和,和棋");
}
}else{
if(inCheck(turn)){
setInfo((turn==='w'?"白方":"黑方")+"将军!");
}else{
setInfo(gameMode==='ai'?(turn==='w'?"你(白方)走棋":"AI走棋"):(turn==='w'?"白方回合":"黑方回合"));
}
}
}
function generateAllLegalMoves(color){
return generateAllLegalMovesLocal(color,board,castling,enPassant);
}
function setInfo(txt){ document.getElementById('info').innerText=txt; }
function renderBoard(){
const bEl=document.getElementById('board');
bEl.innerHTML='';
for(let r=0;r<8;r++){
for(let c=0;c<8;c++){
const div=document.createElement('div');
div.className='sq';
div.dataset.r=r; div.dataset.c=c;
if(selectState){
if(selectState.r===r&&selectState.c===c){
div.classList.add('selected');
}
const hit=selectState.legalMoves.find(m=>m.r===r&&m.c===c);
if(hit){
if(board[r][c]) div.classList.add('hint-cap');
else div.classList.add('hint-move');
}
}
const pc=board[r][c];
if(pc){
const imgSrc = PIECE_ICONS[pc];
if(imgSrc){
const img=document.createElement('img');
img.className='piece-img';
img.src = imgSrc;
div.appendChild(img);
}else{
div.innerText = pc==='K'?"♔":"♚";
}
}
bEl.appendChild(div);
}
}
}
const floating=document.getElementById('floating');
function getEventPos(evt){
if(evt.touches) return {x:evt.touches[0].clientX,y:evt.touches[0].clientY};
return {x:evt.clientX,y:evt.clientY};
}
document.getElementById('board').addEventListener('click',(e)=>{
if(gameOver||aiThinking) return;
const sq=e.target.closest('.sq');
if(!sq) return;
const r=Number(sq.dataset.r);
const c=Number(sq.dataset.c);
const piece=board[r][c];
// =========新点击逻辑=========
if(selectState){
//已经选中一个棋子
const legalHit=selectState.legalMoves.find(m=>m.r===r&&m.c===c);
if(legalHit){
//点合法格子,执行走棋
doRealMove(selectState.r,selectState.c,{r,c},legalHit);
turn= turn==='w'?'b':'w';
selectState=null;
checkEnd();
renderBoard();
if(gameMode==='ai'&&turn==='b'&&!gameOver){
aiTurn();
}
return;
}
if(piece && getColor(piece)===turn){
//点击己方另外棋子:切换选中对象,刷新高亮
selectState={r,c,legalMoves:getLegalMovesForPiece(r,c)};
renderBoard();
return;
}
//点空白或者敌方不可吃格子:取消选中
selectState=null;
renderBoard();
return;
}
//没有选中状态,点击己方棋子:选中它,显示合法位置
if(piece && getColor(piece)===turn){
if(gameMode==='ai' && getColor(piece)==='b') return;
selectState={r,c,legalMoves:getLegalMovesForPiece(r,c)};
renderBoard();
}
});
document.getElementById('board').addEventListener('mousedown',startDrag);
document.getElementById('board').addEventListener('touchstart',startDrag,{passive:false});
document.addEventListener('mousemove',onMove);
document.addEventListener('touchmove',onMove,{passive:false});
document.addEventListener('mouseup',endDrag);
document.addEventListener('touchend',endDrag);
function startDrag(e){
e.preventDefault();
if(gameOver||aiThinking) return;
const t=e.target.closest('.sq');
if(!t) return;
const r=Number(t.dataset.r),c=Number(t.dataset.c);
const p=board[r][c];
if(!p) return;
if(gameMode==='ai'&&getColor(p)==='b') return;
if(getColor(p)!==turn) return;
dragState={fromR:r,fromC:c,legalMoves:getLegalMovesForPiece(r,c)};
const pos=getEventPos(e);
const imgSrc = PIECE_ICONS[p];
if(imgSrc){
floating.src = imgSrc;
}
floating.style.display='block';
floating.style.left=pos.x+'px';
floating.style.top=pos.y+'px';
renderBoard();
}
function onMove(e){
if(!dragState) return;
e.preventDefault();
const pos=getEventPos(e);
floating.style.left=pos.x+'px';
floating.style.top=pos.y+'px';
}
function endDrag(e){
if(!dragState){ floating.style.display='none';return; }
const pos=getEventPos(e);
floating.style.display='none';
const rect=document.getElementById('board').getBoundingClientRect();
const sqSize=64;
const dropR=Math.floor((pos.y - rect.top)/sqSize);
const dropC=Math.floor((pos.x - rect.left)/sqSize);
const legalHit=dragState.legalMoves.find(m=>m.r===dropR&&m.c===dropC);
if(legalHit&&dropR>=0&&dropR<8&&dropC>=0&&dropC<8){
doRealMove(dragState.fromR,dragState.fromC,{r:dropR,c:dropC},legalHit);
turn= turn==='w'?'b':'w';
selectState=null;
checkEnd();
renderBoard();
if(gameMode==='ai'&&turn==='b'&&!gameOver){
aiTurn();
}
}
dragState=null;
renderBoard();
}
document.getElementById('btnPvP').onclick=()=>{gameMode='pvp';initBoard();};
document.getElementById('btnAI').onclick=()=>{gameMode='ai';initBoard();};
document.getElementById('resetBtn').onclick=()=>{if(gameMode)initBoard();};
initBoard();
</script>
</body>
</html>