First draft of Magnetic chess
[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 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 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; //opponent
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 checkRepetition()
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 true;
726 }
727 }
728 return false;
729 }
730
731 checkGameOver()
732 {
733 if (this.checkRepetition())
734 return "1/2";
735
736 if (this.atLeastOneMove()) // game not over
737 return "*";
738
739 // Game over
740 return this.checkGameEnd();
741 }
742
743 // No moves are possible: compute score
744 checkGameEnd()
745 {
746 const color = this.turn;
747 // No valid move: stalemate or checkmate?
748 if (!this.isAttacked(this.kingPos[color], this.getOppCol(color)))
749 return "1/2";
750 // OK, checkmate
751 return color == "w" ? "0-1" : "1-0";
752 }
753
754 ////////
755 //ENGINE
756
757 // Pieces values
758 static get VALUES() {
759 return {
760 'p': 1,
761 'r': 5,
762 'n': 3,
763 'b': 3,
764 'q': 9,
765 'k': 1000
766 };
767 }
768
769 // Assumption: at least one legal move
770 getComputerMove()
771 {
772 const color = this.turn;
773
774 // Rank moves using a min-max at depth 2
775 let moves1 = this.getAllValidMoves();
776
777 for (let i=0; i<moves1.length; i++)
778 {
779 moves1[i].eval = (color=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
780 let eval2 = (color=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
781 this.play(moves1[i]);
782 // Second half-move:
783 let moves2 = this.getAllValidMoves();
784 // If no possible moves AND underCheck, eval2 is correct.
785 // If !underCheck, eval2 is 0 (stalemate).
786 if (moves2.length == 0 && this.checkGameEnd() == "1/2")
787 eval2 = 0;
788 for (let j=0; j<moves2.length; j++)
789 {
790 this.play(moves2[j]);
791 let evalPos = this.evalPosition();
792 if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
793 eval2 = evalPos;
794 this.undo(moves2[j]);
795 }
796 if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval))
797 moves1[i].eval = eval2;
798 this.undo(moves1[i]);
799 }
800 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
801
802 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
803 for (let i=0; i<moves1.length; i++)
804 {
805 this.play(moves1[i]);
806 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
807 moves1[i].eval = 0.1*moves1[i].eval + this.alphabeta(2, -1000, 1000);
808 this.undo(moves1[i]);
809 }
810 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
811
812 let candidates = [0]; //indices of candidates moves
813 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
814 candidates.push(j);
815
816 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
817 return moves1[_.sample(candidates, 1)];
818 }
819
820 alphabeta(depth, alpha, beta)
821 {
822 const color = this.turn;
823 if (!this.atLeastOneMove())
824 {
825 switch (this.checkGameEnd())
826 {
827 case "1/2": return 0;
828 default: return color=="w" ? -1000 : 1000;
829 }
830 }
831 if (depth == 0)
832 return this.evalPosition();
833 const moves = this.getAllValidMoves();
834 let v = color=="w" ? -1000 : 1000;
835 if (color == "w")
836 {
837 for (let i=0; i<moves.length; i++)
838 {
839 this.play(moves[i]);
840 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
841 this.undo(moves[i]);
842 alpha = Math.max(alpha, v);
843 if (alpha >= beta)
844 break; //beta cutoff
845 }
846 }
847 else //color=="b"
848 {
849 for (let i=0; i<moves.length; i++)
850 {
851 this.play(moves[i]);
852 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
853 this.undo(moves[i]);
854 beta = Math.min(beta, v);
855 if (alpha >= beta)
856 break; //alpha cutoff
857 }
858 }
859 return v;
860 }
861
862 evalPosition()
863 {
864 const [sizeX,sizeY] = VariantRules.size;
865 let evaluation = 0;
866 //Just count material for now
867 for (let i=0; i<sizeX; i++)
868 {
869 for (let j=0; j<sizeY; j++)
870 {
871 if (this.board[i][j] != VariantRules.EMPTY)
872 {
873 const sign = this.getColor(i,j) == "w" ? 1 : -1;
874 evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)];
875 }
876 }
877 }
878 return evaluation;
879 }
880
881 ////////////
882 // FEN utils
883
884 // Overridable..
885 static GenRandInitFen()
886 {
887 let pieces = [new Array(8), new Array(8)];
888 // Shuffle pieces on first and last rank
889 for (let c = 0; c <= 1; c++)
890 {
891 let positions = _.range(8);
892
893 // Get random squares for bishops
894 let randIndex = 2 * _.random(3);
895 let bishop1Pos = positions[randIndex];
896 // The second bishop must be on a square of different color
897 let randIndex_tmp = 2 * _.random(3) + 1;
898 let bishop2Pos = positions[randIndex_tmp];
899 // Remove chosen squares
900 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
901 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
902
903 // Get random squares for knights
904 randIndex = _.random(5);
905 let knight1Pos = positions[randIndex];
906 positions.splice(randIndex, 1);
907 randIndex = _.random(4);
908 let knight2Pos = positions[randIndex];
909 positions.splice(randIndex, 1);
910
911 // Get random square for queen
912 randIndex = _.random(3);
913 let queenPos = positions[randIndex];
914 positions.splice(randIndex, 1);
915
916 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
917 let rook1Pos = positions[0];
918 let kingPos = positions[1];
919 let rook2Pos = positions[2];
920
921 // Finally put the shuffled pieces in the board array
922 pieces[c][rook1Pos] = 'r';
923 pieces[c][knight1Pos] = 'n';
924 pieces[c][bishop1Pos] = 'b';
925 pieces[c][queenPos] = 'q';
926 pieces[c][kingPos] = 'k';
927 pieces[c][bishop2Pos] = 'b';
928 pieces[c][knight2Pos] = 'n';
929 pieces[c][rook2Pos] = 'r';
930 }
931 let fen = pieces[0].join("") +
932 "/pppppppp/8/8/8/8/PPPPPPPP/" +
933 pieces[1].join("").toUpperCase() +
934 " 1111"; //add flags
935 return fen;
936 }
937
938 // Return current fen according to pieces+colors state
939 getFen()
940 {
941 return this.getBaseFen() + " " + this.getFlagsFen();
942 }
943
944 getBaseFen()
945 {
946 let fen = "";
947 let [sizeX,sizeY] = VariantRules.size;
948 for (let i=0; i<sizeX; i++)
949 {
950 let emptyCount = 0;
951 for (let j=0; j<sizeY; j++)
952 {
953 if (this.board[i][j] == VariantRules.EMPTY)
954 emptyCount++;
955 else
956 {
957 if (emptyCount > 0)
958 {
959 // Add empty squares in-between
960 fen += emptyCount;
961 emptyCount = 0;
962 }
963 fen += VariantRules.board2fen(this.board[i][j]);
964 }
965 }
966 if (emptyCount > 0)
967 {
968 // "Flush remainder"
969 fen += emptyCount;
970 }
971 if (i < sizeX - 1)
972 fen += "/"; //separate rows
973 }
974 return fen;
975 }
976
977 // Overridable..
978 getFlagsFen()
979 {
980 let fen = "";
981 // Add castling flags
982 for (let i of ['w','b'])
983 {
984 for (let j=0; j<2; j++)
985 fen += this.flags[i][j] ? '1' : '0';
986 }
987 return fen;
988 }
989
990 // Context: just before move is played, turn hasn't changed
991 getNotation(move)
992 {
993 if (move.appear.length == 2)
994 {
995 // Castle
996 if (move.end.y < move.start.y)
997 return "0-0-0";
998 else
999 return "0-0";
1000 }
1001
1002 // Translate final square
1003 let finalSquare =
1004 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1005
1006 let piece = this.getPiece(move.start.x, move.start.y);
1007 if (piece == VariantRules.PAWN)
1008 {
1009 // Pawn move
1010 let notation = "";
1011 if (move.vanish.length > 1)
1012 {
1013 // Capture
1014 let startColumn = String.fromCharCode(97 + move.start.y);
1015 notation = startColumn + "x" + finalSquare;
1016 }
1017 else //no capture
1018 notation = finalSquare;
1019 if (move.appear.length > 0 && piece != move.appear[0].p) //promotion
1020 notation += "=" + move.appear[0].p.toUpperCase();
1021 return notation;
1022 }
1023
1024 else
1025 {
1026 // Piece movement
1027 return piece.toUpperCase() + (move.vanish.length > 1 ? "x" : "") + finalSquare;
1028 }
1029 }
1030
1031 // The score is already computed when calling this function
1032 getPGN(mycolor, score, fenStart, mode)
1033 {
1034 let pgn = "";
1035 pgn += '[Site "vchess.club"]<br>';
1036 const d = new Date();
1037 const opponent = mode=="human" ? "Anonymous" : "Computer";
1038 pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate() + '"]<br>';
1039 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1040 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
1041 pgn += '[Fen "' + fenStart + '"]<br>';
1042 pgn += '[Result "' + score + '"]<br><br>';
1043
1044 for (let i=0; i<this.moves.length; i++)
1045 {
1046 if (i % 2 == 0)
1047 pgn += ((i/2)+1) + ".";
1048 pgn += this.moves[i].notation + " ";
1049 }
1050
1051 pgn += score;
1052 return pgn;
1053 }
1054 }