I've been trying to implement a Minimax algorithm for a simple chess bot and I feel I understand the basics and general principles behind it, but my code isn't really working and I'm trying to figure out why.
This is my function for generating the boardScore.
const boardScore = (fen) => {
// fen = rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
// caps are for white
// white is maximizing player
const pieceWorth = {
p: -1,
P: 1,
k: -3,
K: 3,
b: -3,
B: 3,
r: -5,
R: 5,
q: -3,
Q: 3,
k: -99999,
K: 99999,
};
const pieces = fen.split(" ")[0].split("");
const score = 0;
for (const piece in pieces) {
score += pieceWorth[pieces[piece]] || 0;
}
if (game.turn() === "b" && game.in_checkmate()) score += 99999999;
if (game.turn() === "w" && game.in_checkmate()) score -= 99999999;
return score;
};
This is my code for the root minimax function that's called. Currently I'm only trying to make it work for the black pieces (the AI's turn)
const minimaxRoot = (game, depth) => {
// checking for black - minimizing player
const minUtility = Infinity;
let bestMove = null;
const moves = game.moves();
for (let i = 0; i < moves.length; i++) {
game.move(moves[i]);
let score = minimax(game, depth - 1);
if (score < minUtility) {
minUtility = score;
bestMove = moves[i];
}
game.undo();
console.log(minUtility);
return bestMove;
}
};
And this is my minimax algorithm.
// white is maximizing player
const minimax = (game, depth, white) => {
console.count();
if (depth === 0) {
return boardScore(game.fen());
}
const moves = game.moves();
if (white) {
let bestScore = -Infinity;
for (let i = 0; i < moves.length; i++) {
game.move(moves[i]);
let score = minimax(game, depth - 1, false);
bestScore = Math.max(bestScore, score);
game.undo();
}
return bestScore;
} else {
let bestScore = Infinity;
for (let i = 0; i < moves.length; i++) {
game.move(moves[i]);
let score = minimax(game, depth - 1, true);
bestScore = Math.min(bestScore, score);
game.undo();
}
return bestScore;
}
};
This is how I'm calling the function, which happens when I make a move.
const blackMove = () => {
game.move(minimaxRoot(game, 3));
setPosition(game.fen());
};
Any help would be appreciated. I've been banging my head working on this for the better part of 2 days and have made very little progress. Most of the examples I've seen include some form of alpha-beta pruning or transposed tables or move-ordering and it makes it more complicated which gives me trouble understanding.