1 // (Orthodox) Chess rules are defined in ChessRules class.
2 // Variants generally inherit from it, and modify some parts.
4 class PiPo
//Piece+Position
6 // o: {piece[p], color[c], posX[x], posY[y]}
16 // TODO: for animation, moves should contains "moving" and "fading" maybe...
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
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
};
31 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
37 static get HasFlags() { return true; } //some variants don't have flags
39 static get HasEnpassant() { return true; } //some variants don't have ep.
44 return b
; //usual pieces in pieces/ folder
47 // Turn "wb" into "B" (for FEN)
50 return b
[0]=='w' ? b
[1].toUpperCase() : b
[1];
53 // Turn "p" into "bp" (for board)
56 return f
.charCodeAt()<=90 ? "w"+f
.toLowerCase() : "b"+f
;
59 // Check if FEN describe a position
62 const fenParsed
= V
.ParseFen(fen
);
64 if (!V
.IsGoodPosition(fenParsed
.position
))
67 if (!fenParsed
.turn
|| !V
.IsGoodTurn(fenParsed
.turn
))
70 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
74 (!fenParsed
.enpassant
|| !V
.IsGoodEnpassant(fenParsed
.enpassant
)))
81 // Is position part of the FEN a priori correct?
82 static IsGoodPosition(position
)
84 if (position
.length
== 0)
86 const rows
= position
.split("/");
87 if (rows
.length
!= V
.size
.x
)
92 for (let i
=0; i
<row
.length
; i
++)
94 if (V
.PIECES
.includes(row
[i
].toLowerCase()))
98 const num
= parseInt(row
[i
]);
104 if (sumElts
!= V
.size
.y
)
111 static IsGoodTurn(turn
)
113 return ["w","b"].includes(turn
);
117 static IsGoodFlags(flags
)
119 return !!flags
.match(/^[01]{4,4}$/);
122 static IsGoodEnpassant(enpassant
)
124 if (enpassant
!= "-")
126 const ep
= V
.SquareToCoords(fenParsed
.enpassant
);
127 if (isNaN(ep
.x
) || !V
.OnBoard(ep
))
133 // 3 --> d (column number to letter)
134 static CoordToColumn(colnum
)
136 return String
.fromCharCode(97 + colnum
);
139 // d --> 3 (column letter to number)
140 static ColumnToCoord(column
)
142 return column
.charCodeAt(0) - 97;
146 static SquareToCoords(sq
)
149 // NOTE: column is always one char => max 26 columns
150 // row is counted from black side => subtraction
151 x: V
.size
.x
- parseInt(sq
.substr(1)),
152 y: sq
[0].charCodeAt() - 97
157 static CoordsToSquare(coords
)
159 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
162 // Aggregates flags into one object
165 return this.castleFlags
;
169 disaggregateFlags(flags
)
171 this.castleFlags
= flags
;
174 // En-passant square, if any
175 getEpSquare(moveOrSquare
)
179 if (typeof moveOrSquare
=== "string")
181 const square
= moveOrSquare
;
184 return V
.SquareToCoords(square
);
186 // Argument is a move:
187 const move = moveOrSquare
;
188 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
189 if (move.appear
[0].p
== V
.PAWN
&& Math
.abs(sx
- ex
) == 2)
196 return undefined; //default
199 // Can thing on square1 take thing on square2
200 canTake([x1
,y1
], [x2
,y2
])
202 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
205 // Is (x,y) on the chessboard?
208 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
211 // Used in interface: 'side' arg == player color
212 canIplay(side
, [x
,y
])
214 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
217 // On which squares is color under check ? (for interface)
218 getCheckSquares(color
)
220 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
221 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
228 // Setup the initial random (assymetric) position
229 static GenRandInitFen()
231 let pieces
= { "w": new Array(8), "b": new Array(8) };
232 // Shuffle pieces on first and last rank
233 for (let c
of ["w","b"])
235 let positions
= _
.range(8);
237 // Get random squares for bishops
238 let randIndex
= 2 * _
.random(3);
239 const bishop1Pos
= positions
[randIndex
];
240 // The second bishop must be on a square of different color
241 let randIndex_tmp
= 2 * _
.random(3) + 1;
242 const bishop2Pos
= positions
[randIndex_tmp
];
243 // Remove chosen squares
244 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
245 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
247 // Get random squares for knights
248 randIndex
= _
.random(5);
249 const knight1Pos
= positions
[randIndex
];
250 positions
.splice(randIndex
, 1);
251 randIndex
= _
.random(4);
252 const knight2Pos
= positions
[randIndex
];
253 positions
.splice(randIndex
, 1);
255 // Get random square for queen
256 randIndex
= _
.random(3);
257 const queenPos
= positions
[randIndex
];
258 positions
.splice(randIndex
, 1);
260 // Rooks and king positions are now fixed,
261 // because of the ordering rook-king-rook
262 const rook1Pos
= positions
[0];
263 const kingPos
= positions
[1];
264 const rook2Pos
= positions
[2];
266 // Finally put the shuffled pieces in the board array
267 pieces
[c
][rook1Pos
] = 'r';
268 pieces
[c
][knight1Pos
] = 'n';
269 pieces
[c
][bishop1Pos
] = 'b';
270 pieces
[c
][queenPos
] = 'q';
271 pieces
[c
][kingPos
] = 'k';
272 pieces
[c
][bishop2Pos
] = 'b';
273 pieces
[c
][knight2Pos
] = 'n';
274 pieces
[c
][rook2Pos
] = 'r';
276 return pieces
["b"].join("") +
277 "/pppppppp/8/8/8/8/PPPPPPPP/" +
278 pieces
["w"].join("").toUpperCase() +
279 " w 1111 -"; //add turn + flags + enpassant
282 // "Parse" FEN: just return untransformed string data
285 const fenParts
= fen
.split(" ");
288 position: fenParts
[0],
293 Object
.assign(res
, {flags: fenParts
[nextIdx
++]});
295 Object
.assign(res
, {enpassant: fenParts
[nextIdx
]});
299 // Return current fen (game state)
302 return this.getBaseFen() + " " + this.getTurnFen() +
303 (V
.HasFlags
? (" " + this.getFlagsFen()) : "") +
304 (V
.HasEnpassant
? (" " + this.getEnpassantFen()) : "");
307 // Position part of the FEN string
311 for (let i
=0; i
<V
.size
.x
; i
++)
314 for (let j
=0; j
<V
.size
.y
; j
++)
316 if (this.board
[i
][j
] == V
.EMPTY
)
322 // Add empty squares in-between
323 position
+= emptyCount
;
326 position
+= V
.board2fen(this.board
[i
][j
]);
332 position
+= emptyCount
;
334 if (i
< V
.size
.x
- 1)
335 position
+= "/"; //separate rows
345 // Flags part of the FEN string
349 // Add castling flags
350 for (let i
of ['w','b'])
352 for (let j
=0; j
<2; j
++)
353 flags
+= (this.castleFlags
[i
][j
] ? '1' : '0');
358 // Enpassant part of the FEN string
361 const L
= this.epSquares
.length
;
362 if (!this.epSquares
[L
-1])
363 return "-"; //no en-passant
364 return V
.CoordsToSquare(this.epSquares
[L
-1]);
367 // Turn position fen into double array ["wb","wp","bk",...]
368 static GetBoard(position
)
370 const rows
= position
.split("/");
371 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
372 for (let i
=0; i
<rows
.length
; i
++)
375 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
377 const character
= rows
[i
][indexInRow
];
378 const num
= parseInt(character
);
380 j
+= num
; //just shift j
381 else //something at position i,j
382 board
[i
][j
++] = V
.fen2board(character
);
388 // Extract (relevant) flags from fen
391 // white a-castle, h-castle, black a-castle, h-castle
392 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
395 for (let i
=0; i
<4; i
++)
396 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
402 // Fen string fully describes the game state
403 constructor(fen
, moves
)
406 const fenParsed
= V
.ParseFen(fen
);
407 this.board
= V
.GetBoard(fenParsed
.position
);
408 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
409 this.setOtherVariables(fen
);
412 // Scan board for kings and rooks positions
415 this.INIT_COL_KING
= {'w':-1, 'b':-1};
416 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
417 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
418 const fenRows
= V
.ParseFen(fen
).position
.split("/");
419 for (let i
=0; i
<fenRows
.length
; i
++)
421 let k
= 0; //column index on board
422 for (let j
=0; j
<fenRows
[i
].length
; j
++)
424 switch (fenRows
[i
].charAt(j
))
427 this.kingPos
['b'] = [i
,k
];
428 this.INIT_COL_KING
['b'] = k
;
431 this.kingPos
['w'] = [i
,k
];
432 this.INIT_COL_KING
['w'] = k
;
435 if (this.INIT_COL_ROOK
['b'][0] < 0)
436 this.INIT_COL_ROOK
['b'][0] = k
;
438 this.INIT_COL_ROOK
['b'][1] = k
;
441 if (this.INIT_COL_ROOK
['w'][0] < 0)
442 this.INIT_COL_ROOK
['w'][0] = k
;
444 this.INIT_COL_ROOK
['w'][1] = k
;
447 const num
= parseInt(fenRows
[i
].charAt(j
));
456 // Some additional variables from FEN (variant dependant)
457 setOtherVariables(fen
)
459 // Set flags and enpassant:
460 const parsedFen
= V
.ParseFen(fen
);
462 this.setFlags(parsedFen
.flags
);
465 const epSq
= parsedFen
.enpassant
!= "-"
466 ? V
.SquareToCoords(parsedFen
.enpassant
)
468 this.epSquares
= [ epSq
];
470 // Search for king and rooks positions:
471 this.scanKingsRooks(fen
);
474 /////////////////////
482 // Color of thing on suqare (i,j). 'undefined' if square is empty
485 return this.board
[i
][j
].charAt(0);
488 // Piece type on square (i,j). 'undefined' if square is empty
491 return this.board
[i
][j
].charAt(1);
494 // Get opponent color
497 return (color
=="w" ? "b" : "w");
502 const L
= this.moves
.length
;
503 return (L
>0 ? this.moves
[L
-1] : null);
506 // Pieces codes (for a clearer code)
507 static get PAWN() { return 'p'; }
508 static get ROOK() { return 'r'; }
509 static get KNIGHT() { return 'n'; }
510 static get BISHOP() { return 'b'; }
511 static get QUEEN() { return 'q'; }
512 static get KING() { return 'k'; }
517 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
521 static get EMPTY() { return ""; }
523 // Some pieces movements
527 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
528 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
529 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
536 // All possible moves from selected square (assumption: color is OK)
537 getPotentialMovesFrom([x
,y
])
539 switch (this.getPiece(x
,y
))
542 return this.getPotentialPawnMoves([x
,y
]);
544 return this.getPotentialRookMoves([x
,y
]);
546 return this.getPotentialKnightMoves([x
,y
]);
548 return this.getPotentialBishopMoves([x
,y
]);
550 return this.getPotentialQueenMoves([x
,y
]);
552 return this.getPotentialKingMoves([x
,y
]);
556 // Build a regular move from its initial and destination squares.
557 // tr: transformation
558 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
565 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
566 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
573 c: this.getColor(sx
,sy
),
574 p: this.getPiece(sx
,sy
)
579 // The opponent piece disappears if we take it
580 if (this.board
[ex
][ey
] != V
.EMPTY
)
586 c: this.getColor(ex
,ey
),
587 p: this.getPiece(ex
,ey
)
594 // Generic method to find possible moves of non-pawn pieces:
595 // "sliding or jumping"
596 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
598 const color
= this.getColor(x
,y
);
601 for (let step
of steps
)
605 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
607 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
608 if (oneStep
!== undefined)
613 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
614 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
619 // What are the pawn moves from square x,y ?
620 getPotentialPawnMoves([x
,y
])
622 const color
= this.turn
;
624 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
625 const shiftX
= (color
== "w" ? -1 : 1);
626 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
627 const startRank
= (color
== "w" ? sizeX
-2 : 1);
628 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
629 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
631 // NOTE: next condition is generally true (no pawn on last rank)
632 if (x
+shiftX
>= 0 && x
+shiftX
< sizeX
)
634 const finalPieces
= x
+ shiftX
== lastRank
635 ? [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
]
637 // One square forward
638 if (this.board
[x
+shiftX
][y
] == V
.EMPTY
)
640 for (let piece
of finalPieces
)
642 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
],
643 {c:pawnColor
,p:piece
}));
645 // Next condition because pawns on 1st rank can generally jump
646 if ([startRank
,firstRank
].includes(x
)
647 && this.board
[x
+2*shiftX
][y
] == V
.EMPTY
)
650 moves
.push(this.getBasicMove([x
,y
], [x
+2*shiftX
,y
]));
654 for (let shiftY
of [-1,1])
656 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
657 && this.board
[x
+shiftX
][y
+shiftY
] != V
.EMPTY
658 && this.canTake([x
,y
], [x
+shiftX
,y
+shiftY
]))
660 for (let piece
of finalPieces
)
662 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
+shiftY
],
663 {c:pawnColor
,p:piece
}));
672 const Lep
= this.epSquares
.length
;
673 const epSquare
= this.epSquares
[Lep
-1]; //always at least one element
674 if (!!epSquare
&& epSquare
.x
== x
+shiftX
&& Math
.abs(epSquare
.y
- y
) == 1)
676 let enpassantMove
= this.getBasicMove([x
,y
], [epSquare
.x
,epSquare
.y
]);
677 enpassantMove
.vanish
.push({
681 c: this.getColor(x
,epSquare
.y
)
683 moves
.push(enpassantMove
);
690 // What are the rook moves from square x,y ?
691 getPotentialRookMoves(sq
)
693 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
696 // What are the knight moves from square x,y ?
697 getPotentialKnightMoves(sq
)
699 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
702 // What are the bishop moves from square x,y ?
703 getPotentialBishopMoves(sq
)
705 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
708 // What are the queen moves from square x,y ?
709 getPotentialQueenMoves(sq
)
711 return this.getSlideNJumpMoves(sq
,
712 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
715 // What are the king moves from square x,y ?
716 getPotentialKingMoves(sq
)
718 // Initialize with normal moves
719 let moves
= this.getSlideNJumpMoves(sq
,
720 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
721 return moves
.concat(this.getCastleMoves(sq
));
724 getCastleMoves([x
,y
])
726 const c
= this.getColor(x
,y
);
727 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
728 return []; //x isn't first rank, or king has moved (shortcut)
731 const oppCol
= this.getOppCol(c
);
734 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
736 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
738 if (!this.castleFlags
[c
][castleSide
])
740 // If this code is reached, rooks and king are on initial position
742 // Nothing on the path of the king ?
743 // (And no checks; OK also if y==finalSquare)
744 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
745 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
747 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
748 // NOTE: next check is enough, because of chessboard constraints
749 (this.getColor(x
,i
) != c
750 || ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
752 continue castlingCheck
;
756 // Nothing on the path to the rook?
757 step
= castleSide
== 0 ? -1 : 1;
758 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
760 if (this.board
[x
][i
] != V
.EMPTY
)
761 continue castlingCheck
;
763 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
765 // Nothing on final squares, except maybe king and castling rook?
768 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
769 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
770 finalSquares
[castleSide
][i
] != rookPos
)
772 continue castlingCheck
;
776 // If this code is reached, castle is valid
777 moves
.push( new Move({
779 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
780 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
782 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
783 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
784 end: Math
.abs(y
- rookPos
) <= 2
786 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
796 // For the interface: possible moves for the current turn from square sq
797 getPossibleMovesFrom(sq
)
799 return this.filterValid( this.getPotentialMovesFrom(sq
) );
802 // TODO: promotions (into R,B,N,Q) should be filtered only once
805 if (moves
.length
== 0)
807 const color
= this.turn
;
808 return moves
.filter(m
=> {
810 const res
= !this.underCheck(color
);
816 // Search for all valid moves considering current turn
817 // (for engine and game end)
820 const color
= this.turn
;
821 const oppCol
= this.getOppCol(color
);
822 let potentialMoves
= [];
823 for (let i
=0; i
<V
.size
.x
; i
++)
825 for (let j
=0; j
<V
.size
.y
; j
++)
827 // Next condition "!= oppCol" to work with checkered variant
828 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
830 Array
.prototype.push
.apply(potentialMoves
,
831 this.getPotentialMovesFrom([i
,j
]));
835 return this.filterValid(potentialMoves
);
838 // Stop at the first move found
841 const color
= this.turn
;
842 const oppCol
= this.getOppCol(color
);
843 for (let i
=0; i
<V
.size
.x
; i
++)
845 for (let j
=0; j
<V
.size
.y
; j
++)
847 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
849 const moves
= this.getPotentialMovesFrom([i
,j
]);
850 if (moves
.length
> 0)
852 for (let k
=0; k
<moves
.length
; k
++)
854 if (this.filterValid([moves
[k
]]).length
> 0)
864 // Check if pieces of color in 'colors' are attacking (king) on square x,y
865 isAttacked(sq
, colors
)
867 return (this.isAttackedByPawn(sq
, colors
)
868 || this.isAttackedByRook(sq
, colors
)
869 || this.isAttackedByKnight(sq
, colors
)
870 || this.isAttackedByBishop(sq
, colors
)
871 || this.isAttackedByQueen(sq
, colors
)
872 || this.isAttackedByKing(sq
, colors
));
875 // Is square x,y attacked by 'colors' pawns ?
876 isAttackedByPawn([x
,y
], colors
)
878 for (let c
of colors
)
880 let pawnShift
= (c
=="w" ? 1 : -1);
881 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
883 for (let i
of [-1,1])
885 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
886 && this.getColor(x
+pawnShift
,y
+i
)==c
)
896 // Is square x,y attacked by 'colors' rooks ?
897 isAttackedByRook(sq
, colors
)
899 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
902 // Is square x,y attacked by 'colors' knights ?
903 isAttackedByKnight(sq
, colors
)
905 return this.isAttackedBySlideNJump(sq
, colors
,
906 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
909 // Is square x,y attacked by 'colors' bishops ?
910 isAttackedByBishop(sq
, colors
)
912 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
915 // Is square x,y attacked by 'colors' queens ?
916 isAttackedByQueen(sq
, colors
)
918 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
919 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
922 // Is square x,y attacked by 'colors' king(s) ?
923 isAttackedByKing(sq
, colors
)
925 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
926 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
929 // Generic method for non-pawn pieces ("sliding or jumping"):
930 // is x,y attacked by a piece of color in array 'colors' ?
931 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
933 for (let step
of steps
)
935 let rx
= x
+step
[0], ry
= y
+step
[1];
936 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
941 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
942 && colors
.includes(this.getColor(rx
,ry
)))
950 // Is color under check after his move ?
953 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
959 // Apply a move on board
960 static PlayOnBoard(board
, move)
962 for (let psq
of move.vanish
)
963 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
964 for (let psq
of move.appear
)
965 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
967 // Un-apply the played move
968 static UndoOnBoard(board
, move)
970 for (let psq
of move.appear
)
971 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
972 for (let psq
of move.vanish
)
973 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
976 // After move is played, update variables + flags
977 updateVariables(move)
979 let piece
= undefined;
981 if (move.vanish
.length
>= 1)
983 // Usual case, something is moved
984 piece
= move.vanish
[0].p
;
985 c
= move.vanish
[0].c
;
989 // Crazyhouse-like variants
990 piece
= move.appear
[0].p
;
991 c
= move.appear
[0].c
;
993 if (c
== "c") //if (!["w","b"].includes(c))
995 // 'c = move.vanish[0].c' doesn't work for Checkered
996 c
= this.getOppCol(this.turn
);
998 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
1000 // Update king position + flags
1001 if (piece
== V
.KING
&& move.appear
.length
> 0)
1003 this.kingPos
[c
][0] = move.appear
[0].x
;
1004 this.kingPos
[c
][1] = move.appear
[0].y
;
1006 this.castleFlags
[c
] = [false,false];
1011 // Update castling flags if rooks are moved
1012 const oppCol
= this.getOppCol(c
);
1013 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
1014 if (move.start
.x
== firstRank
//our rook moves?
1015 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
1017 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
1018 this.castleFlags
[c
][flagIdx
] = false;
1020 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
1021 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
1023 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
1024 this.castleFlags
[oppCol
][flagIdx
] = false;
1029 // After move is undo-ed *and flags resetted*, un-update other variables
1030 // TODO: more symmetry, by storing flags increment in move (?!)
1031 unupdateVariables(move)
1033 // (Potentially) Reset king position
1034 const c
= this.getColor(move.start
.x
,move.start
.y
);
1035 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
1036 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1042 // if (!this.states) this.states = [];
1043 // if (!ingame) this.states.push(this.getFen());
1046 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
1049 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1051 this.epSquares
.push( this.getEpSquare(move) );
1052 V
.PlayOnBoard(this.board
, move);
1053 this.turn
= this.getOppCol(this.turn
);
1054 this.moves
.push(move);
1055 this.updateVariables(move);
1059 // Hash of current game state *after move*, to detect repetitions
1060 move.hash
= hex_md5(this.getFen());
1067 this.epSquares
.pop();
1069 this.disaggregateFlags(JSON
.parse(move.flags
));
1070 V
.UndoOnBoard(this.board
, move);
1071 this.turn
= this.getOppCol(this.turn
);
1073 this.unupdateVariables(move);
1076 // if (this.getFen() != this.states[this.states.length-1])
1078 // this.states.pop();
1084 // Check for 3 repetitions (position + flags + turn)
1087 if (!this.hashStates
)
1088 this.hashStates
= {};
1090 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
1091 // Update this.hashStates with last move (or all moves if continuation)
1092 // NOTE: redundant storage, but faster and moderate size
1093 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
1095 const move = this.moves
[i
];
1096 if (!this.hashStates
[move.hash
])
1097 this.hashStates
[move.hash
] = 1;
1099 this.hashStates
[move.hash
]++;
1101 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
1104 // Is game over ? And if yes, what is the score ?
1107 if (this.checkRepetition())
1110 if (this.atLeastOneMove()) // game not over
1114 return this.checkGameEnd();
1117 // No moves are possible: compute score
1120 const color
= this.turn
;
1121 // No valid move: stalemate or checkmate?
1122 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
1125 return (color
== "w" ? "0-1" : "1-0");
1144 // "Checkmate" (unreachable eval)
1145 static get INFINITY() { return 9999; }
1147 // At this value or above, the game is over
1148 static get THRESHOLD_MATE() { return V
.INFINITY
; }
1150 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1151 static get SEARCH_DEPTH() { return 3; }
1153 // Assumption: at least one legal move
1154 // NOTE: works also for extinction chess because depth is 3...
1157 const maxeval
= V
.INFINITY
;
1158 const color
= this.turn
;
1159 // Some variants may show a bigger moves list to the human (Switching),
1160 // thus the argument "computer" below (which is generally ignored)
1161 let moves1
= this.getAllValidMoves("computer");
1163 // Can I mate in 1 ? (for Magnetic & Extinction)
1164 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
1166 this.play(moves1
[i
]);
1167 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
1168 if (!finish
&& !this.atLeastOneMove())
1170 // Test mate (for other variants)
1171 const score
= this.checkGameEnd();
1175 this.undo(moves1
[i
]);
1180 // Rank moves using a min-max at depth 2
1181 for (let i
=0; i
<moves1
.length
; i
++)
1183 // Initial self evaluation is very low: "I'm checkmated"
1184 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
;
1185 this.play(moves1
[i
]);
1186 let eval2
= undefined;
1187 if (this.atLeastOneMove())
1189 // Initial enemy evaluation is very low too, for him
1190 eval2
= (color
=="w" ? 1 : -1) * maxeval
;
1191 // Second half-move:
1192 let moves2
= this.getAllValidMoves("computer");
1193 for (let j
=0; j
<moves2
.length
; j
++)
1195 this.play(moves2
[j
]);
1196 let evalPos
= undefined;
1197 if (this.atLeastOneMove())
1198 evalPos
= this.evalPosition()
1201 // Working with scores is more accurate (necessary for Loser variant)
1202 const score
= this.checkGameEnd();
1203 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1205 if ((color
== "w" && evalPos
< eval2
)
1206 || (color
=="b" && evalPos
> eval2
))
1210 this.undo(moves2
[j
]);
1215 const score
= this.checkGameEnd();
1216 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1218 if ((color
=="w" && eval2
> moves1
[i
].eval
)
1219 || (color
=="b" && eval2
< moves1
[i
].eval
))
1221 moves1
[i
].eval
= eval2
;
1223 this.undo(moves1
[i
]);
1225 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1227 let candidates
= [0]; //indices of candidates moves
1228 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1230 let currentBest
= moves1
[_
.sample(candidates
, 1)];
1232 // From here, depth >= 3: may take a while, so we control time
1233 const timeStart
= Date
.now();
1235 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1236 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
1238 for (let i
=0; i
<moves1
.length
; i
++)
1240 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
1241 return currentBest
; //depth 2 at least
1242 this.play(moves1
[i
]);
1243 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1244 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
1245 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
1246 this.undo(moves1
[i
]);
1248 moves1
.sort( (a
,b
) => {
1249 return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1253 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1256 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1258 return moves1
[_
.sample(candidates
, 1)];
1261 alphabeta(depth
, alpha
, beta
)
1263 const maxeval
= V
.INFINITY
;
1264 const color
= this.turn
;
1265 if (!this.atLeastOneMove())
1267 switch (this.checkGameEnd())
1272 const score
= this.checkGameEnd();
1273 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1277 return this.evalPosition();
1278 const moves
= this.getAllValidMoves("computer");
1279 let v
= color
=="w" ? -maxeval : maxeval
;
1282 for (let i
=0; i
<moves
.length
; i
++)
1284 this.play(moves
[i
]);
1285 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1286 this.undo(moves
[i
]);
1287 alpha
= Math
.max(alpha
, v
);
1289 break; //beta cutoff
1294 for (let i
=0; i
<moves
.length
; i
++)
1296 this.play(moves
[i
]);
1297 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1298 this.undo(moves
[i
]);
1299 beta
= Math
.min(beta
, v
);
1301 break; //alpha cutoff
1310 // Just count material for now
1311 for (let i
=0; i
<V
.size
.x
; i
++)
1313 for (let j
=0; j
<V
.size
.y
; j
++)
1315 if (this.board
[i
][j
] != V
.EMPTY
)
1317 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1318 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1325 /////////////////////////
1326 // MOVES + GAME NOTATION
1327 /////////////////////////
1329 // Context: just before move is played, turn hasn't changed
1332 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1333 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1335 // Translate final square
1336 const finalSquare
= V
.CoordsToSquare(move.end
);
1338 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1339 if (piece
== V
.PAWN
)
1343 if (move.vanish
.length
> move.appear
.length
)
1346 const startColumn
= V
.CoordToColumn(move.start
.y
);
1347 notation
= startColumn
+ "x" + finalSquare
;
1350 notation
= finalSquare
;
1351 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
) //promotion
1352 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1359 return piece
.toUpperCase() +
1360 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1364 // Complete the usual notation, may be required for de-ambiguification
1365 getLongNotation(move)
1367 // Not encoding move. But short+long is enough
1368 return V
.CoordsToSquare(move.start
) + V
.CoordsToSquare(move.end
);
1371 // The score is already computed when calling this function
1372 getPGN(mycolor
, score
, fenStart
, mode
)
1375 pgn
+= '[Site "vchess.club"]<br>';
1376 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1377 pgn
+= '[Variant "' + variant
+ '"]<br>';
1378 pgn
+= '[Date "' + getDate(new Date()) + '"]<br>';
1379 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1380 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1381 pgn
+= '[FenStart "' + fenStart
+ '"]<br>';
1382 pgn
+= '[Fen "' + this.getFen() + '"]<br>';
1383 pgn
+= '[Result "' + score
+ '"]<br><br>';
1386 for (let i
=0; i
<this.moves
.length
; i
++)
1389 pgn
+= ((i
/2)+1) + ".";
1390 pgn
+= this.moves
[i
].notation
[0] + " ";
1394 // "Complete moves" PGN (helping in ambiguous cases)
1395 for (let i
=0; i
<this.moves
.length
; i
++)
1398 pgn
+= ((i
/2)+1) + ".";
1399 pgn
+= this.moves
[i
].notation
[1] + " ";