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