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