-
Notifications
You must be signed in to change notification settings - Fork 0
/
chessboard.js
1817 lines (1466 loc) · 57.5 KB
/
chessboard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// chessboard.js v@VERSION
// https://github.com/oakmac/chessboardjs/
//
// Copyright (c) 2017, Chris Oakman
// Released under the MIT license
// https://github.com/oakmac/chessboardjs/blob/master/LICENSE.md
// start anonymous scope
;(function () {
'use strict'
var $ = window['jQuery']
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
var COLUMNS = 'abcdefgh'.split('')
var DEFAULT_DRAG_THROTTLE_RATE = 20
var ELLIPSIS = '…'
var MINIMUM_JQUERY_VERSION = '1.8.3'
var RUN_ASSERTS = true
var START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'
var START_POSITION = fenToObj(START_FEN)
// default animation speeds
var DEFAULT_APPEAR_SPEED = 200
var DEFAULT_MOVE_SPEED = 200
var DEFAULT_SNAPBACK_SPEED = 60
var DEFAULT_SNAP_SPEED = 30
var DEFAULT_TRASH_SPEED = 100
// use unique class names to prevent clashing with anything else on the page
// and simplify selectors
// NOTE: these should never change
var CSS = {}
CSS['alpha'] = 'alpha-d2270'
CSS['black'] = 'black-3c85d'
CSS['board'] = 'board-b72b1'
CSS['chessboard'] = 'chessboard-63f37'
CSS['clearfix'] = 'clearfix-7da63'
CSS['highlight1'] = 'highlight1-32417'
CSS['highlight2'] = 'highlight2-9c5d2'
CSS['notation'] = 'notation-322f9'
CSS['numeric'] = 'numeric-fc462'
CSS['piece'] = 'piece-417db'
CSS['row'] = 'row-5277c'
CSS['sparePieces'] = 'spare-pieces-7492f'
CSS['sparePiecesBottom'] = 'spare-pieces-bottom-ae20f'
CSS['sparePiecesTop'] = 'spare-pieces-top-4028b'
CSS['square'] = 'square-55d63'
CSS['white'] = 'white-1e1d7'
// ---------------------------------------------------------------------------
// Misc Util Functions
// ---------------------------------------------------------------------------
function throttle (f, interval, scope) {
var timeout = 0
var shouldFire = false
var args = []
var handleTimeout = function () {
timeout = 0
if (shouldFire) {
shouldFire = false
fire()
}
}
var fire = function () {
timeout = window.setTimeout(handleTimeout, interval)
f.apply(scope, args)
}
return function (_args) {
args = arguments
if (!timeout) {
fire()
} else {
shouldFire = true
}
}
}
// function debounce (f, interval, scope) {
// var timeout = 0
// return function (_args) {
// window.clearTimeout(timeout)
// var args = arguments
// timeout = window.setTimeout(function () {
// f.apply(scope, args)
// }, interval)
// }
// }
function uuid () {
return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function (c) {
var r = (Math.random() * 16) | 0
return r.toString(16)
})
}
function deepCopy (thing) {
return JSON.parse(JSON.stringify(thing))
}
function parseSemVer (version) {
var tmp = version.split('.')
return {
major: parseInt(tmp[0], 10),
minor: parseInt(tmp[1], 10),
patch: parseInt(tmp[2], 10)
}
}
// returns true if version is >= minimum
function validSemanticVersion (version, minimum) {
version = parseSemVer(version)
minimum = parseSemVer(minimum)
var versionNum = (version.major * 100000 * 100000) +
(version.minor * 100000) +
version.patch
var minimumNum = (minimum.major * 100000 * 100000) +
(minimum.minor * 100000) +
minimum.patch
return versionNum >= minimumNum
}
function interpolateTemplate (str, obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue
var keyTemplateStr = '{' + key + '}'
var value = obj[key]
while (str.indexOf(keyTemplateStr) !== -1) {
str = str.replace(keyTemplateStr, value)
}
}
return str
}
if (RUN_ASSERTS) {
console.assert(interpolateTemplate('abc', {a: 'x'}) === 'abc')
console.assert(interpolateTemplate('{a}bc', {}) === '{a}bc')
console.assert(interpolateTemplate('{a}bc', {p: 'q'}) === '{a}bc')
console.assert(interpolateTemplate('{a}bc', {a: 'x'}) === 'xbc')
console.assert(interpolateTemplate('{a}bc{a}bc', {a: 'x'}) === 'xbcxbc')
console.assert(interpolateTemplate('{a}{a}{b}', {a: 'x', b: 'y'}) === 'xxy')
}
// ---------------------------------------------------------------------------
// Predicates
// ---------------------------------------------------------------------------
function isString (s) {
return typeof s === 'string'
}
function isFunction (f) {
return typeof f === 'function'
}
function isInteger (n) {
return typeof n === 'number' &&
isFinite(n) &&
Math.floor(n) === n
}
function validAnimationSpeed (speed) {
if (speed === 'fast' || speed === 'slow') return true
if (!isInteger(speed)) return false
return speed >= 0
}
function validThrottleRate (rate) {
return isInteger(rate) &&
rate >= 1
}
function validMove (move) {
// move should be a string
if (!isString(move)) return false
// move should be in the form of "e2-e4", "f6-d5"
var squares = move.split('-')
if (squares.length !== 2) return false
return validSquare(squares[0]) && validSquare(squares[1])
}
function validSquare (square) {
return isString(square) && square.search(/^[a-h][1-8]$/) !== -1
}
if (RUN_ASSERTS) {
console.assert(validSquare('a1'))
console.assert(validSquare('e2'))
console.assert(!validSquare('D2'))
console.assert(!validSquare('g9'))
console.assert(!validSquare('a'))
console.assert(!validSquare(true))
console.assert(!validSquare(null))
console.assert(!validSquare({}))
}
function validPieceCode (code) {
return isString(code) && code.search(/^[bw][KQRNBP]$/) !== -1
}
if (RUN_ASSERTS) {
console.assert(validPieceCode('bP'))
console.assert(validPieceCode('bK'))
console.assert(validPieceCode('wK'))
console.assert(validPieceCode('wR'))
console.assert(!validPieceCode('WR'))
console.assert(!validPieceCode('Wr'))
console.assert(!validPieceCode('a'))
console.assert(!validPieceCode(true))
console.assert(!validPieceCode(null))
console.assert(!validPieceCode({}))
}
function validFen (fen) {
if (!isString(fen)) return false
// cut off any move, castling, etc info from the end
// we're only interested in position information
fen = fen.replace(/ .+$/, '')
// expand the empty square numbers to just 1s
fen = expandFenEmptySquares(fen)
// FEN should be 8 sections separated by slashes
var chunks = fen.split('/')
if (chunks.length !== 8) return false
// check each section
for (var i = 0; i < 8; i++) {
if (chunks[i].length !== 8 ||
chunks[i].search(/[^kqrnbpKQRNBP1]/) !== -1) {
return false
}
}
return true
}
if (RUN_ASSERTS) {
console.assert(validFen(START_FEN))
console.assert(validFen('8/8/8/8/8/8/8/8'))
console.assert(validFen('r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R'))
console.assert(validFen('3r3r/1p4pp/2nb1k2/pP3p2/8/PB2PN2/p4PPP/R4RK1 b - - 0 1'))
console.assert(!validFen('3r3z/1p4pp/2nb1k2/pP3p2/8/PB2PN2/p4PPP/R4RK1 b - - 0 1'))
console.assert(!validFen('anbqkbnr/8/8/8/8/8/PPPPPPPP/8'))
console.assert(!validFen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/'))
console.assert(!validFen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBN'))
console.assert(!validFen('888888/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'))
console.assert(!validFen('888888/pppppppp/74/8/8/8/PPPPPPPP/RNBQKBNR'))
console.assert(!validFen({}))
}
function validPositionObject (pos) {
if (!$.isPlainObject(pos)) return false
for (var i in pos) {
if (!pos.hasOwnProperty(i)) continue
if (!validSquare(i) || !validPieceCode(pos[i])) {
return false
}
}
return true
}
if (RUN_ASSERTS) {
console.assert(validPositionObject(START_POSITION))
console.assert(validPositionObject({}))
console.assert(validPositionObject({e2: 'wP'}))
console.assert(validPositionObject({e2: 'wP', d2: 'wP'}))
console.assert(!validPositionObject({e2: 'BP'}))
console.assert(!validPositionObject({y2: 'wP'}))
console.assert(!validPositionObject(null))
console.assert(!validPositionObject('start'))
console.assert(!validPositionObject(START_FEN))
}
function isTouchDevice () {
return 'ontouchstart' in document.documentElement
}
function validJQueryVersion () {
return typeof window.$ &&
$.fn &&
$.fn.jquery &&
validSemanticVersion($.fn.jquery, MINIMUM_JQUERY_VERSION)
}
// ---------------------------------------------------------------------------
// Chess Util Functions
// ---------------------------------------------------------------------------
// convert FEN piece code to bP, wK, etc
function fenToPieceCode (piece) {
// black piece
if (piece.toLowerCase() === piece) {
return 'b' + piece.toUpperCase()
}
// white piece
return 'w' + piece.toUpperCase()
}
// convert bP, wK, etc code to FEN structure
function pieceCodeToFen (piece) {
var pieceCodeLetters = piece.split('')
// white piece
if (pieceCodeLetters[0] === 'w') {
return pieceCodeLetters[1].toUpperCase()
}
// black piece
return pieceCodeLetters[1].toLowerCase()
}
// convert FEN string to position object
// returns false if the FEN string is invalid
function fenToObj (fen) {
if (!validFen(fen)) return false
// cut off any move, castling, etc info from the end
// we're only interested in position information
fen = fen.replace(/ .+$/, '')
var rows = fen.split('/')
var position = {}
var currentRow = 8
for (var i = 0; i < 8; i++) {
var row = rows[i].split('')
var colIdx = 0
// loop through each character in the FEN section
for (var j = 0; j < row.length; j++) {
// number / empty squares
if (row[j].search(/[1-8]/) !== -1) {
var numEmptySquares = parseInt(row[j], 10)
colIdx = colIdx + numEmptySquares
} else {
// piece
var square = COLUMNS[colIdx] + currentRow
position[square] = fenToPieceCode(row[j])
colIdx = colIdx + 1
}
}
currentRow = currentRow - 1
}
return position
}
// position object to FEN string
// returns false if the obj is not a valid position object
function objToFen (obj) {
if (!validPositionObject(obj)) return false
var fen = ''
var currentRow = 8
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
var square = COLUMNS[j] + currentRow
// piece exists
if (obj.hasOwnProperty(square)) {
fen = fen + pieceCodeToFen(obj[square])
} else {
// empty space
fen = fen + '1'
}
}
if (i !== 7) {
fen = fen + '/'
}
currentRow = currentRow - 1
}
// squeeze the empty numbers together
fen = squeezeFenEmptySquares(fen)
return fen
}
if (RUN_ASSERTS) {
console.assert(objToFen(START_POSITION) === START_FEN)
console.assert(objToFen({}) === '8/8/8/8/8/8/8/8')
console.assert(objToFen({a2: 'wP', 'b2': 'bP'}) === '8/8/8/8/8/8/Pp6/8')
}
function squeezeFenEmptySquares (fen) {
return fen.replace(/11111111/g, '8')
.replace(/1111111/g, '7')
.replace(/111111/g, '6')
.replace(/11111/g, '5')
.replace(/1111/g, '4')
.replace(/111/g, '3')
.replace(/11/g, '2')
}
function expandFenEmptySquares (fen) {
return fen.replace(/8/g, '11111111')
.replace(/7/g, '1111111')
.replace(/6/g, '111111')
.replace(/5/g, '11111')
.replace(/4/g, '1111')
.replace(/3/g, '111')
.replace(/2/g, '11')
}
// returns the distance between two squares
function squareDistance (squareA, squareB) {
var squareAArray = squareA.split('')
var squareAx = COLUMNS.indexOf(squareAArray[0]) + 1
var squareAy = parseInt(squareAArray[1], 10)
var squareBArray = squareB.split('')
var squareBx = COLUMNS.indexOf(squareBArray[0]) + 1
var squareBy = parseInt(squareBArray[1], 10)
var xDelta = Math.abs(squareAx - squareBx)
var yDelta = Math.abs(squareAy - squareBy)
if (xDelta >= yDelta) return xDelta
return yDelta
}
// returns the square of the closest instance of piece
// returns false if no instance of piece is found in position
function findClosestPiece (position, piece, square) {
// create array of closest squares from square
var closestSquares = createRadius(square)
// search through the position in order of distance for the piece
for (var i = 0; i < closestSquares.length; i++) {
var s = closestSquares[i]
if (position.hasOwnProperty(s) && position[s] === piece) {
return s
}
}
return false
}
// returns an array of closest squares from square
function createRadius (square) {
var squares = []
// calculate distance of all squares
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 8; j++) {
var s = COLUMNS[i] + (j + 1)
// skip the square we're starting from
if (square === s) continue
squares.push({
square: s,
distance: squareDistance(square, s)
})
}
}
// sort by distance
squares.sort(function (a, b) {
return a.distance - b.distance
})
// just return the square code
var surroundingSquares = []
for (i = 0; i < squares.length; i++) {
surroundingSquares.push(squares[i].square)
}
return surroundingSquares
}
// given a position and a set of moves, return a new position
// with the moves executed
function calculatePositionFromMoves (position, moves) {
var newPosition = deepCopy(position)
for (var i in moves) {
if (!moves.hasOwnProperty(i)) continue
// skip the move if the position doesn't have a piece on the source square
if (!newPosition.hasOwnProperty(i)) continue
var piece = newPosition[i]
delete newPosition[i]
newPosition[moves[i]] = piece
}
return newPosition
}
// TODO: add some asserts here for calculatePositionFromMoves
// ---------------------------------------------------------------------------
// HTML
// ---------------------------------------------------------------------------
function buildContainerHTML (hasSparePieces) {
var html = '<div class="{chessboard}">'
if (hasSparePieces) {
html += '<div class="{sparePieces} {sparePiecesTop}"></div>'
}
html += '<div class="{board}"></div>'
if (hasSparePieces) {
html += '<div class="{sparePieces} {sparePiecesBottom}"></div>'
}
html += '</div>'
return interpolateTemplate(html, CSS)
}
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
function expandConfigArgumentShorthand (config) {
if (config === 'start') {
config = {position: deepCopy(START_POSITION)}
} else if (validFen(config)) {
config = {position: fenToObj(config)}
} else if (validPositionObject(config)) {
config = {position: deepCopy(config)}
}
// config must be an object
if (!$.isPlainObject(config)) config = {}
return config
}
// validate config / set default options
function expandConfig (config) {
// default for orientation is white
if (config.orientation !== 'black') config.orientation = 'white'
// default for showNotation is true
if (config.showNotation !== false) config.showNotation = true
// default for draggable is false
if (config.draggable !== true) config.draggable = false
// default for dropOffBoard is 'snapback'
if (config.dropOffBoard !== 'trash') config.dropOffBoard = 'snapback'
// default for sparePieces is false
if (config.sparePieces !== true) config.sparePieces = false
// draggable must be true if sparePieces is enabled
if (config.sparePieces) config.draggable = true
// default piece theme is wikipedia
if (!config.hasOwnProperty('pieceTheme') ||
(!isString(config.pieceTheme) && !isFunction(config.pieceTheme))) {
config.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png'
}
// animation speeds
if (!validAnimationSpeed(config.appearSpeed)) config.appearSpeed = DEFAULT_APPEAR_SPEED
if (!validAnimationSpeed(config.moveSpeed)) config.moveSpeed = DEFAULT_MOVE_SPEED
if (!validAnimationSpeed(config.snapbackSpeed)) config.snapbackSpeed = DEFAULT_SNAPBACK_SPEED
if (!validAnimationSpeed(config.snapSpeed)) config.snapSpeed = DEFAULT_SNAP_SPEED
if (!validAnimationSpeed(config.trashSpeed)) config.trashSpeed = DEFAULT_TRASH_SPEED
// throttle rate
if (!validThrottleRate(config.dragThrottleRate)) config.dragThrottleRate = DEFAULT_DRAG_THROTTLE_RATE
return config
}
// ---------------------------------------------------------------------------
// Dependencies
// ---------------------------------------------------------------------------
// check for a compatible version of jQuery
function checkJQuery () {
if (!validJQueryVersion()) {
var errorMsg = 'Chessboard Error 1005: Unable to find a valid version of jQuery. ' +
'Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or higher on the page' +
'\n\n' +
'Exiting' + ELLIPSIS
window.alert(errorMsg)
return false
}
return true
}
// return either boolean false or the $container element
function checkContainerArg (containerElOrString) {
if (containerElOrString === '') {
var errorMsg1 = 'Chessboard Error 1001: ' +
'The first argument to Chessboard() cannot be an empty string.' +
'\n\n' +
'Exiting' + ELLIPSIS
window.alert(errorMsg1)
return false
}
// convert containerEl to query selector if it is a string
if (isString(containerElOrString) &&
containerElOrString.charAt(0) !== '#') {
containerElOrString = '#' + containerElOrString
}
// containerEl must be something that becomes a jQuery collection of size 1
var $container = $(containerElOrString)
if ($container.length !== 1) {
var errorMsg2 = 'Chessboard Error 1003: ' +
'The first argument to Chessboard() must be the ID of a DOM node, ' +
'an ID query selector, or a single DOM node.' +
'\n\n' +
'Exiting' + ELLIPSIS
window.alert(errorMsg2)
return false
}
return $container
}
// ---------------------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------------------
function constructor (containerElOrString, config) {
// first things first: check basic dependencies
if (!checkJQuery()) return null
var $container = checkContainerArg(containerElOrString)
if (!$container) return null
// ensure the config object is what we expect
config = expandConfigArgumentShorthand(config)
config = expandConfig(config)
// DOM elements
var $board = null
var $draggedPiece = null
var $sparePiecesTop = null
var $sparePiecesBottom = null
// constructor return object
var widget = {}
// -------------------------------------------------------------------------
// Stateful
// -------------------------------------------------------------------------
var boardBorderSize = 2
var currentOrientation = 'white'
var currentPosition = {}
var draggedPiece = null
var draggedPieceLocation = null
var draggedPieceSource = null
var isDragging = false
var sparePiecesElsIds = {}
var squareElsIds = {}
var squareElsOffsets = {}
var squareSize = 16
// -------------------------------------------------------------------------
// Validation / Errors
// -------------------------------------------------------------------------
function error (code, msg, obj) {
// do nothing if showErrors is not set
if (
config.hasOwnProperty('showErrors') !== true ||
config.showErrors === false
) {
return
}
var errorText = 'Chessboard Error ' + code + ': ' + msg
// print to console
if (
config.showErrors === 'console' &&
typeof console === 'object' &&
typeof console.log === 'function'
) {
console.log(errorText)
if (arguments.length >= 2) {
console.log(obj)
}
return
}
// alert errors
if (config.showErrors === 'alert') {
if (obj) {
errorText += '\n\n' + JSON.stringify(obj)
}
window.alert(errorText)
return
}
// custom function
if (isFunction(config.showErrors)) {
config.showErrors(code, msg, obj)
}
}
function setInitialState () {
currentOrientation = config.orientation
// make sure position is valid
if (config.hasOwnProperty('position')) {
if (config.position === 'start') {
currentPosition = deepCopy(START_POSITION)
} else if (validFen(config.position)) {
currentPosition = fenToObj(config.position)
} else if (validPositionObject(config.position)) {
currentPosition = deepCopy(config.position)
} else {
error(
7263,
'Invalid value passed to config.position.',
config.position
)
}
}
}
// -------------------------------------------------------------------------
// DOM Misc
// -------------------------------------------------------------------------
// calculates square size based on the width of the container
// got a little CSS black magic here, so let me explain:
// get the width of the container element (could be anything), reduce by 1 for
// fudge factor, and then keep reducing until we find an exact mod 8 for
// our square size
function calculateSquareSize () {
var containerWidth = parseInt($container.width(), 10)
// defensive, prevent infinite loop
if (!containerWidth || containerWidth <= 0) {
return 0
}
// pad one pixel
var boardWidth = containerWidth - 1
while (boardWidth % 8 !== 0 && boardWidth > 0) {
boardWidth = boardWidth - 1
}
return boardWidth / 8
}
// create random IDs for elements
function createElIds () {
// squares on the board
for (var i = 0; i < COLUMNS.length; i++) {
for (var j = 1; j <= 8; j++) {
var square = COLUMNS[i] + j
squareElsIds[square] = square + '-' + uuid()
}
}
// spare pieces
var pieces = 'KQRNBP'.split('')
for (i = 0; i < pieces.length; i++) {
var whitePiece = 'w' + pieces[i]
var blackPiece = 'b' + pieces[i]
sparePiecesElsIds[whitePiece] = whitePiece + '-' + uuid()
sparePiecesElsIds[blackPiece] = blackPiece + '-' + uuid()
}
}
// -------------------------------------------------------------------------
// Markup Building
// -------------------------------------------------------------------------
function buildBoardHTML (orientation) {
if (orientation !== 'black') {
orientation = 'white'
}
var html = ''
// algebraic notation / orientation
var alpha = deepCopy(COLUMNS)
var row = 8
if (orientation === 'black') {
alpha.reverse()
row = 1
}
var squareColor = 'white'
for (var i = 0; i < 8; i++) {
html += '<div class="{row}">'
for (var j = 0; j < 8; j++) {
var square = alpha[j] + row
html += '<div class="{square} ' + CSS[squareColor] + ' ' +
'square-' + square + '" ' +
'style="width:' + squareSize + 'px;height:' + squareSize + 'px;" ' +
'id="' + squareElsIds[square] + '" ' +
'data-square="' + square + '">'
if (config.showNotation) {
// alpha notation
if ((orientation === 'white' && row === 1) ||
(orientation === 'black' && row === 8)) {
html += '<div class="{notation} {alpha}">' + alpha[j] + '</div>'
}
// numeric notation
if (j === 0) {
html += '<div class="{notation} {numeric}">' + row + '</div>'
}
}
html += '</div>' // end .square
squareColor = (squareColor === 'white') ? 'black' : 'white'
}
html += '<div class="{clearfix}"></div></div>'
squareColor = (squareColor === 'white') ? 'black' : 'white'
if (orientation === 'white') {
row = row - 1
} else {
row = row + 1
}
}
return interpolateTemplate(html, CSS)
}
function buildPieceImgSrc (piece) {
if (isFunction(config.pieceTheme)) {
return config.pieceTheme(piece)
}
if (isString(config.pieceTheme)) {
return interpolateTemplate(config.pieceTheme, {piece: piece})
}
// NOTE: this should never happen
error(8272, 'Unable to build image source for config.pieceTheme.')
return ''
}
function buildPieceHTML (piece, hidden, id) {
var html = '<img src="' + buildPieceImgSrc(piece) + '" '
if (isString(id) && id !== '') {
html += 'id="' + id + '" '
}
html += 'alt="" ' +
'class="{piece}" ' +
'data-piece="' + piece + '" ' +
'style="width:' + squareSize + 'px;' + 'height:' + squareSize + 'px;'
if (hidden) {
html += 'display:none;'
}
html += '" />'
return interpolateTemplate(html, CSS)
}
function buildSparePiecesHTML (color) {
var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP']
if (color === 'black') {
pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP']
}
var html = ''
for (var i = 0; i < pieces.length; i++) {
html += buildPieceHTML(pieces[i], false, sparePiecesElsIds[pieces[i]])
}
return html
}
// -------------------------------------------------------------------------
// Animations
// -------------------------------------------------------------------------
function animateSquareToSquare (src, dest, piece, completeFn) {
// get information about the source and destination squares
var $srcSquare = $('#' + squareElsIds[src])
var srcSquarePosition = $srcSquare.offset()
var $destSquare = $('#' + squareElsIds[dest])
var destSquarePosition = $destSquare.offset()
// create the animated piece and absolutely position it
// over the source square
var animatedPieceId = uuid()
$('body').append(buildPieceHTML(piece, true, animatedPieceId))
var $animatedPiece = $('#' + animatedPieceId)
$animatedPiece.css({
display: '',
position: 'absolute',
top: srcSquarePosition.top,
left: srcSquarePosition.left
})
// remove original piece from source square
$srcSquare.find('.' + CSS.piece).remove()
function onFinishAnimation1 () {
// add the "real" piece to the destination square
$destSquare.append(buildPieceHTML(piece))
// remove the animated piece
$animatedPiece.remove()
// run complete function
if (isFunction(completeFn)) {
completeFn()
}
}
// animate the piece to the destination square
var opts = {
duration: config.moveSpeed,
complete: onFinishAnimation1
}
$animatedPiece.animate(destSquarePosition, opts)
}
function animateSparePieceToSquare (piece, dest, completeFn) {
var srcOffset = $('#' + sparePiecesElsIds[piece]).offset()
var $destSquare = $('#' + squareElsIds[dest])
var destOffset = $destSquare.offset()
// create the animate piece
var pieceId = uuid()
$('body').append(buildPieceHTML(piece, true, pieceId))
var $animatedPiece = $('#' + pieceId)
$animatedPiece.css({
display: '',
position: 'absolute',
left: srcOffset.left,
top: srcOffset.top
})
// on complete
function onFinishAnimation2 () {
// add the "real" piece to the destination square
$destSquare.find('.' + CSS.piece).remove()
$destSquare.append(buildPieceHTML(piece))
// remove the animated piece
$animatedPiece.remove()
// run complete function
if (isFunction(completeFn)) {
completeFn()
}
}
// animate the piece to the destination square
var opts = {
duration: config.moveSpeed,
complete: onFinishAnimation2
}
$animatedPiece.animate(destOffset, opts)
}
// execute an array of animations
function doAnimations (animations, oldPos, newPos) {
if (animations.length === 0) return
var numFinished = 0
function onFinishAnimation3 () {
// exit if all the animations aren't finished
numFinished = numFinished + 1
if (numFinished !== animations.length) return
drawPositionInstant()