我正在制作一个使用极小极大算法的国际象棋机器人。我也在使用 chess.js 库。它目前运行非常缓慢,即使在非常低的深度。我怎样才能让我的算法运行得更快?任何帮助将不胜感激!
这里是算法
class MiniMaxBot
{
constructor(chessGame,player_color)
{
this.chess = chessGame;
this.color = player_color == "w"? 'b': 'w';
this.depthLimit = 3;
}
move()
{ let maxIndex = 0;
let maxScore = -Infinity;
let moves = this.chess.moves();
let fen = this.chess.fen();
for(let i = 0; i < moves.length; i++)
{
let chess = new Chess();
chess.load(fen);
chess.move(moves[i]);
let score = this.minimax(chess.fen(),this.depthLimit,-Infinity, Infinity, true);
if(maxScore < score )
{
maxScore = score;
maxIndex = i;
}
//console.log(score);
}
return moves[maxIndex];
}
minimax(fen,depth, alpha, beta, max)
{
let chess = new Chess();
chess.load(fen);
if(depth <= 0 || this.leafNode(fen) == true)
{
let value = this.evaluation(fen);
return value;
}
if (max == true)
{
let moves = chess.moves();
let bestValue = -Infinity;
for(let i = 0; i < moves.length; i++)
{ chess.load(fen);
chess.move(moves[i]);
let value = this.minimax(chess.fen(),depth-1, alpha, beta, false);
bestValue = Math.max(value,bestValue);
alpha = Math.max(alpha, bestValue);
if(beta <= alpha)
break;
}
return bestValue;
}
else if( max == false)
{
let moves = chess.moves();
let bestValue = Infinity;
for(let i = 0; i < moves.length; i++)
{
chess.load(fen);
chess.move(moves[i]);
let value = this.minimax(chess.fen(),depth-1, alpha, beta, true);
bestValue = Math.min(value,bestValue);
beta = Math.min(beta, bestValue);
if(beta <= alpha)
break;
}
return bestValue;
}
}
leafNode(fen)
{
let chess = new Chess();
chess.load(fen);
if(chess.in_checkmate() || chess.in_stalemate() || chess.in_threefold_repetition() )
return true;
else
return false;
}
evaluation(fen) {
let pieceValues = this.pieceValues();
let score = 0;
const boardState = fen.split(' ')[0];
const rows = boardState.split('/');
for (let i = 0; i < rows.length; i++) {
let columnIndex = 0;
const row = rows[i];
for (let j = 0; j < row.length; j++) {
const currentChar = row[j];
if (currentChar in pieceValues) {
score += pieceValues[currentChar];
} else {
columnIndex += parseInt(currentChar);
}
}
}
return score;
}
pieceValues()
{let black = {
'p': -10,
'n': -30,
'b': -30,
'r': -50,
'q': -90,
'P': 10,
'N': 30,
'B': 30,
'R': 50,
'Q': 90
};
let white = {
'p': -10,
'n': -30,
'b': -30,
'r': -50,
'q': -90,
'P': 10,
'N': 30,
'B': 30,
'R': 50,
'Q': 90
};
return this.color == 'b' ? black:white;
}
}
这里是我的 github 仓库 https://github.com/jakmo3000/chessAI/tree/main/chess