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