-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdraughts.js
1519 lines (1247 loc) · 50.6 KB
/
draughts.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
// The MIT License (MIT)
//
// Copyright (c) 2014 Gabriel Reitz Giannattasio ([email protected])
//
// Original source at: https://github.com/gartz/draughtsjs
/*global CustomEvent, MouseEvent, HTMLDocument*/
(function () {
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
if (Element.prototype.addEventListener || !Object.defineProperty) {
return;
}
// create an MS event object and get prototype
var proto = document.createEventObject().constructor.prototype;
Object.defineProperty(proto, 'target', {
get: function() { return this.srcElement; }
});
// IE8 addEventLister shim
var addEventListenerFunc = function(type, handler) {
var fn = handler;
if (!('on' + type in this)) {
this.__elemetIEid = this.__elemetIEid || '__ie__' + Math.random();
var customEventId = type + this.__elemetIEid;
document.documentElement[customEventId];
var element = this;
document.documentElement.attachEvent('onpropertychange',
function (event) {
// if the property changed is the custom jqmReady property
if (event.propertyName === customEventId) {
fn.call(element, document.documentElement[customEventId]);
}
});
return;
}
this.attachEvent('on' + type, fn.bind(this));
};
// setup the DOM and window objects
HTMLDocument.prototype.addEventListener = addEventListenerFunc;
Element.prototype.addEventListener = addEventListenerFunc;
window.addEventListener = addEventListenerFunc;
CustomEvent = function (type, obj) {
obj = obj || {};
obj.name = type;
obj.customEvent = true;
return obj;
};
MouseEvent = function (type, obj) {
var event = document.createEventObject();
event.type = 'on' + type;
for (var prop in obj) {
event[prop] = obj[prop];
}
return event;
};
var dispatchEventFunc = function (e) {
if (!e.customEvent) {
this.fireEvent(e.type, e);
return;
}
// no event registred
if (!this.__elemetIEid) {
return;
}
var customEventId = e.name + this.__elemetIEid;
document.documentElement[customEventId] = e;
};
// setup the Element dispatchEvent used to trigger events on the board
HTMLDocument.prototype.dispatchEvent = dispatchEventFunc;
Element.prototype.dispatchEvent = dispatchEventFunc;
window.dispatchEvent = dispatchEventFunc;
})();
// modern browser support forEach, probably will be IE8
var modernBrowser = 'forEach' in Array.prototype;
// IE8 pollyfills:
// IE8 slice doesn't work with NodeList
if (!modernBrowser) {
var builtinSlice = Array.prototype.slice;
Array.prototype.slice = function(action, that) {
'use strict';
var arr = [];
for (var i = 0, n = this.length; i < n; i++)
if (i in this)
arr.push(this[i]);
return builtinSlice.apply(arr, arguments);
};
}
if (!('forEach' in Array.prototype)) {
Array.prototype.forEach = function(action, that) {
'use strict';
for (var i = 0, n = this.length; i < n; i++)
if (i in this)
action.call(that, this[i], i);
};
}
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisArg */) {
'use strict';
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != 'function')
throw new TypeError();
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) res.push(val);
}
}
return res;
};
}
(function () {
// Helpers
function removeClass(el, className) {
// Remove a className, IE8 doesn't support classList :(
el.className = el.className.replace(className, '').trim();
}
function queryField(line, column) {
// Help mount a querySelector to find a field
return 'div.line' + line + '.column' + column;
}
function closestClassMatchElement(element, match) {
// Match closest element with match param
var el = element;
while(el.className.match(match) === null && el.parentElement) {
el = el.parentElement;
}
if (!el.className.match(match)) {
return;
}
return el;
}
function closestPieceElement(element) {
// find the piece element on parent elements
return closestClassMatchElement(element, /player([0-9])/i);
}
function DraughtsBoard(opt) {
// Data from a DraughtsBoard element
//
// Options:
//
// - size
// Is the number of field to be added in the x and y axis of the
// board
// - turn
// Begin the game in a specifc turn (use map + turn to restore a
// game)
// - element
// HTMLElement, when there isn't a element, the board will create
// one
// - forceAttack
// When you force attack, the if attack is possible the player need
// to execute an attack
// - forceHoldPiece
// After click to hold a piece, the player can't change his mind,
// it will need to play with it
// - map
// Array map with the player pieces of the board, where
// - 0 = empty
// - 1 = player 1 piece
// - 2 = player 2 piece
// - 3 = player 1 queen piece
// - 4 = player 2 queen piece
// Example:
// [
// [3,0,1,0,1,0],
// [0,1,0,1,0,1],
// [0,0,0,0,0,0],
// [0,2,0,2,0,2],
// [4,0,2,0,2,0]
// ]
//
// Events:
//
// - changeturn
// Dispatch when change the turn value
// - destroyboard
// Dispatch when the board is destroyed (every field is removed)
// - addedfield
// Dispatch when the field is appended to the board element
// Ensure options object
if (typeof opt !== 'object') {
opt = {};
}
// Setup the HTMLElement to be the board
this.element = opt.element || document.createElement('div');
// Only because IE8 doesn't support Object.defineProperty I need to
// substitute the previous div, if already has size defined for a new
// one or the defineProperty wont work as expected
if (this.element.size) {
// This is a workaround, because I would need to remove all events
// from the board element, to reuse it, so for demo is easier to
// create a new one, but it will lose the events, an oh GC I love
// you so mutch but, I don't have time to fix it now, I take care
// better of you everytime I can :~(
var parentEl = this.element.parentElement;
var oldEl = this.element;
this.element = document.createElement('div');
this.element.id = oldEl.id;
this.element.className = oldEl.className;
if (parentEl) {
parentEl.insertBefore(this.element, oldEl);
parentEl.removeChild(oldEl);
}
}
this.element.data = this;
// Set default board size to 8 if is a invalid value
var size = !isNaN(opt.size) && (+ opt.size) % 2 === 0 ? + opt.size : 8;
if (size < 5) {
throw new Error('Board size must be greater then 5');
}
// Constants or get/set need to be in the element because of IE8
// Size is a constant from the board
Object.defineProperty(this.element, 'size', {
get: function () {
return size;
}
});
// Set default value to forceAttack as true
var forceAttack = opt.forceAttack !== false;
// ForceAttack is a constant from the board
Object.defineProperty(this.element, 'forceAttack', {
get: function () {
return forceAttack;
}
});
// Set default value to forcePieceHold as true
var forcePieceHold = opt.forcePieceHold === true;
// ForceAttack is a constant from the board
Object.defineProperty(this.element, 'forcePieceHold', {
get: function () {
return forcePieceHold;
}
});
// Set default value to allowBackwardAttack as false
var allowQueenRun = opt.allowQueenRun !== false;
// ForceAttack is a constant from the board
Object.defineProperty(this.element, 'allowQueenRun', {
get: function () {
return allowQueenRun;
}
});
// Set default value to allowBackwardAttack as true
var allowBackwardAttack = opt.allowBackwardAttack === true;
// ForceAttack is a constant from the board
Object.defineProperty(this.element, 'allowBackwardAttack', {
get: function () {
return allowBackwardAttack;
}
});
// Set default value to allowQueenAttackRun as false
var allowQueenAttackRun = opt.allowQueenAttackRun === true;
// ForceAttack is a constant from the board
Object.defineProperty(this.element, 'allowQueenAttackRun', {
get: function () {
return allowQueenAttackRun;
}
});
// Number of turns played
var turn = Number(opt.turn) || 0;
Object.defineProperty(this.element, 'turn', {
get: function () {
return turn;
},
set: function (val) {
if (isNaN(val)) throw new Error('Invalid turn');
var old = turn;
turn = + val;
// It's useful old value from turn to validate if you jump over
// turns for future online features
var event = new CustomEvent('changeturn', { 'detail': {
oldValue: old,
value: turn
}});
// trigger draughts
this.dispatchEvent(event);
}
});
// setup the game map
if (opt.map instanceof Array) {
this.element.map = opt.map;
}
// Default triggers
this.element.addEventListener('addedfield', function (event) {
// When a field is added to the board, setup it
// no default? just leave...
if (event.defaultPrevented) {
return;
}
var pos = event.detail.position;
var fieldEl = event.detail.field.element;
var s = 100 / this.size;
// Set the field size idependent of CSS, allow any size board
var style = 'width: ' + s + '%;height: ' + s + '%;';
fieldEl.setAttribute('style', style);
// Check if the field need to be disabled (white color)
if (!(pos % 2 === (pos / this.size << 0) % 2)) {
fieldEl.className = 'white';
return;
}
event = new CustomEvent('addpiece', {
'detail': event.detail
});
// Each field dispatch a addedfield event
this.dispatchEvent(event);
});
this.element.addEventListener('addpiece', function (event) {
// When a field is added to the board, append the player piece
// no default just leave...
if (event.defaultPrevented) {
return;
}
var position = event.detail.position;
var piece;
if (!this.map) {
// Create a new game from the default start
if (position < (this.size * this.size / 2) - this.size) {
piece = new DraughtsPiece({
player: 0
});
}
if (position >= (this.size * this.size / 2) + this.size) {
piece = new DraughtsPiece({
player: 1
});
}
} else {
var rule = this.map[event.detail.line]
if (!rule) {
return;
}
rule = rule[event.detail.column];
if (!rule) {
return;
}
if (rule > 0 && rule < 3) {
piece = new DraughtsPiece({
player: (rule % 2) ^ 1
});
} else {
piece = new DraughtsPieceQueen({
player: (rule % 2) ^ 1
});
}
}
if (piece) {
event.detail.field.element.appendChild(piece.element);
piece.board = this;
event.detail.piece = piece;
event = new CustomEvent('addedpiece', {
'detail': event.detail
});
// Each field dispatch a addedfield event
this.dispatchEvent(event);
}
});
this.element.addEventListener('created', function (event) {
// When a finish creating the board, change the turn to 1
// no default just leave...
if (event.defaultPrevented) {
return;
}
this.turn++;
});
this.element.addEventListener('changeturn', function (event) {
// When change a turn, re-calculate the possible moves
// no default just leave...
if (event.defaultPrevented) {
return;
}
var player = event.detail.value % 2 ^ 1;
this.data.removeAllMasks();
// Select other player pieces (IE8 not support attr selector)
var pieces = this.data.playerPieces(player ^ 1);
// Remove href and focus from other player pieces
pieces.forEach(function (piece) {
piece.data.denyMove();
});
// Select current player pieces
pieces = this.data.playerPieces(player);
// Store allowed attacks and moves
var attacks = [];
var moves = [];
// Check for allowed moviments
pieces.forEach(function (piece) {
if (piece.data.allowedAttacks().length > 0) {
attacks.push(piece);
}
if (piece.data.allowedMoves().length > 0) {
moves.push(piece);
}
});
if (attacks.length > 0) {
attacks.forEach(function (piece) {
piece.data.allowMove();
});
// When forcing attacks it must not hit the default moves
if (this.forceAttack) {
return;
}
}
if (moves.length > 0) {
moves.forEach(function (piece) {
piece.data.allowMove();
});
return;
}
var gameoverEvent = new CustomEvent('gameover', { 'detail': {
winner: player ^ 1,
motive: 'no_more_moves',
turn: turn - 1
}});
// trigger draughts
this.dispatchEvent(gameoverEvent);
});
this.element.addEventListener('mousedown', function (event) {
// Focus the piece when click on it (when it's possible)
// no default just leave...
if (event.defaultPrevented) {
return;
}
var piece = closestPieceElement(event.target || event.srcElement);
if (!piece) {
return;
}
piece.focus();
});
function pieceHoldDispatcher(event) {
// If clicking in a piece, dipatch piecehold if is possible
// no default just leave...
if (event.defaultPrevented) {
return;
}
var piece = closestPieceElement(event.target || event.srcElement);
if (!piece || !piece.parentElement) {
return;
}
if (!piece.getAttribute('href')) {
return;
}
// Trigger a piece hold event
var event = new CustomEvent('piecehold', { 'detail': {
piece: piece,
field: piece.parentElement
}});
// trigger draughts
this.dispatchEvent(event);
}
// Event in mousedown because user can start clicking in the element
// but move the mouse and mouseup in other element, this ensure to
// focus the right element
this.element.addEventListener('mousedown', pieceHoldDispatcher);
// Click is for click and when you keydown enter key, it dispatch click
this.element.addEventListener('click', pieceHoldDispatcher);
// Drag'n'dropp effect, not use standart because it always clone the
// view element
var dragging;
this.element.addEventListener('mousedown', function (event) {
// If clicking in a piece, dipatch piecehold if is possible
// no default just leave...
if (event.defaultPrevented) {
return;
}
var piece = closestPieceElement(event.target || event.srcElement);
if (!piece) {
return;
}
if (piece.className.indexOf('focus') === -1) {
return;
}
dragging = {
piece: piece,
x: event.clientX,
y: event.clientY
};
piece.className += ' startdrag';
});
this.element.addEventListener('mousemove', function (event) {
if (!dragging) {
return;
}
var field = dragging.piece.parentElement;
var x = event.clientX - dragging.x;
var y = event.clientY - dragging.y;
dragging.piece.style.left = x + 'px';
dragging.piece.style.top = y + 'px';
var masks = this.querySelectorAll('.move');
dragging.mask = undefined;
Array.prototype.slice.call(masks).forEach(function (mask) {
mask.blur();
if (!(mask.offsetTop < event.clientY)) {
return;
}
if (!(mask.offsetTop + mask.offsetHeight > event.clientY)) {
return;
}
if (!(mask.offsetLeft < event.clientX)) {
return;
}
if (!(mask.offsetLeft + mask.offsetWidth > event.clientX)) {
return;
}
dragging.mask = mask;
mask.focus();
});
});
this.element.addEventListener('mouseup', function (event) {
// If clicking in a piece, dipatch piecehold if is possible
// no default just leave...
if (event.defaultPrevented || !dragging) {
return;
}
var piece = dragging.piece;
piece.className = piece.className.replace('startdrag', '');
piece.style.left = '';
piece.style.top = '';
if (dragging.mask) {
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'target': piece
});
dragging.mask.dispatchEvent(clickEvent);
}
dragging = undefined;
});
this.element.addEventListener('click', function (event) {
// If clicking in a mask, dipatch piecerelease if is holding a piece
// no default just leave...
if (event.defaultPrevented) {
return;
}
event.target = event.target || event.srcElement;
var mask = closestClassMatchElement(event.target, /move/i);
if (!mask || !mask.parentElement) {
return;
}
var piece = this.querySelector('a.focus');
if (!piece) {
return;
}
var field = mask.parentElement;
// Trigger a piece hold event
var event = new CustomEvent('piecerelease', { 'detail': {
piece: piece,
destine: field,
mask: mask
}});
// trigger draughts
this.dispatchEvent(event);
});
var holding;
this.element.addEventListener('piecehold', function (event) {
// Hold the piece to be able to move it in the board, will add the
// possible moves and attacks masks in the field
// no default just leave...
if (event.defaultPrevented) {
return;
}
var piece = event.detail.piece;
// Check if can change the holding piece
if (this.forcePieceHold) {
if (holding) {
return;
}
holding = true;
var pieces = this.data.playerPieces(piece.data.player());
// Remove href and focus from other player pieces
pieces.forEach(function (piece) {
if (event.detail.piece === piece) {
return;
}
piece.data.denyMove();
});
}
// workaround for IE8 focus
var selectedFields = this.querySelectorAll('a.focus');
Array.prototype.slice.call(selectedFields).forEach(function (el) {
removeClass(el, 'focus');
});
piece.className += ' focus';
piece.focus();
this.data.removeAllMasks();
var attacks = piece.data.allowedAttacks();
if (attacks.length > 0) {
// add masks to allowed attacks fields
attacks.forEach(function (attack) {
attack.field.data.addMask({
attack: attack.opponent
});
});
// Attack is possible and forcing so don't let other moves
if (this.forceAttack) {
return;
}
}
var moves = piece.data.allowedMoves();
if (moves.length > 0) {
moves.forEach(function (field) {
field.data.addMask();
});
}
});
this.element.addEventListener('piecerelease', function (event) {
// Release piece in some field mask, do the action (move or attack)
// no default just leave...
if (event.defaultPrevented) {
return;
}
var piece = event.detail.piece;
holding = false;
this.data.removeAllMasks();
piece.data.moveTo(event.detail.destine, event.detail.mask);
});
this.element.addEventListener('piecemove', function (event) {
// When the move is an attack dispatch a attack event and check if
// can still attacking with the same piece, if so, then avoid
// changeTurn
var piece = event.detail.piece;
var mask = event.detail.mask;
var toField = event.detail.toField;
var fromField = event.detail.fromField;
// mask has opponent details?
if (!mask.data.opponent.length === 0) {
return;
}
var isAttack;
mask.data.opponent.forEach(function (opponent) {
// Attack the opponent
piece.data.attack(opponent, fromField, toField);
isAttack = true;
});
if (!isAttack) {
return;
}
piece.data.attackTurn++;
var attacks = piece.data.allowedAttacks();
if (attacks.length > 0) {
event.detail.changeTurn = false;
}
// Remove href and focus from other pieces
this.data.playerPieces(piece.data.player()).forEach(function (p) {
if (piece === p) {
return;
}
p.data.denyMove();
})
// This will help to show what is your new allowed moves
var clickEvent = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'target': piece
});
piece.dispatchEvent(clickEvent);
});
this.element.addEventListener('piecemove', function (event) {
// Check if hit the other border of board and transform a piece in
// a queen piece
var piece = event.detail.piece;
var toField = event.detail.toField;
var bottomBorder = toField.data.line === this.size - 1;
var topBorder = toField.data.line === 0;
if (!bottomBorder && !topBorder) {
return;
}
var playerId = piece.data.player();
if (playerId === 0 && !bottomBorder) {
return;
}
if (playerId === 1 && !topBorder) {
return;
}
new DraughtsPieceQueen({
extend: piece
});
});
// Create the board
// but a ticker after register listeners from the instance creator...
setTimeout(this.create.bind(this), 4);
}
DraughtsBoard.prototype = {
// no Object.observer... No problem! Let's use the element to have event
// listeners
addEventListener: function () {
// Bind addEventListener
this.element.addEventListener.apply(this.element, arguments);
},
dispatchEvent: function () {
// Bind dispatchEvent
this.element.dispatchEvent.apply(this.element, arguments);
},
size: function () {
// Bind dispatchEvent
return this.element.size;
},
destroy: function () {
// Remove all childrens from the board
while (this.element.children.length > 0) {
this.element.removeChild(this.element.children[0]);
}
var event = new CustomEvent('destroyboard');
// trigger draughts
this.element.dispatchEvent(event);
},
create: function () {
// Create the board based on the options passed
// Before create remove all childrens
if (this.element.children.length > 0) {
this.destroy();
}
var size = this.size();
var event;
for (var i = 0; i < size * size; i++) {
var field = new DraughtsBoardField(i / size << 0, i % size);
// Append field element as board element children
this.element.appendChild(field.element);
event = new CustomEvent('addedfield', {
'detail': {
field: field,
position: i,
line: field.line,
column: field.column
}
});
// Each field dispatch a addedfield event
this.element.dispatchEvent(event);
}
event = new CustomEvent('created');
// After create all fields dispatch created
this.element.dispatchEvent(event);
},
removeAllMasks: function () {
// Remove all masks in the board
var mask = this.element.querySelectorAll('a.move');
Array.prototype.slice.call(mask).forEach(function (mask) {
// Ensure it's on DOM
if (mask.parentElement) {
// And remove it...
mask.parentElement.removeChild(mask);
}
});
},
playerPieces: function(id) {
var pieces = this.element.querySelectorAll('a.player' + id);
return Array.prototype.slice.call(pieces);
},
map: function () {
// Export the game pieces positions to a array map
// 0: empty field
// 1: player1 piece
// 2: player2 piece
// 3: player1 queen
// 4: player2 queen
var map = [];
//TODO: for in board, each line is a new array
return map;
}
};
function DraughtsBoardField(line, column) {
// Data from a Field element of a DraughtsBoard
var field = document.createElement('div');
this.element = field;
field.data = this;
this.line = line;
this.column = column;
// Add class to the field, let search using querySelector
// ... not using dataset because of IE8
field.className += ' line' + line;
field.className += ' column' + column;
}
DraughtsBoardField.prototype = {
addMask: function (opt) {
// Create and append a mask that allow focus, click or dragevent
// options:
// - attack: piece element or array of piece elements
var mask = document.createElement('a');
mask.className = 'move';
mask.setAttribute('href', 'javascript: ');