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