Some improvements; to be continuated
[vchess.git] / public / javascripts / base_rules.js
1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
3
4 class PiPo //Piece+Position
5 {
6 // o: {piece[p], color[c], posX[x], posY[y]}
7 constructor(o)
8 {
9 this.p = o.p;
10 this.c = o.c;
11 this.x = o.x;
12 this.y = o.y;
13 }
14 }
15
16 // TODO: for animation, moves should contains "moving" and "fading" maybe...
17 class Move
18 {
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
22 constructor(o)
23 {
24 this.appear = o.appear;
25 this.vanish = o.vanish;
26 this.start = !!o.start ? o.start : {x:o.vanish[0].x, y:o.vanish[0].y};
27 this.end = !!o.end ? o.end : {x:o.appear[0].x, y:o.appear[0].y};
28 }
29 }
30
31 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
32 class ChessRules
33 {
34 //////////////
35 // MISC UTILS
36
37 static get HasFlags() { return true; } //some variants don't have flags
38
39 static get HasEnpassant() { return true; } //some variants don't have ep.
40
41 // Path to pieces
42 static getPpath(b)
43 {
44 return b; //usual pieces in pieces/ folder
45 }
46
47 // Turn "wb" into "B" (for FEN)
48 static board2fen(b)
49 {
50 return b[0]=='w' ? b[1].toUpperCase() : b[1];
51 }
52
53 // Turn "p" into "bp" (for board)
54 static fen2board(f)
55 {
56 return f.charCodeAt()<=90 ? "w"+f.toLowerCase() : "b"+f;
57 }
58
59 // Check if FEN describe a position
60 static IsGoodFen(fen)
61 {
62 const fenParsed = V.ParseFen(fen);
63 // 1) Check position
64 if (!V.IsGoodPosition(fenParsed.position))
65 return false;
66 // 2) Check turn
67 if (!fenParsed.turn || !["w","b"].includes(fenParsed.turn))
68 return false;
69 // 3) Check flags
70 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
71 return false;
72 // 4) Check enpassant
73 if (V.HasEnpassant)
74 {
75 if (!fenParsed.enpassant)
76 return false;
77 if (fenParsed.enpassant != "-")
78 {
79 const ep = V.SquareToCoords(fenParsed.enpassant);
80 if (isNaN(ep.x) || !V.OnBoard(ep))
81 return false;
82 }
83 }
84 return true;
85 }
86
87 // Is position part of the FEN a priori correct?
88 static IsGoodPosition(position)
89 {
90 if (position.length == 0)
91 return false;
92 const rows = position.split("/");
93 if (rows.length != V.size.x)
94 return false;
95 for (let row of rows)
96 {
97 let sumElts = 0;
98 for (let i=0; i<row.length; i++)
99 {
100 if (V.PIECES.includes(row[i].toLowerCase()))
101 sumElts++;
102 else
103 {
104 const num = parseInt(row[i]);
105 if (isNaN(num))
106 return false;
107 sumElts += num;
108 }
109 }
110 if (sumElts != V.size.y)
111 return false;
112 }
113 return true;
114 }
115
116 // For FEN checking
117 static IsGoodFlags(flags)
118 {
119 return !!flags.match(/^[01]{4,4}$/);
120 }
121
122 // 3 --> d (column number to letter)
123 static CoordToColumn(colnum)
124 {
125 return String.fromCharCode(97 + colnum);
126 }
127
128 // d --> 3 (column letter to number)
129 static ColumnToCoord(colnum)
130 {
131 return String.fromCharCode(97 + colnum);
132 }
133
134 // a4 --> {x:3,y:0}
135 static SquareToCoords(sq)
136 {
137 return {
138 // NOTE: column is always one char => max 26 columns
139 // row is counted from black side => subtraction
140 x: V.size.x - parseInt(sq.substr(1)),
141 y: sq[0].charCodeAt() - 97
142 };
143 }
144
145 // {x:0,y:4} --> e8
146 static CoordsToSquare(coords)
147 {
148 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
149 }
150
151 // Aggregates flags into one object
152 aggregateFlags()
153 {
154 return this.castleFlags;
155 }
156
157 // Reverse operation
158 disaggregateFlags(flags)
159 {
160 this.castleFlags = flags;
161 }
162
163 // En-passant square, if any
164 getEpSquare(moveOrSquare)
165 {
166 if (!moveOrSquare)
167 return undefined;
168 if (typeof moveOrSquare === "string")
169 {
170 const square = moveOrSquare;
171 if (square == "-")
172 return undefined;
173 return V.SquareToCoords(square);
174 }
175 // Argument is a move:
176 const move = moveOrSquare;
177 const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
178 if (this.getPiece(sx,sy) == V.PAWN && Math.abs(sx - ex) == 2)
179 {
180 return {
181 x: (sx + ex)/2,
182 y: sy
183 };
184 }
185 return undefined; //default
186 }
187
188 // Can thing on square1 take thing on square2
189 canTake([x1,y1], [x2,y2])
190 {
191 return this.getColor(x1,y1) !== this.getColor(x2,y2);
192 }
193
194 // Is (x,y) on the chessboard?
195 static OnBoard(x,y)
196 {
197 return (x>=0 && x<V.size.x && y>=0 && y<V.size.y);
198 }
199
200 // Used in interface: 'side' arg == player color
201 canIplay(side, [x,y])
202 {
203 return (this.turn == side && this.getColor(x,y) == side);
204 }
205
206 // On which squares is color under check ? (for interface)
207 getCheckSquares(color)
208 {
209 return this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
210 ? [JSON.parse(JSON.stringify(this.kingPos[color]))] //need to duplicate!
211 : [];
212 }
213
214 /////////////
215 // FEN UTILS
216
217 // Setup the initial random (assymetric) position
218 static GenRandInitFen()
219 {
220 let pieces = { "w": new Array(8), "b": new Array(8) };
221 // Shuffle pieces on first and last rank
222 for (let c of ["w","b"])
223 {
224 let positions = _.range(8);
225
226 // Get random squares for bishops
227 let randIndex = 2 * _.random(3);
228 const bishop1Pos = positions[randIndex];
229 // The second bishop must be on a square of different color
230 let randIndex_tmp = 2 * _.random(3) + 1;
231 const bishop2Pos = positions[randIndex_tmp];
232 // Remove chosen squares
233 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
234 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
235
236 // Get random squares for knights
237 randIndex = _.random(5);
238 const knight1Pos = positions[randIndex];
239 positions.splice(randIndex, 1);
240 randIndex = _.random(4);
241 const knight2Pos = positions[randIndex];
242 positions.splice(randIndex, 1);
243
244 // Get random square for queen
245 randIndex = _.random(3);
246 const queenPos = positions[randIndex];
247 positions.splice(randIndex, 1);
248
249 // Rooks and king positions are now fixed,
250 // because of the ordering rook-king-rook
251 const rook1Pos = positions[0];
252 const kingPos = positions[1];
253 const rook2Pos = positions[2];
254
255 // Finally put the shuffled pieces in the board array
256 pieces[c][rook1Pos] = 'r';
257 pieces[c][knight1Pos] = 'n';
258 pieces[c][bishop1Pos] = 'b';
259 pieces[c][queenPos] = 'q';
260 pieces[c][kingPos] = 'k';
261 pieces[c][bishop2Pos] = 'b';
262 pieces[c][knight2Pos] = 'n';
263 pieces[c][rook2Pos] = 'r';
264 }
265 return pieces["b"].join("") +
266 "/pppppppp/8/8/8/8/PPPPPPPP/" +
267 pieces["w"].join("").toUpperCase() +
268 " w 1111 -"; //add turn + flags + enpassant
269 }
270
271 // "Parse" FEN: just return untransformed string data
272 static ParseFen(fen)
273 {
274 const fenParts = fen.split(" ");
275 let res =
276 {
277 position: fenParts[0],
278 turn: fenParts[1],
279 };
280 let nextIdx = 2;
281 if (V.HasFlags)
282 Object.assign(res, {flags: fenParts[nextIdx++]});
283 if (V.HasEnpassant)
284 Object.assign(res, {enpassant: fenParts[nextIdx]});
285 return res;
286 }
287
288 // Return current fen (game state)
289 getFen()
290 {
291 return this.getBaseFen() + " " + this.turn +
292 (V.HasFlags ? (" " + this.getFlagsFen()) : "") +
293 (V.HasEnpassant ? (" " + this.getEnpassantFen()) : "");
294 }
295
296 // Position part of the FEN string
297 getBaseFen()
298 {
299 let position = "";
300 for (let i=0; i<V.size.x; i++)
301 {
302 let emptyCount = 0;
303 for (let j=0; j<V.size.y; j++)
304 {
305 if (this.board[i][j] == V.EMPTY)
306 emptyCount++;
307 else
308 {
309 if (emptyCount > 0)
310 {
311 // Add empty squares in-between
312 position += emptyCount;
313 emptyCount = 0;
314 }
315 position += V.board2fen(this.board[i][j]);
316 }
317 }
318 if (emptyCount > 0)
319 {
320 // "Flush remainder"
321 position += emptyCount;
322 }
323 if (i < V.size.x - 1)
324 position += "/"; //separate rows
325 }
326 return position;
327 }
328
329 // Flags part of the FEN string
330 getFlagsFen()
331 {
332 let flags = "";
333 // Add castling flags
334 for (let i of ['w','b'])
335 {
336 for (let j=0; j<2; j++)
337 flags += (this.castleFlags[i][j] ? '1' : '0');
338 }
339 return flags;
340 }
341
342 // Enpassant part of the FEN string
343 getEnpassantFen()
344 {
345 const L = this.epSquares.length;
346 if (!this.epSquares[L-1])
347 return "-"; //no en-passant
348 return V.CoordsToSquare(this.epSquares[L-1]);
349 }
350
351 // Turn position fen into double array ["wb","wp","bk",...]
352 static GetBoard(position)
353 {
354 const rows = position.split("/");
355 let board = doubleArray(V.size.x, V.size.y, "");
356 for (let i=0; i<rows.length; i++)
357 {
358 let j = 0;
359 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
360 {
361 const character = rows[i][indexInRow];
362 const num = parseInt(character);
363 if (!isNaN(num))
364 j += num; //just shift j
365 else //something at position i,j
366 board[i][j++] = V.fen2board(character);
367 }
368 }
369 return board;
370 }
371
372 // Extract (relevant) flags from fen
373 setFlags(fenflags)
374 {
375 // white a-castle, h-castle, black a-castle, h-castle
376 this.castleFlags = {'w': [true,true], 'b': [true,true]};
377 if (!fenflags)
378 return;
379 for (let i=0; i<4; i++)
380 this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (fenflags.charAt(i) == '1');
381 }
382
383 //////////////////
384 // INITIALIZATION
385
386 // Fen string fully describes the game state
387 constructor(fen, moves)
388 {
389 this.moves = moves;
390 const fenParsed = V.ParseFen(fen);
391 this.board = V.GetBoard(fenParsed.position);
392 this.turn = (fenParsed.turn || "w");
393 this.setOtherVariables(fen);
394 }
395
396 // Scan board for kings and rooks positions
397 scanKingsRooks(fen)
398 {
399 this.INIT_COL_KING = {'w':-1, 'b':-1};
400 this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
401 this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
402 const fenRows = V.ParseFen(fen).position.split("/");
403 for (let i=0; i<fenRows.length; i++)
404 {
405 let k = 0; //column index on board
406 for (let j=0; j<fenRows[i].length; j++)
407 {
408 switch (fenRows[i].charAt(j))
409 {
410 case 'k':
411 this.kingPos['b'] = [i,k];
412 this.INIT_COL_KING['b'] = k;
413 break;
414 case 'K':
415 this.kingPos['w'] = [i,k];
416 this.INIT_COL_KING['w'] = k;
417 break;
418 case 'r':
419 if (this.INIT_COL_ROOK['b'][0] < 0)
420 this.INIT_COL_ROOK['b'][0] = k;
421 else
422 this.INIT_COL_ROOK['b'][1] = k;
423 break;
424 case 'R':
425 if (this.INIT_COL_ROOK['w'][0] < 0)
426 this.INIT_COL_ROOK['w'][0] = k;
427 else
428 this.INIT_COL_ROOK['w'][1] = k;
429 break;
430 default:
431 const num = parseInt(fenRows[i].charAt(j));
432 if (!isNaN(num))
433 k += (num-1);
434 }
435 k++;
436 }
437 }
438 }
439
440 // Some additional variables from FEN (variant dependant)
441 setOtherVariables(fen)
442 {
443 // Set flags and enpassant:
444 const parsedFen = V.ParseFen(fen);
445 if (V.HasFlags)
446 this.setFlags(parsedFen.flags);
447 if (V.HasEnpassant)
448 {
449 const epSq = parsedFen.enpassant != "-"
450 ? V.SquareToCoords(parsedFen.enpassant)
451 : undefined;
452 this.epSquares = [ epSq ];
453 }
454 // Search for king and rooks positions:
455 this.scanKingsRooks(fen);
456 }
457
458 /////////////////////
459 // GETTERS & SETTERS
460
461 static get size()
462 {
463 return {x:8, y:8};
464 }
465
466 // Color of thing on suqare (i,j). 'undefined' if square is empty
467 getColor(i,j)
468 {
469 return this.board[i][j].charAt(0);
470 }
471
472 // Piece type on square (i,j). 'undefined' if square is empty
473 getPiece(i,j)
474 {
475 return this.board[i][j].charAt(1);
476 }
477
478 // Get opponent color
479 getOppCol(color)
480 {
481 return (color=="w" ? "b" : "w");
482 }
483
484 get lastMove()
485 {
486 const L = this.moves.length;
487 return (L>0 ? this.moves[L-1] : null);
488 }
489
490 // Pieces codes (for a clearer code)
491 static get PAWN() { return 'p'; }
492 static get ROOK() { return 'r'; }
493 static get KNIGHT() { return 'n'; }
494 static get BISHOP() { return 'b'; }
495 static get QUEEN() { return 'q'; }
496 static get KING() { return 'k'; }
497
498 // For FEN checking:
499 static get PIECES()
500 {
501 return [V.PAWN,V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN,V.KING];
502 }
503
504 // Empty square
505 static get EMPTY() { return ""; }
506
507 // Some pieces movements
508 static get steps()
509 {
510 return {
511 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
512 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
513 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
514 };
515 }
516
517 ////////////////////
518 // MOVES GENERATION
519
520 // All possible moves from selected square (assumption: color is OK)
521 getPotentialMovesFrom([x,y])
522 {
523 switch (this.getPiece(x,y))
524 {
525 case V.PAWN:
526 return this.getPotentialPawnMoves([x,y]);
527 case V.ROOK:
528 return this.getPotentialRookMoves([x,y]);
529 case V.KNIGHT:
530 return this.getPotentialKnightMoves([x,y]);
531 case V.BISHOP:
532 return this.getPotentialBishopMoves([x,y]);
533 case V.QUEEN:
534 return this.getPotentialQueenMoves([x,y]);
535 case V.KING:
536 return this.getPotentialKingMoves([x,y]);
537 }
538 }
539
540 // Build a regular move from its initial and destination squares.
541 // tr: transformation
542 getBasicMove([sx,sy], [ex,ey], tr)
543 {
544 let mv = new Move({
545 appear: [
546 new PiPo({
547 x: ex,
548 y: ey,
549 c: !!tr ? tr.c : this.getColor(sx,sy),
550 p: !!tr ? tr.p : this.getPiece(sx,sy)
551 })
552 ],
553 vanish: [
554 new PiPo({
555 x: sx,
556 y: sy,
557 c: this.getColor(sx,sy),
558 p: this.getPiece(sx,sy)
559 })
560 ]
561 });
562
563 // The opponent piece disappears if we take it
564 if (this.board[ex][ey] != V.EMPTY)
565 {
566 mv.vanish.push(
567 new PiPo({
568 x: ex,
569 y: ey,
570 c: this.getColor(ex,ey),
571 p: this.getPiece(ex,ey)
572 })
573 );
574 }
575 return mv;
576 }
577
578 // Generic method to find possible moves of non-pawn pieces:
579 // "sliding or jumping"
580 getSlideNJumpMoves([x,y], steps, oneStep)
581 {
582 const color = this.getColor(x,y);
583 let moves = [];
584 outerLoop:
585 for (let step of steps)
586 {
587 let i = x + step[0];
588 let j = y + step[1];
589 while (V.OnBoard(i,j) && this.board[i][j] == V.EMPTY)
590 {
591 moves.push(this.getBasicMove([x,y], [i,j]));
592 if (oneStep !== undefined)
593 continue outerLoop;
594 i += step[0];
595 j += step[1];
596 }
597 if (V.OnBoard(i,j) && this.canTake([x,y], [i,j]))
598 moves.push(this.getBasicMove([x,y], [i,j]));
599 }
600 return moves;
601 }
602
603 // What are the pawn moves from square x,y ?
604 getPotentialPawnMoves([x,y])
605 {
606 const color = this.turn;
607 let moves = [];
608 const [sizeX,sizeY] = [V.size.x,V.size.y];
609 const shiftX = (color == "w" ? -1 : 1);
610 const firstRank = (color == 'w' ? sizeX-1 : 0);
611 const startRank = (color == "w" ? sizeX-2 : 1);
612 const lastRank = (color == "w" ? 0 : sizeX-1);
613 const pawnColor = this.getColor(x,y); //can be different for checkered
614
615 if (x+shiftX >= 0 && x+shiftX < sizeX) //TODO: always true
616 {
617 const finalPieces = x + shiftX == lastRank
618 ? [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN]
619 : [V.PAWN]
620 // One square forward
621 if (this.board[x+shiftX][y] == V.EMPTY)
622 {
623 for (let piece of finalPieces)
624 {
625 moves.push(this.getBasicMove([x,y], [x+shiftX,y],
626 {c:pawnColor,p:piece}));
627 }
628 // Next condition because pawns on 1st rank can generally jump
629 if ([startRank,firstRank].includes(x)
630 && this.board[x+2*shiftX][y] == V.EMPTY)
631 {
632 // Two squares jump
633 moves.push(this.getBasicMove([x,y], [x+2*shiftX,y]));
634 }
635 }
636 // Captures
637 for (let shiftY of [-1,1])
638 {
639 if (y + shiftY >= 0 && y + shiftY < sizeY
640 && this.board[x+shiftX][y+shiftY] != V.EMPTY
641 && this.canTake([x,y], [x+shiftX,y+shiftY]))
642 {
643 for (let piece of finalPieces)
644 {
645 moves.push(this.getBasicMove([x,y], [x+shiftX,y+shiftY],
646 {c:pawnColor,p:piece}));
647 }
648 }
649 }
650 }
651
652 if (V.HasEnpassant)
653 {
654 // En passant
655 const Lep = this.epSquares.length;
656 const epSquare = this.epSquares[Lep-1]; //always at least one element
657 if (!!epSquare && epSquare.x == x+shiftX && Math.abs(epSquare.y - y) == 1)
658 {
659 let enpassantMove = this.getBasicMove([x,y], [epSquare.x,epSquare.y]);
660 enpassantMove.vanish.push({
661 x: x,
662 y: epSquare.y,
663 p: 'p',
664 c: this.getColor(x,epSquare.y)
665 });
666 moves.push(enpassantMove);
667 }
668 }
669
670 return moves;
671 }
672
673 // What are the rook moves from square x,y ?
674 getPotentialRookMoves(sq)
675 {
676 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
677 }
678
679 // What are the knight moves from square x,y ?
680 getPotentialKnightMoves(sq)
681 {
682 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
683 }
684
685 // What are the bishop moves from square x,y ?
686 getPotentialBishopMoves(sq)
687 {
688 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
689 }
690
691 // What are the queen moves from square x,y ?
692 getPotentialQueenMoves(sq)
693 {
694 return this.getSlideNJumpMoves(sq,
695 V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
696 }
697
698 // What are the king moves from square x,y ?
699 getPotentialKingMoves(sq)
700 {
701 // Initialize with normal moves
702 let moves = this.getSlideNJumpMoves(sq,
703 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
704 return moves.concat(this.getCastleMoves(sq));
705 }
706
707 getCastleMoves([x,y])
708 {
709 const c = this.getColor(x,y);
710 if (x != (c=="w" ? V.size.x-1 : 0) || y != this.INIT_COL_KING[c])
711 return []; //x isn't first rank, or king has moved (shortcut)
712
713 // Castling ?
714 const oppCol = this.getOppCol(c);
715 let moves = [];
716 let i = 0;
717 const finalSquares = [ [2,3], [V.size.y-2,V.size.y-3] ]; //king, then rook
718 castlingCheck:
719 for (let castleSide=0; castleSide < 2; castleSide++) //large, then small
720 {
721 if (!this.castleFlags[c][castleSide])
722 continue;
723 // If this code is reached, rooks and king are on initial position
724
725 // Nothing on the path of the king ?
726 // (And no checks; OK also if y==finalSquare)
727 let step = finalSquares[castleSide][0] < y ? -1 : 1;
728 for (i=y; i!=finalSquares[castleSide][0]; i+=step)
729 {
730 if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY &&
731 // NOTE: next check is enough, because of chessboard constraints
732 (this.getColor(x,i) != c
733 || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
734 {
735 continue castlingCheck;
736 }
737 }
738
739 // Nothing on the path to the rook?
740 step = castleSide == 0 ? -1 : 1;
741 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step)
742 {
743 if (this.board[x][i] != V.EMPTY)
744 continue castlingCheck;
745 }
746 const rookPos = this.INIT_COL_ROOK[c][castleSide];
747
748 // Nothing on final squares, except maybe king and castling rook?
749 for (i=0; i<2; i++)
750 {
751 if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
752 this.getPiece(x,finalSquares[castleSide][i]) != V.KING &&
753 finalSquares[castleSide][i] != rookPos)
754 {
755 continue castlingCheck;
756 }
757 }
758
759 // If this code is reached, castle is valid
760 moves.push( new Move({
761 appear: [
762 new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}),
763 new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})],
764 vanish: [
765 new PiPo({x:x,y:y,p:V.KING,c:c}),
766 new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})],
767 end: Math.abs(y - rookPos) <= 2
768 ? {x:x, y:rookPos}
769 : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)}
770 }) );
771 }
772
773 return moves;
774 }
775
776 ////////////////////
777 // MOVES VALIDATION
778
779 // For the interface: possible moves for the current turn from square sq
780 getPossibleMovesFrom(sq)
781 {
782 return this.filterValid( this.getPotentialMovesFrom(sq) );
783 }
784
785 // TODO: promotions (into R,B,N,Q) should be filtered only once
786 filterValid(moves)
787 {
788 if (moves.length == 0)
789 return [];
790 const color = this.turn;
791 return moves.filter(m => {
792 this.play(m);
793 const res = !this.underCheck(color);
794 this.undo(m);
795 return res;
796 });
797 }
798
799 // Search for all valid moves considering current turn
800 // (for engine and game end)
801 getAllValidMoves()
802 {
803 const color = this.turn;
804 const oppCol = this.getOppCol(color);
805 let potentialMoves = [];
806 for (let i=0; i<V.size.x; i++)
807 {
808 for (let j=0; j<V.size.y; j++)
809 {
810 // Next condition "!= oppCol" to work with checkered variant
811 if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol)
812 {
813 Array.prototype.push.apply(potentialMoves,
814 this.getPotentialMovesFrom([i,j]));
815 }
816 }
817 }
818 return this.filterValid(potentialMoves);
819 }
820
821 // Stop at the first move found
822 atLeastOneMove()
823 {
824 const color = this.turn;
825 const oppCol = this.getOppCol(color);
826 for (let i=0; i<V.size.x; i++)
827 {
828 for (let j=0; j<V.size.y; j++)
829 {
830 if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol)
831 {
832 const moves = this.getPotentialMovesFrom([i,j]);
833 if (moves.length > 0)
834 {
835 for (let k=0; k<moves.length; k++)
836 {
837 if (this.filterValid([moves[k]]).length > 0)
838 return true;
839 }
840 }
841 }
842 }
843 }
844 return false;
845 }
846
847 // Check if pieces of color in 'colors' are attacking (king) on square x,y
848 isAttacked(sq, colors)
849 {
850 return (this.isAttackedByPawn(sq, colors)
851 || this.isAttackedByRook(sq, colors)
852 || this.isAttackedByKnight(sq, colors)
853 || this.isAttackedByBishop(sq, colors)
854 || this.isAttackedByQueen(sq, colors)
855 || this.isAttackedByKing(sq, colors));
856 }
857
858 // Is square x,y attacked by 'colors' pawns ?
859 isAttackedByPawn([x,y], colors)
860 {
861 for (let c of colors)
862 {
863 let pawnShift = (c=="w" ? 1 : -1);
864 if (x+pawnShift>=0 && x+pawnShift<V.size.x)
865 {
866 for (let i of [-1,1])
867 {
868 if (y+i>=0 && y+i<V.size.y && this.getPiece(x+pawnShift,y+i)==V.PAWN
869 && this.getColor(x+pawnShift,y+i)==c)
870 {
871 return true;
872 }
873 }
874 }
875 }
876 return false;
877 }
878
879 // Is square x,y attacked by 'colors' rooks ?
880 isAttackedByRook(sq, colors)
881 {
882 return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
883 }
884
885 // Is square x,y attacked by 'colors' knights ?
886 isAttackedByKnight(sq, colors)
887 {
888 return this.isAttackedBySlideNJump(sq, colors,
889 V.KNIGHT, V.steps[V.KNIGHT], "oneStep");
890 }
891
892 // Is square x,y attacked by 'colors' bishops ?
893 isAttackedByBishop(sq, colors)
894 {
895 return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]);
896 }
897
898 // Is square x,y attacked by 'colors' queens ?
899 isAttackedByQueen(sq, colors)
900 {
901 return this.isAttackedBySlideNJump(sq, colors, V.QUEEN,
902 V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
903 }
904
905 // Is square x,y attacked by 'colors' king(s) ?
906 isAttackedByKing(sq, colors)
907 {
908 return this.isAttackedBySlideNJump(sq, colors, V.KING,
909 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
910 }
911
912 // Generic method for non-pawn pieces ("sliding or jumping"):
913 // is x,y attacked by a piece of color in array 'colors' ?
914 isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
915 {
916 for (let step of steps)
917 {
918 let rx = x+step[0], ry = y+step[1];
919 while (V.OnBoard(rx,ry) && this.board[rx][ry] == V.EMPTY && !oneStep)
920 {
921 rx += step[0];
922 ry += step[1];
923 }
924 if (V.OnBoard(rx,ry) && this.getPiece(rx,ry) === piece
925 && colors.includes(this.getColor(rx,ry)))
926 {
927 return true;
928 }
929 }
930 return false;
931 }
932
933 // Is color under check after his move ?
934 underCheck(color)
935 {
936 return this.isAttacked(this.kingPos[color], [this.getOppCol(color)]);
937 }
938
939 /////////////////
940 // MOVES PLAYING
941
942 // Apply a move on board
943 static PlayOnBoard(board, move)
944 {
945 for (let psq of move.vanish)
946 board[psq.x][psq.y] = V.EMPTY;
947 for (let psq of move.appear)
948 board[psq.x][psq.y] = psq.c + psq.p;
949 }
950 // Un-apply the played move
951 static UndoOnBoard(board, move)
952 {
953 for (let psq of move.appear)
954 board[psq.x][psq.y] = V.EMPTY;
955 for (let psq of move.vanish)
956 board[psq.x][psq.y] = psq.c + psq.p;
957 }
958
959 // After move is played, update variables + flags
960 updateVariables(move)
961 {
962 const piece = move.vanish[0].p;
963 const c = this.getOppCol(this.turn); //'move.vanish[0].c' doesn't work for Checkered
964 const firstRank = (c == "w" ? V.size.x-1 : 0);
965
966 // Update king position + flags
967 if (piece == V.KING && move.appear.length > 0)
968 {
969 this.kingPos[c][0] = move.appear[0].x;
970 this.kingPos[c][1] = move.appear[0].y;
971 this.castleFlags[c] = [false,false];
972 return;
973 }
974 const oppCol = this.getOppCol(c);
975 const oppFirstRank = (V.size.x-1) - firstRank;
976 if (move.start.x == firstRank //our rook moves?
977 && this.INIT_COL_ROOK[c].includes(move.start.y))
978 {
979 const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
980 this.castleFlags[c][flagIdx] = false;
981 }
982 else if (move.end.x == oppFirstRank //we took opponent rook?
983 && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
984 {
985 const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
986 this.castleFlags[oppCol][flagIdx] = false;
987 }
988 }
989
990 // After move is undo-ed *and flags resetted*, un-update other variables
991 // TODO: more symmetry, by storing flags increment in move (?!)
992 unupdateVariables(move)
993 {
994 // (Potentially) Reset king position
995 const c = this.getColor(move.start.x,move.start.y);
996 if (this.getPiece(move.start.x,move.start.y) == V.KING)
997 this.kingPos[c] = [move.start.x, move.start.y];
998 }
999
1000 play(move, ingame)
1001 {
1002 // DEBUG:
1003 // if (!this.states) this.states = [];
1004 // if (!ingame) this.states.push(this.getFen());
1005
1006 if (!!ingame)
1007 move.notation = [this.getNotation(move), this.getLongNotation(move)];
1008
1009 if (V.HasFlags)
1010 move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo)
1011 if (V.HasEnpassant)
1012 this.epSquares.push( this.getEpSquare(move) );
1013 V.PlayOnBoard(this.board, move);
1014 this.turn = this.getOppCol(this.turn);
1015 this.moves.push(move);
1016 this.updateVariables(move);
1017
1018 if (!!ingame)
1019 {
1020 // Hash of current game state *after move*, to detect repetitions
1021 move.hash = hex_md5(this.getFen());
1022 }
1023 }
1024
1025 undo(move)
1026 {
1027 if (V.HasEnpassant)
1028 this.epSquares.pop();
1029 if (V.HasFlags)
1030 this.disaggregateFlags(JSON.parse(move.flags));
1031 V.UndoOnBoard(this.board, move);
1032 this.turn = this.getOppCol(this.turn);
1033 this.moves.pop();
1034 this.unupdateVariables(move);
1035
1036 // DEBUG:
1037 // if (this.getFen() != this.states[this.states.length-1])
1038 // debugger;
1039 // this.states.pop();
1040 }
1041
1042 ///////////////
1043 // END OF GAME
1044
1045 // Check for 3 repetitions (position + flags + turn)
1046 checkRepetition()
1047 {
1048 if (!this.hashStates)
1049 this.hashStates = {};
1050 const startIndex =
1051 Object.values(this.hashStates).reduce((a,b) => { return a+b; }, 0)
1052 // Update this.hashStates with last move (or all moves if continuation)
1053 // NOTE: redundant storage, but faster and moderate size
1054 for (let i=startIndex; i<this.moves.length; i++)
1055 {
1056 const move = this.moves[i];
1057 if (!this.hashStates[move.hash])
1058 this.hashStates[move.hash] = 1;
1059 else
1060 this.hashStates[move.hash]++;
1061 }
1062 return Object.values(this.hashStates).some(elt => { return (elt >= 3); });
1063 }
1064
1065 // Is game over ? And if yes, what is the score ?
1066 checkGameOver()
1067 {
1068 if (this.checkRepetition())
1069 return "1/2";
1070
1071 if (this.atLeastOneMove()) // game not over
1072 return "*";
1073
1074 // Game over
1075 return this.checkGameEnd();
1076 }
1077
1078 // No moves are possible: compute score
1079 checkGameEnd()
1080 {
1081 const color = this.turn;
1082 // No valid move: stalemate or checkmate?
1083 if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
1084 return "1/2";
1085 // OK, checkmate
1086 return color == "w" ? "0-1" : "1-0";
1087 }
1088
1089 ///////////////
1090 // ENGINE PLAY
1091
1092 // Pieces values
1093 static get VALUES()
1094 {
1095 return {
1096 'p': 1,
1097 'r': 5,
1098 'n': 3,
1099 'b': 3,
1100 'q': 9,
1101 'k': 1000
1102 };
1103 }
1104
1105 // "Checkmate" (unreachable eval)
1106 static get INFINITY() { return 9999; }
1107
1108 // At this value or above, the game is over
1109 static get THRESHOLD_MATE() { return V.INFINITY; }
1110
1111 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1112 static get SEARCH_DEPTH() { return 3; }
1113
1114 // Assumption: at least one legal move
1115 // NOTE: works also for extinction chess because depth is 3...
1116 getComputerMove()
1117 {
1118 const maxeval = V.INFINITY;
1119 const color = this.turn;
1120 // Some variants may show a bigger moves list to the human (Switching),
1121 // thus the argument "computer" below (which is generally ignored)
1122 let moves1 = this.getAllValidMoves("computer");
1123
1124 // Can I mate in 1 ? (for Magnetic & Extinction)
1125 for (let i of _.shuffle(_.range(moves1.length)))
1126 {
1127 this.play(moves1[i]);
1128 let finish = (Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE);
1129 if (!finish && !this.atLeastOneMove())
1130 {
1131 // Test mate (for other variants)
1132 const score = this.checkGameEnd();
1133 if (score != "1/2")
1134 finish = true;
1135 }
1136 this.undo(moves1[i]);
1137 if (finish)
1138 return moves1[i];
1139 }
1140
1141 // Rank moves using a min-max at depth 2
1142 for (let i=0; i<moves1.length; i++)
1143 {
1144 // Initial self evaluation is very low: "I'm checkmated"
1145 moves1[i].eval = (color=="w" ? -1 : 1) * maxeval;
1146 this.play(moves1[i]);
1147 let eval2 = undefined;
1148 if (this.atLeastOneMove())
1149 {
1150 // Initial enemy evaluation is very low too, for him
1151 eval2 = (color=="w" ? 1 : -1) * maxeval;
1152 // Second half-move:
1153 let moves2 = this.getAllValidMoves("computer");
1154 for (let j=0; j<moves2.length; j++)
1155 {
1156 this.play(moves2[j]);
1157 let evalPos = undefined;
1158 if (this.atLeastOneMove())
1159 evalPos = this.evalPosition()
1160 else
1161 {
1162 // Working with scores is more accurate (necessary for Loser variant)
1163 const score = this.checkGameEnd();
1164 evalPos = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1165 }
1166 if ((color == "w" && evalPos < eval2)
1167 || (color=="b" && evalPos > eval2))
1168 {
1169 eval2 = evalPos;
1170 }
1171 this.undo(moves2[j]);
1172 }
1173 }
1174 else
1175 {
1176 const score = this.checkGameEnd();
1177 eval2 = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1178 }
1179 if ((color=="w" && eval2 > moves1[i].eval)
1180 || (color=="b" && eval2 < moves1[i].eval))
1181 {
1182 moves1[i].eval = eval2;
1183 }
1184 this.undo(moves1[i]);
1185 }
1186 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
1187
1188 let candidates = [0]; //indices of candidates moves
1189 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
1190 candidates.push(j);
1191 let currentBest = moves1[_.sample(candidates, 1)];
1192
1193 // From here, depth >= 3: may take a while, so we control time
1194 const timeStart = Date.now();
1195
1196 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1197 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE)
1198 {
1199 for (let i=0; i<moves1.length; i++)
1200 {
1201 if (Date.now()-timeStart >= 5000) //more than 5 seconds
1202 return currentBest; //depth 2 at least
1203 this.play(moves1[i]);
1204 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1205 moves1[i].eval = 0.1*moves1[i].eval +
1206 this.alphabeta(V.SEARCH_DEPTH-1, -maxeval, maxeval);
1207 this.undo(moves1[i]);
1208 }
1209 moves1.sort( (a,b) => {
1210 return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
1211 }
1212 else
1213 return currentBest;
1214 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1215
1216 candidates = [0];
1217 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
1218 candidates.push(j);
1219 return moves1[_.sample(candidates, 1)];
1220 }
1221
1222 alphabeta(depth, alpha, beta)
1223 {
1224 const maxeval = V.INFINITY;
1225 const color = this.turn;
1226 if (!this.atLeastOneMove())
1227 {
1228 switch (this.checkGameEnd())
1229 {
1230 case "1/2":
1231 return 0;
1232 default:
1233 const score = this.checkGameEnd();
1234 return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1235 }
1236 }
1237 if (depth == 0)
1238 return this.evalPosition();
1239 const moves = this.getAllValidMoves("computer");
1240 let v = color=="w" ? -maxeval : maxeval;
1241 if (color == "w")
1242 {
1243 for (let i=0; i<moves.length; i++)
1244 {
1245 this.play(moves[i]);
1246 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
1247 this.undo(moves[i]);
1248 alpha = Math.max(alpha, v);
1249 if (alpha >= beta)
1250 break; //beta cutoff
1251 }
1252 }
1253 else //color=="b"
1254 {
1255 for (let i=0; i<moves.length; i++)
1256 {
1257 this.play(moves[i]);
1258 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
1259 this.undo(moves[i]);
1260 beta = Math.min(beta, v);
1261 if (alpha >= beta)
1262 break; //alpha cutoff
1263 }
1264 }
1265 return v;
1266 }
1267
1268 evalPosition()
1269 {
1270 let evaluation = 0;
1271 // Just count material for now
1272 for (let i=0; i<V.size.x; i++)
1273 {
1274 for (let j=0; j<V.size.y; j++)
1275 {
1276 if (this.board[i][j] != V.EMPTY)
1277 {
1278 const sign = this.getColor(i,j) == "w" ? 1 : -1;
1279 evaluation += sign * V.VALUES[this.getPiece(i,j)];
1280 }
1281 }
1282 }
1283 return evaluation;
1284 }
1285
1286 /////////////////////////
1287 // MOVES + GAME NOTATION
1288 /////////////////////////
1289
1290 // Context: just before move is played, turn hasn't changed
1291 getNotation(move)
1292 {
1293 if (move.appear.length == 2 && move.appear[0].p == V.KING) //castle
1294 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
1295
1296 // Translate final square
1297 const finalSquare = V.CoordsToSquare(move.end);
1298
1299 const piece = this.getPiece(move.start.x, move.start.y);
1300 if (piece == V.PAWN)
1301 {
1302 // Pawn move
1303 let notation = "";
1304 if (move.vanish.length > move.appear.length)
1305 {
1306 // Capture
1307 const startColumn = V.CoordToColumn(move.start.y);
1308 notation = startColumn + "x" + finalSquare;
1309 }
1310 else //no capture
1311 notation = finalSquare;
1312 if (move.appear.length > 0 && move.appear[0].p != V.PAWN) //promotion
1313 notation += "=" + move.appear[0].p.toUpperCase();
1314 return notation;
1315 }
1316
1317 else
1318 {
1319 // Piece movement
1320 return piece.toUpperCase() +
1321 (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
1322 }
1323 }
1324
1325 // Complete the usual notation, may be required for de-ambiguification
1326 getLongNotation(move)
1327 {
1328 // Not encoding move. But short+long is enough
1329 return V.CoordsToSquare(move.start) + V.CoordsToSquare(move.end);
1330 }
1331
1332 // The score is already computed when calling this function
1333 getPGN(mycolor, score, fenStart, mode)
1334 {
1335 let pgn = "";
1336 pgn += '[Site "vchess.club"]<br>';
1337 const opponent = mode=="human" ? "Anonymous" : "Computer";
1338 pgn += '[Variant "' + variant + '"]<br>';
1339 pgn += '[Date "' + getDate(new Date()) + '"]<br>';
1340 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1341 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
1342 pgn += '[FenStart "' + fenStart + '"]<br>';
1343 pgn += '[Fen "' + this.getFen() + '"]<br>';
1344 pgn += '[Result "' + score + '"]<br><br>';
1345
1346 // Standard PGN
1347 for (let i=0; i<this.moves.length; i++)
1348 {
1349 if (i % 2 == 0)
1350 pgn += ((i/2)+1) + ".";
1351 pgn += this.moves[i].notation[0] + " ";
1352 }
1353 pgn += "<br><br>";
1354
1355 // "Complete moves" PGN (helping in ambiguous cases)
1356 for (let i=0; i<this.moves.length; i++)
1357 {
1358 if (i % 2 == 0)
1359 pgn += ((i/2)+1) + ".";
1360 pgn += this.moves[i].notation[1] + " ";
1361 }
1362
1363 return pgn;
1364 }
1365 }