User:קיפודנחש/chess-animator.js

/*** * this script is meant to demonstrate "chess viewer" (sometimes called pgn viewer) prototype * it's 100% free, no attribution required. *  *///

$(function {

var allPositionClasses = '01234567' .split('') .map(function(r) { return 'pgn-prow-' + r + ' pgn-pfile-' + r; } ) .join(' ');

function processOneDiv { var $div = $(this), data = $div.data('chess'), boards, pieces = [], timer, boardDiv = $div.find('.pgn-board-img'), currentBoard;

function createPiece(letter) { var ll = letter.toLowerCase, color = letter == ll ? 'd' : 'l'; var piece = $(' ') .data('piece', letter) .addClass('pgn-chessPiece pgn-ptype-color-' + ll + color) .appendTo(boardDiv); pieces.push(piece); return piece; }

function processFen(fen) { var fenAr = fen.split('/'), board = []; for (var i in fenAr) { var j = 0 letters = fenAr[i].split(''); for (var li in letters) { var l = letters[li]; if (/[prnbqk]/i.test(l)) { board[(7 - i) * 8 + j] = createPiece(l); j++; }					else j += parseInt(l); }		}		return board; }

function processPly(board, ply) { newBoard = board.slice; for (var i in ply) { var component = ply[i] if (component.length == 1) delete newBoard[component[0]]; else if (/[prnbqk]/i.test(component[0])) newBoard[component[1]] = createPiece(component[0]); else { newBoard[component[1]] = newBoard[component[0]]; delete newBoard[component[0]]; }		}		return newBoard; }

function gotoBoard(i) { currentBoard = i;		var board = boards[i]; hidden = pieces.filter(function(piece) { return $.inArray(piece, pieces) + 1; }); for (var i in hidden) hidden[i].addClass('pgn-piece-hidden'); for (var j in board) { board[j] .removeClass(allPositionClasses + ' pgn-piece-hidden') .addClass('pgn-prow-' + parseInt(j / 8) + ' pgn-pfile-' + j % 8 ); }		if (i == boards.length - 1) stopAutoplay; }

function advance { if (currentBoard < boards.length - 1) gotoBoard(currentBoard + 1); }

function retreat { if (currentBoard > 0) gotoBoard(currentBoard - 1); }

function gotoStart { gotoBoard(0); stopAutoplay }

function gotoEnd { gotoBoard(boards.length - 1); }

function clickPlay { if (currentBoard == boards.length - 1) gotoBoard(0);

if (timer) stopAutoplay; else startAutoplay; }

function stopAutoplay { clearTimeout(timer); $('.pgn-button-play').removeClass('pgn-image-button-on'); timer = null; }

function startAutoplay { timer = setInterval(advance, 500); $('.pgn-button-play').addClass('pgn-image-button-on'); }

function connectButtons { $('.pgn-button-advance', $div).click(advance); $('.pgn-button-retreat', $div).click(retreat); $('.pgn-button-tostart', $div).click(gotoStart); $('.pgn-button-toend', $div).click(gotoEnd); $('.pgn-button-play', $div).click(clickPlay); }

if (data) { var board = processFen(data.fen); boards = [board] for (ind in data.plys) { var ply = data.plys[ind]; board = processPly(board, ply); boards.push(board); }		// onsole.log(JSON.stringify(boards, 4)); connectButtons; gotoBoard(0); }

}

$('.pgnviewer').each(processOneDiv); });