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