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