forked from jhlywa/chess.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.js
1546 lines (1296 loc) · 42.2 KB
/
chess.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
/*
* Copyright (c) 2011, Jeff Hlywa ([email protected])
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*----------------------------------------------------------------------------*/
var Chess = function(fen) {
var BLACK = 'b';
var WHITE = 'w';
var EMPTY = -1;
var PAWN = 'p';
var KNIGHT = 'n';
var BISHOP = 'b';
var ROOK = 'r';
var QUEEN = 'q';
var KING = 'k';
var SYMBOLS = 'pnbrqkPNBRQK';
var DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
var POSSIBLE_RESULTS = ['1-0', '0-1', '1/2-1/2', '*'];
var PAWN_OFFSETS = {
b: [16, 32, 17, 15],
w: [-16, -32, -17, -15]
};
var PIECE_OFFSETS = {
n: [-18, -33, -31, -14, 18, 33, 31, 14],
b: [-17, -15, 17, 15],
r: [-16, 1, 16, -1],
q: [-17, -16, -15, 1, 17, 16, 15, -1],
k: [-17, -16, -15, 1, 17, 16, 15, -1]
};
var ATTACKS = [
20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20, 0,
0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0,
0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0,
0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0,
0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
24,24,24,24,24,24,56, 0, 56,24,24,24,24,24,24, 0,
0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0,
0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0,
0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0,
0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0,
20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20
];
var RAYS = [
17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0,
0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0,
0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0,
0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0,
0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1,-1, -1, -1, -1, 0,
0, 0, 0, 0, 0, 0,-15,-16,-17, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0,-15, 0,-16, 0,-17, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,-15, 0, 0,-16, 0, 0,-17, 0, 0, 0, 0, 0,
0, 0, 0,-15, 0, 0, 0,-16, 0, 0, 0,-17, 0, 0, 0, 0,
0, 0,-15, 0, 0, 0, 0,-16, 0, 0, 0, 0,-17, 0, 0, 0,
0,-15, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0,-17, 0, 0,
-15, 0, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0, 0,-17
];
var SHIFTS = { p: 0, n: 1, b: 2, r: 3, q: 4, k: 5 };
var FLAGS = {
NORMAL: 'n',
CAPTURE: 'c',
BIG_PAWN: 'b',
EP_CAPTURE: 'e',
PROMOTION: 'p',
KSIDE_CASTLE: 'k',
QSIDE_CASTLE: 'q'
};
var BITS = {
NORMAL: 1,
CAPTURE: 2,
BIG_PAWN: 4,
EP_CAPTURE: 8,
PROMOTION: 16,
KSIDE_CASTLE: 32,
QSIDE_CASTLE: 64
};
var RANK_1 = 7;
var RANK_2 = 6;
var RANK_3 = 5;
var RANK_4 = 4;
var RANK_5 = 3;
var RANK_6 = 2;
var RANK_7 = 1;
var RANK_8 = 0;
var SQUARES = {
a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7,
a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23,
a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39,
a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55,
a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71,
a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87,
a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103,
a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119
};
var ROOKS = {
w: [{square: SQUARES.a1, flag: BITS.QSIDE_CASTLE},
{square: SQUARES.h1, flag: BITS.KSIDE_CASTLE}],
b: [{square: SQUARES.a8, flag: BITS.QSIDE_CASTLE},
{square: SQUARES.h8, flag: BITS.KSIDE_CASTLE}]
};
var board = new Array(128);
var kings = {w: EMPTY, b: EMPTY};
var turn = WHITE;
var castling = {w: 0, b: 0};
var ep_square = EMPTY;
var half_moves = 0;
var move_number = 1;
var history = [];
var header = {};
/* if the user passes in a fen string, load it, else default to
* starting position
*/
if (typeof fen == 'undefined') {
load(DEFAULT_POSITION);
} else {
load(fen);
}
function clear() {
board = new Array(128);
kings = {w: EMPTY, b: EMPTY};
turn = WHITE;
castling = {w: '', b: ''};
ep_square = EMPTY;
half_moves = 0;
move_number = 1;
history = [];
header = {};
update_setup(generate_fen());
}
function reset() {
load(DEFAULT_POSITION);
}
function load(fen) {
var tokens = fen.split(/\s+/);
var position = tokens[0];
var square = 0;
var valid = SYMBOLS + '12345678/';
if (!validate_fen(fen).valid) {
return false;
}
clear();
for (var i = 0; i < position.length; i++) {
var piece = position.charAt(i);
if (piece == '/') {
square += 8;
} else if (is_digit(piece)) {
square += parseInt(piece, 10);
} else {
var color = (piece < 'a') ? WHITE : BLACK;
put({type: piece.toLowerCase(), color: color}, algebraic(square));
square++;
}
}
turn = tokens[1];
if (tokens[2].indexOf('K') > -1) {
castling.w |= BITS.KSIDE_CASTLE;
}
if (tokens[2].indexOf('Q') > -1) {
castling.w |= BITS.QSIDE_CASTLE;
}
if (tokens[2].indexOf('k') > -1) {
castling.b |= BITS.KSIDE_CASTLE;
}
if (tokens[2].indexOf('q') > -1) {
castling.b |= BITS.QSIDE_CASTLE;
}
ep_square = (tokens[3] == '-') ? EMPTY : SQUARES[tokens[3]];
half_moves = parseInt(tokens[4], 10);
move_number = parseInt(tokens[5], 10);
update_setup(generate_fen());
return true;
}
function validate_fen(fen) {
var errors = {
0: 'No errors.',
1: 'FEN string must contain six space-delimited fields.',
2: '6th field (move number) must be a positive integer.',
3: '5th field (half move counter) must be a non-negative integer.',
4: '4th field (en-passant square) is invalid.',
5: '3rd field (castling availability) is invalid.',
6: '2nd field (side to move) is invalid.',
7: '1st field (piece positions) does not contain 8 \'/\'-delimited rows.',
8: '1st field (piece positions) is invalid [consecutive numbers].',
9: '1st field (piece positions) is invalid [invalid piece].',
10: '1st field (piece positions) is invalid [row too large].',
};
/* 1st criterion: 6 space-seperated fields? */
var tokens = fen.split(/\s+/);
if (tokens.length != 6) {
return {valid: false, error_number: 1, error: errors[1]};
}
/* 2nd criterion: move number field is a integer value > 0? */
if (isNaN(tokens[5]) || (parseInt(tokens[5], 10) <= 0)) {
return {valid: false, error_number: 2, error: errors[2]};
}
/* 3rd criterion: half move counter is an integer >= 0? */
if (isNaN(tokens[4]) || (parseInt(tokens[4], 10) < 0)) {
return {valid: false, error_number: 3, error: errors[3]};
}
/* 4th criterion: 4th field is a valid e.p.-string? */
if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) {
return {valid: false, error_number: 4, error: errors[4]};
}
/* 5th criterion: 3th field is a valid castle-string? */
if( !/^(KQ?k?q?|Qk?q?|kq?|q|-)$/.test(tokens[2])) {
return {valid: false, error_number: 5, error: errors[5]};
}
/* 6th criterion: 2nd field is "w" (white) or "b" (black)? */
if (!/^(w|b)$/.test(tokens[1])) {
return {valid: false, error_number: 6, error: errors[6]};
}
/* 7th criterion: 1st field contains 8 rows? */
var rows = tokens[0].split("/");
if (rows.length != 8) {
return {valid: false, error_number: 7, error: errors[7]};
}
/* 8th criterion: every row is valid? */
for (var i = 0; i < rows.length; i++) {
/* check for right sum of fields AND not two numbers in succession */
var sum_fields = 0;
var previous_was_number = false;
for (var k = 0; k < rows[i].length; k++) {
if (!isNaN(rows[i][k])) {
if (previous_was_number) {
return {valid: false, error_number: 8, error: errors[8]};
}
sum_fields += parseInt(rows[i][k]);
previous_was_number = true;
} else {
if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) {
return {valid: false, error_number: 9, error: errors[9]};
}
sum_fields += 1;
previous_was_number = false;
}
}
if (sum_fields != 8) {
return {valid: false, error_number: 10, error: errors[10]};
}
}
/* everything's okay! */
return {valid: true, error_number: 0, error: errors[0]};
}
function generate_fen() {
var empty = 0;
var fen = '';
for (var i = SQUARES.a8; i <= SQUARES.h1; i++) {
if (board[i] == null) {
empty++;
} else {
if (empty > 0) {
fen += empty;
empty = 0;
}
var color = board[i].color;
var piece = board[i].type;
fen += (color == WHITE) ?
piece.toUpperCase() : piece.toLowerCase();
}
if ((i + 1) & 0x88) {
if (empty > 0) {
fen += empty;
}
if (i != SQUARES.h1) {
fen += '/';
}
empty = 0;
i += 8;
}
}
var cflags = '';
if (castling[WHITE] & BITS.KSIDE_CASTLE) { cflags += 'K'; }
if (castling[WHITE] & BITS.QSIDE_CASTLE) { cflags += 'Q'; }
if (castling[BLACK] & BITS.KSIDE_CASTLE) { cflags += 'k'; }
if (castling[BLACK] & BITS.QSIDE_CASTLE) { cflags += 'q'; }
/* do we have an empty castling flag? */
cflags = cflags || '-';
var epflags = (ep_square == EMPTY) ? '-' : algebraic(ep_square);
return [fen, turn, cflags, epflags, half_moves, move_number].join(' ')
}
function set_header(args) {
for (var i = 0; i < args.length; i += 2) {
if (typeof args[i] == "string" &&
typeof args[i + 1] == "string") {
header[args[i]] = args[i + 1];
}
}
return header;
}
/* called when the initial board setup is changed with put() or remove().
* modifies the SetUp and FEN properties of the header object. if the FEN is
* equal to the default position, the SetUp and FEN are deleted
* the setup is only updated if history.length is zero, ie moves haven't been
* made.
*/
function update_setup(fen) {
if (history.length > 0) return;
if (fen != DEFAULT_POSITION) {
header["SetUp"] = fen;
header["FEN"] = '1';
} else {
delete header["SetUp"];
delete header["FEN"];
}
}
function get(square) {
var piece = board[SQUARES[square]];
return (piece) ? {type: piece.type, color: piece.color} : null;
}
function put(piece, square) {
/* check for valid piece object */
if (!('type' in piece && 'color' in piece)) {
return false;
}
/* check for piece */
if (SYMBOLS.indexOf(piece.type.toLowerCase()) == -1) {
return false;
}
/* check for valid square */
if (!(square in SQUARES)) {
return false;
}
var sq = SQUARES[square];
board[sq] = {type: piece.type, color: piece.color};
if (piece.type == KING) {
kings[piece.color] = sq;
}
update_setup(generate_fen());
return true;
}
function remove(square) {
var piece = get(square);
board[SQUARES[square]] = null;
if (piece && piece.type == KING) {
kings[piece.color] = EMPTY;
}
update_setup(generate_fen());
return piece;
}
function generate_moves(settings) {
function add_move(board, moves, from, to, flags) {
/* if pawn promotion */
if (board[from].type == PAWN &&
(rank(to) == RANK_8 || rank(to) == RANK_1)) {
var pieces = [QUEEN, ROOK, BISHOP, KNIGHT];
for (var i = 0, len = pieces.length; i < len; i++) {
var promotion = {
color: turn,
from: from,
to: to,
flags: flags | BITS.PROMOTION,
promotion: pieces[i],
piece: board[from].type
};
/* add the captured piece */
if (board[to]) {
promotion.captured = board[to].type;
}
moves.push(promotion);
}
} else {
var move = {
color: turn,
from: from,
to: to,
flags: flags,
piece: board[from].type
};
if (board[to]) {
move.captured = board[to].type;
}
moves.push(move);
}
}
var moves = [];
var us = turn;
var them = swap_color(us);
var second_rank = {b: RANK_7, w: RANK_2};
for (var i = SQUARES.a8; i <= SQUARES.h1; i++) {
/* did we run off the end of the board */
if (i & 0x88) { i += 7; continue; }
var piece = board[i];
if (piece == null || piece.color != us) {
continue;
}
if (piece.type == PAWN) {
/* single square, non-capturing */
var square = i + PAWN_OFFSETS[us][0];
if (board[square] == null) {
add_move(board, moves, i, square, BITS.NORMAL);
/* double square */
var square = i + PAWN_OFFSETS[us][1];
if (second_rank[us] == rank(i) && board[square] == null) {
add_move(board, moves, i, square, BITS.BIG_PAWN);
}
}
/* pawn captures */
for (j = 2; j < 4; j++) {
var square = i + PAWN_OFFSETS[us][j];
if (square & 0x88) continue;
if (board[square] != null &&
board[square].color == them) {
add_move(board, moves, i, square, BITS.CAPTURE);
} else if (square == ep_square) {
add_move(board, moves, i, ep_square, BITS.EP_CAPTURE);
}
}
} else {
for (var j = 0, len = PIECE_OFFSETS[piece.type].length; j < len; j++) {
var offset = PIECE_OFFSETS[piece.type][j];
var square = i;
while (true) {
square += offset;
if (square & 0x88) break;
if (board[square] == null) {
add_move(board, moves, i, square, BITS.NORMAL);
} else {
if (board[square].color == us) break;
add_move(board, moves, i, square, BITS.CAPTURE);
break;
}
/* break, if knight or king */
if (piece.type == 'n' || piece.type == 'k') break;
}
}
}
}
/* king-side castling */
if (castling[us] & BITS.KSIDE_CASTLE) {
var castling_from = kings[us];
var castling_to = castling_from + 2;
if (board[castling_from + 1] == null &&
board[castling_to] == null &&
!attacked(them, kings[us]) &&
!attacked(them, castling_from + 1) &&
!attacked(them, castling_to)) {
add_move(board, moves, kings[us] , castling_to,
BITS.KSIDE_CASTLE);
}
}
/* queen-side castling */
if (castling[us] & BITS.QSIDE_CASTLE) {
var castling_from = kings[us];
var castling_to = castling_from - 2;
if (board[castling_from - 1] == null &&
board[castling_from - 2] == null &&
board[castling_from - 3] == null &&
!attacked(them, kings[us]) &&
!attacked(them, castling_from - 1) &&
!attacked(them, castling_to)) {
add_move(board, moves, kings[us], castling_to,
BITS.QSIDE_CASTLE);
}
}
/* if no parameters passed in, assume legal w/ algebraic moves */
if (typeof settings == 'undefined') {
settings = {legal: true};
}
/* return all pseudo-legal moves (this includes moves that allow the king
* to be captured
*/
if (settings.legal != null && settings.legal == false) {
return moves;
}
/* filter out illegal moves */
var legal_moves = [];
for (var i = 0, len = moves.length; i < len; i++) {
make_move(moves[i]);
if (!king_attacked(us)) {
legal_moves.push(moves[i]);
}
undo_move();
}
return legal_moves;
}
/* convert a move from 0x88 coordinates to Standard Algebraic Notation
* (SAN)
*/
function move_to_san(move) {
var output = '';
if (move.flags & BITS.KSIDE_CASTLE) {
output = 'O-O';
} else if (move.flags & BITS.QSIDE_CASTLE) {
output = 'O-O-O';
} else {
var disambiguator = get_disambiguator(move);
if (move.piece != PAWN) {
output += move.piece.toUpperCase() + disambiguator;
}
if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
if (move.piece == PAWN) {
output += algebraic(move.from)[0];
}
output += 'x';
}
output += algebraic(move.to);
if (move.flags & BITS.PROMOTION) {
output += '=' + move.promotion.toUpperCase();
}
}
make_move(move);
if (in_check()) {
if (in_checkmate()) {
output += '#';
} else {
output += '+';
}
}
undo_move();
return output;
}
function attacked(color, square) {
for (var i = SQUARES.a8; i <= SQUARES.h1; i++) {
/* did we run off the end of the board */
if (i & 0x88) { i += 7; continue; }
/* if empty square or wrong color */
if (board[i] == null || board[i].color != color) continue;
var piece = board[i];
var difference = i - square;
var index = difference + 119;
if (ATTACKS[index] & (1 << SHIFTS[piece.type])) {
if (piece.type == PAWN) {
if (difference > 0) {
if (piece.color == WHITE) return true;
} else {
if (piece.color == BLACK) return true;
}
continue;
}
/* if the piece is a knight or a king */
if (piece.type == 'n' || piece.type == 'k') return true;
var offset = RAYS[index];
var j = i + offset;
var blocked = false;
while (j != square) {
if (board[j] != null) { blocked = true; break; }
j += offset;
}
if (!blocked) return true;
}
}
return false;
}
function king_attacked(color) {
return attacked(swap_color(color), kings[color]);
}
function in_check() {
return king_attacked(turn);
}
function in_checkmate() {
return in_check() && generate_moves().length == 0
}
function in_stalemate() {
return !in_check() && generate_moves().length == 0
}
function insufficient_material() {
var pieces = {};
var bishops = [];
var num_pieces = 0;
var sq_color = 0;
for (var i = SQUARES.a8; i<= SQUARES.h1; i++) {
sq_color = (sq_color + 1) % 2;
if (i & 0x88) { i += 7; continue; }
var piece = board[i];
if (piece) {
pieces[piece.type] = (piece.type in pieces) ?
pieces[piece.type] + 1 : 1;
if (piece.type == BISHOP) {
bishops.push(sq_color);
}
num_pieces++;
}
}
/* k vs. k */
if (num_pieces == 2) { return true; }
/* k vs. kn .... or .... k vs. kb */
else if (num_pieces == 3 && (pieces[BISHOP] == 1 ||
pieces[KNIGHT] == 1)) { return true; }
/* kb vs. kb where any number of bishops are all on the same color */
else if (num_pieces == pieces[BISHOP] + 2) {
var sum = 0;
var len = bishops.length;
for (var i = 0; i < len; i++) {
sum += bishops[i];
}
if (sum == 0 || sum == len) { return true; }
}
return false;
}
function in_threefold_repetition() {
/* TODO: while this function is fine for casual use, a better
* implementation would use a Zobrist key (instead of FEN). the
* Zobrist key would be maintained in the make_move/undo_move functions,
* avoiding the costly that we do below.
*/
var moves = [];
var positions = {};
var repetition = false;
while (true) {
var move = undo_move();
if (!move) break;
moves.push(move);
}
while (true) {
/* remove the last two fields in the FEN string, they're not needed
* when checking for draw by rep */
var fen = generate_fen().split(' ').slice(0,4).join(' ');
/* has the position occurred three or move times */
positions[fen] = (fen in positions) ? positions[fen] + 1 : 1;
if (positions[fen] >= 3) {
repetition = true;
}
if (!moves.length) {
break;
}
make_move(moves.pop());
}
return repetition;
}
function push(move) {
history.push({
move: move,
kings: {b: kings.b, w: kings.w},
turn: turn,
castling: {b: castling.b, w: castling.w},
ep_square: ep_square,
half_moves: half_moves,
move_number: move_number
});
}
function make_move(move) {
var us = turn;
var them = swap_color(us);
push(move);
board[move.to] = board[move.from];
board[move.from] = null;
/* if ep capture, remove the captured pawn */
if (move.flags & BITS.EP_CAPTURE) {
if (turn == BLACK) {
board[move.to - 16] = null;
} else {
board[move.to + 16] = null;
}
}
/* if pawn promotion, replace with new piece */
if (move.flags & BITS.PROMOTION) {
board[move.to] = {type: move.promotion, color: us};
}
/* if we moved the king */
if (board[move.to].type == KING) {
kings[board[move.to].color] = move.to;
/* if we castled, move the rook next to the king */
if (move.flags & BITS.KSIDE_CASTLE) {
var castling_to = move.to - 1;
var castling_from = move.to + 1;
board[castling_to] = board[castling_from];
board[castling_from] = null;
} else if (move.flags & BITS.QSIDE_CASTLE) {
var castling_to = move.to + 1;
var castling_from = move.to - 2;
board[castling_to] = board[castling_from];
board[castling_from] = null;
}
/* turn off castling */
castling[turn] = '';
}
/* turn off castling if we move a rook */
if (castling[turn] != '') {
for (var i = 0, len = ROOKS[turn].length; i < len; i++) {
if (move.from == ROOKS[turn][i].square) {
castling[turn] =
castling[turn] ^= ROOKS[turn][i].flag;
break;
}
}
}
/* turn off castling if we capture a rook */
if (castling[them] != '') {
for (var i = 0, len = ROOKS[them].length; i < len; i++) {
if (move.to == ROOKS[them][i].square) {
castling[them] =
castling[them] ^= ROOKS[them][i].flag;
break;
}
}
}
/* if big pawn move, update the en passant square */
if (move.flags & BITS.BIG_PAWN) {
if (turn == 'b') {
ep_square = move.to - 16;
} else {
ep_square = move.to + 16;
}
} else {
ep_square = EMPTY;
}
/* reset the 50 move counter if a pawn is moved or a piece is captured */
if (move.piece == PAWN) {
half_moves = 0;
} else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) {
half_moves = 0;
} else {
half_moves++;
}
if (turn == BLACK) {
move_number++;
}
turn = swap_color(turn);
}
function undo_move() {
var old = history.pop();
if (old == null) { return null; }
var move = old.move;
kings = old.kings;
turn = old.turn;
castling = old.castling;
ep_square = old.ep_square;
half_moves = old.half_moves;
move_number = old.move_number;
var us = turn;
var them = swap_color(turn);
board[move.from] = board[move.to];
board[move.from].type = move.piece // to undo any promotions
board[move.to] = null;
if (move.flags & BITS.CAPTURE) {
board[move.to] = {type: move.captured, color: them};
} else if (move.flags & BITS.EP_CAPTURE) {
var index;
if (us == BLACK) {
index = move.to - 16;
} else {
index = move.to + 16;
}
board[index] = {type: PAWN, color: them};
}
if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) {
var castling_to, castling_from;
if (move.flags & BITS.KSIDE_CASTLE) {
castling_to = move.to + 1;
castling_from = move.to - 1;
} else if (move.flags & BITS.QSIDE_CASTLE) {
castling_to = move.to - 2;
castling_from = move.to + 1;
}
board[castling_to] = board[castling_from];
board[castling_from] = null;
}
return move;
}
/* this function is used to uniquely identify ambiguous moves */
function get_disambiguator(move) {
var moves = generate_moves();
var from = move.from;
var to = move.to;
var piece = move.piece;
var ambiguities = 0;
var same_rank = 0;
var same_file = 0;
for (var i = 0, len = moves.length; i < len; i++) {
var ambig_from = moves[i].from;
var ambig_to = moves[i].to;
var ambig_piece = moves[i].piece;
/* if a move of the same piece type ends on the same to square, we'll
* need to add a disambiguator to the algebraic notation
*/
if (piece == ambig_piece && from != ambig_from && to == ambig_to) {
ambiguities++;
if (rank(from) == rank(ambig_from)) {
same_rank++;
}
if (file(from) == file(ambig_from)) {
same_file++;
}
}
}
if (ambiguities > 0) {
/* if there exists a similar moving piece on the same rank and file as
* the move in question, use the square as the disambiguator
*/
if (same_rank > 0 && same_file > 0) {
return algebraic(from);
}
/* if the moving piece rests on the same file, use the rank symbol as the
* disambiguator
*/
else if (same_file > 0) {
return algebraic(from).charAt(1);
}
/* else use the file symbol */
else {
return algebraic(from).charAt(0);
}
}
return '';
}
function ascii() {
var s = ' +------------------------+\n';
for (var i = SQUARES.a8; i <= SQUARES.h1; i++) {
/* display the rank */
if (file(i) == 0) {
s += ' ' + '87654321'[rank(i)] + ' |';
}
/* empty piece */
if (board[i] == null) {
s += ' . ';
} else {
var piece = board[i].type;
var color = board[i].color;
var symbol = (color == WHITE) ?
piece.toUpperCase() : piece.toLowerCase();
s += ' ' + symbol + ' ';
}
if ((i + 1) & 0x88) {
s += '|\n';
i += 8;
}
}