-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Employ minimax solution to generate opponent move #12
Comments
Variant of minimax is Negamax Pseudo Code =
|
So instead of just returning the highest score from moves...
Depth should be a minimum of 1 |
Functions needed =
|
Evaluate function-
In negaMax practice (simplified)-
This method allows both calculations to be hardcoded, and who2Move is dependent on the fen passed in. In Practice
|
Progress-import { player, canMove, pieceMoves, prepFen } from './fenmap';
var Chess = require('chess.js').Chess;
// Make negaMax
export const negaMax = (depth, fen) => {
if ( depth === 0 ) return evaluate(fen);
let max = -Infinity;
let moves = getMoves(fen);
let bestMove;
for (let move of moves) {
let newFen = newFenFromMove(fen, move);
let score = -(negaMax(depth - 1, newFen));
if( score > max )
max = score;
bestMove = move;
}
return bestMove;
};
// Simplified Evaluate Function
export const evaluate = (fen) => {
let whosGo = new Chess(fen).turn(); // Returns 'w' or 'b'
let materialScore =
(200 * (pieceTotal(fen,'K') - pieceTotal(fen,'k'))) +
(9 * (pieceTotal(fen,'Q') - pieceTotal(fen,'q'))) +
(5 * (pieceTotal(fen,'R') - pieceTotal(fen,'r'))) +
(3 * (pieceTotal(fen,'N') - pieceTotal(fen,'n'))) +
(3 * (pieceTotal(fen,'B') - pieceTotal(fen,'b'))) +
(1 * (pieceTotal(fen,'P') - pieceTotal(fen,'p')));
let mobilityScore = 0.1 * (getMoves(fen).length);
return (materialScore + mobilityScore) * (whosGo === 'w' ? 1 : -1);
};
// Returns array of objects with (from & to)
export const getMoves = (fen) => {
let flatten = (arr) => [].concat(...arr);
let twoDimArr =
canMove(fen, player(fen))
.map(moveable => pieceMoves(fen, moveable)
.map(newPos => { return {from: moveable, to: newPos};}));
return flatten(twoDimArr);
};
// Returns array or empty array
export const pieceTotal = (fen, piece) => {
let arr = prepFen(fen).join("").match(new RegExp(piece, 'g')) || [];
return arr.length;
};
// newFenFromMove
export const newFenFromMove = (fen, move) => {
let newPos = new Chess(fen);
newPos.move(move);
return newPos.fen();
};
// Default Export
export const bestMove = (fen) => negaMax(3, fen); Is a working solution with a depth of 3 (computer analyses 3 moves ahead)... . . .. . .. . .TOOK 4 MINUTES TO CALCULATE !Issue label added for help wanted |
https://en.wikipedia.org/wiki/Minimax
The text was updated successfully, but these errors were encountered: