d85ff869a22eea9ba8e841040efc3734ea889ccb
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
|| !["w","b"].includes(fenParsed
.turn
))
70 if (V
.HasFlags
&& (!fenParsed
.flags
|| !V
.IsGoodFlags(fenParsed
.flags
)))
75 if (!fenParsed
.enpassant
)
77 if (fenParsed
.enpassant
!= "-")
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
)
87 // Is position part of the FEN a priori correct?
88 static IsGoodPosition(position
)
90 if (position
.length
== 0)
92 const rows
= position
.split("/");
93 if (rows
.length
!= V
.size
.x
)
98 for (let i
=0; i
<row
.length
; i
++)
100 if (V
.PIECES
.includes(row
[i
].toLowerCase()))
104 const num
= parseInt(row
[i
]);
110 if (sumElts
!= V
.size
.y
)
117 static IsGoodFlags(flags
)
119 return !!flags
.match(/^[01]{4,4}$/);
122 // 3 --> d (column letter from number)
123 static GetColumn(colnum
)
125 return String
.fromCharCode(97 + colnum
);
129 static SquareToCoords(sq
)
132 x: V
.size
.x
- parseInt(sq
.substr(1)),
133 y: sq
[0].charCodeAt() - 97
138 static CoordsToSquare(coords
)
140 return V
.GetColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
143 // Aggregates flags into one object
146 return this.castleFlags
;
150 disaggregateFlags(flags
)
152 this.castleFlags
= flags
;
155 // En-passant square, if any
156 getEpSquare(moveOrSquare
)
160 if (typeof moveOrSquare
=== "string")
162 const square
= moveOrSquare
;
165 return V
.SquareToCoords(square
);
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)
177 return undefined; //default
180 // Can thing on square1 take thing on square2
181 canTake([x1
,y1
], [x2
,y2
])
183 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
186 // Is (x,y) on the chessboard?
189 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
192 // Used in interface: 'side' arg == player color
193 canIplay(side
, [x
,y
])
195 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
198 // On which squares is opponent under check after our move ? (for interface)
199 getCheckSquares(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!
213 // Setup the initial random (assymetric) position
214 static GenRandInitFen()
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"])
220 let positions
= _
.range(8);
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);
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);
240 // Get random square for queen
241 randIndex
= _
.random(3);
242 let queenPos
= positions
[randIndex
];
243 positions
.splice(randIndex
, 1);
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];
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';
260 return pieces
["b"].join("") +
261 "/pppppppp/8/8/8/8/PPPPPPPP/" +
262 pieces
["w"].join("").toUpperCase() +
263 " w 1111 -"; //add turn + flags + enpassant
266 // "Parse" FEN: just return untransformed string data
269 const fenParts
= fen
.split(" ");
272 position: fenParts
[0],
277 Object
.assign(res
, {flags: fenParts
[nextIdx
++]});
279 Object
.assign(res
, {enpassant: fenParts
[nextIdx
]});
283 // Return current fen (game state)
286 return this.getBaseFen() + " " + this.turn
+
287 (V
.HasFlags
? (" " + this.getFlagsFen()) : "") +
288 (V
.HasEnpassant
? (" " + this.getEnpassantFen()) : "");
291 // Position part of the FEN string
295 for (let i
=0; i
<V
.size
.x
; i
++)
298 for (let j
=0; j
<V
.size
.y
; j
++)
300 if (this.board
[i
][j
] == V
.EMPTY
)
306 // Add empty squares in-between
307 position
+= emptyCount
;
310 position
+= V
.board2fen(this.board
[i
][j
]);
316 position
+= emptyCount
;
318 if (i
< V
.size
.x
- 1)
319 position
+= "/"; //separate rows
324 // Flags part of the FEN string
328 // Add castling flags
329 for (let i
of ['w','b'])
331 for (let j
=0; j
<2; j
++)
332 flags
+= (this.castleFlags
[i
][j
] ? '1' : '0');
337 // Enpassant part of the FEN string
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]);
346 // Turn position fen into double array ["wb","wp","bk",...]
347 static GetBoard(position
)
349 const rows
= position
.split("/");
350 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
351 for (let i
=0; i
<rows
.length
; i
++)
354 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
356 const character
= rows
[i
][indexInRow
];
357 const num
= parseInt(character
);
359 j
+= num
; //just shift j
360 else //something at position i,j
361 board
[i
][j
++] = V
.fen2board(character
);
367 // Extract (relevant) flags from fen
370 // white a-castle, h-castle, black a-castle, h-castle
371 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
374 for (let i
=0; i
<4; i
++)
375 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
381 // Fen string fully describes the game state
382 constructor(fen
, moves
)
385 const fenParsed
= V
.ParseFen(fen
);
386 this.board
= V
.GetBoard(fenParsed
.position
);
387 this.turn
= (fenParsed
.turn
|| "w");
388 this.setOtherVariables(fen
);
391 // Scan board for kings and rooks positions
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
++)
400 let k
= 0; //column index on board
401 for (let j
=0; j
<fenRows
[i
].length
; j
++)
403 switch (fenRows
[i
].charAt(j
))
406 this.kingPos
['b'] = [i
,k
];
407 this.INIT_COL_KING
['b'] = k
;
410 this.kingPos
['w'] = [i
,k
];
411 this.INIT_COL_KING
['w'] = k
;
414 if (this.INIT_COL_ROOK
['b'][0] < 0)
415 this.INIT_COL_ROOK
['b'][0] = k
;
417 this.INIT_COL_ROOK
['b'][1] = k
;
420 if (this.INIT_COL_ROOK
['w'][0] < 0)
421 this.INIT_COL_ROOK
['w'][0] = k
;
423 this.INIT_COL_ROOK
['w'][1] = k
;
426 const num
= parseInt(fenRows
[i
].charAt(j
));
435 // Some additional variables from FEN (variant dependant)
436 setOtherVariables(fen
)
438 // Set flags and enpassant:
439 const parsedFen
= V
.ParseFen(fen
);
441 this.setFlags(parsedFen
.flags
);
444 const epSq
= parsedFen
.enpassant
!= "-"
445 ? V
.SquareToCoords(parsedFen
.enpassant
)
447 this.epSquares
= [ epSq
];
449 // Search for king and rooks positions:
450 this.scanKingsRooks(fen
);
453 /////////////////////
461 // Color of thing on suqare (i,j). 'undefined' if square is empty
464 return this.board
[i
][j
].charAt(0);
467 // Piece type on square (i,j). 'undefined' if square is empty
470 return this.board
[i
][j
].charAt(1);
473 // Get opponent color
476 return (color
=="w" ? "b" : "w");
481 const L
= this.moves
.length
;
482 return (L
>0 ? this.moves
[L
-1] : null);
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'; }
496 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
500 static get EMPTY() { return ""; }
502 // Some pieces movements
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] ],
515 // All possible moves from selected square (assumption: color is OK)
516 getPotentialMovesFrom([x
,y
])
518 switch (this.getPiece(x
,y
))
521 return this.getPotentialPawnMoves([x
,y
]);
523 return this.getPotentialRookMoves([x
,y
]);
525 return this.getPotentialKnightMoves([x
,y
]);
527 return this.getPotentialBishopMoves([x
,y
]);
529 return this.getPotentialQueenMoves([x
,y
]);
531 return this.getPotentialKingMoves([x
,y
]);
535 // Build a regular move from its initial and destination squares; tr: transformation
536 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
543 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
544 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
551 c: this.getColor(sx
,sy
),
552 p: this.getPiece(sx
,sy
)
557 // The opponent piece disappears if we take it
558 if (this.board
[ex
][ey
] != V
.EMPTY
)
564 c: this.getColor(ex
,ey
),
565 p: this.getPiece(ex
,ey
)
572 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
573 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
575 const color
= this.getColor(x
,y
);
578 for (let step
of steps
)
582 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
584 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
585 if (oneStep
!== undefined)
590 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
591 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
596 // What are the pawn moves from square x,y ?
597 getPotentialPawnMoves([x
,y
])
599 const color
= this.turn
;
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
608 if (x
+shiftX
>= 0 && x
+shiftX
< sizeX
) //TODO: always true
610 const finalPieces
= x
+ shiftX
== lastRank
611 ? [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
]
613 // One square forward
614 if (this.board
[x
+shiftX
][y
] == V
.EMPTY
)
616 for (let piece
of finalPieces
)
618 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
],
619 {c:pawnColor
,p:piece
}));
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
)
626 moves
.push(this.getBasicMove([x
,y
], [x
+2*shiftX
,y
]));
630 for (let shiftY
of [-1,1])
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
]))
636 for (let piece
of finalPieces
)
638 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
+shiftY
],
639 {c:pawnColor
,p:piece
}));
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)
652 let enpassantMove
= this.getBasicMove([x
,y
], [epSquare
.x
,epSquare
.y
]);
653 enpassantMove
.vanish
.push({
657 c: this.getColor(x
,epSquare
.y
)
659 moves
.push(enpassantMove
);
666 // What are the rook moves from square x,y ?
667 getPotentialRookMoves(sq
)
669 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
672 // What are the knight moves from square x,y ?
673 getPotentialKnightMoves(sq
)
675 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
678 // What are the bishop moves from square x,y ?
679 getPotentialBishopMoves(sq
)
681 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
684 // What are the queen moves from square x,y ?
685 getPotentialQueenMoves(sq
)
687 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
690 // What are the king moves from square x,y ?
691 getPotentialKingMoves(sq
)
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
));
699 getCastleMoves([x
,y
])
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)
706 const oppCol
= this.getOppCol(c
);
709 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
711 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
713 if (!this.castleFlags
[c
][castleSide
])
715 // If this code is reached, rooks and king are on initial position
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
)
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
)))))
725 continue castlingCheck
;
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
)
733 if (this.board
[x
][i
] != V
.EMPTY
)
734 continue castlingCheck
;
736 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
738 // Nothing on final squares, except maybe king and castling rook?
741 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
742 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
743 finalSquares
[castleSide
][i
] != rookPos
)
745 continue castlingCheck
;
749 // If this code is reached, castle is valid
750 moves
.push( new Move({
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
})],
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
759 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
769 getPossibleMovesFrom(sq
)
771 // Assuming color is right (already checked)
772 return this.filterValid( this.getPotentialMovesFrom(sq
) );
775 // TODO: promotions (into R,B,N,Q) should be filtered only once
778 if (moves
.length
== 0)
780 return moves
.filter(m
=> { return !this.underCheck(m
); });
783 // Search for all valid moves considering current turn (for engine and game end)
786 const color
= this.turn
;
787 const oppCol
= this.getOppCol(color
);
788 let potentialMoves
= [];
789 for (let i
=0; i
<V
.size
.x
; i
++)
791 for (let j
=0; j
<V
.size
.y
; j
++)
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
]));
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
);
803 // Stop at the first move found
806 const color
= this.turn
;
807 const oppCol
= this.getOppCol(color
);
808 for (let i
=0; i
<V
.size
.x
; i
++)
810 for (let j
=0; j
<V
.size
.y
; j
++)
812 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
814 const moves
= this.getPotentialMovesFrom([i
,j
]);
815 if (moves
.length
> 0)
817 for (let k
=0; k
<moves
.length
; k
++)
819 if (this.filterValid([moves
[k
]]).length
> 0)
829 // Check if pieces of color in array 'colors' are attacking (king) on square x,y
830 isAttacked(sq
, colors
)
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
));
840 // Is square x,y attacked by 'colors' pawns ?
841 isAttackedByPawn([x
,y
], colors
)
843 for (let c
of colors
)
845 let pawnShift
= (c
=="w" ? 1 : -1);
846 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
848 for (let i
of [-1,1])
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
)
861 // Is square x,y attacked by 'colors' rooks ?
862 isAttackedByRook(sq
, colors
)
864 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
867 // Is square x,y attacked by 'colors' knights ?
868 isAttackedByKnight(sq
, colors
)
870 return this.isAttackedBySlideNJump(sq
, colors
,
871 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
874 // Is square x,y attacked by 'colors' bishops ?
875 isAttackedByBishop(sq
, colors
)
877 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
880 // Is square x,y attacked by 'colors' queens ?
881 isAttackedByQueen(sq
, colors
)
883 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
884 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
887 // Is square x,y attacked by 'colors' king(s) ?
888 isAttackedByKing(sq
, colors
)
890 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
891 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
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
)
898 for (let step
of steps
)
900 let rx
= x
+step
[0], ry
= y
+step
[1];
901 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
906 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
907 && colors
.includes(this.getColor(rx
,ry
)))
915 // Is current player under check after his move ?
918 const color
= this.turn
;
920 let res
= this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
928 // Apply a move on board
929 static PlayOnBoard(board
, move)
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
;
936 // Un-apply the played move
937 static UndoOnBoard(board
, move)
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
;
945 // Before move is played, update variables + flags
946 updateVariables(move)
948 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
950 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
952 // Update king position + flags
953 if (piece
== V
.KING
&& move.appear
.length
> 0)
955 this.kingPos
[c
][0] = move.appear
[0].x
;
956 this.kingPos
[c
][1] = move.appear
[0].y
;
957 this.castleFlags
[c
] = [false,false];
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
))
965 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
966 this.castleFlags
[c
][flagIdx
] = false;
968 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
969 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
971 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
972 this.castleFlags
[oppCol
][flagIdx
] = false;
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)
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
];
989 // if (!this.states) this.states = [];
990 // if (!ingame) this.states.push(this.getFen());
993 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
996 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
997 this.updateVariables(move);
998 this.moves
.push(move);
1000 this.epSquares
.push( this.getEpSquare(move) );
1001 this.turn
= this.getOppCol(this.turn
);
1002 V
.PlayOnBoard(this.board
, move);
1006 // Hash of current game state *after move*, to detect repetitions
1007 move.hash
= hex_md5(this.getFen());
1013 V
.UndoOnBoard(this.board
, move);
1014 this.turn
= this.getOppCol(this.turn
);
1016 this.epSquares
.pop();
1018 this.unupdateVariables(move);
1020 this.disaggregateFlags(JSON
.parse(move.flags
));
1023 // if (this.getFen() != this.states[this.states.length-1])
1025 // this.states.pop();
1031 // Check for 3 repetitions (position + flags + turn)
1034 if (!this.hashStates
)
1035 this.hashStates
= {};
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
++)
1042 const move = this.moves
[i
];
1043 if (!this.hashStates
[move.hash
])
1044 this.hashStates
[move.hash
] = 1;
1046 this.hashStates
[move.hash
]++;
1048 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
1051 // Is game over ? And if yes, what is the score ?
1054 if (this.checkRepetition())
1057 if (this.atLeastOneMove()) // game not over
1061 return this.checkGameEnd();
1064 // No moves are possible: compute score
1067 const color
= this.turn
;
1068 // No valid move: stalemate or checkmate?
1069 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
1072 return color
== "w" ? "0-1" : "1-0";
1091 // "Checkmate" (unreachable eval)
1092 static get INFINITY() { return 9999; }
1094 // At this value or above, the game is over
1095 static get THRESHOLD_MATE() { return V
.INFINITY
; }
1097 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1098 static get SEARCH_DEPTH() { return 3; }
1100 // Assumption: at least one legal move
1101 // NOTE: works also for extinction chess because depth is 3...
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");
1110 // Can I mate in 1 ? (for Magnetic & Extinction)
1111 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
1113 this.play(moves1
[i
]);
1114 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
1115 if (!finish
&& !this.atLeastOneMove())
1117 // Test mate (for other variants)
1118 const score
= this.checkGameEnd();
1122 this.undo(moves1
[i
]);
1127 // Rank moves using a min-max at depth 2
1128 for (let i
=0; i
<moves1
.length
; i
++)
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())
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
++)
1140 this.play(moves2
[j
]);
1141 let evalPos
= undefined;
1142 if (this.atLeastOneMove())
1143 evalPos
= this.evalPosition()
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
);
1150 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
1152 this.undo(moves2
[j
]);
1157 const score
= this.checkGameEnd();
1158 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1160 if ((color
=="w" && eval2
> moves1
[i
].eval
)
1161 || (color
=="b" && eval2
< moves1
[i
].eval
))
1163 moves1
[i
].eval
= eval2
;
1165 this.undo(moves1
[i
]);
1167 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1169 let candidates
= [0]; //indices of candidates moves
1170 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1172 let currentBest
= moves1
[_
.sample(candidates
, 1)];
1174 // From here, depth >= 3: may take a while, so we control time
1175 const timeStart
= Date
.now();
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
)
1180 for (let i
=0; i
<moves1
.length
; i
++)
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
]);
1190 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1194 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1197 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1199 return moves1
[_
.sample(candidates
, 1)];
1202 alphabeta(depth
, alpha
, beta
)
1204 const maxeval
= V
.INFINITY
;
1205 const color
= this.turn
;
1206 if (!this.atLeastOneMove())
1208 switch (this.checkGameEnd())
1213 const score
= this.checkGameEnd();
1214 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1218 return this.evalPosition();
1219 const moves
= this.getAllValidMoves("computer");
1220 let v
= color
=="w" ? -maxeval : maxeval
;
1223 for (let i
=0; i
<moves
.length
; i
++)
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
);
1230 break; //beta cutoff
1235 for (let i
=0; i
<moves
.length
; i
++)
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
);
1242 break; //alpha cutoff
1251 // Just count material for now
1252 for (let i
=0; i
<V
.size
.x
; i
++)
1254 for (let j
=0; j
<V
.size
.y
; j
++)
1256 if (this.board
[i
][j
] != V
.EMPTY
)
1258 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1259 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1266 /////////////////////////
1267 // MOVES + GAME NOTATION
1268 /////////////////////////
1270 // Context: just before move is played, turn hasn't changed
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");
1276 // Translate final square
1277 const finalSquare
= V
.CoordsToSquare(move.end
);
1279 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1280 if (piece
== V
.PAWN
)
1284 if (move.vanish
.length
> move.appear
.length
)
1287 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1288 notation
= startColumn
+ "x" + finalSquare
;
1291 notation
= finalSquare
;
1292 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1293 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1300 return piece
.toUpperCase() +
1301 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1305 // Complete the usual notation, may be required for de-ambiguification
1306 getLongNotation(move)
1308 // Not encoding move. But short+long is enough
1309 return V
.CoordsToSquare(move.start
) + V
.CoordsToSquare(move.end
);
1312 // The score is already computed when calling this function
1313 getPGN(mycolor
, score
, fenStart
, mode
)
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>';
1327 for (let i
=0; i
<this.moves
.length
; i
++)
1330 pgn
+= ((i
/2)+1) + ".";
1331 pgn
+= this.moves
[i
].notation
[0] + " ";
1335 // "Complete moves" PGN (helping in ambiguous cases)
1336 for (let i
=0; i
<this.moves
.length
; i
++)
1339 pgn
+= ((i
/2)+1) + ".";
1340 pgn
+= this.moves
[i
].notation
[1] + " ";