-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.js
executable file
·1937 lines (1625 loc) · 76.7 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
/******************************************************************************
* *
* TITLE: Chess JavaScript File *
* *
* AUTHOR: Milo Toor *
* *
* DATE: 30 May 2011 *
* *
* DESCRIPTION: This is the JavaScript file to accompany the game of chess *
* located and played in chess.html. This file contains *
* literally all the dynamic aspects of the chess game and is *
* thus the essential ingredient in the program's funcitonality. *
* Currently the code is organized logically under headers *
* within this file. Were I inclined to do so I might separate *
* the code under each header into a file of its own, then *
* unite the various files here. At the moment I choose to *
* leave all the code here. A table of contents is provided *
* below. *
* *
* LEGEND: FUNCTION TYPE LINE NUMBER *
* Global Items 40 *
* Hover Functions 85 *
* Executive Function 122 *
* Click Functions 416 *
* Confirmation Functions 520 *
* Move Validation Functions 738 *
* Castling Functions 1037 *
* Endgame Functions 1154 *
* Commentary Functions 1305 *
* Conversion Functions 1372 *
* Move Guide Functions 1528 *
* Undo Functions 1642 *
* Notation Functions 1753 *
* Auxiliary Functions 1913 *
* *
******************************************************************************/
/******************************************************************************
*** GLOBAL ITEMS ******************************************** GLOBAL ITEMS ***
******************************************************************************/
/* Initial state of the board. 0's represent an empty square. *
* IMPORTANT OBSERVATION: JavaScript is CASE SENSITIVE. *
* Lower case represents white pieces, and upper case *
* represents black pieces. *
* *
* LEGEND: *
* i: pawn j: bishop *
* l: rook m: queen *
* k: knight n: king *
* *
* These letter choices are hard-wired into the Chess Alpha 2 *
* font, and are not of my selection. They MAY NOT be changed. */
var board = [["L", "K", "J", "M", "N", "J", "K", "L"],
["I", "I", "I", "I", "I", "I", "I", "I"],
["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0"],
["0", "0", "0", "0", "0", "0", "0", "0"],
["i", "i", "i", "i", "i", "i", "i", "i"],
["l", "k", "j", "m", "n", "j", "k", "l"]];
var boardLength = board[0].length;
/* previousBoards is an array which will hold the previous *
* states of the board, so that a user may use the undo button. */
var previousBoards = [];
/* Several useful variables: *
* 'moveNo' tells us the turn number. *
* 'selection' tells us the id (square number) of the piece *
* that is selected, if there is one. *
* 'displayMoveGuide' tells us if the user has the move guide *
* option on or off. *
* 'displayInstr' tells us if the user would like instructions *
* for the selected piece. */
var moveNo = 1;
var selection = "";
var displayMoveGuide = false;
var displayInstr = false;
/******************************************************************************
*** HOVER FUNCTIONS ************************************** HOVER FUNCTIONS ***
******************************************************************************/
/* Function to make the background color of playable pieces *
* change when hovered over. */
function hover(id)
{
/* We only activate 'hover' if the square we are hovering *
* over is not the currently selected piece. */
if (id != selection) {
var element = document.getElementById(id);
/* When a playable piece is hovered over, we change the background *
* color and the pointer. */
element.setAttribute('style',
'background-color: #ffffe9; cursor: pointer;');
element.setAttribute('onMouseOut', 'unHover(id)');
}
return;
}
// Function to remove the hover effect when the user un-hovers. //
function unHover(id)
{
/* Likewise, we only activate unHover if the square in *
* in question is not selected one. */
if (id != selection) {
var element = document.getElementById(id);
element.setAttribute('style', '');
}
return;
}
/******************************************************************************
*** EXECUTIVE FUNCTIONS ****************************** EXECUTIVE FUNCTIONS ***
******************************************************************************/
/* updateBoard takes care of all the logistical work behind every *
* move. It updates both the matrix-board and the visual-board, *
* augments the number of moves, renders the updated version of *
* the game, and updates the piece grave yard. */
function updateBoard(idCur, idMov)
{
/* These variables dictate where the currently selected piece *
* is, and where we are trying to move it. */
var coordsMov = idToCoords(idMov);
var rowNumMov = coordsMov[0];
var colNumMov = coordsMov[1];
var coordsCur = idToCoords(idCur);
var rowNumCur = coordsCur[0];
var colNumCur = coordsCur[1];
// The characters on the two relevant squares. //
var pieceMov = board[rowNumMov][colNumMov];
var pieceCur = board[rowNumCur][colNumCur];
// And, update the board! //
board[rowNumMov][colNumMov] = pieceCur;
board[rowNumCur][colNumCur] = "0";
/* Additional check, to see if the move was a castle, in which *
* case we need to move the rook too. */
if (pieceCur == 'n') { // White king is moving. //
if (colNumCur - colNumMov == 2) { // Castling to left. //
board[rowNumMov][colNumMov + 1] = "l";
board[rowNumMov][0] = "0";
hasMovedWhiteRookL = true;
}
else if (colNumMov - colNumCur == 2) { // Castling to right. //
board[rowNumMov][colNumMov - 1] = "l";
board[rowNumMov][boardLength - 1] = "0";
hasMovedWhiteRookR = true;
}
}
else if (pieceCur == 'N') { // Black king is moving. //
if (colNumCur - colNumMov == 2) { // Castling to left. //
board[rowNumMov][colNumMov + 1] = "L";
board[rowNumMov][0] = "0";
hasMovedBlackRookL = true;
}
else if (colNumMov - colNumCur == 2) { // Castling to right. //
board[rowNumMov][colNumMov - 1] = "L";
board[rowNumMov][boardLength - 1] = "0";
hasMovedBlackRookR = true;
}
}
// Check to see if a pawn reached the other end. //
if (pieceCur == 'i' &&
rowNumMov == 0) // White pawn reached end.
board[rowNumMov][colNumMov] = "m";
if (pieceCur == 'I' &&
rowNumMov == boardLength - 1) // Black pawn reached end.
board[rowNumMov][colNumMov] = "M";
// Update the visual representation of the board. //
moveNo += 1;
render(board, moveNo);
// If a piece was killed by the move, reflect this. //
if (pieceMov != "0")
updateGraveyard(pieceMov, "in");
// Reset the selection. //
document.getElementById(selection).setAttribute('style', '');
document.getElementById("board").setAttribute('style', '');
selection = "";
// If move guide is on, update it (by erasing the highlights). //
if (displayMoveGuide)
updateMoveGuide();
addNotation(pieceCur, pieceMov, rowNumMov,
colNumMov, rowNumCur, colNumCur);
/* Variable to represent the current player's color. Necessary *
* for isStalemate() and isCheckmate(). I inverse the colors *
* because we want to determine if the OTHER player is checkmated *
* or stalemated by the move just made. */
var color;
if (isWhitePiece(pieceCur))
color = 'b';
else
color = 'w';
// If the game is now in stalemate, end it. //
if(isStalemate(color))
endGame("stalemate", color);
// Alternatively, if the other player is now checkmated, end the game. //
if(isCheckmate(color))
endGame("checkmate", color);
return;
}
/* render is responsible for updating the visual representation *
* of the chess game. After a move is made and confirmed valid, *
* and after the appropriate change is made to the internal *
* matrix-board, we need to update the visual board as well, *
* along with the accompanying HTML. If white made the move *
* being rendered, we now need to hand control to black, which *
* means a lot of changes need to be made to the onClick() *
* calls, as well as the onMouseOver() calls. */
function render(chessBoard, moveCount)
{
/* First we will update whose turn it is. An odd number of *
* moves indicates it's white's turn, and an even number *
* indicates it's black's turn. */
var whoseMove;
if ((moveCount % 2) == 1) // Odd numbered turn, white's move. //
whoseMove = "White";
else // Even numbered turn, black's move. //
whoseMove = "Black";
// Update whose turn it is. //
document.getElementById("whoseMove").innerHTML=whoseMove+"'s Move";
/* Now we need to scroll through every square of the board, *
* one by one, replacing the current content of the square, *
* the onClick() calls and the onMouseOver() calls. */
var colLetter;
var rowNumber;
var id;
for (row = 0; row < boardLength; ++row) {
for (col = 0; col < boardLength; ++col) {
// First, identify the square by its id. //
id = coordsToId(row, col);
/* Now, update that square's content. Keep in mind *
* we don't want to do this if the content is a 0. */
if (chessBoard[row][col] != "0")
document.getElementById(id).innerHTML = chessBoard[row][col];
else
document.getElementById(id).innerHTML = "";
/* Update the square's onMouseOver() and onClick() calls. *
* If the square is now home to a piece belonging to the *
* player whose turn it is, onMouseOver() should call *
* hover(), and otherwise onMouseOver() should do nothing. *
* For these same squares, onClick() should call choose, *
* and for all other squares it should call move(). *
* *
* NOTE: At the moment I am reusing the line *
* *
* document.getElementById(id) *
* *
* about a thousand times instead of declaring a variable *
* to represent it. This is because, for some reason, I *
* have had endless trouble trying to make JavaScript *
* assign the same variable more than one HTML element, and *
* have been unable to generate code that will work when *
* run through a loop. This problem is UNRESOLVED. */
if (whoseMove == "White") { // White's turn. //
if (isWhitePiece(chessBoard[row][col])) { // On a white piece. //
document.getElementById(id).setAttribute('onClick',
'choose("'+id+'")');
document.getElementById(id).setAttribute('onMouseOver',
'hover("'+id+'")');
}
else { // Not on a white piece. //
document.getElementById(id).setAttribute('onClick',
'move("'+id+'")');
document.getElementById(id).setAttribute('onMouseOver',
'');
}
}
else { // Black's turn.
if (isBlackPiece(chessBoard[row][col])) { // On a black piece. //
document.getElementById(id).setAttribute('onClick',
'choose("'+id+'")');
document.getElementById(id).setAttribute('onMouseOver',
'hover("'+id+'")');
}
else { // Not on a black piece. //
document.getElementById(id).setAttribute('onClick',
'move("'+id+'")');
document.getElementById(id).setAttribute('onMouseOver',
'');
}
}
}
}
/* Finally, remove the informational text, and *
* king-check warning, if there is one. */
updateCommentary("");
kingCheck(0);
return;
}
/* The game-ending function. This function does no real evaluation *
* to determine if the game is over. Instead, evaluation is done *
* by the functions isStalemate() or isCheckmate(), and if either *
* of these things returns true, updateBoard() calls endGame to *
* do exactly what its name suggests. */
function endGame(type, color)
{
/* These declarations might look odd. The color attribute *
* will only be used to announce who has won the game (in *
* the case of a checkmate). It's important to recall that *
* in updateGame (endGame's calling function), color is *
* used to represent the player who has been checkmated. *
* Hence, here we reverse the color. */
if (color == 'w')
color = 'Black';
else
color = 'White';
// Inform the user. //
var comHead = document.getElementById("comHead");
if (type == "stalemate")
comHead.innerHTML = "Stalemate!";
else if(type == "checkmate")
comHead.innerHTML = "Checkmate! "+color+" wins!";
document.getElementById("whoseMove").innerHTML="";
// Then remove all the JavaScript options from the board. //
var row;
var col;
var id;
for (row = 0; row < boardLength; ++row) {
for (col = 0; col < boardLength; ++col) {
id = coordsToId(row, col);
square = document.getElementById(id);
square.setAttribute('onMouseOver', '');
square.setAttribute('onClick', '');
}
}
}
/* updateGraveyard takes in a character representing a killed *
* piece and places it in the appropriate graveyard. Pawns go *
* in a player's inner graveyard, and all other pieces go in *
* a player's outer graveyard. The direction argument enables *
* us to both add and remove pieces from the graveyard (we *
* may wish to remove pieces in the event of undoing a move). */
function updateGraveyard(piece, direction)
{
/* graveyard will represent the table cell we need to update, *
* and alreadyDead will contain the pieces already within *
* that graveyard. */
var graveyard;
var alreadyDead;
if (isWhitePiece(piece)) { // If the piece is white... //
if(piece == "i") // White pawn. //
graveyard = document.getElementById("whiteInnerGraveyard");
else // Other white piece. //
graveyard = document.getElementById("whiteOuterGraveyard");
}
else { // The piece is black... //
if(piece == "I") // Black pawn. //
graveyard = document.getElementById("blackInnerGraveyard");
else // Other black piece. //
graveyard = document.getElementById("blackOuterGraveyard");
}
/* Now that we know what graveyard we're dealing with, grab *
* the pieces currently in that graveyard and then update. */
alreadyDead = graveyard.innerHTML;
if (direction == "in")
graveyard.innerHTML = alreadyDead + piece;
else
graveyard.innerHTML = alreadyDead.substring(0, alreadyDead.length - 1);
return;
}
/******************************************************************************
*** CLICK FUNCTIONS ************************************** CLICK FUNCTIONS ***
******************************************************************************/
/* choose is responsible for the logistics involved in clicking on *
* a playable piece. If a player clicks on one of their pieces, *
* that piece's background color changes, the move guide changes, *
* and the cursor is made into a pointer. choose handles all this. */
function choose(id)
{
var element = document.getElementById(id);
/* If we're clicking the same square, then we want to deselect *
* the piece. */
if (id == selection) {
unChoose("choose")
return;
}
/* If we're selecting a different square, then we first want *
* to fix the already selected square, update the selection *
* variables, and change the background color of our newly *
* selected piece. The if is there so that when we first make *
* a selection we don't attempt to reset a previous *
* (nonexistent) selection. */
if (selection != "") {
var oldElem = document.getElementById(selection);
oldElem.setAttribute('style', '');
}
selection = id;
var board = document.getElementById("board");
element.setAttribute('style', 'background-color: #aaccff;');
board.setAttribute('style', 'cursor: pointer;');
if (displayMoveGuide)
updateMoveGuide(id);
updateCommentary(selection);
return;
}
// Function for deselecting a piece. //
function unChoose(calledBy)
{
var element = document.getElementById(selection);
/* If unChoose was called by choose(), then we want *
* to set the element's cursor to pointer. However, *
* if unChoose was called by undo(), then we want to *
* set the element's style to nothing. */
element.setAttribute('style', '');
if (calledBy == "choose")
element.setAttribute('style', 'cursor: pointer;');
/* In either case, we also want to clear the selection variables *
* and set the board's style back to normal. */
document.getElementById("board").setAttribute('style', '');
selection = "";
if (displayMoveGuide)
updateMoveGuide(selection);
updateCommentary(selection);
return;
}
/* After a player selects a piece (handled by choose()), the *
* player may then wish to move the piece. This option, and all *
* the various baggage that comes with it, is handled by move. *
* move not only ensures that a move is valid, it also makes *
* several calls to update the array of previous boards (necessary *
* for the undo function), to update the castling variables, and *
* to update the board itself. */
function move(id)
{
/* If selection is the empty string, there's no piece selected, *
* so just stop right there. */
if (selection == "")
return;
// First we must check that the move is valid. //
if (checkValid(selection, id, board, "move")) {
// Coordinates representing the two squares of interest. //
var coordsMov = idToCoords(id);
var coordsCur = idToCoords(selection);
// Update the array of previous moves. //
updateUndo(coordsMov[0], coordsMov[1]);
// Update the castling variables. //
updateCastleVariables(coordsCur[0], coordsCur[1]);
// And finally, update the board.
updateBoard(selection, id);
}
return; // The deed is done. //
}
/******************************************************************************
*** CONFIRMATION FUNCTIONS ************************ CONFIRMATION FUNCTIONS ***
******************************************************************************/
/* checkValid takes in the id of a square the current player is *
* attempting to move a selected piece to. It confirms, through lengthy *
* conditional checking, that the move is valid. This code is very *
* long and, as mentioned, highly conditional, but this is the nature *
* of chess and there really is no work around. Also, for clarification, *
* the calledBy parameter is merely there so that, in case checkValid is *
* being called by the updateMoveGuide(), isStalemate() or isCheckmate() *
* functions -- all of which are call checkValid() based on hypothetical *
* moves and not moves the user is requesting -- we do not bother to *
* throw kingCheck exceptions. */
function checkValid(selected, id, chessBoard, calledBy)
{
/* These variables dictate where the currently selected piece *
* is, and where we are trying to move it. */
var coordsMov = idToCoords(id);
var rowNumMov = coordsMov[0];
var colNumMov = coordsMov[1];
var coordsCur = idToCoords(selected);
var rowNumCur = coordsCur[0];
var colNumCur = coordsCur[1];
// First we find which pieces we are dealing with. //
var pieceMov = getPieceID(id);
var pieceCur = getPieceID(selected);
/* Declare a boolean variable, then branch. isValid, unsurprisingly, *
* will hold whether or not the proposed move is possible without *
* taking into consideration whether or not the move endangers the *
* player's king. */
var isValid;
switch(pieceCur) {
case 'i': // WHITE PAWN //
isValid = validatePawn(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'I': // BLACK PAWN //
isValid = validatePawn(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
case 'l': // WHITE ROOK //
isValid = validateRook(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'L': // BLACK ROOK //
isValid = validateRook(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
case 'k': // WHITE KNIGHT //
isValid = validateKnight(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'K': // BLACK KNIGHT //
isValid = validateKnight(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
case 'j': // WHITE BISHOP //
isValid = validateBishop(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'J': // BLACK BISHOP //
isValid = validateBishop(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
case 'm': // WHITE QUEEN //
isValid = validateQueen(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'M': // BLACK QUEEN //
isValid = validateQueen(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
case 'n': // WHITE KING //
isValid = validateKing(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'w', chessBoard);
break;
case 'N': // BLACK KING //
isValid = validateKing(colNumMov, colNumCur,
rowNumMov, rowNumCur, 'b', chessBoard);
break;
}
if (!isValid)
return false;
/* Now that we know that the move is feasible, we need to *
* confirm that the player is not endangering their king by *
* making the move. That means that, if the king is currently *
* in check before the move, the player cannot ignore this, *
* and it also means they cannot make a move that would put *
* their king in check. To make these judgements, I need to *
* advance the board according to the current move, and to do *
* so I use a copy of the board. */
var tempBoard = copyBoard();
// Update the imaginary board with the new move. //
tempBoard[rowNumMov][colNumMov] = tempBoard[rowNumCur][colNumCur];
tempBoard[rowNumCur][colNumCur] = "0";
/* Before we make the actual checks, we need to know *
* the moving player's color (for underAttack()) */
var color;
if (isWhitePiece(tempBoard[rowNumMov][colNumMov]))
color = 'w';
else
color = 'b';
var kingIDNow = findKing(color, board);
var kingIDAfter = findKing(color, tempBoard)
var kingInCheckNow = underAttack(color, kingIDNow, board);
var kingInCheckAfter = underAttack(color, kingIDAfter, tempBoard);
/* If the king is in check right now and he remains in check *
* after the move, we call the 1st king-check error. */
if (kingInCheckNow && kingInCheckAfter) {
if(calledBy != "moveGuide" &&
calledBy != "stalemate" &&
calledBy != "checkmate")
kingCheck(1);
return false;
}
/* If the king is not in check right now but is in check after *
* the move, we call the 2nd king-check error. */
else if (!kingInCheckNow && kingInCheckAfter) {
if(calledBy != "moveGuide" &&
calledBy != "stalemate" &&
calledBy != "checkmate")
kingCheck(2);
return false;
}
return true; // The move is valid! //
}
/* underAttack returns true or false depending on whether the given *
* color is under attack on the given square. */
function underAttack(color, square, chessBoard)
{
/* The methodology is simple: Loop through every square on the board. *
* If you find a piece of the opposing color, check to see if that *
* piece can attack the given square by using checkValid(). */
var row;
var col;
var id;
for (row = 0; row < boardLength; ++row) {
for (col = 0; col < boardLength; ++col) {
// The player is white and the square holds a black piece. //
if (color == 'w' && isBlackPiece(chessBoard[row][col])) {
// First, identify the square by it's id. //
id = coordsToId(row, col);
/* Check if the piece can attack the square. If it can, *
* return true. */
if (checkValid(id, square, chessBoard, "underAttack"))
return true;
}
else if (color == 'b' && isWhitePiece(chessBoard[row][col])) {
id = coordsToId(row, col);
/* Check if the piece can attack the square. If it can, *
* return true. */
if (checkValid(id, square, chessBoard, "underAttack"))
return true;
}
}
}
/* We've scrolled through the whole board and no *
* piece could attack the square. */
return false;
}
// A simple function that determines if a given character is a white piece. //
function isWhitePiece(char)
{
var whitePieces = ["i", "l", "k", "j", "m", "n"];
for (i = 0; i < whitePieces.length; ++i) {
if (char == whitePieces[i])
return true;
}
return false; // The character is not a white piece. //
}
// Same function as isWhitePiece(), except for black pieces. //
function isBlackPiece(char)
{
var blackPieces = ["I", "L", "K", "J", "M", "N"];
for (i = 0; i < blackPieces.length; ++i) {
if (char == blackPieces[i])
return true;
}
return false; // The character is not a black piece. //
}
/******************************************************************************
*** MOVE VALIDATION FUNCTIONS ****************** MOVE VALIDATION FUNCTIONS ***
******************************************************************************/
/* All of the following functions take in the board-coordinates of the *
* currently selected piece and a location where this piece is trying *
* to move. They then confirm (or deny) that this location is a valid *
* one according to the rules of chess. For the sake of reusing code, *
* the functions also accept a 'color' parameter, permitting us to *
* handle both white and black moves in one function. */
// Validate a pawn's move. //
function validatePawn(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
var pieceMov = chessBoard[rowNumMov][colNumMov];
/* In order to handle both white and black pawn movements, we *
* need to be able to switch the magnitude of *
* rowNumCur - rowNumMov on several occasions. */
var colorMultiplier;
/* We also need to distinguish between the row number of the pawn's *
* first row. */
var origRow;
// If the given color is white, do nothing. Otherwise, switch magnitude. //
if (color == 'w') {
colorMultiplier = 1;
origRow = 6;
}
else if(color == 'b') {
colorMultiplier = -1;
origRow = 1;
}
// If neither of the first two cases triggered, something went wrong. //
else {
postError(2);
return false;
}
/* This conditional confirms location. The pawn's movement *
* can either be one or two spaces forward (the first three *
* conditions), or it can be one space forward, one space *
* diagonally. (the last two conditons) */
if (((colNumCur == colNumMov) &&
(((rowNumCur - rowNumMov)*colorMultiplier == 1) ||
((rowNumCur - rowNumMov)*colorMultiplier == 2))) ||
(((rowNumCur - rowNumMov)*colorMultiplier == 1) &&
(Math.abs(colNumCur - colNumMov) == 1))) {
/* This conditional confirms the pawn's move is valid when *
* the player is moving one or two steps forward. Note that *
* the player can move a pawn two steps forward only if the *
* pawn has not moved. */
if ((colNumCur == colNumMov) &&
(pieceMov == "0") &&
(((rowNumCur - rowNumMov)*colorMultiplier == 1) ||
(((rowNumCur - rowNumMov)*colorMultiplier == 2) &&
(rowNumCur == origRow) &&
chessBoard[rowNumCur - 1*colorMultiplier][colNumCur] == "0")))
return true;
/* Finally, the only other valid move is if the pawn is *
* moving one space diagonally to attack an opponent's *
* piece. */
else if (((rowNumCur - rowNumMov)*colorMultiplier == 1) &&
(Math.abs(colNumCur - colNumMov) == 1))
if ((color == 'w' && isBlackPiece(pieceMov)) ||
(color == 'b' && isWhitePiece(pieceMov)))
return true;
}
return false; // Not a valid move. //
}
// Validate a rook's move. //
function validateRook(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
/* If there is a piece at the destination, and it isn't capturable, *
* then the move is not valid. I include this condition first so *
* that now I need only confirm that the location is a valid one. */
var pieceAtLocation = chessBoard[rowNumMov][colNumMov];
if (pieceAtLocation != "0")
if ((color == 'w' && !isBlackPiece(pieceAtLocation)) ||
(color == 'b' && !isWhitePiece(pieceAtLocation)))
return false;
/* Confirm location. Rooks can only move straight up and down *
* or straight left and right, so either the column number *
* won't change or the row number won't. */
if (!((colNumMov == colNumCur) ||
(rowNumMov == rowNumCur)))
return false;
if (colNumMov != colNumCur) { // Rook is moving horizontally. //
/* Logic: If there is anything but a 0 between the current *
* location and the destination, then the move is invalid *
* as the rook is trying to move through another piece. */
var col;
var startCol = Math.min(colNumCur, colNumMov);
var endCol = Math.max(colNumCur, colNumMov);
for (col = startCol + 1; col < endCol; ++col)
if (chessBoard[rowNumMov][col] != "0")
return false;
}
else { // Rook is moving vertically. //
// Same logic as above. //
var row;
var startRow = Math.min(rowNumCur, rowNumMov);
var endRow = Math.max(rowNumCur, rowNumMov);
for (row = startRow + 1; row < endRow; ++ row)
if (chessBoard[row][colNumMov] != "0")
return false;
}
/* At this point, we have confirmed that the rook does not move *
* through any pieces, and that the location it is trying to *
* move to is either empty or is occupied by a capturable piece. *
* Hence, the move is valid, so return true. */
return true;
}
// Validate a knight's move. //
function validateKnight(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
/* If there is a piece at the destination, and it isn't capturable, *
* then the move is not valid. I include this condition first so *
* that now I need only confirm that the location is a valid one. */
var pieceAtLocation = chessBoard[rowNumMov][colNumMov];
if (pieceAtLocation != "0")
if ((color == 'w' && !isBlackPiece(pieceAtLocation)) ||
(color == 'b' && !isWhitePiece(pieceAtLocation)))
return false;
/* The move is valid if the knight is moving in an 'L' fashion, that *
* is, if the knight is moving two spaces up or down and one space *
* left or right (first two conditions) or if it is moving two spaces *
* left or right and one space up or down (last two conditions). */
if (((Math.abs(rowNumMov - rowNumCur) == 2) &&
(Math.abs(colNumMov - colNumCur) == 1)) ||
((Math.abs(rowNumMov - rowNumCur) == 1) &&
(Math.abs(colNumMov - colNumCur) == 2)))
return true;
return false; // Not a valid move. //
}
// Validate a bishop's move. //
function validateBishop(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
/* First confirm that the location is either empty or is occupied *
* by a piece of the opposite color. */
var pieceAtLocation = chessBoard[rowNumMov][colNumMov];
if (pieceAtLocation != "0")
if ((color == 'w' && !isBlackPiece(pieceAtLocation)) ||
(color == 'b' && !isWhitePiece(pieceAtLocation)))
return false;
/* The bishop can only move diagonally, meaning that the number *
* of spaces it travels up or down needs to equal the number *
* of spaces it travels left or right. */
if (!(Math.abs(rowNumMov - rowNumCur) ==
Math.abs(colNumMov - colNumCur)))
return false;
// Represents how far the bishop travels diagonally. //
var distance = Math.abs(rowNumMov - rowNumCur);
var index;
var startRow;
var startCol = Math.min(colNumMov, colNumCur);
/* Logic: If there is anything but a 0 between the current *
* location and the destination, then the move is invalid *
* as the bishop is trying to move through another piece. */
/* This conditional tests if the bishop is moving up-left or *
* down-right. If the bishop moves in one of these two ways, *
* then the column number and the row number either both *
* increase or both decrease as the bishop moves. */
if ((rowNumMov > rowNumCur && colNumMov > colNumCur) ||
(rowNumMov < rowNumCur && colNumMov < colNumCur)) {
startRow = Math.min(rowNumMov, rowNumCur);
for (index = 1; index < distance; ++index)
if (chessBoard[startRow + index][startCol + index] != "0")
return false;
}
/* Otherwise, the bishop is moving up-right or down-left, in *
* which case the column number and row number will not change *
* in the same direction. */
else {
startRow = Math.max(rowNumMov, rowNumCur);
for (index = 1; index < distance; ++index)
if (chessBoard[startRow - index][startCol + index] != "0")
return false;
}
/* At this point, we have confirmed that the bishop does not move *
* through any pieces, and that the location it is trying to *
* move to is either empty or is occupied by a capturable piece. *
* Hence, the move is valid, so return true. */
return true;
}
// Validate a queen's move. //
function validateQueen(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
/* Note: a queen is essentially the same thing as a rook and *
* bishop combined. The queen can move in any direction -- *
* up, down, left, right or diagonally -- in as many spaces *
* as possible. A bishop can move diagonally as many spaces *
* as possible, and a rook can move up, down, left or right *
* as many spaces as possible. Hence, combining the rook and *
* the bishop yields the functionality of the queen. */
return (validateRook(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard) ||
validateBishop(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard));
}
// Validate a king's move. //
function validateKing(colNumMov, colNumCur,
rowNumMov, rowNumCur, color, chessBoard)
{
/* First confirm that the location is either empty or is occupied *
* by a piece of the opposite color. */
var pieceAtLocation = chessBoard[rowNumMov][colNumMov];
if (pieceAtLocation != "0")
if ((color == 'w' && !isBlackPiece(pieceAtLocation)) ||
(color == 'b' && !isWhitePiece(pieceAtLocation)))
return false;
/* There is one stipulation that I need to get out of the way *
* before anything else. Due to the way I have structured *
* the code, if a player has the move guide on and they attempt *
* to move a king onto a square which the other king can attack, an *
* infinite loop is triggered (checkValid() calls underAttack() which *
* calls checkValid, etc). An easy way around this dilemma is by *
* simply making the restriction that a player can not move a king *
* to a square already adjacent to the other king. */
var row;
var col;
for (row = rowNumMov - 1; row <= rowNumMov + 1; ++row) {
// Make sure that the row index is not beyond the array's index. //
if (row < 0 || row > boardLength - 1)
continue;
for (col = colNumMov - 1; col <= colNumMov + 1; ++col) {