Add true repetition detection
[vchess.git] / public / javascripts / base_rules.js
CommitLineData
92342261
BA
1// (Orthodox) Chess rules are defined in ChessRules class.
2// Variants generally inherit from it, and modify some parts.
3
1d184b4c
BA
4class PiPo //Piece+Position
5{
6 // o: {piece[p], color[c], posX[x], posY[y]}
7 constructor(o)
8 {
9 this.p = o.p;
10 this.c = o.c;
11 this.x = o.x;
12 this.y = o.y;
13 }
14}
15
098e8468 16// TODO: for animation, moves should contains "moving" and "fading" maybe...
1d184b4c
BA
17class Move
18{
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
22 constructor(o)
23 {
24 this.appear = o.appear;
25 this.vanish = o.vanish;
26 this.start = !!o.start ? o.start : {x:o.vanish[0].x, y:o.vanish[0].y};
27 this.end = !!o.end ? o.end : {x:o.appear[0].x, y:o.appear[0].y};
28 }
29}
30
31// NOTE: x coords = top to bottom; y = left to right (from white player perspective)
32class ChessRules
33{
34 // Path to pieces
35 static getPpath(b)
36 {
37 return b; //usual pieces in pieces/ folder
38 }
39 // Turn "wb" into "B" (for FEN)
40 static board2fen(b)
41 {
42 return b[0]=='w' ? b[1].toUpperCase() : b[1];
43 }
44 // Turn "p" into "bp" (for board)
45 static fen2board(f)
46 {
47 return f.charCodeAt()<=90 ? "w"+f.toLowerCase() : "b"+f;
48 }
49
50 /////////////////
51 // INITIALIZATION
52
d3334c3a 53 // fen == "position flags"
dfb4afc1 54 constructor(fen, moves)
1d184b4c 55 {
dfb4afc1 56 this.moves = moves;
331fc58c 57 this.hashStates = {}; //for repetitions detection
1d184b4c 58 // Use fen string to initialize variables, flags and board
1d184b4c 59 this.board = VariantRules.GetBoard(fen);
2526c041 60 this.setFlags(fen);
ffbae57a 61 this.initVariables(fen);
1d184b4c
BA
62 }
63
64 initVariables(fen)
65 {
66 this.INIT_COL_KING = {'w':-1, 'b':-1};
67 this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
92342261 68 this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king
1d184b4c
BA
69 const fenParts = fen.split(" ");
70 const position = fenParts[0].split("/");
71 for (let i=0; i<position.length; i++)
72 {
6037f1d8
BA
73 let k = 0; //column index on board
74 for (let j=0; j<position[i].length; j++)
1d184b4c
BA
75 {
76 switch (position[i].charAt(j))
77 {
78 case 'k':
6037f1d8
BA
79 this.kingPos['b'] = [i,k];
80 this.INIT_COL_KING['b'] = k;
1d184b4c
BA
81 break;
82 case 'K':
6037f1d8
BA
83 this.kingPos['w'] = [i,k];
84 this.INIT_COL_KING['w'] = k;
1d184b4c
BA
85 break;
86 case 'r':
87 if (this.INIT_COL_ROOK['b'][0] < 0)
6037f1d8 88 this.INIT_COL_ROOK['b'][0] = k;
1d184b4c 89 else
6037f1d8 90 this.INIT_COL_ROOK['b'][1] = k;
1d184b4c
BA
91 break;
92 case 'R':
93 if (this.INIT_COL_ROOK['w'][0] < 0)
6037f1d8 94 this.INIT_COL_ROOK['w'][0] = k;
1d184b4c 95 else
6037f1d8 96 this.INIT_COL_ROOK['w'][1] = k;
1d184b4c
BA
97 break;
98 default:
99 let num = parseInt(position[i].charAt(j));
100 if (!isNaN(num))
6037f1d8 101 k += (num-1);
1d184b4c 102 }
6037f1d8 103 k++;
1d184b4c
BA
104 }
105 }
f3802fcd 106 const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
1d184b4c 107 this.epSquares = [ epSq ];
1d184b4c
BA
108 }
109
110 // Turn diagram fen into double array ["wb","wp","bk",...]
111 static GetBoard(fen)
112 {
113 let rows = fen.split(" ")[0].split("/");
46302e64 114 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
115 let board = doubleArray(sizeX, sizeY, "");
116 for (let i=0; i<rows.length; i++)
117 {
118 let j = 0;
119 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
120 {
121 let character = rows[i][indexInRow];
122 let num = parseInt(character);
123 if (!isNaN(num))
124 j += num; //just shift j
125 else //something at position i,j
126 board[i][j++] = VariantRules.fen2board(character);
127 }
128 }
129 return board;
130 }
131
dda21a71 132 // Extract (relevant) flags from fen
2526c041 133 setFlags(fen)
1d184b4c
BA
134 {
135 // white a-castle, h-castle, black a-castle, h-castle
2526c041
BA
136 this.castleFlags = {'w': new Array(2), 'b': new Array(2)};
137 let flags = fen.split(" ")[1]; //flags right after position
1d184b4c 138 for (let i=0; i<4; i++)
2526c041 139 this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (flags.charAt(i) == '1');
1d184b4c
BA
140 }
141
142 ///////////////////
143 // GETTERS, SETTERS
144
1d184b4c
BA
145 static get size() { return [8,8]; }
146 // Two next functions return 'undefined' if called on empty square
147 getColor(i,j) { return this.board[i][j].charAt(0); }
148 getPiece(i,j) { return this.board[i][j].charAt(1); }
149
150 // Color
151 getOppCol(color) { return color=="w" ? "b" : "w"; }
152
153 get lastMove() {
154 const L = this.moves.length;
155 return L>0 ? this.moves[L-1] : null;
156 }
157 get turn() {
d3334c3a 158 return this.moves.length%2==0 ? 'w' : 'b';
1d184b4c
BA
159 }
160
161 // Pieces codes
162 static get PAWN() { return 'p'; }
163 static get ROOK() { return 'r'; }
164 static get KNIGHT() { return 'n'; }
165 static get BISHOP() { return 'b'; }
166 static get QUEEN() { return 'q'; }
167 static get KING() { return 'k'; }
168
169 // Empty square
170 static get EMPTY() { return ''; }
171
172 // Some pieces movements
173 static get steps() {
174 return {
175 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
176 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
177 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
1d184b4c
BA
178 };
179 }
180
2526c041
BA
181 // Aggregates flags into one object
182 get flags() {
183 return this.castleFlags;
184 }
185
186 // Reverse operation
187 parseFlags(flags)
188 {
189 this.castleFlags = flags;
190 }
191
1d184b4c
BA
192 // En-passant square, if any
193 getEpSquare(move)
194 {
195 const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
196 if (this.getPiece(sx,sy) == VariantRules.PAWN && Math.abs(sx - ex) == 2)
197 {
198 return {
199 x: (sx + ex)/2,
200 y: sy
201 };
202 }
203 return undefined; //default
204 }
205
dda21a71 206 // Can thing on square1 take thing on square2
46302e64 207 canTake([x1,y1], [x2,y2])
1d184b4c 208 {
46302e64 209 return this.getColor(x1,y1) != this.getColor(x2,y2);
1d184b4c
BA
210 }
211
212 ///////////////////
213 // MOVES GENERATION
214
215 // All possible moves from selected square (assumption: color is OK)
216 getPotentialMovesFrom([x,y])
217 {
1d184b4c
BA
218 switch (this.getPiece(x,y))
219 {
220 case VariantRules.PAWN:
46302e64 221 return this.getPotentialPawnMoves([x,y]);
1d184b4c 222 case VariantRules.ROOK:
46302e64 223 return this.getPotentialRookMoves([x,y]);
1d184b4c 224 case VariantRules.KNIGHT:
46302e64 225 return this.getPotentialKnightMoves([x,y]);
1d184b4c 226 case VariantRules.BISHOP:
46302e64 227 return this.getPotentialBishopMoves([x,y]);
1d184b4c 228 case VariantRules.QUEEN:
46302e64 229 return this.getPotentialQueenMoves([x,y]);
1d184b4c 230 case VariantRules.KING:
46302e64 231 return this.getPotentialKingMoves([x,y]);
1d184b4c
BA
232 }
233 }
234
235 // Build a regular move from its initial and destination squares; tr: transformation
46302e64 236 getBasicMove([sx,sy], [ex,ey], tr)
1d184b4c 237 {
2526c041 238 let mv = new Move({
1d184b4c
BA
239 appear: [
240 new PiPo({
241 x: ex,
242 y: ey,
46302e64
BA
243 c: !!tr ? tr.c : this.getColor(sx,sy),
244 p: !!tr ? tr.p : this.getPiece(sx,sy)
1d184b4c
BA
245 })
246 ],
247 vanish: [
248 new PiPo({
249 x: sx,
250 y: sy,
251 c: this.getColor(sx,sy),
252 p: this.getPiece(sx,sy)
253 })
254 ]
255 });
256
257 // The opponent piece disappears if we take it
258 if (this.board[ex][ey] != VariantRules.EMPTY)
259 {
260 mv.vanish.push(
261 new PiPo({
262 x: ex,
263 y: ey,
264 c: this.getColor(ex,ey),
265 p: this.getPiece(ex,ey)
266 })
267 );
268 }
269 return mv;
270 }
271
272 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
46302e64 273 getSlideNJumpMoves([x,y], steps, oneStep)
1d184b4c 274 {
46302e64 275 const color = this.getColor(x,y);
2526c041 276 let moves = [];
46302e64 277 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
278 outerLoop:
279 for (let step of steps)
280 {
46302e64
BA
281 let i = x + step[0];
282 let j = y + step[1];
1221ac47
BA
283 while (i>=0 && i<sizeX && j>=0 && j<sizeY
284 && this.board[i][j] == VariantRules.EMPTY)
1d184b4c 285 {
46302e64 286 moves.push(this.getBasicMove([x,y], [i,j]));
1d184b4c
BA
287 if (oneStep !== undefined)
288 continue outerLoop;
289 i += step[0];
290 j += step[1];
291 }
efb20746 292 if (i>=0 && i<sizeX && j>=0 && j<sizeY && this.canTake([x,y], [i,j]))
46302e64 293 moves.push(this.getBasicMove([x,y], [i,j]));
1d184b4c
BA
294 }
295 return moves;
296 }
297
dda21a71 298 // What are the pawn moves from square x,y ?
46302e64 299 getPotentialPawnMoves([x,y])
1d184b4c 300 {
2526c041
BA
301 const color = this.turn;
302 let moves = [];
303 const V = VariantRules;
1221ac47 304 const [sizeX,sizeY] = V.size;
2526c041 305 const shift = (color == "w" ? -1 : 1);
cf130369
BA
306 const firstRank = (color == 'w' ? sizeX-1 : 0);
307 const startRank = (color == "w" ? sizeX-2 : 1);
308 const lastRank = (color == "w" ? 0 : sizeX-1);
1d184b4c
BA
309
310 if (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank)
311 {
312 // Normal moves
313 if (this.board[x+shift][y] == V.EMPTY)
314 {
46302e64 315 moves.push(this.getBasicMove([x,y], [x+shift,y]));
1221ac47 316 // Next condition because variants with pawns on 1st rank allow them to jump
2526c041 317 if ([startRank,firstRank].includes(x) && this.board[x+2*shift][y] == V.EMPTY)
1d184b4c
BA
318 {
319 // Two squares jump
46302e64 320 moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
1d184b4c
BA
321 }
322 }
323 // Captures
1221ac47
BA
324 if (y>0 && this.canTake([x,y], [x+shift,y-1])
325 && this.board[x+shift][y-1] != V.EMPTY)
326 {
46302e64 327 moves.push(this.getBasicMove([x,y], [x+shift,y-1]));
1221ac47
BA
328 }
329 if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
330 && this.board[x+shift][y+1] != V.EMPTY)
331 {
46302e64 332 moves.push(this.getBasicMove([x,y], [x+shift,y+1]));
1221ac47 333 }
1d184b4c
BA
334 }
335
336 if (x+shift == lastRank)
337 {
338 // Promotion
68f5ccc8 339 const pawnColor = this.getColor(x,y); //can be different for checkered
1d184b4c
BA
340 let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN];
341 promotionPieces.forEach(p => {
342 // Normal move
343 if (this.board[x+shift][y] == V.EMPTY)
68f5ccc8 344 moves.push(this.getBasicMove([x,y], [x+shift,y], {c:pawnColor,p:p}));
1d184b4c 345 // Captures
1221ac47
BA
346 if (y>0 && this.canTake([x,y], [x+shift,y-1])
347 && this.board[x+shift][y-1] != V.EMPTY)
348 {
68f5ccc8 349 moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p}));
1221ac47
BA
350 }
351 if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
352 && this.board[x+shift][y+1] != V.EMPTY)
353 {
68f5ccc8 354 moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p}));
1221ac47 355 }
1d184b4c
BA
356 });
357 }
358
359 // En passant
360 const Lep = this.epSquares.length;
361 const epSquare = Lep>0 ? this.epSquares[Lep-1] : undefined;
362 if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1)
363 {
364 let epStep = epSquare.y - y;
46302e64 365 var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
1d184b4c
BA
366 enpassantMove.vanish.push({
367 x: x,
368 y: y+epStep,
369 p: 'p',
370 c: this.getColor(x,y+epStep)
371 });
372 moves.push(enpassantMove);
373 }
374
375 return moves;
376 }
377
378 // What are the rook moves from square x,y ?
46302e64 379 getPotentialRookMoves(sq)
1d184b4c 380 {
46302e64 381 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]);
1d184b4c
BA
382 }
383
384 // What are the knight moves from square x,y ?
46302e64 385 getPotentialKnightMoves(sq)
1d184b4c 386 {
92342261
BA
387 return this.getSlideNJumpMoves(
388 sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
1d184b4c
BA
389 }
390
391 // What are the bishop moves from square x,y ?
46302e64 392 getPotentialBishopMoves(sq)
1d184b4c 393 {
46302e64 394 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]);
1d184b4c
BA
395 }
396
397 // What are the queen moves from square x,y ?
46302e64 398 getPotentialQueenMoves(sq)
1d184b4c 399 {
a37076f1
BA
400 const V = VariantRules;
401 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
1d184b4c
BA
402 }
403
404 // What are the king moves from square x,y ?
46302e64 405 getPotentialKingMoves(sq)
1d184b4c 406 {
a37076f1 407 const V = VariantRules;
1d184b4c 408 // Initialize with normal moves
a37076f1
BA
409 let moves = this.getSlideNJumpMoves(sq,
410 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
46302e64 411 return moves.concat(this.getCastleMoves(sq));
1d184b4c
BA
412 }
413
46302e64 414 getCastleMoves([x,y])
1d184b4c 415 {
46302e64 416 const c = this.getColor(x,y);
c6052161
BA
417 const [sizeX,sizeY] = VariantRules.size;
418 if (x != (c=="w" ? sizeX-1 : 0) || y != this.INIT_COL_KING[c])
1d184b4c
BA
419 return []; //x isn't first rank, or king has moved (shortcut)
420
421 const V = VariantRules;
422
423 // Castling ?
424 const oppCol = this.getOppCol(c);
425 let moves = [];
426 let i = 0;
c6052161 427 const finalSquares = [ [2,3], [sizeY-2,sizeY-3] ]; //king, then rook
1d184b4c
BA
428 castlingCheck:
429 for (let castleSide=0; castleSide < 2; castleSide++) //large, then small
430 {
2526c041 431 if (!this.castleFlags[c][castleSide])
1d184b4c
BA
432 continue;
433 // If this code is reached, rooks and king are on initial position
434
435 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
436 let step = finalSquares[castleSide][0] < y ? -1 : 1;
437 for (i=y; i!=finalSquares[castleSide][0]; i+=step)
438 {
cf130369 439 if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY &&
1d184b4c
BA
440 // NOTE: next check is enough, because of chessboard constraints
441 (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
442 {
443 continue castlingCheck;
444 }
445 }
446
447 // Nothing on the path to the rook?
448 step = castleSide == 0 ? -1 : 1;
449 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step)
450 {
451 if (this.board[x][i] != V.EMPTY)
452 continue castlingCheck;
453 }
454 const rookPos = this.INIT_COL_ROOK[c][castleSide];
455
456 // Nothing on final squares, except maybe king and castling rook?
457 for (i=0; i<2; i++)
458 {
459 if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
460 this.getPiece(x,finalSquares[castleSide][i]) != V.KING &&
461 finalSquares[castleSide][i] != rookPos)
462 {
463 continue castlingCheck;
464 }
465 }
466
467 // If this code is reached, castle is valid
468 moves.push( new Move({
469 appear: [
470 new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}),
471 new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})],
472 vanish: [
473 new PiPo({x:x,y:y,p:V.KING,c:c}),
474 new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})],
475 end: Math.abs(y - rookPos) <= 2
476 ? {x:x, y:rookPos}
477 : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)}
478 }) );
479 }
480
481 return moves;
482 }
483
484 ///////////////////
485 // MOVES VALIDATION
486
46302e64 487 canIplay(side, [x,y])
1d184b4c 488 {
92342261
BA
489 return ((side=='w' && this.moves.length%2==0)
490 || (side=='b' && this.moves.length%2==1))
46302e64 491 && this.getColor(x,y) == side;
1d184b4c
BA
492 }
493
494 getPossibleMovesFrom(sq)
495 {
496 // Assuming color is right (already checked)
497 return this.filterValid( this.getPotentialMovesFrom(sq) );
498 }
499
92342261 500 // TODO: promotions (into R,B,N,Q) should be filtered only once
1d184b4c
BA
501 filterValid(moves)
502 {
503 if (moves.length == 0)
504 return [];
b8121223 505 return moves.filter(m => { return !this.underCheck(m); });
1d184b4c
BA
506 }
507
508 // Search for all valid moves considering current turn (for engine and game end)
46302e64 509 getAllValidMoves()
1d184b4c 510 {
46302e64 511 const color = this.turn;
1d184b4c 512 const oppCol = this.getOppCol(color);
c6052161
BA
513 let potentialMoves = [];
514 const [sizeX,sizeY] = VariantRules.size;
a6abf094 515 for (let i=0; i<sizeX; i++)
1d184b4c 516 {
a6abf094 517 for (let j=0; j<sizeY; j++)
1d184b4c 518 {
92342261 519 // Next condition "!= oppCol" = harmless hack to work with checkered variant
1d184b4c
BA
520 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
521 Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
522 }
523 }
524 // NOTE: prefer lazy undercheck tests, letting the king being taken?
525 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
526 return this.filterValid(potentialMoves);
527 }
9de73b71 528
e64a4eff 529 // Stop at the first move found
46302e64 530 atLeastOneMove()
e64a4eff 531 {
46302e64 532 const color = this.turn;
e64a4eff 533 const oppCol = this.getOppCol(color);
c6052161 534 const [sizeX,sizeY] = VariantRules.size;
9de73b71 535 for (let i=0; i<sizeX; i++)
e64a4eff 536 {
9de73b71 537 for (let j=0; j<sizeY; j++)
e64a4eff
BA
538 {
539 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
540 {
541 const moves = this.getPotentialMovesFrom([i,j]);
542 if (moves.length > 0)
543 {
9de73b71 544 for (let k=0; k<moves.length; k++)
e64a4eff 545 {
9de73b71 546 if (this.filterValid([moves[k]]).length > 0)
e64a4eff
BA
547 return true;
548 }
549 }
550 }
551 }
552 }
553 return false;
554 }
1d184b4c 555
dda21a71 556 // Check if pieces of color in array 'colors' are attacking square x,y
46302e64 557 isAttacked(sq, colors)
1d184b4c 558 {
46302e64
BA
559 return (this.isAttackedByPawn(sq, colors)
560 || this.isAttackedByRook(sq, colors)
561 || this.isAttackedByKnight(sq, colors)
562 || this.isAttackedByBishop(sq, colors)
563 || this.isAttackedByQueen(sq, colors)
564 || this.isAttackedByKing(sq, colors));
1d184b4c
BA
565 }
566
dda21a71 567 // Is square x,y attacked by 'colors' pawns ?
46302e64 568 isAttackedByPawn([x,y], colors)
1d184b4c 569 {
efb20746 570 const [sizeX,sizeY] = VariantRules.size;
46302e64 571 for (let c of colors)
1d184b4c 572 {
46302e64 573 let pawnShift = (c=="w" ? 1 : -1);
efb20746 574 if (x+pawnShift>=0 && x+pawnShift<sizeX)
1d184b4c 575 {
46302e64 576 for (let i of [-1,1])
1d184b4c 577 {
efb20746 578 if (y+i>=0 && y+i<sizeY && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
46302e64
BA
579 && this.getColor(x+pawnShift,y+i)==c)
580 {
581 return true;
582 }
1d184b4c
BA
583 }
584 }
585 }
586 return false;
587 }
588
dda21a71 589 // Is square x,y attacked by 'colors' rooks ?
46302e64 590 isAttackedByRook(sq, colors)
1d184b4c 591 {
46302e64 592 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
593 VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
594 }
595
dda21a71 596 // Is square x,y attacked by 'colors' knights ?
46302e64 597 isAttackedByKnight(sq, colors)
1d184b4c 598 {
46302e64 599 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
600 VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
601 }
602
dda21a71 603 // Is square x,y attacked by 'colors' bishops ?
46302e64 604 isAttackedByBishop(sq, colors)
1d184b4c 605 {
46302e64 606 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
607 VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
608 }
609
dda21a71 610 // Is square x,y attacked by 'colors' queens ?
46302e64 611 isAttackedByQueen(sq, colors)
1d184b4c 612 {
a37076f1
BA
613 const V = VariantRules;
614 return this.isAttackedBySlideNJump(sq, colors, V.QUEEN,
615 V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
1d184b4c
BA
616 }
617
dda21a71 618 // Is square x,y attacked by 'colors' king(s) ?
46302e64 619 isAttackedByKing(sq, colors)
1d184b4c 620 {
a37076f1
BA
621 const V = VariantRules;
622 return this.isAttackedBySlideNJump(sq, colors, V.KING,
623 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
1d184b4c
BA
624 }
625
1221ac47 626 // Generic method for non-pawn pieces ("sliding or jumping"):
dda21a71 627 // is x,y attacked by a piece of color in array 'colors' ?
46302e64 628 isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
1d184b4c 629 {
efb20746 630 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
631 for (let step of steps)
632 {
633 let rx = x+step[0], ry = y+step[1];
efb20746
BA
634 while (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
635 && this.board[rx][ry] == VariantRules.EMPTY && !oneStep)
1d184b4c
BA
636 {
637 rx += step[0];
638 ry += step[1];
639 }
efb20746
BA
640 if (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
641 && this.board[rx][ry] != VariantRules.EMPTY
46302e64 642 && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
1d184b4c
BA
643 {
644 return true;
645 }
646 }
647 return false;
648 }
649
dda21a71 650 // Is current player under check after his move ?
46302e64 651 underCheck(move)
1d184b4c 652 {
46302e64 653 const color = this.turn;
1d184b4c 654 this.play(move);
cf130369 655 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]);
1d184b4c
BA
656 this.undo(move);
657 return res;
658 }
659
dda21a71 660 // On which squares is opponent under check after our move ?
46302e64 661 getCheckSquares(move)
4b5fe306
BA
662 {
663 this.play(move);
204e289b 664 const color = this.turn; //opponent
cf130369 665 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
46302e64 666 ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
4b5fe306
BA
667 : [ ];
668 this.undo(move);
669 return res;
670 }
671
1d184b4c
BA
672 // Apply a move on board
673 static PlayOnBoard(board, move)
674 {
675 for (let psq of move.vanish)
676 board[psq.x][psq.y] = VariantRules.EMPTY;
677 for (let psq of move.appear)
678 board[psq.x][psq.y] = psq.c + psq.p;
679 }
680 // Un-apply the played move
681 static UndoOnBoard(board, move)
682 {
683 for (let psq of move.appear)
684 board[psq.x][psq.y] = VariantRules.EMPTY;
685 for (let psq of move.vanish)
686 board[psq.x][psq.y] = psq.c + psq.p;
687 }
688
d3334c3a 689 // Before move is played, update variables + flags
1d184b4c
BA
690 updateVariables(move)
691 {
692 const piece = this.getPiece(move.start.x,move.start.y);
693 const c = this.getColor(move.start.x,move.start.y);
c6052161
BA
694 const [sizeX,sizeY] = VariantRules.size;
695 const firstRank = (c == "w" ? sizeX-1 : 0);
1d184b4c
BA
696
697 // Update king position + flags
698 if (piece == VariantRules.KING && move.appear.length > 0)
699 {
700 this.kingPos[c][0] = move.appear[0].x;
701 this.kingPos[c][1] = move.appear[0].y;
2526c041 702 this.castleFlags[c] = [false,false];
1d184b4c
BA
703 return;
704 }
705 const oppCol = this.getOppCol(c);
c6052161 706 const oppFirstRank = (sizeX-1) - firstRank;
1d184b4c
BA
707 if (move.start.x == firstRank //our rook moves?
708 && this.INIT_COL_ROOK[c].includes(move.start.y))
709 {
2526c041
BA
710 const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
711 this.castleFlags[c][flagIdx] = false;
1d184b4c
BA
712 }
713 else if (move.end.x == oppFirstRank //we took opponent rook?
aea1443e 714 && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
1d184b4c 715 {
2526c041
BA
716 const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
717 this.castleFlags[oppCol][flagIdx] = false;
1d184b4c
BA
718 }
719 }
720
dda21a71
BA
721 // After move is undo-ed, un-update variables (flags are reset)
722 // TODO: more symmetry, by storing flags increment in move...
d3334c3a 723 unupdateVariables(move)
1d184b4c 724 {
d3334c3a
BA
725 // (Potentially) Reset king position
726 const c = this.getColor(move.start.x,move.start.y);
727 if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
728 this.kingPos[c] = [move.start.x, move.start.y];
729 }
1d184b4c 730
331fc58c
BA
731 // Store a hash of the position + flags + turn after a move is played
732 // (for repetitions detection)
733 addHashState()
734 {
735 const strToHash = this.getFen() + " " + this.turn;
736 const hash = hex_md5(strToHash);
737 if (!this.hashStates[hash])
738 this.hashStates[hash] = 1;
739 else
740 this.hashStates[hash]++;
741 }
742
d3334c3a
BA
743 play(move, ingame)
744 {
a3c86ec9
BA
745 // DEBUG:
746// if (!this.states) this.states = [];
747// if (!ingame) this.states.push(JSON.stringify(this.board));
748
dfb4afc1 749 if (!!ingame)
6752407b 750 move.notation = [this.getNotation(move), this.getLongNotation(move)];
dfb4afc1 751
2526c041 752 move.flags = JSON.stringify(this.flags); //save flags (for undo)
d3334c3a
BA
753 this.updateVariables(move);
754 this.moves.push(move);
1d184b4c
BA
755 this.epSquares.push( this.getEpSquare(move) );
756 VariantRules.PlayOnBoard(this.board, move);
331fc58c
BA
757
758 if (!!ingame)
759 this.addHashState();
1d184b4c
BA
760 }
761
cd4cad04 762 undo(move)
1d184b4c
BA
763 {
764 VariantRules.UndoOnBoard(this.board, move);
765 this.epSquares.pop();
d3334c3a
BA
766 this.moves.pop();
767 this.unupdateVariables(move);
2526c041 768 this.parseFlags(JSON.parse(move.flags));
a3c86ec9
BA
769
770 // DEBUG:
771// if (JSON.stringify(this.board) != this.states[this.states.length-1])
772// debugger;
773// this.states.pop();
1d184b4c
BA
774 }
775
776 //////////////
777 // END OF GAME
778
331fc58c 779 // Check for 3 repetitions (position + flags + turn)
1af36beb 780 checkRepetition()
1d184b4c 781 {
331fc58c 782 return Object.values(this.hashStates).some(elt => { return (elt >= 3); });
1af36beb 783 }
1d184b4c 784
dda21a71 785 // Is game over ? And if yes, what is the score ?
1af36beb
BA
786 checkGameOver()
787 {
788 if (this.checkRepetition())
789 return "1/2";
790
791 if (this.atLeastOneMove()) // game not over
1d184b4c 792 return "*";
1d184b4c
BA
793
794 // Game over
46302e64 795 return this.checkGameEnd();
1d184b4c
BA
796 }
797
46302e64
BA
798 // No moves are possible: compute score
799 checkGameEnd()
1d184b4c 800 {
46302e64 801 const color = this.turn;
1d184b4c 802 // No valid move: stalemate or checkmate?
cf130369 803 if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
1d184b4c
BA
804 return "1/2";
805 // OK, checkmate
806 return color == "w" ? "0-1" : "1-0";
807 }
808
809 ////////
810 //ENGINE
811
812 // Pieces values
813 static get VALUES() {
814 return {
815 'p': 1,
816 'r': 5,
817 'n': 3,
818 'b': 3,
819 'q': 9,
820 'k': 1000
821 };
822 }
823
9e42b4dd
BA
824 static get INFINITY() {
825 return 9999; //"checkmate" (unreachable eval)
826 }
827
828 static get THRESHOLD_MATE() {
829 // At this value or above, the game is over
830 return VariantRules.INFINITY;
831 }
832
3c09dc49
BA
833 static get SEARCH_DEPTH() {
834 return 3; //2 for high branching factor, 4 for small (Loser chess)
835 }
836
1d184b4c 837 // Assumption: at least one legal move
a6abf094
BA
838 // NOTE: works also for extinction chess because depth is 3...
839 getComputerMove()
1d184b4c 840 {
9e42b4dd 841 const maxeval = VariantRules.INFINITY;
46302e64 842 const color = this.turn;
15952ada
BA
843 // Some variants may show a bigger moves list to the human (Switching),
844 // thus the argument "computer" below (which is generally ignored)
845 let moves1 = this.getAllValidMoves("computer");
a6abf094
BA
846
847 // Can I mate in 1 ? (for Magnetic & Extinction)
848 for (let i of _.shuffle(_.range(moves1.length)))
849 {
850 this.play(moves1[i]);
851 const finish = (Math.abs(this.evalPosition()) >= VariantRules.THRESHOLD_MATE);
852 this.undo(moves1[i]);
853 if (finish)
854 return moves1[i];
855 }
1d184b4c 856
06ddfe34 857 // Rank moves using a min-max at depth 2
1d184b4c
BA
858 for (let i=0; i<moves1.length; i++)
859 {
9e42b4dd 860 moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; //very low, I'm checkmated
1d184b4c 861 this.play(moves1[i]);
68f5ccc8
BA
862 let eval2 = undefined;
863 if (this.atLeastOneMove())
1d184b4c 864 {
68f5ccc8
BA
865 eval2 = (color=="w" ? 1 : -1) * maxeval; //initialized with checkmate value
866 // Second half-move:
15952ada 867 let moves2 = this.getAllValidMoves("computer");
68f5ccc8
BA
868 for (let j=0; j<moves2.length; j++)
869 {
870 this.play(moves2[j]);
871 let evalPos = undefined;
872 if (this.atLeastOneMove())
873 evalPos = this.evalPosition()
874 else
875 {
876 // Work with scores for Loser variant
877 const score = this.checkGameEnd();
878 evalPos = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
879 }
880 if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
881 eval2 = evalPos;
882 this.undo(moves2[j]);
883 }
884 }
885 else
886 {
887 const score = this.checkGameEnd();
888 eval2 = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1d184b4c 889 }
92342261
BA
890 if ((color=="w" && eval2 > moves1[i].eval)
891 || (color=="b" && eval2 < moves1[i].eval))
892 {
1d184b4c 893 moves1[i].eval = eval2;
92342261 894 }
1d184b4c
BA
895 this.undo(moves1[i]);
896 }
897 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
11a31682 898 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1d184b4c 899
3c09dc49
BA
900 let candidates = [0]; //indices of candidates moves
901 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
902 candidates.push(j);
903 let currentBest = moves1[_.sample(candidates, 1)];
904
e82cd979
BA
905 // From here, depth >= 3: may take a while, so we control time
906 const timeStart = Date.now();
907
a6abf094 908 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
3c09dc49
BA
909 if (VariantRules.SEARCH_DEPTH >= 3
910 && Math.abs(moves1[0].eval) < VariantRules.THRESHOLD_MATE)
e64a4eff 911 {
9e42b4dd
BA
912 for (let i=0; i<moves1.length; i++)
913 {
e82cd979
BA
914 if (Date.now()-timeStart >= 5000) //more than 5 seconds
915 return currentBest; //depth 2 at least
9e42b4dd
BA
916 this.play(moves1[i]);
917 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
3c09dc49
BA
918 moves1[i].eval = 0.1*moves1[i].eval +
919 this.alphabeta(VariantRules.SEARCH_DEPTH-1, -maxeval, maxeval);
9e42b4dd
BA
920 this.undo(moves1[i]);
921 }
922 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
e64a4eff 923 }
3c09dc49
BA
924 else
925 return currentBest;
68f5ccc8 926 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1d184b4c 927
3c09dc49 928 candidates = [0];
1d184b4c
BA
929 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
930 candidates.push(j);
1d184b4c
BA
931 return moves1[_.sample(candidates, 1)];
932 }
933
46302e64 934 alphabeta(depth, alpha, beta)
1d184b4c 935 {
9e42b4dd 936 const maxeval = VariantRules.INFINITY;
46302e64
BA
937 const color = this.turn;
938 if (!this.atLeastOneMove())
1d184b4c 939 {
46302e64 940 switch (this.checkGameEnd())
1d184b4c 941 {
68f5ccc8
BA
942 case "1/2":
943 return 0;
944 default:
945 const score = this.checkGameEnd();
946 return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1d184b4c
BA
947 }
948 }
949 if (depth == 0)
950 return this.evalPosition();
15952ada 951 const moves = this.getAllValidMoves("computer");
9e42b4dd 952 let v = color=="w" ? -maxeval : maxeval;
1d184b4c
BA
953 if (color == "w")
954 {
955 for (let i=0; i<moves.length; i++)
956 {
957 this.play(moves[i]);
46302e64 958 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
1d184b4c
BA
959 this.undo(moves[i]);
960 alpha = Math.max(alpha, v);
961 if (alpha >= beta)
962 break; //beta cutoff
963 }
964 }
965 else //color=="b"
966 {
967 for (let i=0; i<moves.length; i++)
968 {
969 this.play(moves[i]);
46302e64 970 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
1d184b4c
BA
971 this.undo(moves[i]);
972 beta = Math.min(beta, v);
973 if (alpha >= beta)
974 break; //alpha cutoff
975 }
976 }
977 return v;
978 }
979
980 evalPosition()
981 {
982 const [sizeX,sizeY] = VariantRules.size;
983 let evaluation = 0;
a6abf094 984 // Just count material for now
1d184b4c
BA
985 for (let i=0; i<sizeX; i++)
986 {
987 for (let j=0; j<sizeY; j++)
988 {
989 if (this.board[i][j] != VariantRules.EMPTY)
990 {
991 const sign = this.getColor(i,j) == "w" ? 1 : -1;
992 evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)];
993 }
994 }
995 }
996 return evaluation;
997 }
998
999 ////////////
1000 // FEN utils
1001
dda21a71 1002 // Setup the initial random (assymetric) position
1d184b4c
BA
1003 static GenRandInitFen()
1004 {
32cfcea4 1005 let pieces = { "w": new Array(8), "b": new Array(8) };
1d184b4c 1006 // Shuffle pieces on first and last rank
32cfcea4 1007 for (let c of ["w","b"])
1d184b4c
BA
1008 {
1009 let positions = _.range(8);
1010
1011 // Get random squares for bishops
1012 let randIndex = 2 * _.random(3);
1013 let bishop1Pos = positions[randIndex];
1014 // The second bishop must be on a square of different color
1015 let randIndex_tmp = 2 * _.random(3) + 1;
1016 let bishop2Pos = positions[randIndex_tmp];
1017 // Remove chosen squares
1018 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
1019 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
1020
1021 // Get random squares for knights
1022 randIndex = _.random(5);
1023 let knight1Pos = positions[randIndex];
1024 positions.splice(randIndex, 1);
1025 randIndex = _.random(4);
1026 let knight2Pos = positions[randIndex];
1027 positions.splice(randIndex, 1);
1028
1029 // Get random square for queen
1030 randIndex = _.random(3);
1031 let queenPos = positions[randIndex];
1032 positions.splice(randIndex, 1);
1033
1034 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
1035 let rook1Pos = positions[0];
1036 let kingPos = positions[1];
1037 let rook2Pos = positions[2];
1038
1039 // Finally put the shuffled pieces in the board array
1040 pieces[c][rook1Pos] = 'r';
1041 pieces[c][knight1Pos] = 'n';
1042 pieces[c][bishop1Pos] = 'b';
1043 pieces[c][queenPos] = 'q';
1044 pieces[c][kingPos] = 'k';
1045 pieces[c][bishop2Pos] = 'b';
1046 pieces[c][knight2Pos] = 'n';
1047 pieces[c][rook2Pos] = 'r';
1048 }
2eef6db6 1049 return pieces["b"].join("") +
1d184b4c 1050 "/pppppppp/8/8/8/8/PPPPPPPP/" +
32cfcea4 1051 pieces["w"].join("").toUpperCase() +
f3802fcd 1052 " 1111"; //add flags
1d184b4c
BA
1053 }
1054
1055 // Return current fen according to pieces+colors state
1056 getFen()
1057 {
f3802fcd 1058 return this.getBaseFen() + " " + this.getFlagsFen();
1d184b4c
BA
1059 }
1060
dda21a71 1061 // Position part of the FEN string
1d184b4c
BA
1062 getBaseFen()
1063 {
1064 let fen = "";
1065 let [sizeX,sizeY] = VariantRules.size;
1066 for (let i=0; i<sizeX; i++)
1067 {
1068 let emptyCount = 0;
1069 for (let j=0; j<sizeY; j++)
1070 {
1071 if (this.board[i][j] == VariantRules.EMPTY)
1072 emptyCount++;
1073 else
1074 {
1075 if (emptyCount > 0)
1076 {
1077 // Add empty squares in-between
1078 fen += emptyCount;
1079 emptyCount = 0;
1080 }
1081 fen += VariantRules.board2fen(this.board[i][j]);
1082 }
1083 }
1084 if (emptyCount > 0)
1085 {
1086 // "Flush remainder"
1087 fen += emptyCount;
1088 }
1089 if (i < sizeX - 1)
1090 fen += "/"; //separate rows
1091 }
1092 return fen;
1093 }
1094
dda21a71 1095 // Flags part of the FEN string
1d184b4c
BA
1096 getFlagsFen()
1097 {
1098 let fen = "";
1099 // Add castling flags
1100 for (let i of ['w','b'])
1101 {
1102 for (let j=0; j<2; j++)
77e1ec78 1103 fen += (this.castleFlags[i][j] ? '1' : '0');
1d184b4c
BA
1104 }
1105 return fen;
1106 }
1107
1108 // Context: just before move is played, turn hasn't changed
1109 getNotation(move)
1110 {
15952ada
BA
1111 if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING) //castle
1112 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
1d184b4c
BA
1113
1114 // Translate final square
270968d6 1115 const finalSquare =
1d184b4c
BA
1116 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1117
270968d6 1118 const piece = this.getPiece(move.start.x, move.start.y);
1d184b4c
BA
1119 if (piece == VariantRules.PAWN)
1120 {
1121 // Pawn move
1122 let notation = "";
5bfb0956 1123 if (move.vanish.length > move.appear.length)
1d184b4c
BA
1124 {
1125 // Capture
270968d6 1126 const startColumn = String.fromCharCode(97 + move.start.y);
1d184b4c
BA
1127 notation = startColumn + "x" + finalSquare;
1128 }
1129 else //no capture
1130 notation = finalSquare;
1131 if (move.appear.length > 0 && piece != move.appear[0].p) //promotion
1132 notation += "=" + move.appear[0].p.toUpperCase();
1133 return notation;
1134 }
1135
1136 else
1137 {
1138 // Piece movement
f3c10e18
BA
1139 return piece.toUpperCase() +
1140 (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
1d184b4c
BA
1141 }
1142 }
dfb4afc1 1143
6752407b
BA
1144 // Complete the usual notation, may be required for de-ambiguification
1145 getLongNotation(move)
1146 {
1147 const startSquare =
1148 String.fromCharCode(97 + move.start.y) + (VariantRules.size[0]-move.start.x);
1149 const finalSquare =
1150 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1151 return startSquare + finalSquare; //not encoding move. But short+long is enough
1152 }
1153
dfb4afc1 1154 // The score is already computed when calling this function
01a135e2 1155 getPGN(mycolor, score, fenStart, mode)
dfb4afc1 1156 {
16984853 1157 const zeroPad = x => { return (x<10 ? "0" : "") + x; };
dfb4afc1
BA
1158 let pgn = "";
1159 pgn += '[Site "vchess.club"]<br>';
1160 const d = new Date();
5e622704 1161 const opponent = mode=="human" ? "Anonymous" : "Computer";
0f51ef98 1162 pgn += '[Variant "' + variant + '"]<br>';
92342261
BA
1163 pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) +
1164 '-' + zeroPad(d.getDate()) + '"]<br>';
01a135e2
BA
1165 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1166 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
04449c97
BA
1167 pgn += '[FenStart "' + fenStart + '"]<br>';
1168 pgn += '[Fen "' + this.getFen() + '"]<br>';
762b7c9c 1169 pgn += '[Result "' + score + '"]<br><br>';
dfb4afc1 1170
6752407b 1171 // Standard PGN
dfb4afc1
BA
1172 for (let i=0; i<this.moves.length; i++)
1173 {
1174 if (i % 2 == 0)
1175 pgn += ((i/2)+1) + ".";
6752407b 1176 pgn += this.moves[i].notation[0] + " ";
dfb4afc1 1177 }
97fc8bf7 1178 pgn += "<br><br>";
dfb4afc1 1179
6752407b
BA
1180 // "Complete moves" PGN (helping in ambiguous cases)
1181 for (let i=0; i<this.moves.length; i++)
1182 {
1183 if (i % 2 == 0)
1184 pgn += ((i/2)+1) + ".";
1185 pgn += this.moves[i].notation[1] + " ";
1186 }
6752407b 1187
dfb4afc1
BA
1188 return pgn;
1189 }
1d184b4c 1190}