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