Play Against Stockfish AI
');
function showMessage(type, message) {
var errorDiv = $('#error-message');
var infoDiv = $('#info-message');
if (type === 'error') {
errorDiv.text(message).removeClass('d-none');
infoDiv.addClass('d-none');
} else if (type === 'info') {
infoDiv.text(message).removeClass('d-none');
errorDiv.addClass('d-none');
}
}
function clearMessages() {
$('#error-message').addClass('d-none');
$('#info-message').addClass('d-none');
}
function onDragStart(source, piece, position, orientation) {
if (game.in_checkmate() || game.in_draw()) {
showMessage('info', 'Game over. Please reset to start a new game.');
return false;
}
if (piece.search(/^b/) !== -1) {
showMessage('info', 'It\'s not Black\'s turn.');
return false;
}
}
function makeMove(move) {
try {
var moveResult = game.move(move);
if (moveResult === null) {
throw new Error('Invalid move. Try again.');
}
board.position(game.fen());
return moveResult;
} catch (error) {
showMessage('error', 'An error occurred while making the move: ' + error.message);
return 'snapback';
}
}
function getBestMove() {
try {
stockfish.postMessage('position fen ' + game.fen());
stockfish.postMessage('go depth 15');
} catch (error) {
showMessage('error', 'An error occurred while communicating with the AI: ' + error.message);
}
}
stockfish.onmessage = function(event) {
var line = event.data;
if (line.startsWith('bestmove')) {
var bestMove = line.split(' ')[1];
makeMove({ from: bestMove.substring(0, 2), to: bestMove.substring(2, 4) });
clearMessages();
} else {
showMessage('info', line);
}
};
function onDrop(source, target) {
clearMessages();
var move = makeMove({ from: source, to: target });
if (move === 'snapback') return move;
window.setTimeout(getBestMove, 250);
}
$(document).ready(function() {
board = Chessboard('board', {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop
});
});