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