360f60c53487bb49210ad5ad2d406593d93e7505
[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"
50 constructor(fen, moves)
51 {
52 this.moves = moves;
53 // Use fen string to initialize variables, flags and board
54 this.board = VariantRules.GetBoard(fen);
55 this.setFlags(fen);
56 this.initVariables(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 k = 0; //column index on board
69 for (let j=0; j<position[i].length; j++)
70 {
71 switch (position[i].charAt(j))
72 {
73 case 'k':
74 this.kingPos['b'] = [i,k];
75 this.INIT_COL_KING['b'] = k;
76 break;
77 case 'K':
78 this.kingPos['w'] = [i,k];
79 this.INIT_COL_KING['w'] = k;
80 break;
81 case 'r':
82 if (this.INIT_COL_ROOK['b'][0] < 0)
83 this.INIT_COL_ROOK['b'][0] = k;
84 else
85 this.INIT_COL_ROOK['b'][1] = k;
86 break;
87 case 'R':
88 if (this.INIT_COL_ROOK['w'][0] < 0)
89 this.INIT_COL_ROOK['w'][0] = k;
90 else
91 this.INIT_COL_ROOK['w'][1] = k;
92 break;
93 default:
94 let num = parseInt(position[i].charAt(j));
95 if (!isNaN(num))
96 k += (num-1);
97 }
98 k++;
99 }
100 }
101 const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
102 this.epSquares = [ epSq ];
103 }
104
105 // Turn diagram fen into double array ["wb","wp","bk",...]
106 static GetBoard(fen)
107 {
108 let rows = fen.split(" ")[0].split("/");
109 const [sizeX,sizeY] = VariantRules.size;
110 let board = doubleArray(sizeX, sizeY, "");
111 for (let i=0; i<rows.length; i++)
112 {
113 let j = 0;
114 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
115 {
116 let character = rows[i][indexInRow];
117 let num = parseInt(character);
118 if (!isNaN(num))
119 j += num; //just shift j
120 else //something at position i,j
121 board[i][j++] = VariantRules.fen2board(character);
122 }
123 }
124 return board;
125 }
126
127 // Overridable: flags can change a lot
128 setFlags(fen)
129 {
130 // white a-castle, h-castle, black a-castle, h-castle
131 this.castleFlags = {'w': new Array(2), 'b': new Array(2)};
132 let flags = fen.split(" ")[1]; //flags right after position
133 for (let i=0; i<4; i++)
134 this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (flags.charAt(i) == '1');
135 }
136
137 ///////////////////
138 // GETTERS, SETTERS
139
140 // Simple useful getters
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 considering color "color" ?
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 let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN];
336 promotionPieces.forEach(p => {
337 // Normal move
338 if (this.board[x+shift][y] == V.EMPTY)
339 moves.push(this.getBasicMove([x,y], [x+shift,y], {c:color,p:p}));
340 // Captures
341 if (y>0 && this.canTake([x,y], [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], {c:color,p:p}));
345 }
346 if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
347 && this.board[x+shift][y+1] != V.EMPTY)
348 {
349 moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:color,p:p}));
350 }
351 });
352 }
353
354 // En passant
355 const Lep = this.epSquares.length;
356 const epSquare = Lep>0 ? this.epSquares[Lep-1] : undefined;
357 if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1)
358 {
359 let epStep = epSquare.y - y;
360 var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
361 enpassantMove.vanish.push({
362 x: x,
363 y: y+epStep,
364 p: 'p',
365 c: this.getColor(x,y+epStep)
366 });
367 moves.push(enpassantMove);
368 }
369
370 return moves;
371 }
372
373 // What are the rook moves from square x,y ?
374 getPotentialRookMoves(sq)
375 {
376 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]);
377 }
378
379 // What are the knight moves from square x,y ?
380 getPotentialKnightMoves(sq)
381 {
382 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
383 }
384
385 // What are the bishop moves from square x,y ?
386 getPotentialBishopMoves(sq)
387 {
388 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]);
389 }
390
391 // What are the queen moves from square x,y ?
392 getPotentialQueenMoves(sq)
393 {
394 const V = VariantRules;
395 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
396 }
397
398 // What are the king moves from square x,y ?
399 getPotentialKingMoves(sq)
400 {
401 const V = VariantRules;
402 // Initialize with normal moves
403 let moves = this.getSlideNJumpMoves(sq,
404 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
405 return moves.concat(this.getCastleMoves(sq));
406 }
407
408 getCastleMoves([x,y])
409 {
410 const c = this.getColor(x,y);
411 const [sizeX,sizeY] = VariantRules.size;
412 if (x != (c=="w" ? sizeX-1 : 0) || y != this.INIT_COL_KING[c])
413 return []; //x isn't first rank, or king has moved (shortcut)
414
415 const V = VariantRules;
416
417 // Castling ?
418 const oppCol = this.getOppCol(c);
419 let moves = [];
420 let i = 0;
421 const finalSquares = [ [2,3], [sizeY-2,sizeY-3] ]; //king, then rook
422 castlingCheck:
423 for (let castleSide=0; castleSide < 2; castleSide++) //large, then small
424 {
425 if (!this.castleFlags[c][castleSide])
426 continue;
427 // If this code is reached, rooks and king are on initial position
428
429 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
430 let step = finalSquares[castleSide][0] < y ? -1 : 1;
431 for (i=y; i!=finalSquares[castleSide][0]; i+=step)
432 {
433 if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY &&
434 // NOTE: next check is enough, because of chessboard constraints
435 (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
436 {
437 continue castlingCheck;
438 }
439 }
440
441 // Nothing on the path to the rook?
442 step = castleSide == 0 ? -1 : 1;
443 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step)
444 {
445 if (this.board[x][i] != V.EMPTY)
446 continue castlingCheck;
447 }
448 const rookPos = this.INIT_COL_ROOK[c][castleSide];
449
450 // Nothing on final squares, except maybe king and castling rook?
451 for (i=0; i<2; i++)
452 {
453 if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
454 this.getPiece(x,finalSquares[castleSide][i]) != V.KING &&
455 finalSquares[castleSide][i] != rookPos)
456 {
457 continue castlingCheck;
458 }
459 }
460
461 // If this code is reached, castle is valid
462 moves.push( new Move({
463 appear: [
464 new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}),
465 new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})],
466 vanish: [
467 new PiPo({x:x,y:y,p:V.KING,c:c}),
468 new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})],
469 end: Math.abs(y - rookPos) <= 2
470 ? {x:x, y:rookPos}
471 : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)}
472 }) );
473 }
474
475 return moves;
476 }
477
478 ///////////////////
479 // MOVES VALIDATION
480
481 canIplay(side, [x,y])
482 {
483 return ((side=='w' && this.moves.length%2==0) || (side=='b' && this.moves.length%2==1))
484 && this.getColor(x,y) == side;
485 }
486
487 getPossibleMovesFrom(sq)
488 {
489 // Assuming color is right (already checked)
490 return this.filterValid( this.getPotentialMovesFrom(sq) );
491 }
492
493 // TODO: once a promotion is filtered, the others results are same: useless computations
494 filterValid(moves)
495 {
496 if (moves.length == 0)
497 return [];
498 return moves.filter(m => { return !this.underCheck(m); });
499 }
500
501 // Search for all valid moves considering current turn (for engine and game end)
502 getAllValidMoves()
503 {
504 const color = this.turn;
505 const oppCol = this.getOppCol(color);
506 let potentialMoves = [];
507 const [sizeX,sizeY] = VariantRules.size;
508 for (let i=0; i<sizeX; i++)
509 {
510 for (let j=0; j<sizeY; j++)
511 {
512 // Next condition ... != oppCol is a little HACK to work with checkered variant
513 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
514 Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
515 }
516 }
517 // NOTE: prefer lazy undercheck tests, letting the king being taken?
518 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
519 return this.filterValid(potentialMoves);
520 }
521
522 // Stop at the first move found
523 atLeastOneMove()
524 {
525 const color = this.turn;
526 const oppCol = this.getOppCol(color);
527 const [sizeX,sizeY] = VariantRules.size;
528 for (let i=0; i<sizeX; i++)
529 {
530 for (let j=0; j<sizeY; j++)
531 {
532 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
533 {
534 const moves = this.getPotentialMovesFrom([i,j]);
535 if (moves.length > 0)
536 {
537 for (let k=0; k<moves.length; k++)
538 {
539 if (this.filterValid([moves[k]]).length > 0)
540 return true;
541 }
542 }
543 }
544 }
545 }
546 return false;
547 }
548
549 // Check if pieces of color 'colors' are attacking square x,y
550 isAttacked(sq, colors)
551 {
552 return (this.isAttackedByPawn(sq, colors)
553 || this.isAttackedByRook(sq, colors)
554 || this.isAttackedByKnight(sq, colors)
555 || this.isAttackedByBishop(sq, colors)
556 || this.isAttackedByQueen(sq, colors)
557 || this.isAttackedByKing(sq, colors));
558 }
559
560 // Is square x,y attacked by pawns of color c ?
561 isAttackedByPawn([x,y], colors)
562 {
563 const [sizeX,sizeY] = VariantRules.size;
564 for (let c of colors)
565 {
566 let pawnShift = (c=="w" ? 1 : -1);
567 if (x+pawnShift>=0 && x+pawnShift<sizeX)
568 {
569 for (let i of [-1,1])
570 {
571 if (y+i>=0 && y+i<sizeY && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
572 && this.getColor(x+pawnShift,y+i)==c)
573 {
574 return true;
575 }
576 }
577 }
578 }
579 return false;
580 }
581
582 // Is square x,y attacked by rooks of color c ?
583 isAttackedByRook(sq, colors)
584 {
585 return this.isAttackedBySlideNJump(sq, colors,
586 VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
587 }
588
589 // Is square x,y attacked by knights of color c ?
590 isAttackedByKnight(sq, colors)
591 {
592 return this.isAttackedBySlideNJump(sq, colors,
593 VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
594 }
595
596 // Is square x,y attacked by bishops of color c ?
597 isAttackedByBishop(sq, colors)
598 {
599 return this.isAttackedBySlideNJump(sq, colors,
600 VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
601 }
602
603 // Is square x,y attacked by queens of color c ?
604 isAttackedByQueen(sq, colors)
605 {
606 const V = VariantRules;
607 return this.isAttackedBySlideNJump(sq, colors, V.QUEEN,
608 V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
609 }
610
611 // Is square x,y attacked by king of color c ?
612 isAttackedByKing(sq, colors)
613 {
614 const V = VariantRules;
615 return this.isAttackedBySlideNJump(sq, colors, V.KING,
616 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
617 }
618
619 // Generic method for non-pawn pieces ("sliding or jumping"):
620 // is x,y attacked by piece !of color in colors?
621 isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
622 {
623 const [sizeX,sizeY] = VariantRules.size;
624 for (let step of steps)
625 {
626 let rx = x+step[0], ry = y+step[1];
627 while (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
628 && this.board[rx][ry] == VariantRules.EMPTY && !oneStep)
629 {
630 rx += step[0];
631 ry += step[1];
632 }
633 if (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
634 && this.board[rx][ry] != VariantRules.EMPTY
635 && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
636 {
637 return true;
638 }
639 }
640 return false;
641 }
642
643 // Is color c under check after move ?
644 underCheck(move)
645 {
646 const color = this.turn;
647 this.play(move);
648 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]);
649 this.undo(move);
650 return res;
651 }
652
653 // On which squares is color c under check (after move) ?
654 getCheckSquares(move)
655 {
656 this.play(move);
657 const color = this.turn; //opponent
658 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
659 ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
660 : [ ];
661 this.undo(move);
662 return res;
663 }
664
665 // Apply a move on board
666 static PlayOnBoard(board, move)
667 {
668 for (let psq of move.vanish)
669 board[psq.x][psq.y] = VariantRules.EMPTY;
670 for (let psq of move.appear)
671 board[psq.x][psq.y] = psq.c + psq.p;
672 }
673 // Un-apply the played move
674 static UndoOnBoard(board, move)
675 {
676 for (let psq of move.appear)
677 board[psq.x][psq.y] = VariantRules.EMPTY;
678 for (let psq of move.vanish)
679 board[psq.x][psq.y] = psq.c + psq.p;
680 }
681
682 // Before move is played, update variables + flags
683 updateVariables(move)
684 {
685 const piece = this.getPiece(move.start.x,move.start.y);
686 const c = this.getColor(move.start.x,move.start.y);
687 const [sizeX,sizeY] = VariantRules.size;
688 const firstRank = (c == "w" ? sizeX-1 : 0);
689
690 // Update king position + flags
691 if (piece == VariantRules.KING && move.appear.length > 0)
692 {
693 this.kingPos[c][0] = move.appear[0].x;
694 this.kingPos[c][1] = move.appear[0].y;
695 this.castleFlags[c] = [false,false];
696 return;
697 }
698 const oppCol = this.getOppCol(c);
699 const oppFirstRank = (sizeX-1) - firstRank;
700 if (move.start.x == firstRank //our rook moves?
701 && this.INIT_COL_ROOK[c].includes(move.start.y))
702 {
703 const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
704 this.castleFlags[c][flagIdx] = false;
705 }
706 else if (move.end.x == oppFirstRank //we took opponent rook?
707 && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
708 {
709 const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
710 this.castleFlags[oppCol][flagIdx] = false;
711 }
712 }
713
714 unupdateVariables(move)
715 {
716 // (Potentially) Reset king position
717 const c = this.getColor(move.start.x,move.start.y);
718 if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
719 this.kingPos[c] = [move.start.x, move.start.y];
720 }
721
722 play(move, ingame)
723 {
724 // DEBUG:
725 // if (!this.states) this.states = [];
726 // if (!ingame) this.states.push(JSON.stringify(this.board));
727
728 if (!!ingame)
729 move.notation = this.getNotation(move);
730
731 move.flags = JSON.stringify(this.flags); //save flags (for undo)
732 this.updateVariables(move);
733 this.moves.push(move);
734 this.epSquares.push( this.getEpSquare(move) );
735 VariantRules.PlayOnBoard(this.board, move);
736 }
737
738 undo(move)
739 {
740 VariantRules.UndoOnBoard(this.board, move);
741 this.epSquares.pop();
742 this.moves.pop();
743 this.unupdateVariables(move);
744 this.parseFlags(JSON.parse(move.flags));
745
746 // DEBUG:
747 // let state = this.states.pop();
748 // if (JSON.stringify(this.board) != state)
749 // debugger;
750 }
751
752 //////////////
753 // END OF GAME
754
755 checkRepetition()
756 {
757 // Check for 3 repetitions
758 if (this.moves.length >= 8)
759 {
760 // NOTE: crude detection, only moves repetition
761 const L = this.moves.length;
762 if (_.isEqual(this.moves[L-1], this.moves[L-5]) &&
763 _.isEqual(this.moves[L-2], this.moves[L-6]) &&
764 _.isEqual(this.moves[L-3], this.moves[L-7]) &&
765 _.isEqual(this.moves[L-4], this.moves[L-8]))
766 {
767 return true;
768 }
769 }
770 return false;
771 }
772
773 checkGameOver()
774 {
775 if (this.checkRepetition())
776 return "1/2";
777
778 if (this.atLeastOneMove()) // game not over
779 return "*";
780
781 // Game over
782 return this.checkGameEnd();
783 }
784
785 // No moves are possible: compute score
786 checkGameEnd()
787 {
788 const color = this.turn;
789 // No valid move: stalemate or checkmate?
790 if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
791 return "1/2";
792 // OK, checkmate
793 return color == "w" ? "0-1" : "1-0";
794 }
795
796 ////////
797 //ENGINE
798
799 // Pieces values
800 static get VALUES() {
801 return {
802 'p': 1,
803 'r': 5,
804 'n': 3,
805 'b': 3,
806 'q': 9,
807 'k': 1000
808 };
809 }
810
811 static get INFINITY() {
812 return 9999; //"checkmate" (unreachable eval)
813 }
814
815 static get THRESHOLD_MATE() {
816 // At this value or above, the game is over
817 return VariantRules.INFINITY;
818 }
819
820 static get SEARCH_DEPTH() {
821 return 3; //2 for high branching factor, 4 for small (Loser chess)
822 }
823
824 // Assumption: at least one legal move
825 // NOTE: works also for extinction chess because depth is 3...
826 getComputerMove()
827 {
828 this.shouldReturn = false;
829 const maxeval = VariantRules.INFINITY;
830 const color = this.turn;
831 let moves1 = this.getAllValidMoves();
832
833 // Can I mate in 1 ? (for Magnetic & Extinction)
834 for (let i of _.shuffle(_.range(moves1.length)))
835 {
836 this.play(moves1[i]);
837 const finish = (Math.abs(this.evalPosition()) >= VariantRules.THRESHOLD_MATE);
838 this.undo(moves1[i]);
839 if (finish)
840 return moves1[i];
841 }
842
843 // Rank moves using a min-max at depth 2
844 for (let i=0; i<moves1.length; i++)
845 {
846 moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; //very low, I'm checkmated
847 let eval2 = (color=="w" ? 1 : -1) * maxeval; //initialized with checkmate value
848 this.play(moves1[i]);
849 // Second half-move:
850 let moves2 = this.getAllValidMoves();
851 // If no possible moves AND underCheck, eval2 is correct.
852 // If !underCheck, eval2 is 0 (stalemate).
853 if (moves2.length == 0 && this.checkGameEnd() == "1/2")
854 eval2 = 0;
855 for (let j=0; j<moves2.length; j++)
856 {
857 this.play(moves2[j]);
858 let evalPos = this.evalPosition();
859 if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
860 eval2 = evalPos;
861 this.undo(moves2[j]);
862 }
863 if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval))
864 moves1[i].eval = eval2;
865 this.undo(moves1[i]);
866 }
867 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
868
869 let candidates = [0]; //indices of candidates moves
870 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
871 candidates.push(j);
872 let currentBest = moves1[_.sample(candidates, 1)];
873
874 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
875 if (VariantRules.SEARCH_DEPTH >= 3
876 && Math.abs(moves1[0].eval) < VariantRules.THRESHOLD_MATE)
877 {
878 for (let i=0; i<moves1.length; i++)
879 {
880 if (this.shouldReturn)
881 return currentBest; //depth-2, minimum
882 this.play(moves1[i]);
883 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
884 moves1[i].eval = 0.1*moves1[i].eval +
885 this.alphabeta(VariantRules.SEARCH_DEPTH-1, -maxeval, maxeval);
886 this.undo(moves1[i]);
887 }
888 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
889 }
890 else
891 return currentBest;
892
893 candidates = [0];
894 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
895 candidates.push(j);
896 // console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
897 return moves1[_.sample(candidates, 1)];
898 }
899
900 alphabeta(depth, alpha, beta)
901 {
902 const maxeval = VariantRules.INFINITY;
903 const color = this.turn;
904 if (!this.atLeastOneMove())
905 {
906 switch (this.checkGameEnd())
907 {
908 case "1/2": return 0;
909 default: return color=="w" ? -maxeval : maxeval;
910 }
911 }
912 if (depth == 0)
913 return this.evalPosition();
914 const moves = this.getAllValidMoves();
915 let v = color=="w" ? -maxeval : maxeval;
916 if (color == "w")
917 {
918 for (let i=0; i<moves.length; i++)
919 {
920 this.play(moves[i]);
921 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
922 this.undo(moves[i]);
923 alpha = Math.max(alpha, v);
924 if (alpha >= beta)
925 break; //beta cutoff
926 }
927 }
928 else //color=="b"
929 {
930 for (let i=0; i<moves.length; i++)
931 {
932 this.play(moves[i]);
933 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
934 this.undo(moves[i]);
935 beta = Math.min(beta, v);
936 if (alpha >= beta)
937 break; //alpha cutoff
938 }
939 }
940 return v;
941 }
942
943 evalPosition()
944 {
945 const [sizeX,sizeY] = VariantRules.size;
946 let evaluation = 0;
947 // Just count material for now
948 for (let i=0; i<sizeX; i++)
949 {
950 for (let j=0; j<sizeY; j++)
951 {
952 if (this.board[i][j] != VariantRules.EMPTY)
953 {
954 const sign = this.getColor(i,j) == "w" ? 1 : -1;
955 evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)];
956 }
957 }
958 }
959 return evaluation;
960 }
961
962 ////////////
963 // FEN utils
964
965 // Overridable..
966 static GenRandInitFen()
967 {
968 let pieces = [new Array(8), new Array(8)];
969 // Shuffle pieces on first and last rank
970 for (let c = 0; c <= 1; c++)
971 {
972 let positions = _.range(8);
973
974 // Get random squares for bishops
975 let randIndex = 2 * _.random(3);
976 let bishop1Pos = positions[randIndex];
977 // The second bishop must be on a square of different color
978 let randIndex_tmp = 2 * _.random(3) + 1;
979 let bishop2Pos = positions[randIndex_tmp];
980 // Remove chosen squares
981 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
982 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
983
984 // Get random squares for knights
985 randIndex = _.random(5);
986 let knight1Pos = positions[randIndex];
987 positions.splice(randIndex, 1);
988 randIndex = _.random(4);
989 let knight2Pos = positions[randIndex];
990 positions.splice(randIndex, 1);
991
992 // Get random square for queen
993 randIndex = _.random(3);
994 let queenPos = positions[randIndex];
995 positions.splice(randIndex, 1);
996
997 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
998 let rook1Pos = positions[0];
999 let kingPos = positions[1];
1000 let rook2Pos = positions[2];
1001
1002 // Finally put the shuffled pieces in the board array
1003 pieces[c][rook1Pos] = 'r';
1004 pieces[c][knight1Pos] = 'n';
1005 pieces[c][bishop1Pos] = 'b';
1006 pieces[c][queenPos] = 'q';
1007 pieces[c][kingPos] = 'k';
1008 pieces[c][bishop2Pos] = 'b';
1009 pieces[c][knight2Pos] = 'n';
1010 pieces[c][rook2Pos] = 'r';
1011 }
1012 let fen = pieces[0].join("") +
1013 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1014 pieces[1].join("").toUpperCase() +
1015 " 1111"; //add flags
1016 return fen;
1017 }
1018
1019 // Return current fen according to pieces+colors state
1020 getFen()
1021 {
1022 return this.getBaseFen() + " " + this.getFlagsFen();
1023 }
1024
1025 getBaseFen()
1026 {
1027 let fen = "";
1028 let [sizeX,sizeY] = VariantRules.size;
1029 for (let i=0; i<sizeX; i++)
1030 {
1031 let emptyCount = 0;
1032 for (let j=0; j<sizeY; j++)
1033 {
1034 if (this.board[i][j] == VariantRules.EMPTY)
1035 emptyCount++;
1036 else
1037 {
1038 if (emptyCount > 0)
1039 {
1040 // Add empty squares in-between
1041 fen += emptyCount;
1042 emptyCount = 0;
1043 }
1044 fen += VariantRules.board2fen(this.board[i][j]);
1045 }
1046 }
1047 if (emptyCount > 0)
1048 {
1049 // "Flush remainder"
1050 fen += emptyCount;
1051 }
1052 if (i < sizeX - 1)
1053 fen += "/"; //separate rows
1054 }
1055 return fen;
1056 }
1057
1058 // Overridable..
1059 getFlagsFen()
1060 {
1061 let fen = "";
1062 // Add castling flags
1063 for (let i of ['w','b'])
1064 {
1065 for (let j=0; j<2; j++)
1066 fen += this.castleFlags[i][j] ? '1' : '0';
1067 }
1068 return fen;
1069 }
1070
1071 // Context: just before move is played, turn hasn't changed
1072 getNotation(move)
1073 {
1074 if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING)
1075 {
1076 // Castle
1077 if (move.end.y < move.start.y)
1078 return "0-0-0";
1079 else
1080 return "0-0";
1081 }
1082
1083 // Translate final square
1084 const finalSquare =
1085 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1086
1087 const piece = this.getPiece(move.start.x, move.start.y);
1088 if (piece == VariantRules.PAWN)
1089 {
1090 // Pawn move
1091 let notation = "";
1092 if (move.vanish.length > move.appear.length)
1093 {
1094 // Capture
1095 const startColumn = String.fromCharCode(97 + move.start.y);
1096 notation = startColumn + "x" + finalSquare;
1097 }
1098 else //no capture
1099 notation = finalSquare;
1100 if (move.appear.length > 0 && piece != move.appear[0].p) //promotion
1101 notation += "=" + move.appear[0].p.toUpperCase();
1102 return notation;
1103 }
1104
1105 else
1106 {
1107 // Piece movement
1108 return piece.toUpperCase() +
1109 (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
1110 }
1111 }
1112
1113 // The score is already computed when calling this function
1114 getPGN(mycolor, score, fenStart, mode)
1115 {
1116 let pgn = "";
1117 pgn += '[Site "vchess.club"]<br>';
1118 const d = new Date();
1119 const opponent = mode=="human" ? "Anonymous" : "Computer";
1120 pgn += '[Variant "' + variant + '"]<br>';
1121 pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate() + '"]<br>';
1122 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1123 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
1124 pgn += '[Fen "' + fenStart + '"]<br>';
1125 pgn += '[Result "' + score + '"]<br><br>';
1126
1127 for (let i=0; i<this.moves.length; i++)
1128 {
1129 if (i % 2 == 0)
1130 pgn += ((i/2)+1) + ".";
1131 pgn += this.moves[i].notation + " ";
1132 }
1133
1134 pgn += score;
1135 return pgn;
1136 }
1137 }