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 (isNaN(ep
.x
) || !V
.OnBoard(ep
))
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 number to letter)
123 static CoordToColumn(colnum
)
125 return String
.fromCharCode(97 + colnum
);
128 // d --> 3 (column letter to number)
129 static ColumnToCoord(colnum
)
131 return String
.fromCharCode(97 + colnum
);
135 static SquareToCoords(sq
)
138 // NOTE: column is always one char => max 26 columns
139 // row is counted from black side => subtraction
140 x: V
.size
.x
- parseInt(sq
.substr(1)),
141 y: sq
[0].charCodeAt() - 97
146 static CoordsToSquare(coords
)
148 return V
.CoordToColumn(coords
.y
) + (V
.size
.x
- coords
.x
);
151 // Aggregates flags into one object
154 return this.castleFlags
;
158 disaggregateFlags(flags
)
160 this.castleFlags
= flags
;
163 // En-passant square, if any
164 getEpSquare(moveOrSquare
)
168 if (typeof moveOrSquare
=== "string")
170 const square
= moveOrSquare
;
173 return V
.SquareToCoords(square
);
175 // Argument is a move:
176 const move = moveOrSquare
;
177 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
178 if (this.getPiece(sx
,sy
) == V
.PAWN
&& Math
.abs(sx
- ex
) == 2)
185 return undefined; //default
188 // Can thing on square1 take thing on square2
189 canTake([x1
,y1
], [x2
,y2
])
191 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
194 // Is (x,y) on the chessboard?
197 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
200 // Used in interface: 'side' arg == player color
201 canIplay(side
, [x
,y
])
203 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
206 // On which squares is color under check ? (for interface)
207 getCheckSquares(color
)
209 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
210 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
217 // Setup the initial random (assymetric) position
218 static GenRandInitFen()
220 let pieces
= { "w": new Array(8), "b": new Array(8) };
221 // Shuffle pieces on first and last rank
222 for (let c
of ["w","b"])
224 let positions
= _
.range(8);
226 // Get random squares for bishops
227 let randIndex
= 2 * _
.random(3);
228 const bishop1Pos
= positions
[randIndex
];
229 // The second bishop must be on a square of different color
230 let randIndex_tmp
= 2 * _
.random(3) + 1;
231 const bishop2Pos
= positions
[randIndex_tmp
];
232 // Remove chosen squares
233 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
234 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
236 // Get random squares for knights
237 randIndex
= _
.random(5);
238 const knight1Pos
= positions
[randIndex
];
239 positions
.splice(randIndex
, 1);
240 randIndex
= _
.random(4);
241 const knight2Pos
= positions
[randIndex
];
242 positions
.splice(randIndex
, 1);
244 // Get random square for queen
245 randIndex
= _
.random(3);
246 const queenPos
= positions
[randIndex
];
247 positions
.splice(randIndex
, 1);
249 // Rooks and king positions are now fixed,
250 // because of the ordering rook-king-rook
251 const rook1Pos
= positions
[0];
252 const kingPos
= positions
[1];
253 const rook2Pos
= positions
[2];
255 // Finally put the shuffled pieces in the board array
256 pieces
[c
][rook1Pos
] = 'r';
257 pieces
[c
][knight1Pos
] = 'n';
258 pieces
[c
][bishop1Pos
] = 'b';
259 pieces
[c
][queenPos
] = 'q';
260 pieces
[c
][kingPos
] = 'k';
261 pieces
[c
][bishop2Pos
] = 'b';
262 pieces
[c
][knight2Pos
] = 'n';
263 pieces
[c
][rook2Pos
] = 'r';
265 return pieces
["b"].join("") +
266 "/pppppppp/8/8/8/8/PPPPPPPP/" +
267 pieces
["w"].join("").toUpperCase() +
268 " w 1111 -"; //add turn + flags + enpassant
271 // "Parse" FEN: just return untransformed string data
274 const fenParts
= fen
.split(" ");
277 position: fenParts
[0],
282 Object
.assign(res
, {flags: fenParts
[nextIdx
++]});
284 Object
.assign(res
, {enpassant: fenParts
[nextIdx
]});
288 // Return current fen (game state)
291 return this.getBaseFen() + " " + this.turn
+
292 (V
.HasFlags
? (" " + this.getFlagsFen()) : "") +
293 (V
.HasEnpassant
? (" " + this.getEnpassantFen()) : "");
296 // Position part of the FEN string
300 for (let i
=0; i
<V
.size
.x
; i
++)
303 for (let j
=0; j
<V
.size
.y
; j
++)
305 if (this.board
[i
][j
] == V
.EMPTY
)
311 // Add empty squares in-between
312 position
+= emptyCount
;
315 position
+= V
.board2fen(this.board
[i
][j
]);
321 position
+= emptyCount
;
323 if (i
< V
.size
.x
- 1)
324 position
+= "/"; //separate rows
329 // Flags part of the FEN string
333 // Add castling flags
334 for (let i
of ['w','b'])
336 for (let j
=0; j
<2; j
++)
337 flags
+= (this.castleFlags
[i
][j
] ? '1' : '0');
342 // Enpassant part of the FEN string
345 const L
= this.epSquares
.length
;
346 if (!this.epSquares
[L
-1])
347 return "-"; //no en-passant
348 return V
.CoordsToSquare(this.epSquares
[L
-1]);
351 // Turn position fen into double array ["wb","wp","bk",...]
352 static GetBoard(position
)
354 const rows
= position
.split("/");
355 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
356 for (let i
=0; i
<rows
.length
; i
++)
359 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
361 const character
= rows
[i
][indexInRow
];
362 const num
= parseInt(character
);
364 j
+= num
; //just shift j
365 else //something at position i,j
366 board
[i
][j
++] = V
.fen2board(character
);
372 // Extract (relevant) flags from fen
375 // white a-castle, h-castle, black a-castle, h-castle
376 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
379 for (let i
=0; i
<4; i
++)
380 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
386 // Fen string fully describes the game state
387 constructor(fen
, moves
)
390 const fenParsed
= V
.ParseFen(fen
);
391 this.board
= V
.GetBoard(fenParsed
.position
);
392 this.turn
= (fenParsed
.turn
|| "w");
393 this.setOtherVariables(fen
);
396 // Scan board for kings and rooks positions
399 this.INIT_COL_KING
= {'w':-1, 'b':-1};
400 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
401 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
402 const fenRows
= V
.ParseFen(fen
).position
.split("/");
403 for (let i
=0; i
<fenRows
.length
; i
++)
405 let k
= 0; //column index on board
406 for (let j
=0; j
<fenRows
[i
].length
; j
++)
408 switch (fenRows
[i
].charAt(j
))
411 this.kingPos
['b'] = [i
,k
];
412 this.INIT_COL_KING
['b'] = k
;
415 this.kingPos
['w'] = [i
,k
];
416 this.INIT_COL_KING
['w'] = k
;
419 if (this.INIT_COL_ROOK
['b'][0] < 0)
420 this.INIT_COL_ROOK
['b'][0] = k
;
422 this.INIT_COL_ROOK
['b'][1] = k
;
425 if (this.INIT_COL_ROOK
['w'][0] < 0)
426 this.INIT_COL_ROOK
['w'][0] = k
;
428 this.INIT_COL_ROOK
['w'][1] = k
;
431 const num
= parseInt(fenRows
[i
].charAt(j
));
440 // Some additional variables from FEN (variant dependant)
441 setOtherVariables(fen
)
443 // Set flags and enpassant:
444 const parsedFen
= V
.ParseFen(fen
);
446 this.setFlags(parsedFen
.flags
);
449 const epSq
= parsedFen
.enpassant
!= "-"
450 ? V
.SquareToCoords(parsedFen
.enpassant
)
452 this.epSquares
= [ epSq
];
454 // Search for king and rooks positions:
455 this.scanKingsRooks(fen
);
458 /////////////////////
466 // Color of thing on suqare (i,j). 'undefined' if square is empty
469 return this.board
[i
][j
].charAt(0);
472 // Piece type on square (i,j). 'undefined' if square is empty
475 return this.board
[i
][j
].charAt(1);
478 // Get opponent color
481 return (color
=="w" ? "b" : "w");
486 const L
= this.moves
.length
;
487 return (L
>0 ? this.moves
[L
-1] : null);
490 // Pieces codes (for a clearer code)
491 static get PAWN() { return 'p'; }
492 static get ROOK() { return 'r'; }
493 static get KNIGHT() { return 'n'; }
494 static get BISHOP() { return 'b'; }
495 static get QUEEN() { return 'q'; }
496 static get KING() { return 'k'; }
501 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
505 static get EMPTY() { return ""; }
507 // Some pieces movements
511 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
512 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
513 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
520 // All possible moves from selected square (assumption: color is OK)
521 getPotentialMovesFrom([x
,y
])
523 switch (this.getPiece(x
,y
))
526 return this.getPotentialPawnMoves([x
,y
]);
528 return this.getPotentialRookMoves([x
,y
]);
530 return this.getPotentialKnightMoves([x
,y
]);
532 return this.getPotentialBishopMoves([x
,y
]);
534 return this.getPotentialQueenMoves([x
,y
]);
536 return this.getPotentialKingMoves([x
,y
]);
540 // Build a regular move from its initial and destination squares.
541 // tr: transformation
542 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
549 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
550 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
557 c: this.getColor(sx
,sy
),
558 p: this.getPiece(sx
,sy
)
563 // The opponent piece disappears if we take it
564 if (this.board
[ex
][ey
] != V
.EMPTY
)
570 c: this.getColor(ex
,ey
),
571 p: this.getPiece(ex
,ey
)
578 // Generic method to find possible moves of non-pawn pieces:
579 // "sliding or jumping"
580 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
582 const color
= this.getColor(x
,y
);
585 for (let step
of steps
)
589 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
591 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
592 if (oneStep
!== undefined)
597 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
598 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
603 // What are the pawn moves from square x,y ?
604 getPotentialPawnMoves([x
,y
])
606 const color
= this.turn
;
608 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
609 const shiftX
= (color
== "w" ? -1 : 1);
610 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
611 const startRank
= (color
== "w" ? sizeX
-2 : 1);
612 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
613 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
615 if (x
+shiftX
>= 0 && x
+shiftX
< sizeX
) //TODO: always true
617 const finalPieces
= x
+ shiftX
== lastRank
618 ? [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
]
620 // One square forward
621 if (this.board
[x
+shiftX
][y
] == V
.EMPTY
)
623 for (let piece
of finalPieces
)
625 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
],
626 {c:pawnColor
,p:piece
}));
628 // Next condition because pawns on 1st rank can generally jump
629 if ([startRank
,firstRank
].includes(x
)
630 && this.board
[x
+2*shiftX
][y
] == V
.EMPTY
)
633 moves
.push(this.getBasicMove([x
,y
], [x
+2*shiftX
,y
]));
637 for (let shiftY
of [-1,1])
639 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
640 && this.board
[x
+shiftX
][y
+shiftY
] != V
.EMPTY
641 && this.canTake([x
,y
], [x
+shiftX
,y
+shiftY
]))
643 for (let piece
of finalPieces
)
645 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
+shiftY
],
646 {c:pawnColor
,p:piece
}));
655 const Lep
= this.epSquares
.length
;
656 const epSquare
= this.epSquares
[Lep
-1]; //always at least one element
657 if (!!epSquare
&& epSquare
.x
== x
+shiftX
&& Math
.abs(epSquare
.y
- y
) == 1)
659 let enpassantMove
= this.getBasicMove([x
,y
], [epSquare
.x
,epSquare
.y
]);
660 enpassantMove
.vanish
.push({
664 c: this.getColor(x
,epSquare
.y
)
666 moves
.push(enpassantMove
);
673 // What are the rook moves from square x,y ?
674 getPotentialRookMoves(sq
)
676 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
679 // What are the knight moves from square x,y ?
680 getPotentialKnightMoves(sq
)
682 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
685 // What are the bishop moves from square x,y ?
686 getPotentialBishopMoves(sq
)
688 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
691 // What are the queen moves from square x,y ?
692 getPotentialQueenMoves(sq
)
694 return this.getSlideNJumpMoves(sq
,
695 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
698 // What are the king moves from square x,y ?
699 getPotentialKingMoves(sq
)
701 // Initialize with normal moves
702 let moves
= this.getSlideNJumpMoves(sq
,
703 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
704 return moves
.concat(this.getCastleMoves(sq
));
707 getCastleMoves([x
,y
])
709 const c
= this.getColor(x
,y
);
710 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
711 return []; //x isn't first rank, or king has moved (shortcut)
714 const oppCol
= this.getOppCol(c
);
717 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
719 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
721 if (!this.castleFlags
[c
][castleSide
])
723 // If this code is reached, rooks and king are on initial position
725 // Nothing on the path of the king ?
726 // (And no checks; OK also if y==finalSquare)
727 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
728 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
730 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
731 // NOTE: next check is enough, because of chessboard constraints
732 (this.getColor(x
,i
) != c
733 || ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
735 continue castlingCheck
;
739 // Nothing on the path to the rook?
740 step
= castleSide
== 0 ? -1 : 1;
741 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
743 if (this.board
[x
][i
] != V
.EMPTY
)
744 continue castlingCheck
;
746 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
748 // Nothing on final squares, except maybe king and castling rook?
751 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
752 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
753 finalSquares
[castleSide
][i
] != rookPos
)
755 continue castlingCheck
;
759 // If this code is reached, castle is valid
760 moves
.push( new Move({
762 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
763 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
765 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
766 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
767 end: Math
.abs(y
- rookPos
) <= 2
769 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
779 // For the interface: possible moves for the current turn from square sq
780 getPossibleMovesFrom(sq
)
782 return this.filterValid( this.getPotentialMovesFrom(sq
) );
785 // TODO: promotions (into R,B,N,Q) should be filtered only once
788 if (moves
.length
== 0)
790 const color
= this.turn
;
791 return moves
.filter(m
=> {
793 const res
= !this.underCheck(color
);
799 // Search for all valid moves considering current turn
800 // (for engine and game end)
803 const color
= this.turn
;
804 const oppCol
= this.getOppCol(color
);
805 let potentialMoves
= [];
806 for (let i
=0; i
<V
.size
.x
; i
++)
808 for (let j
=0; j
<V
.size
.y
; j
++)
810 // Next condition "!= oppCol" to work with checkered variant
811 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
813 Array
.prototype.push
.apply(potentialMoves
,
814 this.getPotentialMovesFrom([i
,j
]));
818 return this.filterValid(potentialMoves
);
821 // Stop at the first move found
824 const color
= this.turn
;
825 const oppCol
= this.getOppCol(color
);
826 for (let i
=0; i
<V
.size
.x
; i
++)
828 for (let j
=0; j
<V
.size
.y
; j
++)
830 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
832 const moves
= this.getPotentialMovesFrom([i
,j
]);
833 if (moves
.length
> 0)
835 for (let k
=0; k
<moves
.length
; k
++)
837 if (this.filterValid([moves
[k
]]).length
> 0)
847 // Check if pieces of color in 'colors' are attacking (king) on square x,y
848 isAttacked(sq
, colors
)
850 return (this.isAttackedByPawn(sq
, colors
)
851 || this.isAttackedByRook(sq
, colors
)
852 || this.isAttackedByKnight(sq
, colors
)
853 || this.isAttackedByBishop(sq
, colors
)
854 || this.isAttackedByQueen(sq
, colors
)
855 || this.isAttackedByKing(sq
, colors
));
858 // Is square x,y attacked by 'colors' pawns ?
859 isAttackedByPawn([x
,y
], colors
)
861 for (let c
of colors
)
863 let pawnShift
= (c
=="w" ? 1 : -1);
864 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
866 for (let i
of [-1,1])
868 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
869 && this.getColor(x
+pawnShift
,y
+i
)==c
)
879 // Is square x,y attacked by 'colors' rooks ?
880 isAttackedByRook(sq
, colors
)
882 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
885 // Is square x,y attacked by 'colors' knights ?
886 isAttackedByKnight(sq
, colors
)
888 return this.isAttackedBySlideNJump(sq
, colors
,
889 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
892 // Is square x,y attacked by 'colors' bishops ?
893 isAttackedByBishop(sq
, colors
)
895 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
898 // Is square x,y attacked by 'colors' queens ?
899 isAttackedByQueen(sq
, colors
)
901 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
902 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
905 // Is square x,y attacked by 'colors' king(s) ?
906 isAttackedByKing(sq
, colors
)
908 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
909 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
912 // Generic method for non-pawn pieces ("sliding or jumping"):
913 // is x,y attacked by a piece of color in array 'colors' ?
914 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
916 for (let step
of steps
)
918 let rx
= x
+step
[0], ry
= y
+step
[1];
919 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
924 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
925 && colors
.includes(this.getColor(rx
,ry
)))
933 // Is color under check after his move ?
936 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
942 // Apply a move on board
943 static PlayOnBoard(board
, move)
945 for (let psq
of move.vanish
)
946 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
947 for (let psq
of move.appear
)
948 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
950 // Un-apply the played move
951 static UndoOnBoard(board
, move)
953 for (let psq
of move.appear
)
954 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
955 for (let psq
of move.vanish
)
956 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
959 // After move is played, update variables + flags
960 updateVariables(move)
962 const piece
= move.vanish
[0].p
;
963 const c
= this.getOppCol(this.turn
); //'move.vanish[0].c' doesn't work for Checkered
964 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
966 // Update king position + flags
967 if (piece
== V
.KING
&& move.appear
.length
> 0)
969 this.kingPos
[c
][0] = move.appear
[0].x
;
970 this.kingPos
[c
][1] = move.appear
[0].y
;
971 this.castleFlags
[c
] = [false,false];
974 const oppCol
= this.getOppCol(c
);
975 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
976 if (move.start
.x
== firstRank
//our rook moves?
977 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
979 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
980 this.castleFlags
[c
][flagIdx
] = false;
982 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
983 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
985 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
986 this.castleFlags
[oppCol
][flagIdx
] = false;
990 // After move is undo-ed *and flags resetted*, un-update other variables
991 // TODO: more symmetry, by storing flags increment in move (?!)
992 unupdateVariables(move)
994 // (Potentially) Reset king position
995 const c
= this.getColor(move.start
.x
,move.start
.y
);
996 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
997 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1003 // if (!this.states) this.states = [];
1004 // if (!ingame) this.states.push(this.getFen());
1007 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
1010 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1012 this.epSquares
.push( this.getEpSquare(move) );
1013 V
.PlayOnBoard(this.board
, move);
1014 this.turn
= this.getOppCol(this.turn
);
1015 this.moves
.push(move);
1016 this.updateVariables(move);
1020 // Hash of current game state *after move*, to detect repetitions
1021 move.hash
= hex_md5(this.getFen());
1028 this.epSquares
.pop();
1030 this.disaggregateFlags(JSON
.parse(move.flags
));
1031 V
.UndoOnBoard(this.board
, move);
1032 this.turn
= this.getOppCol(this.turn
);
1034 this.unupdateVariables(move);
1037 // if (this.getFen() != this.states[this.states.length-1])
1039 // this.states.pop();
1045 // Check for 3 repetitions (position + flags + turn)
1048 if (!this.hashStates
)
1049 this.hashStates
= {};
1051 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
1052 // Update this.hashStates with last move (or all moves if continuation)
1053 // NOTE: redundant storage, but faster and moderate size
1054 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
1056 const move = this.moves
[i
];
1057 if (!this.hashStates
[move.hash
])
1058 this.hashStates
[move.hash
] = 1;
1060 this.hashStates
[move.hash
]++;
1062 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
1065 // Is game over ? And if yes, what is the score ?
1068 if (this.checkRepetition())
1071 if (this.atLeastOneMove()) // game not over
1075 return this.checkGameEnd();
1078 // No moves are possible: compute score
1081 const color
= this.turn
;
1082 // No valid move: stalemate or checkmate?
1083 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
1086 return color
== "w" ? "0-1" : "1-0";
1105 // "Checkmate" (unreachable eval)
1106 static get INFINITY() { return 9999; }
1108 // At this value or above, the game is over
1109 static get THRESHOLD_MATE() { return V
.INFINITY
; }
1111 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1112 static get SEARCH_DEPTH() { return 3; }
1114 // Assumption: at least one legal move
1115 // NOTE: works also for extinction chess because depth is 3...
1118 const maxeval
= V
.INFINITY
;
1119 const color
= this.turn
;
1120 // Some variants may show a bigger moves list to the human (Switching),
1121 // thus the argument "computer" below (which is generally ignored)
1122 let moves1
= this.getAllValidMoves("computer");
1124 // Can I mate in 1 ? (for Magnetic & Extinction)
1125 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
1127 this.play(moves1
[i
]);
1128 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
1129 if (!finish
&& !this.atLeastOneMove())
1131 // Test mate (for other variants)
1132 const score
= this.checkGameEnd();
1136 this.undo(moves1
[i
]);
1141 // Rank moves using a min-max at depth 2
1142 for (let i
=0; i
<moves1
.length
; i
++)
1144 // Initial self evaluation is very low: "I'm checkmated"
1145 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
;
1146 this.play(moves1
[i
]);
1147 let eval2
= undefined;
1148 if (this.atLeastOneMove())
1150 // Initial enemy evaluation is very low too, for him
1151 eval2
= (color
=="w" ? 1 : -1) * maxeval
;
1152 // Second half-move:
1153 let moves2
= this.getAllValidMoves("computer");
1154 for (let j
=0; j
<moves2
.length
; j
++)
1156 this.play(moves2
[j
]);
1157 let evalPos
= undefined;
1158 if (this.atLeastOneMove())
1159 evalPos
= this.evalPosition()
1162 // Working with scores is more accurate (necessary for Loser variant)
1163 const score
= this.checkGameEnd();
1164 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1166 if ((color
== "w" && evalPos
< eval2
)
1167 || (color
=="b" && evalPos
> eval2
))
1171 this.undo(moves2
[j
]);
1176 const score
= this.checkGameEnd();
1177 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1179 if ((color
=="w" && eval2
> moves1
[i
].eval
)
1180 || (color
=="b" && eval2
< moves1
[i
].eval
))
1182 moves1
[i
].eval
= eval2
;
1184 this.undo(moves1
[i
]);
1186 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1188 let candidates
= [0]; //indices of candidates moves
1189 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1191 let currentBest
= moves1
[_
.sample(candidates
, 1)];
1193 // From here, depth >= 3: may take a while, so we control time
1194 const timeStart
= Date
.now();
1196 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1197 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
1199 for (let i
=0; i
<moves1
.length
; i
++)
1201 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
1202 return currentBest
; //depth 2 at least
1203 this.play(moves1
[i
]);
1204 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1205 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
1206 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
1207 this.undo(moves1
[i
]);
1209 moves1
.sort( (a
,b
) => {
1210 return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1214 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1217 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1219 return moves1
[_
.sample(candidates
, 1)];
1222 alphabeta(depth
, alpha
, beta
)
1224 const maxeval
= V
.INFINITY
;
1225 const color
= this.turn
;
1226 if (!this.atLeastOneMove())
1228 switch (this.checkGameEnd())
1233 const score
= this.checkGameEnd();
1234 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1238 return this.evalPosition();
1239 const moves
= this.getAllValidMoves("computer");
1240 let v
= color
=="w" ? -maxeval : maxeval
;
1243 for (let i
=0; i
<moves
.length
; i
++)
1245 this.play(moves
[i
]);
1246 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1247 this.undo(moves
[i
]);
1248 alpha
= Math
.max(alpha
, v
);
1250 break; //beta cutoff
1255 for (let i
=0; i
<moves
.length
; i
++)
1257 this.play(moves
[i
]);
1258 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1259 this.undo(moves
[i
]);
1260 beta
= Math
.min(beta
, v
);
1262 break; //alpha cutoff
1271 // Just count material for now
1272 for (let i
=0; i
<V
.size
.x
; i
++)
1274 for (let j
=0; j
<V
.size
.y
; j
++)
1276 if (this.board
[i
][j
] != V
.EMPTY
)
1278 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1279 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1286 /////////////////////////
1287 // MOVES + GAME NOTATION
1288 /////////////////////////
1290 // Context: just before move is played, turn hasn't changed
1293 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1294 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1296 // Translate final square
1297 const finalSquare
= V
.CoordsToSquare(move.end
);
1299 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1300 if (piece
== V
.PAWN
)
1304 if (move.vanish
.length
> move.appear
.length
)
1307 const startColumn
= V
.CoordToColumn(move.start
.y
);
1308 notation
= startColumn
+ "x" + finalSquare
;
1311 notation
= finalSquare
;
1312 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
) //promotion
1313 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1320 return piece
.toUpperCase() +
1321 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1325 // Complete the usual notation, may be required for de-ambiguification
1326 getLongNotation(move)
1328 // Not encoding move. But short+long is enough
1329 return V
.CoordsToSquare(move.start
) + V
.CoordsToSquare(move.end
);
1332 // The score is already computed when calling this function
1333 getPGN(mycolor
, score
, fenStart
, mode
)
1336 pgn
+= '[Site "vchess.club"]<br>';
1337 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1338 pgn
+= '[Variant "' + variant
+ '"]<br>';
1339 pgn
+= '[Date "' + getDate(new Date()) + '"]<br>';
1340 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1341 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1342 pgn
+= '[FenStart "' + fenStart
+ '"]<br>';
1343 pgn
+= '[Fen "' + this.getFen() + '"]<br>';
1344 pgn
+= '[Result "' + score
+ '"]<br><br>';
1347 for (let i
=0; i
<this.moves
.length
; i
++)
1350 pgn
+= ((i
/2)+1) + ".";
1351 pgn
+= this.moves
[i
].notation
[0] + " ";
1355 // "Complete moves" PGN (helping in ambiguous cases)
1356 for (let i
=0; i
<this.moves
.length
; i
++)
1359 pgn
+= ((i
/2)+1) + ".";
1360 pgn
+= this.moves
[i
].notation
[1] + " ";