-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess-ai.js
73 lines (63 loc) · 1.48 KB
/
chess-ai.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Credit To ChatGPT For Generating This
import { Chess } from 'chess.js';
function minimax(depth, game, isMaximizing) {
if (depth === 0 || game.game_over()) {
return -evaluateBoard(game.board());
}
let bestMove;
let bestScore;
if (isMaximizing) {
bestScore = -Infinity;
game.moves().forEach(move => {
game.move(move);
const score = minimax(depth - 1, game, false);
game.undo();
if (score > bestScore) {
bestScore = score;
bestMove = move;
}
});
} else {
bestScore = Infinity;
game.moves().forEach(move => {
game.move(move);
const score = minimax(depth - 1, game, true);
game.undo();
if (score < bestScore) {
bestScore = score;
bestMove = move;
}
});
}
if (isMaximizing) {
return [bestScore, bestMove];
} else {
return [bestScore, bestMove];
}
}
function evaluateBoard(board) {
let score = 0;
board.forEach(row => {
row.forEach(piece => {
if (piece) {
score += getPieceValue(piece);
}
});
});
return score;
}
function getPieceValue(piece) {
if (piece.type === 'p') return 10;
if (piece.type === 'n') return 30;
if (piece.type === 'b') return 30;
if (piece.type === 'r') return 50;
if (piece.type === 'q') return 90;
if (piece.type === 'k') return 900;
return 0;
}
function getAIMove(fen) {
const game = new Chess(fen);
const [score, move] = minimax(4, game, true);
return move;
}
export default getAIMove;