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