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');
192 window.ChessBoard = function(containerElOrId, cfg) {
197 //------------------------------------------------------------------------------
199 //------------------------------------------------------------------------------
201 var MINIMUM_JQUERY_VERSION = '1.7.0',
202 START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
203 START_POSITION = fenToObj(START_FEN);
205 // use unique class names to prevent clashing with anything else on the page
206 // and simplify selectors
208 alpha: 'alpha-d2270',
209 board: 'board-b72b1',
210 chessboard: 'chessboard-63f37',
211 clearfix: 'clearfix-7da63',
212 highlight1: 'highlight1-32417',
213 highlight2: 'highlight2-9c5d2',
214 notation: 'notation-322f9',
215 numeric: 'numeric-fc462',
216 piece: 'piece-417db',
218 sparePieces: 'spare-pieces-7492f',
219 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
220 sparePiecesTop: 'spare-pieces-top-4028b',
221 square: 'square-55d63'
224 CSSColor['white'] = 'white-1e1d7';
225 CSSColor['black'] = 'black-3c85d';
227 //------------------------------------------------------------------------------
228 // Module Scope Variables
229 //------------------------------------------------------------------------------
238 // constructor return object
241 //------------------------------------------------------------------------------
243 //------------------------------------------------------------------------------
245 var ANIMATION_HAPPENING = false,
246 BOARD_BORDER_SIZE = 2,
247 CURRENT_ORIENTATION = 'white',
248 CURRENT_POSITION = {},
251 DRAGGED_PIECE_LOCATION,
252 DRAGGED_PIECE_SOURCE,
253 DRAGGING_A_PIECE = false,
254 SPARE_PIECE_ELS_IDS = {},
258 //------------------------------------------------------------------------------
260 //------------------------------------------------------------------------------
262 // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
263 function createId() {
264 return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function(c) {
265 var r = Math.random() * 16 | 0;
266 return r.toString(16);
270 function deepCopy(thing) {
271 return JSON.parse(JSON.stringify(thing));
274 function parseSemVer(version) {
275 var tmp = version.split('.');
277 major: parseInt(tmp[0], 10),
278 minor: parseInt(tmp[1], 10),
279 patch: parseInt(tmp[2], 10)
283 // returns true if version is >= minimum
284 function compareSemVer(version, minimum) {
285 version = parseSemVer(version);
286 minimum = parseSemVer(minimum);
288 var versionNum = (version.major * 10000 * 10000) +
289 (version.minor * 10000) + version.patch;
290 var minimumNum = (minimum.major * 10000 * 10000) +
291 (minimum.minor * 10000) + minimum.patch;
293 return (versionNum >= minimumNum);
296 //------------------------------------------------------------------------------
297 // Validation / Errors
298 //------------------------------------------------------------------------------
301 * @param {!number} code
302 * @param {!string} msg
303 * @param {Object=} obj
305 function error(code, msg, obj) {
306 // do nothing if showErrors is not set
307 if (cfg.hasOwnProperty('showErrors') !== true ||
308 cfg.showErrors === false) {
312 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
315 if (cfg.showErrors === 'console' &&
316 typeof console === 'object' &&
317 typeof console.log === 'function') {
318 console.log(errorText);
319 if (arguments.length >= 2) {
326 if (cfg.showErrors === 'alert') {
328 errorText += '\n\n' + JSON.stringify(obj);
330 window.alert(errorText);
335 if (typeof cfg.showErrors === 'function') {
336 cfg.showErrors(code, msg, obj);
340 // check dependencies
341 function checkDeps() {
342 // if containerId is a string, it must be the ID of a DOM node
343 if (typeof containerElOrId === 'string') {
345 if (containerElOrId === '') {
346 window.alert('ChessBoard Error 1001: ' +
347 'The first argument to ChessBoard() cannot be an empty string.' +
352 // make sure the container element exists in the DOM
353 var el = document.getElementById(containerElOrId);
355 window.alert('ChessBoard Error 1002: Element with id "' +
356 containerElOrId + '" does not exist in the DOM.' +
361 // set the containerEl
365 // else it must be something that becomes a jQuery collection
367 // ie: a single DOM node or jQuery object
369 containerEl = $(containerElOrId);
371 if (containerEl.length !== 1) {
372 window.alert('ChessBoard Error 1003: The first argument to ' +
373 'ChessBoard() must be an ID or a single DOM node.' +
381 typeof JSON.stringify !== 'function' ||
382 typeof JSON.parse !== 'function') {
383 window.alert('ChessBoard Error 1004: JSON does not exist. ' +
384 'Please include a JSON polyfill.\n\nExiting...');
388 // check for a compatible version of jQuery
389 if (! (typeof window.$ && $.fn && $.fn.jquery &&
390 compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) {
391 window.alert('ChessBoard Error 1005: Unable to find a valid version ' +
392 'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' +
393 'higher on the page.\n\nExiting...');
400 function validAnimationSpeed(speed) {
401 if (speed === 'fast' || speed === 'slow') {
405 if ((parseInt(speed, 10) + '') !== (speed + '')) {
412 // validate config / set default options
413 function expandConfig() {
414 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
420 // default for orientation is white
421 if (cfg.orientation !== 'black') {
422 cfg.orientation = 'white';
424 CURRENT_ORIENTATION = cfg.orientation;
426 // default for showNotation is true
427 if (cfg.showNotation !== false) {
428 cfg.showNotation = true;
431 // default for draggable is false
432 if (cfg.draggable !== true) {
433 cfg.draggable = false;
436 // default for dropOffBoard is 'snapback'
437 if (cfg.dropOffBoard !== 'trash') {
438 cfg.dropOffBoard = 'snapback';
441 // default for sparePieces is false
442 if (cfg.sparePieces !== true) {
443 cfg.sparePieces = false;
446 // draggable must be true if sparePieces is enabled
447 if (cfg.sparePieces === true) {
448 cfg.draggable = true;
451 // default piece theme is wikipedia
452 if (cfg.hasOwnProperty('pieceTheme') !== true ||
453 (typeof cfg.pieceTheme !== 'string' &&
454 typeof cfg.pieceTheme !== 'function')) {
455 cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
459 if (cfg.hasOwnProperty('appearSpeed') !== true ||
460 validAnimationSpeed(cfg.appearSpeed) !== true) {
461 cfg.appearSpeed = 200;
463 if (cfg.hasOwnProperty('moveSpeed') !== true ||
464 validAnimationSpeed(cfg.moveSpeed) !== true) {
467 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
468 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
469 cfg.snapbackSpeed = 50;
471 if (cfg.hasOwnProperty('snapSpeed') !== true ||
472 validAnimationSpeed(cfg.snapSpeed) !== true) {
475 if (cfg.hasOwnProperty('trashSpeed') !== true ||
476 validAnimationSpeed(cfg.trashSpeed) !== true) {
477 cfg.trashSpeed = 100;
480 // make sure position is valid
481 if (cfg.hasOwnProperty('position') === true) {
482 if (cfg.position === 'start') {
483 CURRENT_POSITION = deepCopy(START_POSITION);
486 else if (validFen(cfg.position) === true) {
487 CURRENT_POSITION = fenToObj(cfg.position);
490 else if (validPositionObject(cfg.position) === true) {
491 CURRENT_POSITION = deepCopy(cfg.position);
495 error(7263, 'Invalid value passed to config.position.', cfg.position);
502 //------------------------------------------------------------------------------
504 //------------------------------------------------------------------------------
506 // calculates square size based on the width of the container
507 // got a little CSS black magic here, so let me explain:
508 // get the width of the container element (could be anything), reduce by 1 for
509 // fudge factor, and then keep reducing until we find an exact mod 8 for
511 function calculateSquareSize() {
512 var containerWidth = parseInt(containerEl.css('width'), 10);
514 // defensive, prevent infinite loop
515 if (! containerWidth || containerWidth <= 0) {
520 var boardWidth = containerWidth - 1;
522 while (boardWidth % 8 !== 0 && boardWidth > 0) {
526 return (boardWidth / 8);
529 // create random IDs for elements
530 function createElIds() {
531 // squares on the board
532 for (var i = 0; i < COLUMNS.length; i++) {
533 for (var j = 1; j <= 8; j++) {
534 var square = COLUMNS[i] + j;
535 SQUARE_ELS_IDS[square] = square + '-' + createId();
540 var pieces = 'KQRBNP'.split('');
541 for (var i = 0; i < pieces.length; i++) {
542 var whitePiece = 'w' + pieces[i];
543 var blackPiece = 'b' + pieces[i];
544 SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
545 SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
549 //------------------------------------------------------------------------------
551 //------------------------------------------------------------------------------
553 function buildBoardContainer() {
554 var html = '<div class="' + CSS.chessboard + '">';
556 if (cfg.sparePieces === true) {
557 html += '<div class="' + CSS.sparePieces + ' ' +
558 CSS.sparePiecesTop + '"></div>';
561 html += '<div class="' + CSS.board + '"></div>';
563 if (cfg.sparePieces === true) {
564 html += '<div class="' + CSS.sparePieces + ' ' +
565 CSS.sparePiecesBottom + '"></div>';
574 var buildSquare = function(color, size, id) {
575 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
576 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
579 if (cfg.showNotation === true) {
589 function buildBoard(orientation) {
590 if (orientation !== 'black') {
591 orientation = 'white';
596 // algebraic notation / orientation
597 var alpha = deepCopy(COLUMNS);
599 if (orientation === 'black') {
604 var squareColor = 'white';
605 for (var i = 0; i < 8; i++) {
606 html += '<div class="' + CSS.row + '">';
607 for (var j = 0; j < 8; j++) {
608 var square = alpha[j] + row;
610 html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
611 'square-' + square + '" ' +
612 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
613 'id="' + SQUARE_ELS_IDS[square] + '" ' +
614 'data-square="' + square + '">';
616 if (cfg.showNotation === true) {
618 if ((orientation === 'white' && row === 1) ||
619 (orientation === 'black' && row === 8)) {
620 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
626 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
631 html += '</div>'; // end .square
633 squareColor = (squareColor === 'white' ? 'black' : 'white');
635 html += '<div class="' + CSS.clearfix + '"></div></div>';
637 squareColor = (squareColor === 'white' ? 'black' : 'white');
639 if (orientation === 'white') {
650 function buildPieceImgSrc(piece) {
651 if (typeof cfg.pieceTheme === 'function') {
652 return cfg.pieceTheme(piece);
655 if (typeof cfg.pieceTheme === 'string') {
656 return cfg.pieceTheme.replace(/{piece}/g, piece);
659 // NOTE: this should never happen
660 error(8272, 'Unable to build image source for cfg.pieceTheme.');
665 * @param {!string} piece
666 * @param {boolean=} hidden
667 * @param {!string=} id
669 function buildPiece(piece, hidden, id) {
670 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
671 if (id && typeof id === 'string') {
672 html += 'id="' + id + '" ';
675 'class="' + CSS.piece + '" ' +
676 'data-piece="' + piece + '" ' +
677 'style="width: ' + SQUARE_SIZE + 'px;' +
678 'height: ' + SQUARE_SIZE + 'px;';
679 if (hidden === true) {
680 html += 'display:none;';
687 function buildSparePieces(color) {
688 var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
689 if (color === 'black') {
690 pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
694 for (var i = 0; i < pieces.length; i++) {
695 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
701 //------------------------------------------------------------------------------
703 //------------------------------------------------------------------------------
705 function animateSquareToSquare(src, dest, piece, completeFn) {
706 // get information about the source and destination squares
707 var srcSquareEl = $('#' + SQUARE_ELS_IDS[src]);
708 var srcSquarePosition = srcSquareEl.offset();
709 var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]);
710 var destSquarePosition = destSquareEl.offset();
712 // create the animated piece and absolutely position it
713 // over the source square
714 var animatedPieceId = createId();
715 $('body').append(buildPiece(piece, true, animatedPieceId));
716 var animatedPieceEl = $('#' + animatedPieceId);
717 animatedPieceEl.css({
719 position: 'absolute',
720 top: srcSquarePosition.top,
721 left: srcSquarePosition.left
724 // remove original piece from source square
725 srcSquareEl.find('.' + CSS.piece).remove();
728 var complete = function() {
729 // add the "real" piece to the destination square
730 destSquareEl.append(buildPiece(piece));
732 // remove the animated piece
733 animatedPieceEl.remove();
735 // run complete function
736 if (typeof completeFn === 'function') {
741 // animate the piece to the destination square
743 duration: cfg.moveSpeed,
746 animatedPieceEl.animate(destSquarePosition, opts);
749 function animateSparePieceToSquare(piece, dest, completeFn) {
750 var srcOffset = $('#' + SPARE_PIECE_ELS_IDS[piece]).offset();
751 var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]);
752 var destOffset = destSquareEl.offset();
754 // create the animate piece
755 var pieceId = createId();
756 $('body').append(buildPiece(piece, true, pieceId));
757 var animatedPieceEl = $('#' + pieceId);
758 animatedPieceEl.css({
760 position: 'absolute',
761 left: srcOffset.left,
766 var complete = function() {
767 // add the "real" piece to the destination square
768 destSquareEl.find('.' + CSS.piece).remove();
769 destSquareEl.append(buildPiece(piece));
771 // remove the animated piece
772 animatedPieceEl.remove();
774 // run complete function
775 if (typeof completeFn === 'function') {
780 // animate the piece to the destination square
782 duration: cfg.moveSpeed,
785 animatedPieceEl.animate(destOffset, opts);
788 // execute an array of animations
789 function doAnimations(a, oldPos, newPos) {
790 ANIMATION_HAPPENING = true;
793 function onFinish() {
796 // exit if all the animations aren't finished
797 if (numFinished !== a.length) return;
799 drawPositionInstant();
800 ANIMATION_HAPPENING = false;
802 // run their onMoveEnd function
803 if (cfg.hasOwnProperty('onMoveEnd') === true &&
804 typeof cfg.onMoveEnd === 'function') {
805 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
809 for (var i = 0; i < a.length; i++) {
811 if (a[i].type === 'clear') {
812 $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece)
813 .fadeOut(cfg.trashSpeed, onFinish);
816 // add a piece (no spare pieces)
817 if (a[i].type === 'add' && cfg.sparePieces !== true) {
818 $('#' + SQUARE_ELS_IDS[a[i].square])
819 .append(buildPiece(a[i].piece, true))
820 .find('.' + CSS.piece)
821 .fadeIn(cfg.appearSpeed, onFinish);
824 // add a piece from a spare piece
825 if (a[i].type === 'add' && cfg.sparePieces === true) {
826 animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
830 if (a[i].type === 'move') {
831 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
837 // returns the distance between two squares
838 function squareDistance(s1, s2) {
840 var s1x = COLUMNS.indexOf(s1[0]) + 1;
841 var s1y = parseInt(s1[1], 10);
844 var s2x = COLUMNS.indexOf(s2[0]) + 1;
845 var s2y = parseInt(s2[1], 10);
847 var xDelta = Math.abs(s1x - s2x);
848 var yDelta = Math.abs(s1y - s2y);
850 if (xDelta >= yDelta) return xDelta;
854 // returns an array of closest squares from square
855 function createRadius(square) {
858 // calculate distance of all squares
859 for (var i = 0; i < 8; i++) {
860 for (var j = 0; j < 8; j++) {
861 var s = COLUMNS[i] + (j + 1);
863 // skip the square we're starting from
864 if (square === s) continue;
868 distance: squareDistance(square, s)
874 squares.sort(function(a, b) {
875 return a.distance - b.distance;
878 // just return the square code
880 for (var i = 0; i < squares.length; i++) {
881 squares2.push(squares[i].square);
887 // returns the square of the closest instance of piece
888 // returns false if no instance of piece is found in position
889 function findClosestPiece(position, piece, square) {
890 // create array of closest squares from square
891 var closestSquares = createRadius(square);
893 // search through the position in order of distance for the piece
894 for (var i = 0; i < closestSquares.length; i++) {
895 var s = closestSquares[i];
897 if (position.hasOwnProperty(s) === true && position[s] === piece) {
905 // calculate an array of animations that need to happen in order to get
907 function calculateAnimations(pos1, pos2) {
908 // make copies of both
909 pos1 = deepCopy(pos1);
910 pos2 = deepCopy(pos2);
913 var squaresMovedTo = {};
915 // remove pieces that are the same in both positions
916 for (var i in pos2) {
917 if (pos2.hasOwnProperty(i) !== true) continue;
919 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
925 // find all the "move" animations
926 for (var i in pos2) {
927 if (pos2.hasOwnProperty(i) !== true) continue;
929 var closestPiece = findClosestPiece(pos1, pos2[i], i);
930 if (closestPiece !== false) {
933 source: closestPiece,
938 delete pos1[closestPiece];
940 squaresMovedTo[i] = true;
944 // add pieces to pos2
945 for (var i in pos2) {
946 if (pos2.hasOwnProperty(i) !== true) continue;
957 // clear pieces from pos1
958 for (var i in pos1) {
959 if (pos1.hasOwnProperty(i) !== true) continue;
961 // do not clear a piece if it is on a square that is the result
962 // of a "move", ie: a piece capture
963 if (squaresMovedTo.hasOwnProperty(i) === true) continue;
977 //------------------------------------------------------------------------------
979 //------------------------------------------------------------------------------
981 function drawPositionInstant() {
983 boardEl.find('.' + CSS.piece).remove();
986 for (var i in CURRENT_POSITION) {
987 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
989 $('#' + SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
993 function drawBoard() {
994 boardEl.html(buildBoard(CURRENT_ORIENTATION));
995 drawPositionInstant();
997 if (cfg.sparePieces === true) {
998 if (CURRENT_ORIENTATION === 'white') {
999 sparePiecesTopEl.html(buildSparePieces('black'));
1000 sparePiecesBottomEl.html(buildSparePieces('white'));
1003 sparePiecesTopEl.html(buildSparePieces('white'));
1004 sparePiecesBottomEl.html(buildSparePieces('black'));
1009 // given a position and a set of moves, return a new position
1010 // with the moves executed
1011 function calculatePositionFromMoves(position, moves) {
1012 position = deepCopy(position);
1014 for (var i in moves) {
1015 if (moves.hasOwnProperty(i) !== true) continue;
1017 // skip the move if the position doesn't have a piece on the source square
1018 if (position.hasOwnProperty(i) !== true) continue;
1020 var piece = position[i];
1022 position[moves[i]] = piece;
1028 function setCurrentPosition(position) {
1029 var oldPos = deepCopy(CURRENT_POSITION);
1030 var newPos = deepCopy(position);
1031 var oldFen = objToFen(oldPos);
1032 var newFen = objToFen(newPos);
1034 // do nothing if no change in position
1035 if (oldFen === newFen) return;
1037 // run their onChange function
1038 if (cfg.hasOwnProperty('onChange') === true &&
1039 typeof cfg.onChange === 'function') {
1040 cfg.onChange(oldPos, newPos);
1044 CURRENT_POSITION = position;
1047 function isXYOnSquare(x, y) {
1048 for (var i in SQUARE_ELS_OFFSETS) {
1049 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1051 var s = SQUARE_ELS_OFFSETS[i];
1052 if (x >= s.left && x < s.left + SQUARE_SIZE &&
1053 y >= s.top && y < s.top + SQUARE_SIZE) {
1061 // records the XY coords of every square into memory
1062 function captureSquareOffsets() {
1063 SQUARE_ELS_OFFSETS = {};
1065 for (var i in SQUARE_ELS_IDS) {
1066 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1068 SQUARE_ELS_OFFSETS[i] = $('#' + SQUARE_ELS_IDS[i]).offset();
1072 function removeSquareHighlights() {
1073 boardEl.find('.' + CSS.square)
1074 .removeClass(CSS.highlight1 + ' ' + CSS.highlight2);
1077 function snapbackDraggedPiece() {
1078 // there is no "snapback" for spare pieces
1079 if (DRAGGED_PIECE_SOURCE === 'spare') {
1080 trashDraggedPiece();
1084 removeSquareHighlights();
1086 // animation complete
1087 function complete() {
1088 drawPositionInstant();
1089 draggedPieceEl.css('display', 'none');
1091 // run their onSnapbackEnd function
1092 if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1093 typeof cfg.onSnapbackEnd === 'function') {
1094 cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1095 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1099 // get source square position
1100 var sourceSquarePosition =
1101 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]).offset();
1103 // animate the piece to the target square
1105 duration: cfg.snapbackSpeed,
1108 draggedPieceEl.animate(sourceSquarePosition, opts);
1111 DRAGGING_A_PIECE = false;
1114 function trashDraggedPiece() {
1115 removeSquareHighlights();
1117 // remove the source piece
1118 var newPosition = deepCopy(CURRENT_POSITION);
1119 delete newPosition[DRAGGED_PIECE_SOURCE];
1120 setCurrentPosition(newPosition);
1122 // redraw the position
1123 drawPositionInstant();
1125 // hide the dragged piece
1126 draggedPieceEl.fadeOut(cfg.trashSpeed);
1129 DRAGGING_A_PIECE = false;
1132 function dropDraggedPieceOnSquare(square) {
1133 removeSquareHighlights();
1136 var newPosition = deepCopy(CURRENT_POSITION);
1137 delete newPosition[DRAGGED_PIECE_SOURCE];
1138 newPosition[square] = DRAGGED_PIECE;
1139 setCurrentPosition(newPosition);
1141 // get target square information
1142 var targetSquarePosition = $('#' + SQUARE_ELS_IDS[square]).offset();
1144 // animation complete
1145 var complete = function() {
1146 drawPositionInstant();
1147 draggedPieceEl.css('display', 'none');
1149 // execute their onSnapEnd function
1150 if (cfg.hasOwnProperty('onSnapEnd') === true &&
1151 typeof cfg.onSnapEnd === 'function') {
1152 cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1156 // snap the piece to the target square
1158 duration: cfg.snapSpeed,
1161 draggedPieceEl.animate(targetSquarePosition, opts);
1164 DRAGGING_A_PIECE = false;
1167 function beginDraggingPiece(source, piece, x, y) {
1168 // run their custom onDragStart function
1169 // their custom onDragStart function can cancel drag start
1170 if (typeof cfg.onDragStart === 'function' &&
1171 cfg.onDragStart(source, piece,
1172 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1177 DRAGGING_A_PIECE = true;
1178 DRAGGED_PIECE = piece;
1179 DRAGGED_PIECE_SOURCE = source;
1181 // if the piece came from spare pieces, location is offboard
1182 if (source === 'spare') {
1183 DRAGGED_PIECE_LOCATION = 'offboard';
1186 DRAGGED_PIECE_LOCATION = source;
1189 // capture the x, y coords of all squares in memory
1190 captureSquareOffsets();
1192 // create the dragged piece
1193 draggedPieceEl.attr('src', buildPieceImgSrc(piece))
1196 position: 'absolute',
1197 left: x - (SQUARE_SIZE / 2),
1198 top: y - (SQUARE_SIZE / 2)
1201 if (source !== 'spare') {
1202 // highlight the source square and hide the piece
1203 $('#' + SQUARE_ELS_IDS[source]).addClass(CSS.highlight1)
1204 .find('.' + CSS.piece).css('display', 'none');
1208 function updateDraggedPiece(x, y) {
1209 // put the dragged piece over the mouse cursor
1210 draggedPieceEl.css({
1211 left: x - (SQUARE_SIZE / 2),
1212 top: y - (SQUARE_SIZE / 2)
1216 var location = isXYOnSquare(x, y);
1218 // do nothing if the location has not changed
1219 if (location === DRAGGED_PIECE_LOCATION) return;
1221 // remove highlight from previous square
1222 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1223 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1224 .removeClass(CSS.highlight2);
1227 // add highlight to new square
1228 if (validSquare(location) === true) {
1229 $('#' + SQUARE_ELS_IDS[location]).addClass(CSS.highlight2);
1233 if (typeof cfg.onDragMove === 'function') {
1234 cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1235 DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1236 deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1240 DRAGGED_PIECE_LOCATION = location;
1243 function stopDraggedPiece(location) {
1244 // determine what the action should be
1245 var action = 'drop';
1246 if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1247 action = 'snapback';
1249 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1253 // run their onDrop function, which can potentially change the drop action
1254 if (cfg.hasOwnProperty('onDrop') === true &&
1255 typeof cfg.onDrop === 'function') {
1256 var newPosition = deepCopy(CURRENT_POSITION);
1258 // source piece is a spare piece and position is off the board
1259 //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1260 // position has not changed; do nothing
1262 // source piece is a spare piece and position is on the board
1263 if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1264 // add the piece to the board
1265 newPosition[location] = DRAGGED_PIECE;
1268 // source piece was on the board and position is off the board
1269 if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1270 // remove the piece from the board
1271 delete newPosition[DRAGGED_PIECE_SOURCE];
1274 // source piece was on the board and position is on the board
1275 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1276 validSquare(location) === true) {
1278 delete newPosition[DRAGGED_PIECE_SOURCE];
1279 newPosition[location] = DRAGGED_PIECE;
1282 var oldPosition = deepCopy(CURRENT_POSITION);
1284 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1285 newPosition, oldPosition, CURRENT_ORIENTATION);
1286 if (result === 'snapback' || result === 'trash') {
1292 if (action === 'snapback') {
1293 snapbackDraggedPiece();
1295 else if (action === 'trash') {
1296 trashDraggedPiece();
1298 else if (action === 'drop') {
1299 dropDraggedPieceOnSquare(location);
1303 //------------------------------------------------------------------------------
1305 //------------------------------------------------------------------------------
1308 widget.clear = function(useAnimation) {
1309 widget.position({}, useAnimation);
1313 // get or set config properties
1314 // TODO: write this, GitHub Issue #1
1315 widget.config = function(arg1, arg2) {
1316 // get the current config
1317 if (arguments.length === 0) {
1318 return deepCopy(cfg);
1323 // remove the widget from the page
1324 widget.destroy = function() {
1326 containerEl.html('');
1327 draggedPieceEl.remove();
1329 // remove event handlers
1330 containerEl.unbind();
1333 // shorthand method to get the current FEN
1334 widget.fen = function() {
1335 return widget.position('fen');
1339 widget.flip = function() {
1340 widget.orientation('flip');
1344 // TODO: write this, GitHub Issue #5
1345 widget.highlight = function() {
1351 widget.move = function() {
1352 // no need to throw an error here; just do nothing
1353 if (arguments.length === 0) return;
1355 var useAnimation = true;
1357 // collect the moves into an object
1359 for (var i = 0; i < arguments.length; i++) {
1360 // any "false" to this function means no animations
1361 if (arguments[i] === false) {
1362 useAnimation = false;
1366 // skip invalid arguments
1367 if (validMove(arguments[i]) !== true) {
1368 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1372 var tmp = arguments[i].split('-');
1373 moves[tmp[0]] = tmp[1];
1376 // calculate position from moves
1377 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1380 widget.position(newPos, useAnimation);
1382 // return the new position object
1386 widget.orientation = function(arg) {
1387 // no arguments, return the current orientation
1388 if (arguments.length === 0) {
1389 return CURRENT_ORIENTATION;
1392 // set to white or black
1393 if (arg === 'white' || arg === 'black') {
1394 CURRENT_ORIENTATION = arg;
1400 if (arg === 'flip') {
1401 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1406 error(5482, 'Invalid value passed to the orientation method.', arg);
1410 * @param {!string|!Object} position
1411 * @param {boolean=} useAnimation
1413 widget.position = function(position, useAnimation) {
1414 // no arguments, return the current position
1415 if (arguments.length === 0) {
1416 return deepCopy(CURRENT_POSITION);
1419 // get position as FEN
1420 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1421 return objToFen(CURRENT_POSITION);
1424 // default for useAnimations is true
1425 if (useAnimation !== false) {
1426 useAnimation = true;
1430 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1431 position = deepCopy(START_POSITION);
1434 // convert FEN to position object
1435 if (validFen(position) === true) {
1436 position = fenToObj(position);
1439 // validate position object
1440 if (validPositionObject(position) !== true) {
1441 error(6482, 'Invalid value passed to the position method.', position);
1445 if (useAnimation === true) {
1446 // start the animations
1447 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1448 CURRENT_POSITION, position);
1450 // set the new position
1451 setCurrentPosition(position);
1455 setCurrentPosition(position);
1456 drawPositionInstant();
1460 widget.resize = function() {
1461 // calulate the new square size
1462 SQUARE_SIZE = calculateSquareSize();
1465 boardEl.css('width', (SQUARE_SIZE * 8) + 'px');
1467 // set drag piece size
1468 draggedPieceEl.css({
1469 height: SQUARE_SIZE,
1474 if (cfg.sparePieces === true) {
1475 containerEl.find('.' + CSS.sparePieces)
1476 .css('paddingLeft', (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px');
1483 // set the starting position
1484 widget.start = function(useAnimation) {
1485 widget.position('start', useAnimation);
1488 //------------------------------------------------------------------------------
1490 //------------------------------------------------------------------------------
1492 function isTouchDevice() {
1493 return ('ontouchstart' in document.documentElement);
1496 // reference: http://www.quirksmode.org/js/detect.html
1498 return (navigator && navigator.userAgent &&
1499 navigator.userAgent.search(/MSIE/) !== -1);
1502 function stopDefault(e) {
1506 function mousedownSquare(e) {
1507 // do nothing if we're not draggable
1508 if (cfg.draggable !== true) return;
1510 var square = $(this).attr('data-square');
1512 // no piece on this square
1513 if (validSquare(square) !== true ||
1514 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1518 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1521 function touchstartSquare(e) {
1522 // do nothing if we're not draggable
1523 if (cfg.draggable !== true) return;
1525 var square = $(this).attr('data-square');
1527 // no piece on this square
1528 if (validSquare(square) !== true ||
1529 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1533 e = e.originalEvent;
1534 beginDraggingPiece(square, CURRENT_POSITION[square],
1535 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1538 function mousedownSparePiece(e) {
1539 // do nothing if sparePieces is not enabled
1540 if (cfg.sparePieces !== true) return;
1542 var piece = $(this).attr('data-piece');
1544 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1547 function touchstartSparePiece(e) {
1548 // do nothing if sparePieces is not enabled
1549 if (cfg.sparePieces !== true) return;
1551 var piece = $(this).attr('data-piece');
1553 e = e.originalEvent;
1554 beginDraggingPiece('spare', piece,
1555 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1558 function mousemoveWindow(e) {
1559 // do nothing if we are not dragging a piece
1560 if (DRAGGING_A_PIECE !== true) return;
1562 updateDraggedPiece(e.pageX, e.pageY);
1565 function touchmoveWindow(e) {
1566 // do nothing if we are not dragging a piece
1567 if (DRAGGING_A_PIECE !== true) return;
1569 // prevent screen from scrolling
1572 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1573 e.originalEvent.changedTouches[0].pageY);
1576 function mouseupWindow(e) {
1577 // do nothing if we are not dragging a piece
1578 if (DRAGGING_A_PIECE !== true) return;
1581 var location = isXYOnSquare(e.pageX, e.pageY);
1583 stopDraggedPiece(location);
1586 function touchendWindow(e) {
1587 // do nothing if we are not dragging a piece
1588 if (DRAGGING_A_PIECE !== true) return;
1591 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1592 e.originalEvent.changedTouches[0].pageY);
1594 stopDraggedPiece(location);
1597 function mouseenterSquare(e) {
1598 // do not fire this event if we are dragging a piece
1599 // NOTE: this should never happen, but it's a safeguard
1600 if (DRAGGING_A_PIECE !== false) return;
1602 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1603 typeof cfg.onMouseoverSquare !== 'function') return;
1606 var square = $(e.currentTarget).attr('data-square');
1608 // NOTE: this should never happen; defensive
1609 if (validSquare(square) !== true) return;
1611 // get the piece on this square
1613 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1614 piece = CURRENT_POSITION[square];
1617 // execute their function
1618 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1619 CURRENT_ORIENTATION);
1622 function mouseleaveSquare(e) {
1623 // do not fire this event if we are dragging a piece
1624 // NOTE: this should never happen, but it's a safeguard
1625 if (DRAGGING_A_PIECE !== false) return;
1627 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1628 typeof cfg.onMouseoutSquare !== 'function') return;
1631 var square = $(e.currentTarget).attr('data-square');
1633 // NOTE: this should never happen; defensive
1634 if (validSquare(square) !== true) return;
1636 // get the piece on this square
1638 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1639 piece = CURRENT_POSITION[square];
1642 // execute their function
1643 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1644 CURRENT_ORIENTATION);
1647 //------------------------------------------------------------------------------
1649 //------------------------------------------------------------------------------
1651 function addEvents() {
1652 // prevent browser "image drag"
1653 $('body').on('mousedown mousemove', '.' + CSS.piece, stopDefault);
1655 // mouse drag pieces
1656 boardEl.on('mousedown', '.' + CSS.square, mousedownSquare);
1657 containerEl.on('mousedown', '.' + CSS.sparePieces + ' .' + CSS.piece,
1658 mousedownSparePiece);
1660 // mouse enter / leave square
1661 boardEl.on('mouseenter', '.' + CSS.square, mouseenterSquare);
1662 boardEl.on('mouseleave', '.' + CSS.square, mouseleaveSquare);
1664 // IE doesn't like the events on the window object, but other browsers
1665 // perform better that way
1666 if (isMSIE() === true) {
1667 // IE-specific prevent browser "image drag"
1668 document.ondragstart = function() { return false; };
1670 $('body').on('mousemove', mousemoveWindow);
1671 $('body').on('mouseup', mouseupWindow);
1674 $(window).on('mousemove', mousemoveWindow);
1675 $(window).on('mouseup', mouseupWindow);
1678 // touch drag pieces
1679 if (isTouchDevice() === true) {
1680 boardEl.on('touchstart', '.' + CSS.square, touchstartSquare);
1681 containerEl.on('touchstart', '.' + CSS.sparePieces + ' .' + CSS.piece,
1682 touchstartSparePiece);
1683 $(window).on('touchmove', touchmoveWindow);
1684 $(window).on('touchend', touchendWindow);
1688 function initDom() {
1689 // build board and save it in memory
1690 containerEl.html(buildBoardContainer());
1691 boardEl = containerEl.find('.' + CSS.board);
1693 if (cfg.sparePieces === true) {
1694 sparePiecesTopEl = containerEl.find('.' + CSS.sparePiecesTop);
1695 sparePiecesBottomEl = containerEl.find('.' + CSS.sparePiecesBottom);
1698 // create the drag piece
1699 var draggedPieceId = createId();
1700 $('body').append(buildPiece('wP', true, draggedPieceId));
1701 draggedPieceEl = $('#' + draggedPieceId);
1703 // get the border size
1704 BOARD_BORDER_SIZE = parseInt(boardEl.css('borderLeftWidth'), 10);
1706 // set the size and draw the board
1711 if (checkDeps() !== true ||
1712 expandConfig() !== true) return;
1714 // create unique IDs for all the elements we will create
1724 // return the widget object
1727 }; // end window.ChessBoard
1729 // expose util functions
1730 window.ChessBoard.fenToObj = fenToObj;
1731 window.ChessBoard.objToFen = objToFen;
1733 })(); // end anonymous wrapper