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