4 * Copyright 2013 Chris Oakman
5 * Released under the MIT license
6 * http://chessboardjs.com/license
11 // start anonymous scope
15 //------------------------------------------------------------------------------
16 // Chess Util Functions
17 //------------------------------------------------------------------------------
18 var COLUMNS = 'abcdefgh'.split('');
20 function validMove(move) {
21 // move should be a string
22 if (typeof move !== 'string') return false;
24 // move should be in the form of "e2-e4", "f6-d5"
25 var tmp = move.split('-');
26 if (tmp.length !== 2) return false;
28 return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
31 function validSquare(square) {
32 if (typeof square !== 'string') return false;
33 return (square.search(/^[a-h][1-8]$/) !== -1);
36 function validPieceCode(code) {
37 if (typeof code !== 'string') return false;
38 return (code.search(/^[bw][KQRNBP]$/) !== -1);
41 // TODO: this whole function could probably be replaced with a single regex
42 function validFen(fen) {
43 if (typeof fen !== 'string') return false;
45 // cut off any move, castling, etc info from the end
46 // we're only interested in position information
47 fen = fen.replace(/ .+$/, '');
49 // FEN should be 8 sections separated by slashes
50 var chunks = fen.split('/');
51 if (chunks.length !== 8) return false;
53 // check the piece sections
54 for (var i = 0; i < 8; i++) {
55 if (chunks[i] === '' ||
56 chunks[i].length > 8 ||
57 chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) {
65 function validPositionObject(pos) {
66 if (typeof pos !== 'object') return false;
69 if (pos.hasOwnProperty(i) !== true) continue;
71 if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
79 // convert FEN piece code to bP, wK, etc
80 function fenToPieceCode(piece) {
82 if (piece.toLowerCase() === piece) {
83 return 'b' + piece.toUpperCase();
87 return 'w' + piece.toUpperCase();
90 // convert bP, wK, etc code to FEN structure
91 function pieceCodeToFen(piece) {
92 var tmp = piece.split('');
96 return tmp[1].toUpperCase();
100 return tmp[1].toLowerCase();
103 // convert FEN string to position object
104 // returns false if the FEN string is invalid
105 function fenToObj(fen) {
106 if (validFen(fen) !== true) {
110 // cut off any move, castling, etc info from the end
111 // we're only interested in position information
112 fen = fen.replace(/ .+$/, '');
114 var rows = fen.split('/');
118 for (var i = 0; i < 8; i++) {
119 var row = rows[i].split('');
122 // loop through each character in the FEN section
123 for (var j = 0; j < row.length; j++) {
124 // number / empty squares
125 if (row[j].search(/[1-8]/) !== -1) {
126 var emptySquares = parseInt(row[j], 10);
127 colIndex += emptySquares;
131 var square = COLUMNS[colIndex] + currentRow;
132 position[square] = fenToPieceCode(row[j]);
143 // position object to FEN string
144 // returns false if the obj is not a valid position object
145 function objToFen(obj) {
146 if (validPositionObject(obj) !== true) {
153 for (var i = 0; i < 8; i++) {
154 for (var j = 0; j < 8; j++) {
155 var square = COLUMNS[j] + currentRow;
158 if (obj.hasOwnProperty(square) === true) {
159 fen += pieceCodeToFen(obj[square]);
175 // squeeze the numbers together
176 // haha, I love this solution...
177 fen = fen.replace(/11111111/g, '8');
178 fen = fen.replace(/1111111/g, '7');
179 fen = fen.replace(/111111/g, '6');
180 fen = fen.replace(/11111/g, '5');
181 fen = fen.replace(/1111/g, '4');
182 fen = fen.replace(/111/g, '3');
183 fen = fen.replace(/11/g, '2');
188 window['ChessBoard'] = window['ChessBoard'] || function(containerElOrId, cfg) {
193 //------------------------------------------------------------------------------
195 //------------------------------------------------------------------------------
197 var MINIMUM_JQUERY_VERSION = '1.7.0',
198 START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
199 START_POSITION = fenToObj(START_FEN);
201 // use unique class names to prevent clashing with anything else on the page
202 // and simplify selectors
204 alpha: 'alpha-d2270',
205 black: 'black-3c85d',
206 board: 'board-b72b1',
207 chessboard: 'chessboard-63f37',
208 clearfix: 'clearfix-7da63',
209 highlight1: 'highlight1-32417',
210 highlight2: 'highlight2-9c5d2',
211 notation: 'notation-322f9',
212 numeric: 'numeric-fc462',
213 piece: 'piece-417db',
215 sparePieces: 'spare-pieces-7492f',
216 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
217 sparePiecesTop: 'spare-pieces-top-4028b',
218 square: 'square-55d63',
222 //------------------------------------------------------------------------------
223 // Module Scope Variables
224 //------------------------------------------------------------------------------
233 // constructor return object
236 //------------------------------------------------------------------------------
238 //------------------------------------------------------------------------------
240 var ANIMATION_HAPPENING = false,
241 BOARD_BORDER_SIZE = 2,
242 CURRENT_ORIENTATION = 'white',
243 CURRENT_POSITION = {},
246 DRAGGED_PIECE_LOCATION,
247 DRAGGED_PIECE_SOURCE,
248 DRAGGING_A_PIECE = false,
249 SPARE_PIECE_ELS_IDS = {},
253 //------------------------------------------------------------------------------
255 //------------------------------------------------------------------------------
257 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
258 function createId() {
259 return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) {
260 var r = Math.random() * 16 | 0;
261 return r.toString(16);
265 function deepCopy(thing) {
266 return JSON.parse(JSON.stringify(thing));
269 function parseSemVer(version) {
270 var tmp = version.split('.');
272 major: parseInt(tmp[0], 10),
273 minor: parseInt(tmp[1], 10),
274 patch: parseInt(tmp[2], 10)
278 // returns true if version is >= minimum
279 function compareSemVer(version, minimum) {
280 version = parseSemVer(version);
281 minimum = parseSemVer(minimum);
283 var versionNum = (version.major * 10000 * 10000) +
284 (version.minor * 10000) + version.patch;
285 var minimumNum = (minimum.major * 10000 * 10000) +
286 (minimum.minor * 10000) + minimum.patch;
288 return (versionNum >= minimumNum);
291 //------------------------------------------------------------------------------
292 // Validation / Errors
293 //------------------------------------------------------------------------------
295 function error(code, msg, obj) {
296 // do nothing if showErrors is not set
297 if (cfg.hasOwnProperty('showErrors') !== true ||
298 cfg.showErrors === false) {
302 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
305 if (cfg.showErrors === 'console' &&
306 typeof console === 'object' &&
307 typeof console.log === 'function') {
308 console.log(errorText);
309 if (arguments.length >= 2) {
316 if (cfg.showErrors === 'alert') {
318 errorText += '\n\n' + JSON.stringify(obj);
320 window.alert(errorText);
325 if (typeof cfg.showErrors === 'function') {
326 cfg.showErrors(code, msg, obj);
330 // check dependencies
331 function checkDeps() {
332 // if containerId is a string, it must be the ID of a DOM node
333 if (typeof containerElOrId === 'string') {
335 if (containerElOrId === '') {
336 window.alert('ChessBoard Error 1001: ' +
337 'The first argument to ChessBoard() cannot be an empty string.' +
342 // make sure the container element exists in the DOM
343 var el = document.getElementById(containerElOrId);
345 window.alert('ChessBoard Error 1002: Element with id "' +
346 containerElOrId + '" does not exist in the DOM.' +
351 // set the containerEl
355 // else it must be something that becomes a jQuery collection
357 // ie: a single DOM node or jQuery object
359 containerEl = $(containerElOrId);
361 if (containerEl.length !== 1) {
362 window.alert('ChessBoard Error 1003: The first argument to ' +
363 'ChessBoard() must be an ID or a single DOM node.' +
371 typeof JSON.stringify !== 'function' ||
372 typeof JSON.parse !== 'function') {
373 window.alert('ChessBoard Error 1004: JSON does not exist. ' +
374 'Please include a JSON polyfill.\n\nExiting...');
378 // check for a compatible version of jQuery
379 if (! (typeof window.$ && $.fn && $.fn.jquery &&
380 compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) {
381 window.alert('ChessBoard Error 1005: Unable to find a valid version ' +
382 'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' +
383 'higher on the page.\n\nExiting...');
390 function validAnimationSpeed(speed) {
391 if (speed === 'fast' || speed === 'slow') {
395 if ((parseInt(speed, 10) + '') !== (speed + '')) {
402 // validate config / set default options
403 function expandConfig() {
404 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
410 // default for orientation is white
411 if (cfg.orientation !== 'black') {
412 cfg.orientation = 'white';
414 CURRENT_ORIENTATION = cfg.orientation;
416 // default for showNotation is true
417 if (cfg.showNotation !== false) {
418 cfg.showNotation = true;
421 // default for draggable is false
422 if (cfg.draggable !== true) {
423 cfg.draggable = false;
426 // default for dropOffBoard is 'snapback'
427 if (cfg.dropOffBoard !== 'trash') {
428 cfg.dropOffBoard = 'snapback';
431 // default for sparePieces is false
432 if (cfg.sparePieces !== true) {
433 cfg.sparePieces = false;
436 // draggable must be true if sparePieces is enabled
437 if (cfg.sparePieces === true) {
438 cfg.draggable = true;
441 // default piece theme is wikipedia
442 if (cfg.hasOwnProperty('pieceTheme') !== true ||
443 (typeof cfg.pieceTheme !== 'string' &&
444 typeof cfg.pieceTheme !== 'function')) {
445 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
449 if (cfg.hasOwnProperty('appearSpeed') !== true ||
450 validAnimationSpeed(cfg.appearSpeed) !== true) {
451 cfg.appearSpeed = 200;
453 if (cfg.hasOwnProperty('moveSpeed') !== true ||
454 validAnimationSpeed(cfg.moveSpeed) !== true) {
457 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
458 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
459 cfg.snapbackSpeed = 50;
461 if (cfg.hasOwnProperty('snapSpeed') !== true ||
462 validAnimationSpeed(cfg.snapSpeed) !== true) {
465 if (cfg.hasOwnProperty('trashSpeed') !== true ||
466 validAnimationSpeed(cfg.trashSpeed) !== true) {
467 cfg.trashSpeed = 100;
470 // make sure position is valid
471 if (cfg.hasOwnProperty('position') === true) {
472 if (cfg.position === 'start') {
473 CURRENT_POSITION = deepCopy(START_POSITION);
476 else if (validFen(cfg.position) === true) {
477 CURRENT_POSITION = fenToObj(cfg.position);
480 else if (validPositionObject(cfg.position) === true) {
481 CURRENT_POSITION = deepCopy(cfg.position);
485 error(7263, 'Invalid value passed to config.position.', cfg.position);
492 //------------------------------------------------------------------------------
494 //------------------------------------------------------------------------------
496 // calculates square size based on the width of the container
497 // got a little CSS black magic here, so let me explain:
498 // get the width of the container element (could be anything), reduce by 1 for
499 // fudge factor, and then keep reducing until we find an exact mod 8 for
501 function calculateSquareSize() {
502 var containerWidth = parseInt(containerEl.css('width'), 10);
504 // defensive, prevent infinite loop
505 if (! containerWidth || containerWidth <= 0) {
510 var boardWidth = containerWidth - 1;
512 while (boardWidth % 8 !== 0 && boardWidth > 0) {
516 return (boardWidth / 8);
519 // create random IDs for elements
520 function createElIds() {
521 // squares on the board
522 for (var i = 0; i < COLUMNS.length; i++) {
523 for (var j = 1; j <= 8; j++) {
524 var square = COLUMNS[i] + j;
525 SQUARE_ELS_IDS[square] = square + '-' + createId();
530 var pieces = 'KQRBNP'.split('');
531 for (var i = 0; i < pieces.length; i++) {
532 var whitePiece = 'w' + pieces[i];
533 var blackPiece = 'b' + pieces[i];
534 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
535 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
539 //------------------------------------------------------------------------------
541 //------------------------------------------------------------------------------
543 function buildBoardContainer() {
544 var html = '<div class="' + CSS.chessboard + '">';
546 if (cfg.sparePieces === true) {
547 html += '<div class="' + CSS.sparePieces + ' ' +
548 CSS.sparePiecesTop + '"></div>';
551 html += '<div class="' + CSS.board + '"></div>';
553 if (cfg.sparePieces === true) {
554 html += '<div class="' + CSS.sparePieces + ' ' +
555 CSS.sparePiecesBottom + '"></div>';
564 var buildSquare = function(color, size, id) {
565 var html = '<div class="' + CSS.square + ' ' + CSS[color] + '" ' +
566 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
569 if (cfg.showNotation === true) {
579 function buildBoard(orientation) {
580 if (orientation !== 'black') {
581 orientation = 'white';
586 // algebraic notation / orientation
587 var alpha = deepCopy(COLUMNS);
589 if (orientation === 'black') {
594 var squareColor = 'white';
595 for (var i = 0; i < 8; i++) {
596 html += '<div class="' + CSS.row + '">';
597 for (var j = 0; j < 8; j++) {
598 var square = alpha[j] + row;
600 html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' +
601 'square-' + square + '" ' +
602 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
603 'id="' + SQUARE_ELS_IDS[square] + '" ' +
604 'data-square="' + square + '">';
606 if (cfg.showNotation === true) {
608 if ((orientation === 'white' && row === 1) ||
609 (orientation === 'black' && row === 8)) {
610 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
616 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
621 html += '</div>'; // end .square
623 squareColor = (squareColor === 'white' ? 'black' : 'white');
625 html += '<div class="' + CSS.clearfix + '"></div></div>';
627 squareColor = (squareColor === 'white' ? 'black' : 'white');
629 if (orientation === 'white') {
640 function buildPieceImgSrc(piece) {
641 if (typeof cfg.pieceTheme === 'function') {
642 return cfg.pieceTheme(piece);
645 if (typeof cfg.pieceTheme === 'string') {
646 return cfg.pieceTheme.replace(/{piece}/g, piece);
649 // NOTE: this should never happen
650 error(8272, 'Unable to build image source for cfg.pieceTheme.');
654 function buildPiece(piece, hidden, id) {
655 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
656 if (id && typeof id === 'string') {
657 html += 'id="' + id + '" ';
660 'class="' + CSS.piece + '" ' +
661 'data-piece="' + piece + '" ' +
662 'style="width: ' + SQUARE_SIZE + 'px;' +
663 'height: ' + SQUARE_SIZE + 'px;';
664 if (hidden === true) {
665 html += 'display:none;';
672 function buildSparePieces(color) {
673 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
674 if (color === 'black') {
675 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
679 for (var i = 0; i < pieces.length; i++) {
680 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
686 //------------------------------------------------------------------------------
688 //------------------------------------------------------------------------------
690 function animateSquareToSquare(src, dest, piece, completeFn) {
691 // get information about the source and destination squares
692 var srcSquareEl = $('#' + SQUARE_ELS_IDS[src]);
693 var srcSquarePosition = srcSquareEl.offset();
694 var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]);
695 var destSquarePosition = destSquareEl.offset();
697 // create the animated piece and absolutely position it
698 // over the source square
699 var animatedPieceId = createId();
700 $('body').append(buildPiece(piece, true, animatedPieceId));
701 var animatedPieceEl = $('#' + animatedPieceId);
702 animatedPieceEl.css({
704 position: 'absolute',
705 top: srcSquarePosition.top,
706 left: srcSquarePosition.left
709 // remove original piece from source square
710 srcSquareEl.find('.' + CSS.piece).remove();
713 var complete = function() {
714 // add the "real" piece to the destination square
715 destSquareEl.append(buildPiece(piece));
717 // remove the animated piece
718 animatedPieceEl.remove();
720 // run complete function
721 if (typeof completeFn === 'function') {
726 // animate the piece to the destination square
728 duration: cfg.moveSpeed,
731 animatedPieceEl.animate(destSquarePosition, opts);
734 function animateSparePieceToSquare(piece, dest, completeFn) {
735 var srcOffset = $('#' + SPARE_PIECE_ELS_IDS[piece]).offset();
736 var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]);
737 var destOffset = destSquareEl.offset();
739 // create the animate piece
740 var pieceId = createId();
741 $('body').append(buildPiece(piece, true, pieceId));
742 var animatedPieceEl = $('#' + pieceId);
743 animatedPieceEl.css({
745 position: 'absolute',
746 left: srcOffset.left,
751 var complete = function() {
752 // add the "real" piece to the destination square
753 destSquareEl.find('.' + CSS.piece).remove();
754 destSquareEl.append(buildPiece(piece));
756 // remove the animated piece
757 animatedPieceEl.remove();
759 // run complete function
760 if (typeof completeFn === 'function') {
765 // animate the piece to the destination square
767 duration: cfg.moveSpeed,
770 animatedPieceEl.animate(destOffset, opts);
773 // execute an array of animations
774 function doAnimations(a, oldPos, newPos) {
775 ANIMATION_HAPPENING = true;
778 function onFinish() {
781 // exit if all the animations aren't finished
782 if (numFinished !== a.length) return;
784 drawPositionInstant();
785 ANIMATION_HAPPENING = false;
787 // run their onMoveEnd function
788 if (cfg.hasOwnProperty('onMoveEnd') === true &&
789 typeof cfg.onMoveEnd === 'function') {
790 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
794 for (var i = 0; i < a.length; i++) {
796 if (a[i].type === 'clear') {
797 $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece)
798 .fadeOut(cfg.trashSpeed, onFinish);
801 // add a piece (no spare pieces)
802 if (a[i].type === 'add' && cfg.sparePieces !== true) {
803 $('#' + SQUARE_ELS_IDS[a[i].square])
804 .append(buildPiece(a[i].piece, true))
805 .find('.' + CSS.piece)
806 .fadeIn(cfg.appearSpeed, onFinish);
809 // add a piece from a spare piece
810 if (a[i].type === 'add' && cfg.sparePieces === true) {
811 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
815 if (a[i].type === 'move') {
816 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
822 // returns the distance between two squares
823 function squareDistance(s1, s2) {
825 var s1x = COLUMNS.indexOf(s1[0]) + 1;
826 var s1y = parseInt(s1[1], 10);
829 var s2x = COLUMNS.indexOf(s2[0]) + 1;
830 var s2y = parseInt(s2[1], 10);
832 var xDelta = Math.abs(s1x - s2x);
833 var yDelta = Math.abs(s1y - s2y);
835 if (xDelta >= yDelta) return xDelta;
839 // returns an array of closest squares from square
840 function createRadius(square) {
843 // calculate distance of all squares
844 for (var i = 0; i < 8; i++) {
845 for (var j = 0; j < 8; j++) {
846 var s = COLUMNS[i] + (j + 1);
848 // skip the square we're starting from
849 if (square === s) continue;
853 distance: squareDistance(square, s)
859 squares.sort(function(a, b) {
860 return a.distance - b.distance;
863 // just return the square code
865 for (var i = 0; i < squares.length; i++) {
866 squares2.push(squares[i].square);
872 // returns the square of the closest instance of piece
873 // returns false if no instance of piece is found in position
874 function findClosestPiece(position, piece, square) {
875 // create array of closest squares from square
876 var closestSquares = createRadius(square);
878 // search through the position in order of distance for the piece
879 for (var i = 0; i < closestSquares.length; i++) {
880 var s = closestSquares[i];
882 if (position.hasOwnProperty(s) === true && position[s] === piece) {
890 // calculate an array of animations that need to happen in order to get
892 function calculateAnimations(pos1, pos2) {
893 // make copies of both
894 pos1 = deepCopy(pos1);
895 pos2 = deepCopy(pos2);
898 var squaresMovedTo = {};
900 // remove pieces that are the same in both positions
901 for (var i in pos2) {
902 if (pos2.hasOwnProperty(i) !== true) continue;
904 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
910 // find all the "move" animations
911 for (var i in pos2) {
912 if (pos2.hasOwnProperty(i) !== true) continue;
914 var closestPiece = findClosestPiece(pos1, pos2[i], i);
915 if (closestPiece !== false) {
918 source: closestPiece,
923 delete pos1[closestPiece];
925 squaresMovedTo[i] = true;
929 // add pieces to pos2
930 for (var i in pos2) {
931 if (pos2.hasOwnProperty(i) !== true) continue;
942 // clear pieces from pos1
943 for (var i in pos1) {
944 if (pos1.hasOwnProperty(i) !== true) continue;
946 // do not clear a piece if it is on a square that is the result
947 // of a "move", ie: a piece capture
948 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
962 //------------------------------------------------------------------------------
964 //------------------------------------------------------------------------------
966 function drawPositionInstant() {
968 boardEl.find('.' + CSS.piece).remove();
971 for (var i in CURRENT_POSITION) {
972 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
974 $('#' + SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
978 function drawBoard() {
979 boardEl.html(buildBoard(CURRENT_ORIENTATION));
980 drawPositionInstant();
982 if (cfg.sparePieces === true) {
983 if (CURRENT_ORIENTATION === 'white') {
984 sparePiecesTopEl.html(buildSparePieces('black'));
985 sparePiecesBottomEl.html(buildSparePieces('white'));
988 sparePiecesTopEl.html(buildSparePieces('white'));
989 sparePiecesBottomEl.html(buildSparePieces('black'));
994 // given a position and a set of moves, return a new position
995 // with the moves executed
996 function calculatePositionFromMoves(position, moves) {
997 position = deepCopy(position);
999 for (var i in moves) {
1000 if (moves.hasOwnProperty(i) !== true) continue;
1002 // skip the move if the position doesn't have a piece on the source square
1003 if (position.hasOwnProperty(i) !== true) continue;
1005 var piece = position[i];
1007 position[moves[i]] = piece;
1013 function setCurrentPosition(position) {
1014 var oldPos = deepCopy(CURRENT_POSITION);
1015 var newPos = deepCopy(position);
1016 var oldFen = objToFen(oldPos);
1017 var newFen = objToFen(newPos);
1019 // do nothing if no change in position
1020 if (oldFen === newFen) return;
1022 // run their onChange function
1023 if (cfg.hasOwnProperty('onChange') === true &&
1024 typeof cfg.onChange === 'function') {
1025 cfg.onChange(oldPos, newPos);
1029 CURRENT_POSITION = position;
1032 function isXYOnSquare(x, y) {
1033 for (var i in SQUARE_ELS_OFFSETS) {
1034 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1036 var s = SQUARE_ELS_OFFSETS[i];
1037 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1038 y >= s.top && y < s.top + SQUARE_SIZE) {
1046 // records the XY coords of every square into memory
1047 function captureSquareOffsets() {
1048 SQUARE_ELS_OFFSETS = {};
1050 for (var i in SQUARE_ELS_IDS) {
1051 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1053 SQUARE_ELS_OFFSETS[i] = $('#' + SQUARE_ELS_IDS[i]).offset();
1057 function removeSquareHighlights() {
1058 boardEl.find('.' + CSS.square)
1059 .removeClass(CSS.highlight1 + ' ' + CSS.highlight2);
1062 function snapbackDraggedPiece() {
1063 // there is no "snapback" for spare pieces
1064 if (DRAGGED_PIECE_SOURCE === 'spare') {
1065 trashDraggedPiece();
1069 removeSquareHighlights();
1071 // animation complete
1072 function complete() {
1073 drawPositionInstant();
1074 draggedPieceEl.css('display', 'none');
1076 // run their onSnapbackEnd function
1077 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1078 typeof cfg.onSnapbackEnd === 'function') {
1079 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1080 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1084 // get source square position
1085 var sourceSquarePosition =
1086 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]).offset();
1088 // animate the piece to the target square
1090 duration: cfg.snapbackSpeed,
1093 draggedPieceEl.animate(sourceSquarePosition, opts);
1096 DRAGGING_A_PIECE = false;
1099 function trashDraggedPiece() {
1100 removeSquareHighlights();
1102 // remove the source piece
1103 var newPosition = deepCopy(CURRENT_POSITION);
1104 delete newPosition[DRAGGED_PIECE_SOURCE];
1105 setCurrentPosition(newPosition);
1107 // redraw the position
1108 drawPositionInstant();
1110 // hide the dragged piece
1111 draggedPieceEl.fadeOut(cfg.trashSpeed);
1114 DRAGGING_A_PIECE = false;
1117 function dropDraggedPieceOnSquare(square) {
1118 removeSquareHighlights();
1121 var newPosition = deepCopy(CURRENT_POSITION);
1122 delete newPosition[DRAGGED_PIECE_SOURCE];
1123 newPosition[square] = DRAGGED_PIECE;
1124 setCurrentPosition(newPosition);
1126 // get target square information
1127 var targetSquarePosition = $('#' + SQUARE_ELS_IDS[square]).offset();
1129 // animation complete
1130 var complete = function() {
1131 drawPositionInstant();
1132 draggedPieceEl.css('display', 'none');
1134 // execute their onSnapEnd function
1135 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1136 typeof cfg.onSnapEnd === 'function') {
1137 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1141 // snap the piece to the target square
1143 duration: cfg.snapSpeed,
1146 draggedPieceEl.animate(targetSquarePosition, opts);
1149 DRAGGING_A_PIECE = false;
1152 function beginDraggingPiece(source, piece, x, y) {
1153 // run their custom onDragStart function
1154 // their custom onDragStart function can cancel drag start
1155 if (typeof cfg.onDragStart === 'function' &&
1156 cfg.onDragStart(source, piece,
1157 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1162 DRAGGING_A_PIECE = true;
1163 DRAGGED_PIECE = piece;
1164 DRAGGED_PIECE_SOURCE = source;
1166 // if the piece came from spare pieces, location is offboard
1167 if (source === 'spare') {
1168 DRAGGED_PIECE_LOCATION = 'offboard';
1171 DRAGGED_PIECE_LOCATION = source;
1174 // capture the x, y coords of all squares in memory
1175 captureSquareOffsets();
1177 // create the dragged piece
1178 draggedPieceEl.attr('src', buildPieceImgSrc(piece))
1181 position: 'absolute',
1182 left: x - (SQUARE_SIZE / 2),
1183 top: y - (SQUARE_SIZE / 2)
1186 if (source !== 'spare') {
1187 // highlight the source square and hide the piece
1188 $('#' + SQUARE_ELS_IDS[source]).addClass(CSS.highlight1)
1189 .find('.' + CSS.piece).css('display', 'none');
1193 function updateDraggedPiece(x, y) {
1194 // put the dragged piece over the mouse cursor
1195 draggedPieceEl.css({
1196 left: x - (SQUARE_SIZE / 2),
1197 top: y - (SQUARE_SIZE / 2)
1201 var location = isXYOnSquare(x, y);
1203 // do nothing if the location has not changed
1204 if (location === DRAGGED_PIECE_LOCATION) return;
1206 // remove highlight from previous square
1207 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1208 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1209 .removeClass(CSS.highlight2);
1212 // add highlight to new square
1213 if (validSquare(location) === true) {
1214 $('#' + SQUARE_ELS_IDS[location]).addClass(CSS.highlight2);
1218 if (typeof cfg.onDragMove === 'function') {
1219 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1220 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1221 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1225 DRAGGED_PIECE_LOCATION = location;
1228 function stopDraggedPiece(location) {
1229 // determine what the action should be
1230 var action = 'drop';
1231 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1232 action = 'snapback';
1234 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1238 // run their onDrop function, which can potentially change the drop action
1239 if (cfg.hasOwnProperty('onDrop') === true &&
1240 typeof cfg.onDrop === 'function') {
1241 var newPosition = deepCopy(CURRENT_POSITION);
1243 // source piece is a spare piece and position is off the board
1244 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1245 // position has not changed; do nothing
1247 // source piece is a spare piece and position is on the board
1248 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1249 // add the piece to the board
1250 newPosition[location] = DRAGGED_PIECE;
1253 // source piece was on the board and position is off the board
1254 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1255 // remove the piece from the board
1256 delete newPosition[DRAGGED_PIECE_SOURCE];
1259 // source piece was on the board and position is on the board
1260 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1261 validSquare(location) === true) {
1263 delete newPosition[DRAGGED_PIECE_SOURCE];
1264 newPosition[location] = DRAGGED_PIECE;
1267 var oldPosition = deepCopy(CURRENT_POSITION);
1269 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1270 newPosition, oldPosition, CURRENT_ORIENTATION);
1271 if (result === 'snapback' || result === 'trash') {
1277 if (action === 'snapback') {
1278 snapbackDraggedPiece();
1280 else if (action === 'trash') {
1281 trashDraggedPiece();
1283 else if (action === 'drop') {
1284 dropDraggedPieceOnSquare(location);
1288 //------------------------------------------------------------------------------
1290 //------------------------------------------------------------------------------
1293 widget.clear = function(useAnimation) {
1294 widget.position({}, useAnimation);
1298 // get or set config properties
1299 // TODO: write this, GitHub Issue #1
1300 widget.config = function(arg1, arg2) {
1301 // get the current config
1302 if (arguments.length === 0) {
1303 return deepCopy(cfg);
1308 // remove the widget from the page
1309 widget.destroy = function() {
1311 containerEl.html('');
1312 draggedPieceEl.remove();
1314 // remove event handlers
1315 containerEl.unbind();
1318 // shorthand method to get the current FEN
1319 widget.fen = function() {
1320 return widget.position('fen');
1324 widget.flip = function() {
1325 widget.orientation('flip');
1329 // TODO: write this, GitHub Issue #5
1330 widget.highlight = function() {
1336 widget.move = function() {
1337 // no need to throw an error here; just do nothing
1338 if (arguments.length === 0) return;
1340 var useAnimation = true;
1342 // collect the moves into an object
1344 for (var i = 0; i < arguments.length; i++) {
1345 // any "false" to this function means no animations
1346 if (arguments[i] === false) {
1347 useAnimation = false;
1351 // skip invalid arguments
1352 if (validMove(arguments[i]) !== true) {
1353 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1357 var tmp = arguments[i].split('-');
1358 moves[tmp[0]] = tmp[1];
1361 // calculate position from moves
1362 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1365 widget.position(newPos, useAnimation);
1367 // return the new position object
1371 widget.orientation = function(arg) {
1372 // no arguments, return the current orientation
1373 if (arguments.length === 0) {
1374 return CURRENT_ORIENTATION;
1377 // set to white or black
1378 if (arg === 'white' || arg === 'black') {
1379 CURRENT_ORIENTATION = arg;
1385 if (arg === 'flip') {
1386 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1391 error(5482, 'Invalid value passed to the orientation method.', arg);
1394 widget.position = function(position, useAnimation) {
1395 // no arguments, return the current position
1396 if (arguments.length === 0) {
1397 return deepCopy(CURRENT_POSITION);
1400 // get position as FEN
1401 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1402 return objToFen(CURRENT_POSITION);
1405 // default for useAnimations is true
1406 if (useAnimation !== false) {
1407 useAnimation = true;
1411 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1412 position = deepCopy(START_POSITION);
1415 // convert FEN to position object
1416 if (validFen(position) === true) {
1417 position = fenToObj(position);
1420 // validate position object
1421 if (validPositionObject(position) !== true) {
1422 error(6482, 'Invalid value passed to the position method.', position);
1426 if (useAnimation === true) {
1427 // start the animations
1428 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1429 CURRENT_POSITION, position);
1431 // set the new position
1432 setCurrentPosition(position);
1436 setCurrentPosition(position);
1437 drawPositionInstant();
1441 widget.resize = function() {
1442 // calulate the new square size
1443 SQUARE_SIZE = calculateSquareSize();
1446 boardEl.css('width', (SQUARE_SIZE * 8) + 'px');
1448 // set drag piece size
1449 draggedPieceEl.css({
1450 height: SQUARE_SIZE,
1455 if (cfg.sparePieces === true) {
1456 containerEl.find('.' + CSS.sparePieces)
1457 .css('paddingLeft', (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px');
1464 // set the starting position
1465 widget.start = function(useAnimation) {
1466 widget.position('start', useAnimation);
1469 //------------------------------------------------------------------------------
1471 //------------------------------------------------------------------------------
1473 function isTouchDevice() {
1474 return ('ontouchstart' in document.documentElement);
1477 // reference: http://www.quirksmode.org/js/detect.html
1479 return (navigator && navigator.userAgent &&
1480 navigator.userAgent.search(/MSIE/) !== -1);
1483 function stopDefault(e) {
1487 function mousedownSquare(e) {
1488 // do nothing if we're not draggable
1489 if (cfg.draggable !== true) return;
1491 var square = $(this).attr('data-square');
1493 // no piece on this square
1494 if (validSquare(square) !== true ||
1495 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1499 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1502 function touchstartSquare(e) {
1503 // do nothing if we're not draggable
1504 if (cfg.draggable !== true) return;
1506 var square = $(this).attr('data-square');
1508 // no piece on this square
1509 if (validSquare(square) !== true ||
1510 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1514 e = e.originalEvent;
1515 beginDraggingPiece(square, CURRENT_POSITION[square],
1516 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1519 function mousedownSparePiece(e) {
1520 // do nothing if sparePieces is not enabled
1521 if (cfg.sparePieces !== true) return;
1523 var piece = $(this).attr('data-piece');
1525 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1528 function touchstartSparePiece(e) {
1529 // do nothing if sparePieces is not enabled
1530 if (cfg.sparePieces !== true) return;
1532 var piece = $(this).attr('data-piece');
1534 e = e.originalEvent;
1535 beginDraggingPiece('spare', piece,
1536 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1539 function mousemoveWindow(e) {
1540 // do nothing if we are not dragging a piece
1541 if (DRAGGING_A_PIECE !== true) return;
1543 updateDraggedPiece(e.pageX, e.pageY);
1546 function touchmoveWindow(e) {
1547 // do nothing if we are not dragging a piece
1548 if (DRAGGING_A_PIECE !== true) return;
1550 // prevent screen from scrolling
1553 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1554 e.originalEvent.changedTouches[0].pageY);
1557 function mouseupWindow(e) {
1558 // do nothing if we are not dragging a piece
1559 if (DRAGGING_A_PIECE !== true) return;
1562 var location = isXYOnSquare(e.pageX, e.pageY);
1564 stopDraggedPiece(location);
1567 function touchendWindow(e) {
1568 // do nothing if we are not dragging a piece
1569 if (DRAGGING_A_PIECE !== true) return;
1572 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1573 e.originalEvent.changedTouches[0].pageY);
1575 stopDraggedPiece(location);
1578 function mouseenterSquare(e) {
1579 // do not fire this event if we are dragging a piece
1580 // NOTE: this should never happen, but it's a safeguard
1581 if (DRAGGING_A_PIECE !== false) return;
1583 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1584 typeof cfg.onMouseoverSquare !== 'function') return;
1587 var square = $(e.currentTarget).attr('data-square');
1589 // NOTE: this should never happen; defensive
1590 if (validSquare(square) !== true) return;
1592 // get the piece on this square
1594 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1595 piece = CURRENT_POSITION[square];
1598 // execute their function
1599 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1600 CURRENT_ORIENTATION);
1603 function mouseleaveSquare(e) {
1604 // do not fire this event if we are dragging a piece
1605 // NOTE: this should never happen, but it's a safeguard
1606 if (DRAGGING_A_PIECE !== false) return;
1608 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1609 typeof cfg.onMouseoutSquare !== 'function') return;
1612 var square = $(e.currentTarget).attr('data-square');
1614 // NOTE: this should never happen; defensive
1615 if (validSquare(square) !== true) return;
1617 // get the piece on this square
1619 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1620 piece = CURRENT_POSITION[square];
1623 // execute their function
1624 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1625 CURRENT_ORIENTATION);
1628 //------------------------------------------------------------------------------
1630 //------------------------------------------------------------------------------
1632 function addEvents() {
1633 // prevent browser "image drag"
1634 $('body').on('mousedown mousemove', '.' + CSS.piece, stopDefault);
1636 // mouse drag pieces
1637 boardEl.on('mousedown', '.' + CSS.square, mousedownSquare);
1638 containerEl.on('mousedown', '.' + CSS.sparePieces + ' .' + CSS.piece,
1639 mousedownSparePiece);
1641 // mouse enter / leave square
1642 boardEl.on('mouseenter', '.' + CSS.square, mouseenterSquare);
1643 boardEl.on('mouseleave', '.' + CSS.square, mouseleaveSquare);
1645 // IE doesn't like the events on the window object, but other browsers
1646 // perform better that way
1647 if (isMSIE() === true) {
1648 // IE-specific prevent browser "image drag"
1649 document.ondragstart = function() { return false; };
1651 $('body').on('mousemove', mousemoveWindow);
1652 $('body').on('mouseup', mouseupWindow);
1655 $(window).on('mousemove', mousemoveWindow);
1656 $(window).on('mouseup', mouseupWindow);
1659 // touch drag pieces
1660 if (isTouchDevice() === true) {
1661 boardEl.on('touchstart', '.' + CSS.square, touchstartSquare);
1662 containerEl.on('touchstart', '.' + CSS.sparePieces + ' .' + CSS.piece,
1663 touchstartSparePiece);
1664 $(window).on('touchmove', touchmoveWindow);
1665 $(window).on('touchend', touchendWindow);
1669 function initDom() {
1670 // build board and save it in memory
1671 containerEl.html(buildBoardContainer());
1672 boardEl = containerEl.find('.' + CSS.board);
1674 if (cfg.sparePieces === true) {
1675 sparePiecesTopEl = containerEl.find('.' + CSS.sparePiecesTop);
1676 sparePiecesBottomEl = containerEl.find('.' + CSS.sparePiecesBottom);
1679 // create the drag piece
1680 var draggedPieceId = createId();
1681 $('body').append(buildPiece('wP', true, draggedPieceId));
1682 draggedPieceEl = $('#' + draggedPieceId);
1684 // get the border size
1685 BOARD_BORDER_SIZE = parseInt(boardEl.css('borderLeftWidth'), 10);
1687 // set the size and draw the board
1692 if (checkDeps() !== true ||
1693 expandConfig() !== true) return;
1695 // create unique IDs for all the elements we will create
1705 // return the widget object
1708 }; // end window.ChessBoard
1710 // expose util functions
1711 window.ChessBoard.fenToObj = fenToObj;
1712 window.ChessBoard.objToFen = objToFen;
1714 })(); // end anonymous wrapper