8f875e4f918d727d99a2e5e404c30703bc5f5f3b
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 // TODO: next conditions are first for Atomic, and third for Checkered
190 if (move.appear
.length
> 0 && move.appear
[0].p
== V
.PAWN
&& ["w","b"].includes(move.appear
[0].c
) && Math
.abs(sx
- ex
) == 2)
197 return undefined; //default
200 // Can thing on square1 take thing on square2
201 canTake([x1
,y1
], [x2
,y2
])
203 return this.getColor(x1
,y1
) !== this.getColor(x2
,y2
);
206 // Is (x,y) on the chessboard?
209 return (x
>=0 && x
<V
.size
.x
&& y
>=0 && y
<V
.size
.y
);
212 // Used in interface: 'side' arg == player color
213 canIplay(side
, [x
,y
])
215 return (this.turn
== side
&& this.getColor(x
,y
) == side
);
218 // On which squares is color under check ? (for interface)
219 getCheckSquares(color
)
221 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)])
222 ? [JSON
.parse(JSON
.stringify(this.kingPos
[color
]))] //need to duplicate!
229 // Setup the initial random (assymetric) position
230 static GenRandInitFen()
232 let pieces
= { "w": new Array(8), "b": new Array(8) };
233 // Shuffle pieces on first and last rank
234 for (let c
of ["w","b"])
236 let positions
= _
.range(8);
238 // Get random squares for bishops
239 let randIndex
= 2 * _
.random(3);
240 const bishop1Pos
= positions
[randIndex
];
241 // The second bishop must be on a square of different color
242 let randIndex_tmp
= 2 * _
.random(3) + 1;
243 const bishop2Pos
= positions
[randIndex_tmp
];
244 // Remove chosen squares
245 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
246 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
248 // Get random squares for knights
249 randIndex
= _
.random(5);
250 const knight1Pos
= positions
[randIndex
];
251 positions
.splice(randIndex
, 1);
252 randIndex
= _
.random(4);
253 const knight2Pos
= positions
[randIndex
];
254 positions
.splice(randIndex
, 1);
256 // Get random square for queen
257 randIndex
= _
.random(3);
258 const queenPos
= positions
[randIndex
];
259 positions
.splice(randIndex
, 1);
261 // Rooks and king positions are now fixed,
262 // because of the ordering rook-king-rook
263 const rook1Pos
= positions
[0];
264 const kingPos
= positions
[1];
265 const rook2Pos
= positions
[2];
267 // Finally put the shuffled pieces in the board array
268 pieces
[c
][rook1Pos
] = 'r';
269 pieces
[c
][knight1Pos
] = 'n';
270 pieces
[c
][bishop1Pos
] = 'b';
271 pieces
[c
][queenPos
] = 'q';
272 pieces
[c
][kingPos
] = 'k';
273 pieces
[c
][bishop2Pos
] = 'b';
274 pieces
[c
][knight2Pos
] = 'n';
275 pieces
[c
][rook2Pos
] = 'r';
277 return pieces
["b"].join("") +
278 "/pppppppp/8/8/8/8/PPPPPPPP/" +
279 pieces
["w"].join("").toUpperCase() +
280 " w 1111 -"; //add turn + flags + enpassant
283 // "Parse" FEN: just return untransformed string data
286 const fenParts
= fen
.split(" ");
289 position: fenParts
[0],
294 Object
.assign(res
, {flags: fenParts
[nextIdx
++]});
296 Object
.assign(res
, {enpassant: fenParts
[nextIdx
]});
300 // Return current fen (game state)
303 return this.getBaseFen() + " " + this.getTurnFen() +
304 (V
.HasFlags
? (" " + this.getFlagsFen()) : "") +
305 (V
.HasEnpassant
? (" " + this.getEnpassantFen()) : "");
308 // Position part of the FEN string
312 for (let i
=0; i
<V
.size
.x
; i
++)
315 for (let j
=0; j
<V
.size
.y
; j
++)
317 if (this.board
[i
][j
] == V
.EMPTY
)
323 // Add empty squares in-between
324 position
+= emptyCount
;
327 position
+= V
.board2fen(this.board
[i
][j
]);
333 position
+= emptyCount
;
335 if (i
< V
.size
.x
- 1)
336 position
+= "/"; //separate rows
346 // Flags part of the FEN string
350 // Add castling flags
351 for (let i
of ['w','b'])
353 for (let j
=0; j
<2; j
++)
354 flags
+= (this.castleFlags
[i
][j
] ? '1' : '0');
359 // Enpassant part of the FEN string
362 const L
= this.epSquares
.length
;
363 if (!this.epSquares
[L
-1])
364 return "-"; //no en-passant
365 return V
.CoordsToSquare(this.epSquares
[L
-1]);
368 // Turn position fen into double array ["wb","wp","bk",...]
369 static GetBoard(position
)
371 const rows
= position
.split("/");
372 let board
= doubleArray(V
.size
.x
, V
.size
.y
, "");
373 for (let i
=0; i
<rows
.length
; i
++)
376 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
378 const character
= rows
[i
][indexInRow
];
379 const num
= parseInt(character
);
381 j
+= num
; //just shift j
382 else //something at position i,j
383 board
[i
][j
++] = V
.fen2board(character
);
389 // Extract (relevant) flags from fen
392 // white a-castle, h-castle, black a-castle, h-castle
393 this.castleFlags
= {'w': [true,true], 'b': [true,true]};
396 for (let i
=0; i
<4; i
++)
397 this.castleFlags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenflags
.charAt(i
) == '1');
403 // Fen string fully describes the game state
404 constructor(fen
, moves
)
407 const fenParsed
= V
.ParseFen(fen
);
408 this.board
= V
.GetBoard(fenParsed
.position
);
409 this.turn
= fenParsed
.turn
[0]; //[0] to work with MarseilleRules
410 this.setOtherVariables(fen
);
413 // Scan board for kings and rooks positions
416 this.INIT_COL_KING
= {'w':-1, 'b':-1};
417 this.INIT_COL_ROOK
= {'w':[-1,-1], 'b':[-1,-1]};
418 this.kingPos
= {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
419 const fenRows
= V
.ParseFen(fen
).position
.split("/");
420 for (let i
=0; i
<fenRows
.length
; i
++)
422 let k
= 0; //column index on board
423 for (let j
=0; j
<fenRows
[i
].length
; j
++)
425 switch (fenRows
[i
].charAt(j
))
428 this.kingPos
['b'] = [i
,k
];
429 this.INIT_COL_KING
['b'] = k
;
432 this.kingPos
['w'] = [i
,k
];
433 this.INIT_COL_KING
['w'] = k
;
436 if (this.INIT_COL_ROOK
['b'][0] < 0)
437 this.INIT_COL_ROOK
['b'][0] = k
;
439 this.INIT_COL_ROOK
['b'][1] = k
;
442 if (this.INIT_COL_ROOK
['w'][0] < 0)
443 this.INIT_COL_ROOK
['w'][0] = k
;
445 this.INIT_COL_ROOK
['w'][1] = k
;
448 const num
= parseInt(fenRows
[i
].charAt(j
));
457 // Some additional variables from FEN (variant dependant)
458 setOtherVariables(fen
)
460 // Set flags and enpassant:
461 const parsedFen
= V
.ParseFen(fen
);
463 this.setFlags(parsedFen
.flags
);
466 const epSq
= parsedFen
.enpassant
!= "-"
467 ? V
.SquareToCoords(parsedFen
.enpassant
)
469 this.epSquares
= [ epSq
];
471 // Search for king and rooks positions:
472 this.scanKingsRooks(fen
);
475 /////////////////////
483 // Color of thing on suqare (i,j). 'undefined' if square is empty
486 return this.board
[i
][j
].charAt(0);
489 // Piece type on square (i,j). 'undefined' if square is empty
492 return this.board
[i
][j
].charAt(1);
495 // Get opponent color
498 return (color
=="w" ? "b" : "w");
503 const L
= this.moves
.length
;
504 return (L
>0 ? this.moves
[L
-1] : null);
507 // Pieces codes (for a clearer code)
508 static get PAWN() { return 'p'; }
509 static get ROOK() { return 'r'; }
510 static get KNIGHT() { return 'n'; }
511 static get BISHOP() { return 'b'; }
512 static get QUEEN() { return 'q'; }
513 static get KING() { return 'k'; }
518 return [V
.PAWN
,V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
,V
.KING
];
522 static get EMPTY() { return ""; }
524 // Some pieces movements
528 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
529 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
530 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
537 // All possible moves from selected square (assumption: color is OK)
538 getPotentialMovesFrom([x
,y
])
540 switch (this.getPiece(x
,y
))
543 return this.getPotentialPawnMoves([x
,y
]);
545 return this.getPotentialRookMoves([x
,y
]);
547 return this.getPotentialKnightMoves([x
,y
]);
549 return this.getPotentialBishopMoves([x
,y
]);
551 return this.getPotentialQueenMoves([x
,y
]);
553 return this.getPotentialKingMoves([x
,y
]);
557 // Build a regular move from its initial and destination squares.
558 // tr: transformation
559 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
566 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
567 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
574 c: this.getColor(sx
,sy
),
575 p: this.getPiece(sx
,sy
)
580 // The opponent piece disappears if we take it
581 if (this.board
[ex
][ey
] != V
.EMPTY
)
587 c: this.getColor(ex
,ey
),
588 p: this.getPiece(ex
,ey
)
595 // Generic method to find possible moves of non-pawn pieces:
596 // "sliding or jumping"
597 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
599 const color
= this.getColor(x
,y
);
602 for (let step
of steps
)
606 while (V
.OnBoard(i
,j
) && this.board
[i
][j
] == V
.EMPTY
)
608 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
609 if (oneStep
!== undefined)
614 if (V
.OnBoard(i
,j
) && this.canTake([x
,y
], [i
,j
]))
615 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
620 // What are the pawn moves from square x,y ?
621 getPotentialPawnMoves([x
,y
])
623 const color
= this.turn
;
625 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
626 const shiftX
= (color
== "w" ? -1 : 1);
627 const firstRank
= (color
== 'w' ? sizeX
-1 : 0);
628 const startRank
= (color
== "w" ? sizeX
-2 : 1);
629 const lastRank
= (color
== "w" ? 0 : sizeX
-1);
630 const pawnColor
= this.getColor(x
,y
); //can be different for checkered
632 // NOTE: next condition is generally true (no pawn on last rank)
633 if (x
+shiftX
>= 0 && x
+shiftX
< sizeX
)
635 const finalPieces
= x
+ shiftX
== lastRank
636 ? [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
]
638 // One square forward
639 if (this.board
[x
+shiftX
][y
] == V
.EMPTY
)
641 for (let piece
of finalPieces
)
643 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
],
644 {c:pawnColor
,p:piece
}));
646 // Next condition because pawns on 1st rank can generally jump
647 if ([startRank
,firstRank
].includes(x
)
648 && this.board
[x
+2*shiftX
][y
] == V
.EMPTY
)
651 moves
.push(this.getBasicMove([x
,y
], [x
+2*shiftX
,y
]));
655 for (let shiftY
of [-1,1])
657 if (y
+ shiftY
>= 0 && y
+ shiftY
< sizeY
658 && this.board
[x
+shiftX
][y
+shiftY
] != V
.EMPTY
659 && this.canTake([x
,y
], [x
+shiftX
,y
+shiftY
]))
661 for (let piece
of finalPieces
)
663 moves
.push(this.getBasicMove([x
,y
], [x
+shiftX
,y
+shiftY
],
664 {c:pawnColor
,p:piece
}));
673 const Lep
= this.epSquares
.length
;
674 const epSquare
= this.epSquares
[Lep
-1]; //always at least one element
675 if (!!epSquare
&& epSquare
.x
== x
+shiftX
&& Math
.abs(epSquare
.y
- y
) == 1)
677 let enpassantMove
= this.getBasicMove([x
,y
], [epSquare
.x
,epSquare
.y
]);
678 enpassantMove
.vanish
.push({
682 c: this.getColor(x
,epSquare
.y
)
684 moves
.push(enpassantMove
);
691 // What are the rook moves from square x,y ?
692 getPotentialRookMoves(sq
)
694 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.ROOK
]);
697 // What are the knight moves from square x,y ?
698 getPotentialKnightMoves(sq
)
700 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.KNIGHT
], "oneStep");
703 // What are the bishop moves from square x,y ?
704 getPotentialBishopMoves(sq
)
706 return this.getSlideNJumpMoves(sq
, V
.steps
[V
.BISHOP
]);
709 // What are the queen moves from square x,y ?
710 getPotentialQueenMoves(sq
)
712 return this.getSlideNJumpMoves(sq
,
713 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
716 // What are the king moves from square x,y ?
717 getPotentialKingMoves(sq
)
719 // Initialize with normal moves
720 let moves
= this.getSlideNJumpMoves(sq
,
721 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
722 return moves
.concat(this.getCastleMoves(sq
));
725 getCastleMoves([x
,y
])
727 const c
= this.getColor(x
,y
);
728 if (x
!= (c
=="w" ? V
.size
.x
-1 : 0) || y
!= this.INIT_COL_KING
[c
])
729 return []; //x isn't first rank, or king has moved (shortcut)
732 const oppCol
= this.getOppCol(c
);
735 const finalSquares
= [ [2,3], [V
.size
.y
-2,V
.size
.y
-3] ]; //king, then rook
737 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
739 if (!this.castleFlags
[c
][castleSide
])
741 // If this code is reached, rooks and king are on initial position
743 // Nothing on the path of the king ?
744 // (And no checks; OK also if y==finalSquare)
745 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
746 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
748 if (this.isAttacked([x
,i
], [oppCol
]) || (this.board
[x
][i
] != V
.EMPTY
&&
749 // NOTE: next check is enough, because of chessboard constraints
750 (this.getColor(x
,i
) != c
751 || ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
753 continue castlingCheck
;
757 // Nothing on the path to the rook?
758 step
= castleSide
== 0 ? -1 : 1;
759 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
761 if (this.board
[x
][i
] != V
.EMPTY
)
762 continue castlingCheck
;
764 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
766 // Nothing on final squares, except maybe king and castling rook?
769 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
770 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
771 finalSquares
[castleSide
][i
] != rookPos
)
773 continue castlingCheck
;
777 // If this code is reached, castle is valid
778 moves
.push( new Move({
780 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
781 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
783 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
784 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
785 end: Math
.abs(y
- rookPos
) <= 2
787 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
797 // For the interface: possible moves for the current turn from square sq
798 getPossibleMovesFrom(sq
)
800 return this.filterValid( this.getPotentialMovesFrom(sq
) );
803 // TODO: promotions (into R,B,N,Q) should be filtered only once
806 if (moves
.length
== 0)
808 const color
= this.turn
;
809 return moves
.filter(m
=> {
811 const res
= !this.underCheck(color
);
817 // Search for all valid moves considering current turn
818 // (for engine and game end)
821 const color
= this.turn
;
822 const oppCol
= this.getOppCol(color
);
823 let potentialMoves
= [];
824 for (let i
=0; i
<V
.size
.x
; i
++)
826 for (let j
=0; j
<V
.size
.y
; j
++)
828 // Next condition "!= oppCol" to work with checkered variant
829 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
831 Array
.prototype.push
.apply(potentialMoves
,
832 this.getPotentialMovesFrom([i
,j
]));
836 return this.filterValid(potentialMoves
);
839 // Stop at the first move found
842 const color
= this.turn
;
843 const oppCol
= this.getOppCol(color
);
844 for (let i
=0; i
<V
.size
.x
; i
++)
846 for (let j
=0; j
<V
.size
.y
; j
++)
848 if (this.board
[i
][j
] != V
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
850 const moves
= this.getPotentialMovesFrom([i
,j
]);
851 if (moves
.length
> 0)
853 for (let k
=0; k
<moves
.length
; k
++)
855 if (this.filterValid([moves
[k
]]).length
> 0)
865 // Check if pieces of color in 'colors' are attacking (king) on square x,y
866 isAttacked(sq
, colors
)
868 return (this.isAttackedByPawn(sq
, colors
)
869 || this.isAttackedByRook(sq
, colors
)
870 || this.isAttackedByKnight(sq
, colors
)
871 || this.isAttackedByBishop(sq
, colors
)
872 || this.isAttackedByQueen(sq
, colors
)
873 || this.isAttackedByKing(sq
, colors
));
876 // Is square x,y attacked by 'colors' pawns ?
877 isAttackedByPawn([x
,y
], colors
)
879 for (let c
of colors
)
881 let pawnShift
= (c
=="w" ? 1 : -1);
882 if (x
+pawnShift
>=0 && x
+pawnShift
<V
.size
.x
)
884 for (let i
of [-1,1])
886 if (y
+i
>=0 && y
+i
<V
.size
.y
&& this.getPiece(x
+pawnShift
,y
+i
)==V
.PAWN
887 && this.getColor(x
+pawnShift
,y
+i
)==c
)
897 // Is square x,y attacked by 'colors' rooks ?
898 isAttackedByRook(sq
, colors
)
900 return this.isAttackedBySlideNJump(sq
, colors
, V
.ROOK
, V
.steps
[V
.ROOK
]);
903 // Is square x,y attacked by 'colors' knights ?
904 isAttackedByKnight(sq
, colors
)
906 return this.isAttackedBySlideNJump(sq
, colors
,
907 V
.KNIGHT
, V
.steps
[V
.KNIGHT
], "oneStep");
910 // Is square x,y attacked by 'colors' bishops ?
911 isAttackedByBishop(sq
, colors
)
913 return this.isAttackedBySlideNJump(sq
, colors
, V
.BISHOP
, V
.steps
[V
.BISHOP
]);
916 // Is square x,y attacked by 'colors' queens ?
917 isAttackedByQueen(sq
, colors
)
919 return this.isAttackedBySlideNJump(sq
, colors
, V
.QUEEN
,
920 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
923 // Is square x,y attacked by 'colors' king(s) ?
924 isAttackedByKing(sq
, colors
)
926 return this.isAttackedBySlideNJump(sq
, colors
, V
.KING
,
927 V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]), "oneStep");
930 // Generic method for non-pawn pieces ("sliding or jumping"):
931 // is x,y attacked by a piece of color in array 'colors' ?
932 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
934 for (let step
of steps
)
936 let rx
= x
+step
[0], ry
= y
+step
[1];
937 while (V
.OnBoard(rx
,ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
)
942 if (V
.OnBoard(rx
,ry
) && this.getPiece(rx
,ry
) === piece
943 && colors
.includes(this.getColor(rx
,ry
)))
951 // Is color under check after his move ?
954 return this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]);
960 // Apply a move on board
961 static PlayOnBoard(board
, move)
963 for (let psq
of move.vanish
)
964 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
965 for (let psq
of move.appear
)
966 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
968 // Un-apply the played move
969 static UndoOnBoard(board
, move)
971 for (let psq
of move.appear
)
972 board
[psq
.x
][psq
.y
] = V
.EMPTY
;
973 for (let psq
of move.vanish
)
974 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
977 // After move is played, update variables + flags
978 updateVariables(move)
980 let piece
= undefined;
982 if (move.vanish
.length
>= 1)
984 // Usual case, something is moved
985 piece
= move.vanish
[0].p
;
986 c
= move.vanish
[0].c
;
990 // Crazyhouse-like variants
991 piece
= move.appear
[0].p
;
992 c
= move.appear
[0].c
;
994 if (c
== "c") //if (!["w","b"].includes(c))
996 // 'c = move.vanish[0].c' doesn't work for Checkered
997 c
= this.getOppCol(this.turn
);
999 const firstRank
= (c
== "w" ? V
.size
.x
-1 : 0);
1001 // Update king position + flags
1002 if (piece
== V
.KING
&& move.appear
.length
> 0)
1004 this.kingPos
[c
][0] = move.appear
[0].x
;
1005 this.kingPos
[c
][1] = move.appear
[0].y
;
1007 this.castleFlags
[c
] = [false,false];
1012 // Update castling flags if rooks are moved
1013 const oppCol
= this.getOppCol(c
);
1014 const oppFirstRank
= (V
.size
.x
-1) - firstRank
;
1015 if (move.start
.x
== firstRank
//our rook moves?
1016 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
1018 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
1019 this.castleFlags
[c
][flagIdx
] = false;
1021 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
1022 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
1024 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
1025 this.castleFlags
[oppCol
][flagIdx
] = false;
1030 // After move is undo-ed *and flags resetted*, un-update other variables
1031 // TODO: more symmetry, by storing flags increment in move (?!)
1032 unupdateVariables(move)
1034 // (Potentially) Reset king position
1035 const c
= this.getColor(move.start
.x
,move.start
.y
);
1036 if (this.getPiece(move.start
.x
,move.start
.y
) == V
.KING
)
1037 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
1043 // if (!this.states) this.states = [];
1044 // if (!ingame) this.states.push(this.getFen());
1047 move.notation
= [this.getNotation(move), this.getLongNotation(move)];
1050 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
1052 this.epSquares
.push( this.getEpSquare(move) );
1053 V
.PlayOnBoard(this.board
, move);
1054 this.turn
= this.getOppCol(this.turn
);
1055 this.moves
.push(move);
1056 this.updateVariables(move);
1060 // Hash of current game state *after move*, to detect repetitions
1061 move.hash
= hex_md5(this.getFen());
1068 this.epSquares
.pop();
1070 this.disaggregateFlags(JSON
.parse(move.flags
));
1071 V
.UndoOnBoard(this.board
, move);
1072 this.turn
= this.getOppCol(this.turn
);
1074 this.unupdateVariables(move);
1077 // if (this.getFen() != this.states[this.states.length-1])
1079 // this.states.pop();
1085 // Check for 3 repetitions (position + flags + turn)
1088 if (!this.hashStates
)
1089 this.hashStates
= {};
1091 Object
.values(this.hashStates
).reduce((a
,b
) => { return a
+b
; }, 0)
1092 // Update this.hashStates with last move (or all moves if continuation)
1093 // NOTE: redundant storage, but faster and moderate size
1094 for (let i
=startIndex
; i
<this.moves
.length
; i
++)
1096 const move = this.moves
[i
];
1097 if (!this.hashStates
[move.hash
])
1098 this.hashStates
[move.hash
] = 1;
1100 this.hashStates
[move.hash
]++;
1102 return Object
.values(this.hashStates
).some(elt
=> { return (elt
>= 3); });
1105 // Is game over ? And if yes, what is the score ?
1108 if (this.checkRepetition())
1111 if (this.atLeastOneMove()) // game not over
1115 return this.checkGameEnd();
1118 // No moves are possible: compute score
1121 const color
= this.turn
;
1122 // No valid move: stalemate or checkmate?
1123 if (!this.isAttacked(this.kingPos
[color
], [this.getOppCol(color
)]))
1126 return (color
== "w" ? "0-1" : "1-0");
1145 // "Checkmate" (unreachable eval)
1146 static get INFINITY() { return 9999; }
1148 // At this value or above, the game is over
1149 static get THRESHOLD_MATE() { return V
.INFINITY
; }
1151 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
1152 static get SEARCH_DEPTH() { return 3; }
1154 // Assumption: at least one legal move
1155 // NOTE: works also for extinction chess because depth is 3...
1158 const maxeval
= V
.INFINITY
;
1159 const color
= this.turn
;
1160 // Some variants may show a bigger moves list to the human (Switching),
1161 // thus the argument "computer" below (which is generally ignored)
1162 let moves1
= this.getAllValidMoves("computer");
1164 // Can I mate in 1 ? (for Magnetic & Extinction)
1165 for (let i
of _
.shuffle(_
.range(moves1
.length
)))
1167 this.play(moves1
[i
]);
1168 let finish
= (Math
.abs(this.evalPosition()) >= V
.THRESHOLD_MATE
);
1169 if (!finish
&& !this.atLeastOneMove())
1171 // Test mate (for other variants)
1172 const score
= this.checkGameEnd();
1176 this.undo(moves1
[i
]);
1181 // Rank moves using a min-max at depth 2
1182 for (let i
=0; i
<moves1
.length
; i
++)
1184 // Initial self evaluation is very low: "I'm checkmated"
1185 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * maxeval
;
1186 this.play(moves1
[i
]);
1187 let eval2
= undefined;
1188 if (this.atLeastOneMove())
1190 // Initial enemy evaluation is very low too, for him
1191 eval2
= (color
=="w" ? 1 : -1) * maxeval
;
1192 // Second half-move:
1193 let moves2
= this.getAllValidMoves("computer");
1194 for (let j
=0; j
<moves2
.length
; j
++)
1196 this.play(moves2
[j
]);
1197 let evalPos
= undefined;
1198 if (this.atLeastOneMove())
1199 evalPos
= this.evalPosition()
1202 // Working with scores is more accurate (necessary for Loser variant)
1203 const score
= this.checkGameEnd();
1204 evalPos
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1206 if ((color
== "w" && evalPos
< eval2
)
1207 || (color
=="b" && evalPos
> eval2
))
1211 this.undo(moves2
[j
]);
1216 const score
= this.checkGameEnd();
1217 eval2
= (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1219 if ((color
=="w" && eval2
> moves1
[i
].eval
)
1220 || (color
=="b" && eval2
< moves1
[i
].eval
))
1222 moves1
[i
].eval
= eval2
;
1224 this.undo(moves1
[i
]);
1226 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1228 let candidates
= [0]; //indices of candidates moves
1229 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1231 let currentBest
= moves1
[_
.sample(candidates
, 1)];
1233 // From here, depth >= 3: may take a while, so we control time
1234 const timeStart
= Date
.now();
1236 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
1237 if (V
.SEARCH_DEPTH
>= 3 && Math
.abs(moves1
[0].eval
) < V
.THRESHOLD_MATE
)
1239 for (let i
=0; i
<moves1
.length
; i
++)
1241 if (Date
.now()-timeStart
>= 5000) //more than 5 seconds
1242 return currentBest
; //depth 2 at least
1243 this.play(moves1
[i
]);
1244 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
1245 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+
1246 this.alphabeta(V
.SEARCH_DEPTH
-1, -maxeval
, maxeval
);
1247 this.undo(moves1
[i
]);
1249 moves1
.sort( (a
,b
) => {
1250 return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
1254 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1257 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
1259 return moves1
[_
.sample(candidates
, 1)];
1262 alphabeta(depth
, alpha
, beta
)
1264 const maxeval
= V
.INFINITY
;
1265 const color
= this.turn
;
1266 if (!this.atLeastOneMove())
1268 switch (this.checkGameEnd())
1273 const score
= this.checkGameEnd();
1274 return (score
=="1/2" ? 0 : (score
=="1-0" ? 1 : -1) * maxeval
);
1278 return this.evalPosition();
1279 const moves
= this.getAllValidMoves("computer");
1280 let v
= color
=="w" ? -maxeval : maxeval
;
1283 for (let i
=0; i
<moves
.length
; i
++)
1285 this.play(moves
[i
]);
1286 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
1287 this.undo(moves
[i
]);
1288 alpha
= Math
.max(alpha
, v
);
1290 break; //beta cutoff
1295 for (let i
=0; i
<moves
.length
; i
++)
1297 this.play(moves
[i
]);
1298 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
1299 this.undo(moves
[i
]);
1300 beta
= Math
.min(beta
, v
);
1302 break; //alpha cutoff
1311 // Just count material for now
1312 for (let i
=0; i
<V
.size
.x
; i
++)
1314 for (let j
=0; j
<V
.size
.y
; j
++)
1316 if (this.board
[i
][j
] != V
.EMPTY
)
1318 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
1319 evaluation
+= sign
* V
.VALUES
[this.getPiece(i
,j
)];
1326 /////////////////////////
1327 // MOVES + GAME NOTATION
1328 /////////////////////////
1330 // Context: just before move is played, turn hasn't changed
1333 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
) //castle
1334 return (move.end
.y
< move.start
.y
? "0-0-0" : "0-0");
1336 // Translate final square
1337 const finalSquare
= V
.CoordsToSquare(move.end
);
1339 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1340 if (piece
== V
.PAWN
)
1344 if (move.vanish
.length
> move.appear
.length
)
1347 const startColumn
= V
.CoordToColumn(move.start
.y
);
1348 notation
= startColumn
+ "x" + finalSquare
;
1351 notation
= finalSquare
;
1352 if (move.appear
.length
> 0 && move.appear
[0].p
!= V
.PAWN
) //promotion
1353 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1360 return piece
.toUpperCase() +
1361 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1365 // Complete the usual notation, may be required for de-ambiguification
1366 getLongNotation(move)
1368 // Not encoding move. But short+long is enough
1369 return V
.CoordsToSquare(move.start
) + V
.CoordsToSquare(move.end
);
1372 // The score is already computed when calling this function
1373 getPGN(mycolor
, score
, fenStart
, mode
)
1376 pgn
+= '[Site "vchess.club"]\n';
1377 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1378 pgn
+= '[Variant "' + variant
+ '"]\n';
1379 pgn
+= '[Date "' + getDate(new Date()) + '"]\n';
1380 // TODO: later when users are a bit less anonymous, use better names
1381 const whiteName
= ["human","computer"].includes(mode
)
1382 ? (mycolor
=='w'?'Myself':opponent
)
1384 const blackName
= ["human","computer"].includes(mode
)
1385 ? (mycolor
=='b'?'Myself':opponent
)
1387 pgn
+= '[White "' + whiteName
+ '"]\n';
1388 pgn
+= '[Black "' + blackName
+ '"]\n';
1389 pgn
+= '[FenStart "' + fenStart
+ '"]\n';
1390 pgn
+= '[Fen "' + this.getFen() + '"]\n';
1391 pgn
+= '[Result "' + score
+ '"]\n\n';
1394 for (let i
=0; i
<this.moves
.length
; i
++)
1397 pgn
+= ((i
/2)+1) + ".";
1398 pgn
+= this.moves
[i
].notation
[0] + " ";
1402 // "Complete moves" PGN (helping in ambiguous cases)
1403 for (let i
=0; i
<this.moves
.length
; i
++)
1406 pgn
+= ((i
/2)+1) + ".";
1407 pgn
+= this.moves
[i
].notation
[1] + " ";