-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdraughtsboard.js
More file actions
2044 lines (1712 loc) · 61.9 KB
/
draughtsboard.js
File metadata and controls
2044 lines (1712 loc) · 61.9 KB
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
(function () {
'use strict'
/**
* @typedef {'w'|'b'|'W'|'B'} PieceCode
* @typedef {Object.<string, PieceCode|null>} Position
* @typedef {'white'|'black'} Orientation
* @typedef {'snapback'|'trash'} DropOffBoardAction
* @typedef {'slow'|'fast'|number} AnimationSpeed
* @typedef {function(string, string, Position, Orientation): string} DropFunction
* @typedef {function(string, PieceCode, Position, Orientation): boolean} DragStartFunction
* @typedef {function(string, PieceCode): void} DragMoveFunction
* @typedef {function(Position, Position): void} ChangeFunction
* @typedef {function(Position, Orientation): void} SnapEndFunction
* @typedef {function(Position, Position): void} MoveEndFunction
* @typedef {function(): void} InitCompleteFunction
* @typedef {function(string, PieceCode, Position, Orientation): void} SnapbackEndFunction
*
* @typedef {Object} DraughtsBoardConfig
* @property {boolean} [draggable=false] - Allow pieces to be dragged
* @property {DropOffBoardAction} [dropOffBoard='snapback'] - What happens when pieces are dropped off board
* @property {Position|string} [position='start'] - Starting position (FEN string or position object)
* @property {Orientation} [orientation='white'] - Board orientation
* @property {boolean} [showNotation=true] - Show square notation
* @property {boolean} [showErrors=false] - Show error messages
* @property {boolean} [sparePieces=false] - Show spare pieces
* @property {string} [pieceTheme='unicode'] - Piece theme
* @property {AnimationSpeed} [appearSpeed=200] - Animation speed for piece appearance
* @property {AnimationSpeed} [moveSpeed=200] - Animation speed for moves
* @property {AnimationSpeed} [snapSpeed=50] - Animation speed for snapping
* @property {AnimationSpeed} [snapbackSpeed=200] - Animation speed for snapback
* @property {AnimationSpeed} [trashSpeed=100] - Animation speed for trashing
* @property {DropFunction} [onDrop] - Callback when piece is dropped
* @property {DragStartFunction} [onDragStart] - Callback when drag starts
* @property {DragMoveFunction} [onDragMove] - Callback when piece is being dragged
* @property {SnapEndFunction} [onSnapEnd] - Callback when snap animation ends
* @property {MoveEndFunction} [onMoveEnd] - Callback when move animation ends
* @property {ChangeFunction} [onChange] - Callback when position changes
* @property {InitCompleteFunction} [onInitComplete] - Callback when initialization is complete
* @property {SnapbackEndFunction} [onSnapbackEnd] - Callback when snapback animation ends
*/
var SIZE
var COLUMNS
var UNICODES = {
'w': '\u26C0',
'b': '\u26C2',
'B': '\u26C3',
'W': '\u26C1',
'0': ' '
}
var START_FEN
/**
* Validates if a move string is in the correct format
* @param {string} move - Move in format "27x31" or "23-32"
* @returns {boolean} True if move is valid format
*/
function validMove (move) {
// move should be a string
if (typeof move !== 'string') return false
// move should be in the form of "27x31", "23-32"
var tmp = move.split(/-|x/)
if (tmp.length !== 2) return false
return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true)
}
/**
* Validates if a square is valid (1-50 for draughts, with optional K prefix for kings)
* @param {string|number} square - Square identifier
* @returns {boolean} True if square is valid
*/
function validSquare (square) {
if (square && square.toString().substr(0, 1) === 'K') {
square = square.toString().substr(1)
}
square = parseInt(square, 10)
return (square >= 1 && square <= 50)
}
/**
* Validates if a piece code is valid (w, b, W, B)
* @param {string} code - Piece code to validate
* @returns {boolean} True if piece code is valid
*/
function validPieceCode (code) {
if (typeof code !== 'string') return false
return (code.search(/^[bwBW]$/) !== -1)
}
/**
* Validates if a FEN string is in the correct draughts format
* @param {string} fen - FEN string to validate
* @returns {boolean} True if FEN is valid
*/
// TODO: this whole function could probably be replaced with a single regex
function validFen (fen) {
if (typeof fen !== 'string') return false
if (fen === START_FEN) return true
// Updated pattern to support ranges (e.g., "31-50") and individual squares with optional K prefix
var FENPattern = /^(W|B):(W|B)([K]?\d+(?:-\d+)?(?:,[K]?\d+(?:-\d+)?)*)(?::(W|B)([K]?\d+(?:-\d+)?(?:,[K]?\d+(?:-\d+)?)*))?$/
var matches = FENPattern.exec(fen)
if (matches != null) {
return true
}
return false
}
/**
* Validates if a position object has valid squares and piece codes
* @param {Position} pos - Position object to validate
* @returns {boolean} True if position is valid
*/
function validPositionObject (pos) {
if (typeof pos !== 'object') return false
// pos = fenToObj(pos)
for (var i in pos) {
if (pos.hasOwnProperty(i) !== true) continue
if (pos[i] == null) {
continue
}
if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
// TODO console.trace('flsed in valid check', i,pos[i], validSquare(i), validPieceCode(pos[i]))
return false
}
}
return true
}
/**
* Filters a position object to only include valid squares and pieces
* @param {Position} pos - Position object to filter
* @returns {Position} Filtered position object with only valid entries
*/
function filterValidPosition (pos) {
if (typeof pos !== 'object' || pos === null) return {}
var filtered = {}
for (var i in pos) {
if (pos.hasOwnProperty(i) !== true) continue
if (pos[i] == null) {
continue
}
if (validSquare(i) === true && validPieceCode(pos[i]) === true) {
filtered[i] = pos[i]
}
}
return filtered
}
/**
* Converts FEN string to position object
* @param {string} fen - FEN string to convert
* @returns {Position|false} Position object or false if invalid
*/
function fenToObj (fen) {
if (validFen(fen) !== true) {
return false
}
// cut off any move, castling, etc info from the end
// we're only interested in position information
fen = fen.replace(/\s+/g, '')
fen = fen.replace(/\..*$/, '')
var rows = fen.split(':')
var position = {}
for (var i = 1; i <= 2; i++) {
var color = rows[i].substr(0, 1)
var row = rows[i].substr(1)
// Split by comma first to handle mixed notation (K1,2-5)
var parts = row.split(',')
for (var p = 0; p < parts.length; p++) {
var part = parts[p]
if (part.indexOf('-') !== -1) {
// Handle ranges (e.g., "2-5")
var rangeParts = part.split('-')
var start = parseInt(rangeParts[0], 10)
var end = parseInt(rangeParts[1], 10)
for (var j = start; j <= end; j++) {
position[j.toString()] = color.toLowerCase()
}
} else if (part.substr(0, 1) === 'K') {
// Handle kings (e.g., "K1")
var square = part.substr(1)
position[square] = color.toUpperCase()
} else {
// Handle individual squares (e.g., "1")
position[part] = color.toLowerCase()
}
}
}
return position
}
// position object to FEN string
// returns false if the obj is not a valid position object
/**
* Converts position object to FEN string
* @param {Position} obj - Position object to convert
* @returns {string|false} FEN string or false if invalid
*/
function objToFen (obj) {
if (validPositionObject(obj) !== true) {
return false
}
var black = []
var white = []
for (var square in obj) {
if (obj.hasOwnProperty(square) !== true) continue
var piece = obj[square]
var squareNum = parseInt(square, 10)
switch (piece) {
case 'w':
white.push(squareNum)
break
case 'W':
white.push('K' + squareNum)
break
case 'b':
black.push(squareNum)
break
case 'B':
black.push('K' + squareNum)
break
default:
break
}
}
// Sort the arrays to ensure consistent output
white.sort(function(a, b) {
var aNum = typeof a === 'string' ? parseInt(a.substr(1), 10) : a
var bNum = typeof b === 'string' ? parseInt(b.substr(1), 10) : b
return aNum - bNum
})
black.sort(function(a, b) {
var aNum = typeof a === 'string' ? parseInt(a.substr(1), 10) : a
var bNum = typeof b === 'string' ? parseInt(b.substr(1), 10) : b
return aNum - bNum
})
return 'W:W' + white.join(',') + ':B' + black.join(',')
}
/**
* Creates a new DraughtsBoard instance
* @param {string|Element} containerElOrId - Container element or ID
* @param {DraughtsBoardConfig} [cfg={}] - Configuration options
* @param {string} [board='draughts'] - Board type ('draughts' or 'checkers')
* @returns {Object} DraughtsBoard widget object with methods
*/
window['DraughtsBoard'] = window['DraughtsBoard'] || function (containerElOrId, cfg, board) {
cfg = cfg || {}
board = board || 'draughts'
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
var MINIMUM_JQUERY_VERSION = '1.7.0'
if (board === 'checkers') {
START_FEN = 'W:W21-32:B1-12'
SIZE = 8
COLUMNS = '01234567'.split('')
} else {
START_FEN = 'W:W31-50:B1-20'
SIZE = 10
COLUMNS = '0123456789'.split('')
}
var START_POSITION = fenToObj(START_FEN)
// use unique class names to prevent clashing with anything else on the page
// and simplify selectors
// NOTE: these should never change
var CSS = {
alpha: 'alpha-d2270',
black: 'black-3c85d',
board: 'board-b72b1',
draughtsboard: 'draughtsboard-63f37',
clearfix: 'clearfix-7da63',
highlight1: 'highlight1-32417',
highlight2: 'highlight2-9c5d2',
notation: 'notation-322f9',
numeric: 'numeric-fc462',
piece: 'piece-417db',
row: 'row-5277c',
sparePieces: 'spare-pieces-7492f',
sparePiecesBottom: 'spare-pieces-bottom-ae20f',
sparePiecesTop: 'spare-pieces-top-4028b',
square: 'square-55d63',
white: 'white-1e1d7'
}
// ------------------------------------------------------------------------------
// Module Scope Variables
// ------------------------------------------------------------------------------
// DOM elements
var containerEl,
boardEl,
draggedPieceEl,
sparePiecesTopEl,
sparePiecesBottomEl
// constructor return object
var widget = {}
// ------------------------------------------------------------------------------
// Stateful
// ------------------------------------------------------------------------------
var ANIMATION_HAPPENING = false
var BOARD_BORDER_SIZE = 2
var CURRENT_ORIENTATION = 'white'
var CURRENT_POSITION = {}
var SQUARE_SIZE
var DRAGGED_PIECE
var DRAGGED_PIECE_LOCATION
var DRAGGED_PIECE_SOURCE
var DRAGGING_A_PIECE = false
var SPARE_PIECE_ELS_IDS = {}
var SQUARE_ELS_IDS = {}
var SQUARE_ELS_OFFSETS
// ------------------------------------------------------------------------------
// JS Util Functions
// ------------------------------------------------------------------------------
// http://tinyurl.com/3ttloxj
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 compareSemVer (version, minimum) {
version = parseSemVer(version)
minimum = parseSemVer(minimum)
var versionNum = (version.major * 10000 * 10000) +
(version.minor * 10000) + version.patch
var minimumNum = (minimum.major * 10000 * 10000) +
(minimum.minor * 10000) + minimum.patch
return (versionNum >= minimumNum)
}
// ------------------------------------------------------------------------------
// Validation / Errors
// ------------------------------------------------------------------------------
/**
* Shows a non-blocking error notification
* @param {string} errorText - Error message to display
*/
function showErrorNotification (errorText) {
// Try to create a visual notification element
try {
var notification = document.createElement('div')
notification.style.cssText = [
'position: fixed',
'top: 20px',
'right: 20px',
'background: #f44336',
'color: white',
'padding: 16px',
'border-radius: 4px',
'box-shadow: 0 4px 12px rgba(0,0,0,0.3)',
'font-family: monospace',
'font-size: 14px',
'max-width: 400px',
'z-index: 10000',
'line-height: 1.4'
].join(';')
// Create close button
var closeButton = document.createElement('span')
closeButton.innerHTML = '×'
closeButton.style.cssText = [
'position: absolute',
'top: 8px',
'right: 12px',
'cursor: pointer',
'font-size: 18px',
'font-weight: bold',
'opacity: 0.7'
].join(';')
closeButton.onclick = function() {
if (notification && notification.parentNode) {
notification.parentNode.removeChild(notification)
}
}
notification.innerHTML = errorText.replace(/\n/g, '<br>')
notification.appendChild(closeButton)
document.body.appendChild(notification)
// Auto-remove after 5 seconds
setTimeout(function() {
if (notification && notification.parentNode) {
notification.parentNode.removeChild(notification)
}
}, 5000)
// Also log to console
console.error('DraughtsBoard:', errorText)
} catch (e) {
// Fallback to console if DOM manipulation fails
console.error('DraughtsBoard:', errorText)
}
}
/**
* Handles error reporting based on configuration
* @param {number} code - Error code
* @param {string} msg - Error message
* @param {*} [obj] - Optional object to log
*/
function error (code, msg, obj) {
// do nothing if showErrors is not set
if (cfg.hasOwnProperty('showErrors') !== true ||
cfg.showErrors === false) {
return
}
var errorText = 'DraughtsBoard Error ' + code + ': ' + msg
// print to console
if (cfg.showErrors === 'console' &&
typeof console === 'object' &&
typeof console.log === 'function') {
console.trace(errorText)
if (arguments.length >= 2) {
console.log(obj)
}
return
}
// show errors as non-blocking notifications
if (cfg.showErrors === 'alert') {
if (obj) {
errorText += '\n\n' + JSON.stringify(obj)
}
showErrorNotification(errorText)
return
}
// custom function
if (typeof cfg.showErrors === 'function') {
cfg.showErrors(code, msg, obj)
}
}
/**
* Safely calls an event handler function with error handling
* @param {Function} handler - Event handler function to call
* @param {...*} [args] - Arguments to pass to the handler
* @returns {*} Handler return value, or undefined if error occurred
*/
function callEventHandler (handler) {
if (typeof handler !== 'function') {
return undefined
}
try {
var args = Array.prototype.slice.call(arguments, 1)
return handler.apply(null, args)
} catch (e) {
// Log the error but don't let it crash the board
error(8001, 'Event handler threw an error: ' + e.message, e)
return undefined
}
}
// check dependencies
function checkDeps () {
// check for null or undefined container
if (containerElOrId === null || containerElOrId === undefined) {
error(1005, 'The first argument to DraughtsBoard() cannot be null or undefined.')
return false
}
// if containerId is a string, it must be the ID of a DOM node
if (typeof containerElOrId === 'string') {
// cannot be empty
if (containerElOrId === '') {
console.error('DraughtsBoard Error 1001: ' +
'The first argument to DraughtsBoard() cannot be an empty string. ' +
'Initialization failed.')
return false
}
// make sure the container element exists in the DOM
var el = document.getElementById(containerElOrId)
if (!el) {
console.error('DraughtsBoard Error 1002: Element with id "' +
containerElOrId + '" does not exist in the DOM. ' +
'Initialization failed.')
return false
}
// set the containerEl
containerEl = $(el)
} else {
// else it must be something that becomes a jQuery collection
// with size 1
// ie: a single DOM node or jQuery object
containerEl = $(containerElOrId)
if (containerEl.length !== 1) {
console.error('DraughtsBoard Error 1003: The first argument to ' +
'DraughtsBoard() must be an ID or a single DOM node. ' +
'Initialization failed.')
return false
}
}
// JSON must exist
if (!window.JSON ||
typeof JSON.stringify !== 'function' ||
typeof JSON.parse !== 'function') {
console.error('DraughtsBoard Error 1004: JSON does not exist. ' +
'Please include a JSON polyfill. Initialization failed.')
return false
}
// check for a compatible version of jQuery
if (!(typeof window.$ && $.fn && $.fn.jquery &&
compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) {
console.error('DraughtsBoard Error 1005: Unable to find a valid version ' +
'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' +
'higher on the page. Initialization failed.')
return false
}
return true
}
function validAnimationSpeed (speed) {
if (speed === 'fast' || speed === 'slow') {
return true
}
if ((parseInt(speed, 10) + '') !== (speed + '')) {
return false
}
return (speed >= 0)
}
// validate config / set default options
/**
* Expands and validates configuration options with defaults
* @returns {boolean} True if config is valid
*/
function expandConfig () {
// Ensure cfg is a proper object
if (typeof cfg !== 'object' || cfg === null) {
if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
cfg = {
position: cfg
}
} else {
cfg = {}
}
}
// default for orientation is white
if (cfg.orientation !== 'black' && cfg.orientation !== 'white') {
cfg.orientation = 'white'
}
CURRENT_ORIENTATION = cfg.orientation
// default for showNotation is true
if (cfg.showNotation !== false) {
cfg.showNotation = true
}
// default for draggable is false
if (cfg.draggable !== true && cfg.draggable !== false) {
cfg.draggable = false
} else if (cfg.draggable !== true) {
cfg.draggable = false
}
// default for dropOffBoard is 'snapback'
if (cfg.dropOffBoard !== 'trash') {
cfg.dropOffBoard = 'snapback'
}
// default for sparePieces is false
if (cfg.sparePieces !== true) {
cfg.sparePieces = false
}
// draggable must be true if sparePieces is enabled
if (cfg.sparePieces === true) {
cfg.draggable = true
}
// default piece theme is unicode
if (cfg.hasOwnProperty('pieceTheme') !== true ||
(typeof cfg.pieceTheme !== 'string' &&
typeof cfg.pieceTheme !== 'function')) {
cfg.pieceTheme = 'unicode'
}
// animation speeds
if (cfg.hasOwnProperty('appearSpeed') !== true ||
validAnimationSpeed(cfg.appearSpeed) !== true) {
cfg.appearSpeed = 200
}
if (cfg.hasOwnProperty('moveSpeed') !== true ||
validAnimationSpeed(cfg.moveSpeed) !== true) {
cfg.moveSpeed = 200
}
if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
validAnimationSpeed(cfg.snapbackSpeed) !== true) {
cfg.snapbackSpeed = 50
}
if (cfg.hasOwnProperty('snapSpeed') !== true ||
validAnimationSpeed(cfg.snapSpeed) !== true) {
cfg.snapSpeed = 25
}
if (cfg.hasOwnProperty('trashSpeed') !== true ||
validAnimationSpeed(cfg.trashSpeed) !== true) {
cfg.trashSpeed = 100
}
// make sure position is valid
if (cfg.hasOwnProperty('position') === true) {
if (cfg.position === 'start') {
CURRENT_POSITION = deepCopy(START_POSITION)
} else if (validFen(cfg.position) === true) {
CURRENT_POSITION = fenToObj(cfg.position)
} else if (validPositionObject(cfg.position) === true) {
CURRENT_POSITION = deepCopy(cfg.position)
} else {
error(7263, 'Invalid value passed to config.position.', cfg.position)
}
}
// validate event handler functions - reset invalid ones to undefined
var eventHandlers = ['onDrop', 'onDragStart', 'onDragMove', 'onChange', 'onSnapEnd', 'onMoveEnd', 'onSnapbackEnd', 'onInitComplete']
for (var i = 0; i < eventHandlers.length; i++) {
var handler = eventHandlers[i]
if (cfg.hasOwnProperty(handler) && typeof cfg[handler] !== 'function') {
cfg[handler] = undefined
}
}
return true
}
// ------------------------------------------------------------------------------
// 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 SIZE for
// our square size
function calculateSquareSize () {
var containerWidth = parseInt(containerEl.width(), 10)
// defensive, prevent infinite loop
if (!containerWidth || containerWidth <= 0) {
return 0
}
// pad one pixel
var boardWidth = containerWidth - 1
while (boardWidth % SIZE !== 0 && boardWidth > 0) {
boardWidth--
}
return (boardWidth / SIZE)
}
// create random IDs for elements
function createElIds () {
// squares on the board
for (var i = 0; i <= (SIZE - 1); i++) {
for (var j = 1; j <= SIZE; j++) {
var square = (i * SIZE) + j
SQUARE_ELS_IDS[square] = square + '-' + uuid()
}
}
// spare pieces
var pieces = 'bBwW'.split('')
for (i = 0; i < pieces.length; i++) {
SPARE_PIECE_ELS_IDS[pieces[i]] = pieces[i] + '-' + uuid()
}
}
// ------------------------------------------------------------------------------
// Markup Building
// ------------------------------------------------------------------------------
function buildBoardContainer () {
var html = '<div class="' + CSS.draughtsboard + '">'
if (cfg.sparePieces === true) {
html += '<div class="' + CSS.sparePieces + ' ' +
CSS.sparePiecesTop + '"></div>'
}
html += '<div class="' + CSS.board + '"></div>'
if (cfg.sparePieces === true) {
html += '<div class="' + CSS.sparePieces + ' ' +
CSS.sparePiecesBottom + '"></div>'
}
html += '</div>'
return html
}
/*
var buildSquare = function(color, size, id) {
var html = '<div class="' + CSS.square + ' ' + CSS[color] + '" ' +
'style="width: ' + size + 'px; height: ' + size + 'px" ' +
'id="' + id + '">'
if (cfg.showNotation === true) {
}
html += '</div>'
return html
}
*/
function buildBoard (orientation) {
if (orientation !== 'black') {
orientation = 'white'
}
var html = ''
// algebraic notation / orientation
var alpha = deepCopy(COLUMNS)
var row = SIZE
if (orientation === 'black') {
alpha.reverse()
row = 1
}
var squareColor = 'white'
for (var i = 0; i < SIZE; i++) {
html += '<div class="' + CSS.row + '">'
for (var j = 1; j <= SIZE; j++) {
var square
if (orientation === 'black') {
square = (parseInt(alpha[i], 10) * SIZE) + ((SIZE + 1) - j)
} else {
square = (parseInt(alpha[i], 10) * SIZE) + j
}
square = Math.round(square / 2)
if (squareColor === 'white') {
html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' +
'square-empty' + '" ' +
'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px">'
} else {
html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' +
'square-' + square + '" ' +
'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
'id="' + SQUARE_ELS_IDS[square] + '" ' +
'data-square="' + square + '">'
if (cfg.showNotation === true) {
html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
square + '</div>'
if (j === 0) {
html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
row + '</div>'
}
}
}
html += '</div>' // end .square
squareColor = (squareColor === 'white' ? 'black' : 'white')
}
html += '<div class="' + CSS.clearfix + '"></div></div>'
squareColor = (squareColor === 'white' ? 'black' : 'white')
if (orientation === 'white') {
row--
} else {
row++
}
}
return html
}
function buildPieceImgSrc (piece) {
// For handling case insensetive windows :(
if (piece === 'W' || piece === 'B') {
piece = 'K' + piece
}
if (typeof cfg.pieceTheme === 'function') {
return cfg.pieceTheme(piece)
}
if (typeof cfg.pieceTheme === 'string') {
return cfg.pieceTheme.replace(/{piece}/g, piece)
}
// NOTE: this should never happen
error(8272, 'Unable to build image source for cfg.pieceTheme.')
return ''
}
function buildPiece (piece, hidden, id) {
if (!piece) {
return false
}
var html
if (cfg.pieceTheme === 'unicode') {
html = '<span '
if (id && typeof id === 'string') {
html += 'id="' + id + '" '
}
html += 'class="unicode ' + piece + ' ' + CSS.piece + '" '
html += 'data-piece="' + piece + '" '
html += 'style="font-size: ' + SQUARE_SIZE + 'px;'
if (hidden === true) {
html += 'display:none;'
}
html += '">' + UNICODES[piece] + '</span>'
return html
}
html = '<img src="' + buildPieceImgSrc(piece) + '" '
if (id && typeof id === 'string') {
html += 'id="' + id + '" '
}
html += 'alt="" ' +
'class="' + CSS.piece + '" ' +
'data-piece="' + piece + '" ' +
'style="width: ' + SQUARE_SIZE + 'px;' +
'height: ' + SQUARE_SIZE + 'px;'
if (hidden === true) {
html += 'display:none;'
}
html += '" />'
return html
}
function buildSparePieces (color) {
var pieces = ['w', 'W']
if (color === 'black') {
pieces = ['b', 'B']
}
var html = ''
for (var i = 0; i < pieces.length; i++) {
html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]])
}
return html
}
// ------------------------------------------------------------------------------
// Animations
// ------------------------------------------------------------------------------
function animateSquareToSquare (src, dest, piece, completeFn) {
// get information about the source and destination squares
var srcSquareEl = $('#' + SQUARE_ELS_IDS[src])
var destSquareEl = $('#' + SQUARE_ELS_IDS[dest])
// check if squares exist
if (srcSquareEl.length === 0 || destSquareEl.length === 0) {
if (typeof completeFn === 'function') {
completeFn()
}
return
}
var srcSquarePosition = srcSquareEl.offset()
var destSquarePosition = destSquareEl.offset()
// check if positions are valid
if (!srcSquarePosition || !destSquarePosition) {
if (typeof completeFn === 'function') {
completeFn()
}
return
}
// create the animated piece and absolutely position it
// over the source square
var animatedPieceId = uuid()
$('body').append(buildPiece(piece, true, animatedPieceId))
var animatedPieceEl = $('#' + animatedPieceId)
animatedPieceEl.css({
display: '',
position: 'absolute',
top: srcSquarePosition.top,
left: srcSquarePosition.left,
fontSize: SQUARE_SIZE + 'px'
})
// remove original piece from source square
srcSquareEl.find('.' + CSS.piece).remove()
// on complete
var complete = function () {
// add the "real" piece to the destination square
destSquareEl.append(buildPiece(piece))
// remove the animated piece
animatedPieceEl.remove()
// run complete function
if (typeof completeFn === 'function') {
completeFn()
}
}
// animate the piece to the destination square
var opts = {
duration: cfg.moveSpeed,
complete: complete,
fail: complete // Ensure completion even if animation fails
}
animatedPieceEl.animate(destSquarePosition, opts)
}
function animateSparePieceToSquare (piece, dest, completeFn) {
var srcOffset = $('#' + SPARE_PIECE_ELS_IDS[piece]).offset()
var destSquareEl = $('#' + SQUARE_ELS_IDS[dest])
var destOffset = destSquareEl.offset()
// create the animate piece
var pieceId = uuid()
$('body').append(buildPiece(piece, true, pieceId))
var animatedPieceEl = $('#' + pieceId)
animatedPieceEl.css({
display: '',
position: 'absolute',
left: srcOffset.left,
top: srcOffset.top,
fontSize: SQUARE_SIZE + 'px'
})
// on complete
var complete = function () {
// add the "real" piece to the destination square
destSquareEl.find('.' + CSS.piece).remove()
destSquareEl.append(buildPiece(piece))
// remove the animated piece
animatedPieceEl.remove()
// run complete function
if (typeof completeFn === 'function') {
completeFn()
}
}
// animate the piece to the destination square
var opts = {
duration: cfg.moveSpeed,
complete: complete,
fail: complete // Ensure completion even if animation fails
}
animatedPieceEl.animate(destOffset, opts)