Improve 'help' modal style on large screens
[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
098e8468 13// TODO: for animation, moves should contains "moving" and "fading" maybe...
1d184b4c
BA
14class Move
15{
16 // o: {appear, vanish, [start,] [end,]}
17 // appear,vanish = arrays of PiPo
18 // start,end = coordinates to apply to trigger move visually (think castle)
19 constructor(o)
20 {
21 this.appear = o.appear;
22 this.vanish = o.vanish;
23 this.start = !!o.start ? o.start : {x:o.vanish[0].x, y:o.vanish[0].y};
24 this.end = !!o.end ? o.end : {x:o.appear[0].x, y:o.appear[0].y};
25 }
26}
27
28// NOTE: x coords = top to bottom; y = left to right (from white player perspective)
29class ChessRules
30{
31 // Path to pieces
32 static getPpath(b)
33 {
34 return b; //usual pieces in pieces/ folder
35 }
36 // Turn "wb" into "B" (for FEN)
37 static board2fen(b)
38 {
39 return b[0]=='w' ? b[1].toUpperCase() : b[1];
40 }
41 // Turn "p" into "bp" (for board)
42 static fen2board(f)
43 {
44 return f.charCodeAt()<=90 ? "w"+f.toLowerCase() : "b"+f;
45 }
46
47 /////////////////
48 // INITIALIZATION
49
d3334c3a 50 // fen == "position flags"
dfb4afc1 51 constructor(fen, moves)
1d184b4c 52 {
dfb4afc1 53 this.moves = moves;
1d184b4c 54 // Use fen string to initialize variables, flags and board
1d184b4c 55 this.board = VariantRules.GetBoard(fen);
2526c041 56 this.setFlags(fen);
ffbae57a 57 this.initVariables(fen);
1d184b4c
BA
58 }
59
60 initVariables(fen)
61 {
62 this.INIT_COL_KING = {'w':-1, 'b':-1};
63 this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]};
64 this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //respective squares of white and black king
65 const fenParts = fen.split(" ");
66 const position = fenParts[0].split("/");
67 for (let i=0; i<position.length; i++)
68 {
6037f1d8
BA
69 let k = 0; //column index on board
70 for (let j=0; j<position[i].length; j++)
1d184b4c
BA
71 {
72 switch (position[i].charAt(j))
73 {
74 case 'k':
6037f1d8
BA
75 this.kingPos['b'] = [i,k];
76 this.INIT_COL_KING['b'] = k;
1d184b4c
BA
77 break;
78 case 'K':
6037f1d8
BA
79 this.kingPos['w'] = [i,k];
80 this.INIT_COL_KING['w'] = k;
1d184b4c
BA
81 break;
82 case 'r':
83 if (this.INIT_COL_ROOK['b'][0] < 0)
6037f1d8 84 this.INIT_COL_ROOK['b'][0] = k;
1d184b4c 85 else
6037f1d8 86 this.INIT_COL_ROOK['b'][1] = k;
1d184b4c
BA
87 break;
88 case 'R':
89 if (this.INIT_COL_ROOK['w'][0] < 0)
6037f1d8 90 this.INIT_COL_ROOK['w'][0] = k;
1d184b4c 91 else
6037f1d8 92 this.INIT_COL_ROOK['w'][1] = k;
1d184b4c
BA
93 break;
94 default:
95 let num = parseInt(position[i].charAt(j));
96 if (!isNaN(num))
6037f1d8 97 k += (num-1);
1d184b4c 98 }
6037f1d8 99 k++;
1d184b4c
BA
100 }
101 }
f3802fcd 102 const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
1d184b4c 103 this.epSquares = [ epSq ];
1d184b4c
BA
104 }
105
106 // Turn diagram fen into double array ["wb","wp","bk",...]
107 static GetBoard(fen)
108 {
109 let rows = fen.split(" ")[0].split("/");
46302e64 110 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
111 let board = doubleArray(sizeX, sizeY, "");
112 for (let i=0; i<rows.length; i++)
113 {
114 let j = 0;
115 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++)
116 {
117 let character = rows[i][indexInRow];
118 let num = parseInt(character);
119 if (!isNaN(num))
120 j += num; //just shift j
121 else //something at position i,j
122 board[i][j++] = VariantRules.fen2board(character);
123 }
124 }
125 return board;
126 }
127
dda21a71 128 // Extract (relevant) flags from fen
2526c041 129 setFlags(fen)
1d184b4c
BA
130 {
131 // white a-castle, h-castle, black a-castle, h-castle
2526c041
BA
132 this.castleFlags = {'w': new Array(2), 'b': new Array(2)};
133 let flags = fen.split(" ")[1]; //flags right after position
1d184b4c 134 for (let i=0; i<4; i++)
2526c041 135 this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (flags.charAt(i) == '1');
1d184b4c
BA
136 }
137
138 ///////////////////
139 // GETTERS, SETTERS
140
1d184b4c
BA
141 static get size() { return [8,8]; }
142 // Two next functions return 'undefined' if called on empty square
143 getColor(i,j) { return this.board[i][j].charAt(0); }
144 getPiece(i,j) { return this.board[i][j].charAt(1); }
145
146 // Color
147 getOppCol(color) { return color=="w" ? "b" : "w"; }
148
149 get lastMove() {
150 const L = this.moves.length;
151 return L>0 ? this.moves[L-1] : null;
152 }
153 get turn() {
d3334c3a 154 return this.moves.length%2==0 ? 'w' : 'b';
1d184b4c
BA
155 }
156
157 // Pieces codes
158 static get PAWN() { return 'p'; }
159 static get ROOK() { return 'r'; }
160 static get KNIGHT() { return 'n'; }
161 static get BISHOP() { return 'b'; }
162 static get QUEEN() { return 'q'; }
163 static get KING() { return 'k'; }
164
165 // Empty square
166 static get EMPTY() { return ''; }
167
168 // Some pieces movements
169 static get steps() {
170 return {
171 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
172 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
173 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
1d184b4c
BA
174 };
175 }
176
2526c041
BA
177 // Aggregates flags into one object
178 get flags() {
179 return this.castleFlags;
180 }
181
182 // Reverse operation
183 parseFlags(flags)
184 {
185 this.castleFlags = flags;
186 }
187
1d184b4c
BA
188 // En-passant square, if any
189 getEpSquare(move)
190 {
191 const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x];
192 if (this.getPiece(sx,sy) == VariantRules.PAWN && Math.abs(sx - ex) == 2)
193 {
194 return {
195 x: (sx + ex)/2,
196 y: sy
197 };
198 }
199 return undefined; //default
200 }
201
dda21a71 202 // Can thing on square1 take thing on square2
46302e64 203 canTake([x1,y1], [x2,y2])
1d184b4c 204 {
46302e64 205 return this.getColor(x1,y1) != this.getColor(x2,y2);
1d184b4c
BA
206 }
207
208 ///////////////////
209 // MOVES GENERATION
210
211 // All possible moves from selected square (assumption: color is OK)
212 getPotentialMovesFrom([x,y])
213 {
1d184b4c
BA
214 switch (this.getPiece(x,y))
215 {
216 case VariantRules.PAWN:
46302e64 217 return this.getPotentialPawnMoves([x,y]);
1d184b4c 218 case VariantRules.ROOK:
46302e64 219 return this.getPotentialRookMoves([x,y]);
1d184b4c 220 case VariantRules.KNIGHT:
46302e64 221 return this.getPotentialKnightMoves([x,y]);
1d184b4c 222 case VariantRules.BISHOP:
46302e64 223 return this.getPotentialBishopMoves([x,y]);
1d184b4c 224 case VariantRules.QUEEN:
46302e64 225 return this.getPotentialQueenMoves([x,y]);
1d184b4c 226 case VariantRules.KING:
46302e64 227 return this.getPotentialKingMoves([x,y]);
1d184b4c
BA
228 }
229 }
230
231 // Build a regular move from its initial and destination squares; tr: transformation
46302e64 232 getBasicMove([sx,sy], [ex,ey], tr)
1d184b4c 233 {
2526c041 234 let mv = new Move({
1d184b4c
BA
235 appear: [
236 new PiPo({
237 x: ex,
238 y: ey,
46302e64
BA
239 c: !!tr ? tr.c : this.getColor(sx,sy),
240 p: !!tr ? tr.p : this.getPiece(sx,sy)
1d184b4c
BA
241 })
242 ],
243 vanish: [
244 new PiPo({
245 x: sx,
246 y: sy,
247 c: this.getColor(sx,sy),
248 p: this.getPiece(sx,sy)
249 })
250 ]
251 });
252
253 // The opponent piece disappears if we take it
254 if (this.board[ex][ey] != VariantRules.EMPTY)
255 {
256 mv.vanish.push(
257 new PiPo({
258 x: ex,
259 y: ey,
260 c: this.getColor(ex,ey),
261 p: this.getPiece(ex,ey)
262 })
263 );
264 }
265 return mv;
266 }
267
268 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
46302e64 269 getSlideNJumpMoves([x,y], steps, oneStep)
1d184b4c 270 {
46302e64 271 const color = this.getColor(x,y);
2526c041 272 let moves = [];
46302e64 273 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
274 outerLoop:
275 for (let step of steps)
276 {
46302e64
BA
277 let i = x + step[0];
278 let j = y + step[1];
1221ac47
BA
279 while (i>=0 && i<sizeX && j>=0 && j<sizeY
280 && this.board[i][j] == VariantRules.EMPTY)
1d184b4c 281 {
46302e64 282 moves.push(this.getBasicMove([x,y], [i,j]));
1d184b4c
BA
283 if (oneStep !== undefined)
284 continue outerLoop;
285 i += step[0];
286 j += step[1];
287 }
efb20746 288 if (i>=0 && i<sizeX && j>=0 && j<sizeY && this.canTake([x,y], [i,j]))
46302e64 289 moves.push(this.getBasicMove([x,y], [i,j]));
1d184b4c
BA
290 }
291 return moves;
292 }
293
dda21a71 294 // What are the pawn moves from square x,y ?
46302e64 295 getPotentialPawnMoves([x,y])
1d184b4c 296 {
2526c041
BA
297 const color = this.turn;
298 let moves = [];
299 const V = VariantRules;
1221ac47 300 const [sizeX,sizeY] = V.size;
2526c041 301 const shift = (color == "w" ? -1 : 1);
cf130369
BA
302 const firstRank = (color == 'w' ? sizeX-1 : 0);
303 const startRank = (color == "w" ? sizeX-2 : 1);
304 const lastRank = (color == "w" ? 0 : sizeX-1);
1d184b4c
BA
305
306 if (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank)
307 {
308 // Normal moves
309 if (this.board[x+shift][y] == V.EMPTY)
310 {
46302e64 311 moves.push(this.getBasicMove([x,y], [x+shift,y]));
1221ac47 312 // Next condition because variants with pawns on 1st rank allow them to jump
2526c041 313 if ([startRank,firstRank].includes(x) && this.board[x+2*shift][y] == V.EMPTY)
1d184b4c
BA
314 {
315 // Two squares jump
46302e64 316 moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
1d184b4c
BA
317 }
318 }
319 // Captures
1221ac47
BA
320 if (y>0 && this.canTake([x,y], [x+shift,y-1])
321 && this.board[x+shift][y-1] != V.EMPTY)
322 {
46302e64 323 moves.push(this.getBasicMove([x,y], [x+shift,y-1]));
1221ac47
BA
324 }
325 if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
326 && this.board[x+shift][y+1] != V.EMPTY)
327 {
46302e64 328 moves.push(this.getBasicMove([x,y], [x+shift,y+1]));
1221ac47 329 }
1d184b4c
BA
330 }
331
332 if (x+shift == lastRank)
333 {
334 // Promotion
68f5ccc8 335 const pawnColor = this.getColor(x,y); //can be different for checkered
1d184b4c
BA
336 let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN];
337 promotionPieces.forEach(p => {
338 // Normal move
339 if (this.board[x+shift][y] == V.EMPTY)
68f5ccc8 340 moves.push(this.getBasicMove([x,y], [x+shift,y], {c:pawnColor,p:p}));
1d184b4c 341 // Captures
1221ac47
BA
342 if (y>0 && this.canTake([x,y], [x+shift,y-1])
343 && this.board[x+shift][y-1] != V.EMPTY)
344 {
68f5ccc8 345 moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p}));
1221ac47
BA
346 }
347 if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1])
348 && this.board[x+shift][y+1] != V.EMPTY)
349 {
68f5ccc8 350 moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p}));
1221ac47 351 }
1d184b4c
BA
352 });
353 }
354
355 // En passant
356 const Lep = this.epSquares.length;
357 const epSquare = Lep>0 ? this.epSquares[Lep-1] : undefined;
358 if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1)
359 {
360 let epStep = epSquare.y - y;
46302e64 361 var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
1d184b4c
BA
362 enpassantMove.vanish.push({
363 x: x,
364 y: y+epStep,
365 p: 'p',
366 c: this.getColor(x,y+epStep)
367 });
368 moves.push(enpassantMove);
369 }
370
371 return moves;
372 }
373
374 // What are the rook moves from square x,y ?
46302e64 375 getPotentialRookMoves(sq)
1d184b4c 376 {
46302e64 377 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]);
1d184b4c
BA
378 }
379
380 // What are the knight moves from square x,y ?
46302e64 381 getPotentialKnightMoves(sq)
1d184b4c 382 {
46302e64 383 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
1d184b4c
BA
384 }
385
386 // What are the bishop moves from square x,y ?
46302e64 387 getPotentialBishopMoves(sq)
1d184b4c 388 {
46302e64 389 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]);
1d184b4c
BA
390 }
391
392 // What are the queen moves from square x,y ?
46302e64 393 getPotentialQueenMoves(sq)
1d184b4c 394 {
a37076f1
BA
395 const V = VariantRules;
396 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
1d184b4c
BA
397 }
398
399 // What are the king moves from square x,y ?
46302e64 400 getPotentialKingMoves(sq)
1d184b4c 401 {
a37076f1 402 const V = VariantRules;
1d184b4c 403 // Initialize with normal moves
a37076f1
BA
404 let moves = this.getSlideNJumpMoves(sq,
405 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
46302e64 406 return moves.concat(this.getCastleMoves(sq));
1d184b4c
BA
407 }
408
46302e64 409 getCastleMoves([x,y])
1d184b4c 410 {
46302e64 411 const c = this.getColor(x,y);
c6052161
BA
412 const [sizeX,sizeY] = VariantRules.size;
413 if (x != (c=="w" ? sizeX-1 : 0) || y != this.INIT_COL_KING[c])
1d184b4c
BA
414 return []; //x isn't first rank, or king has moved (shortcut)
415
416 const V = VariantRules;
417
418 // Castling ?
419 const oppCol = this.getOppCol(c);
420 let moves = [];
421 let i = 0;
c6052161 422 const finalSquares = [ [2,3], [sizeY-2,sizeY-3] ]; //king, then rook
1d184b4c
BA
423 castlingCheck:
424 for (let castleSide=0; castleSide < 2; castleSide++) //large, then small
425 {
2526c041 426 if (!this.castleFlags[c][castleSide])
1d184b4c
BA
427 continue;
428 // If this code is reached, rooks and king are on initial position
429
430 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
431 let step = finalSquares[castleSide][0] < y ? -1 : 1;
432 for (i=y; i!=finalSquares[castleSide][0]; i+=step)
433 {
cf130369 434 if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY &&
1d184b4c
BA
435 // NOTE: next check is enough, because of chessboard constraints
436 (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i)))))
437 {
438 continue castlingCheck;
439 }
440 }
441
442 // Nothing on the path to the rook?
443 step = castleSide == 0 ? -1 : 1;
444 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step)
445 {
446 if (this.board[x][i] != V.EMPTY)
447 continue castlingCheck;
448 }
449 const rookPos = this.INIT_COL_ROOK[c][castleSide];
450
451 // Nothing on final squares, except maybe king and castling rook?
452 for (i=0; i<2; i++)
453 {
454 if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
455 this.getPiece(x,finalSquares[castleSide][i]) != V.KING &&
456 finalSquares[castleSide][i] != rookPos)
457 {
458 continue castlingCheck;
459 }
460 }
461
462 // If this code is reached, castle is valid
463 moves.push( new Move({
464 appear: [
465 new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}),
466 new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})],
467 vanish: [
468 new PiPo({x:x,y:y,p:V.KING,c:c}),
469 new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})],
470 end: Math.abs(y - rookPos) <= 2
471 ? {x:x, y:rookPos}
472 : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)}
473 }) );
474 }
475
476 return moves;
477 }
478
479 ///////////////////
480 // MOVES VALIDATION
481
46302e64 482 canIplay(side, [x,y])
1d184b4c 483 {
46302e64
BA
484 return ((side=='w' && this.moves.length%2==0) || (side=='b' && this.moves.length%2==1))
485 && this.getColor(x,y) == side;
1d184b4c
BA
486 }
487
488 getPossibleMovesFrom(sq)
489 {
490 // Assuming color is right (already checked)
491 return this.filterValid( this.getPotentialMovesFrom(sq) );
492 }
493
494 // TODO: once a promotion is filtered, the others results are same: useless computations
495 filterValid(moves)
496 {
497 if (moves.length == 0)
498 return [];
b8121223 499 return moves.filter(m => { return !this.underCheck(m); });
1d184b4c
BA
500 }
501
502 // Search for all valid moves considering current turn (for engine and game end)
46302e64 503 getAllValidMoves()
1d184b4c 504 {
46302e64 505 const color = this.turn;
1d184b4c 506 const oppCol = this.getOppCol(color);
c6052161
BA
507 let potentialMoves = [];
508 const [sizeX,sizeY] = VariantRules.size;
a6abf094 509 for (let i=0; i<sizeX; i++)
1d184b4c 510 {
a6abf094 511 for (let j=0; j<sizeY; j++)
1d184b4c
BA
512 {
513 // Next condition ... != oppCol is a little HACK to work with checkered variant
514 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
515 Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
516 }
517 }
518 // NOTE: prefer lazy undercheck tests, letting the king being taken?
519 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
520 return this.filterValid(potentialMoves);
521 }
9de73b71 522
e64a4eff 523 // Stop at the first move found
46302e64 524 atLeastOneMove()
e64a4eff 525 {
46302e64 526 const color = this.turn;
e64a4eff 527 const oppCol = this.getOppCol(color);
c6052161 528 const [sizeX,sizeY] = VariantRules.size;
9de73b71 529 for (let i=0; i<sizeX; i++)
e64a4eff 530 {
9de73b71 531 for (let j=0; j<sizeY; j++)
e64a4eff
BA
532 {
533 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
534 {
535 const moves = this.getPotentialMovesFrom([i,j]);
536 if (moves.length > 0)
537 {
9de73b71 538 for (let k=0; k<moves.length; k++)
e64a4eff 539 {
9de73b71 540 if (this.filterValid([moves[k]]).length > 0)
e64a4eff
BA
541 return true;
542 }
543 }
544 }
545 }
546 }
547 return false;
548 }
1d184b4c 549
dda21a71 550 // Check if pieces of color in array 'colors' are attacking square x,y
46302e64 551 isAttacked(sq, colors)
1d184b4c 552 {
46302e64
BA
553 return (this.isAttackedByPawn(sq, colors)
554 || this.isAttackedByRook(sq, colors)
555 || this.isAttackedByKnight(sq, colors)
556 || this.isAttackedByBishop(sq, colors)
557 || this.isAttackedByQueen(sq, colors)
558 || this.isAttackedByKing(sq, colors));
1d184b4c
BA
559 }
560
dda21a71 561 // Is square x,y attacked by 'colors' pawns ?
46302e64 562 isAttackedByPawn([x,y], colors)
1d184b4c 563 {
efb20746 564 const [sizeX,sizeY] = VariantRules.size;
46302e64 565 for (let c of colors)
1d184b4c 566 {
46302e64 567 let pawnShift = (c=="w" ? 1 : -1);
efb20746 568 if (x+pawnShift>=0 && x+pawnShift<sizeX)
1d184b4c 569 {
46302e64 570 for (let i of [-1,1])
1d184b4c 571 {
efb20746 572 if (y+i>=0 && y+i<sizeY && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
46302e64
BA
573 && this.getColor(x+pawnShift,y+i)==c)
574 {
575 return true;
576 }
1d184b4c
BA
577 }
578 }
579 }
580 return false;
581 }
582
dda21a71 583 // Is square x,y attacked by 'colors' rooks ?
46302e64 584 isAttackedByRook(sq, colors)
1d184b4c 585 {
46302e64 586 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
587 VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
588 }
589
dda21a71 590 // Is square x,y attacked by 'colors' knights ?
46302e64 591 isAttackedByKnight(sq, colors)
1d184b4c 592 {
46302e64 593 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
594 VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
595 }
596
dda21a71 597 // Is square x,y attacked by 'colors' bishops ?
46302e64 598 isAttackedByBishop(sq, colors)
1d184b4c 599 {
46302e64 600 return this.isAttackedBySlideNJump(sq, colors,
1d184b4c
BA
601 VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
602 }
603
dda21a71 604 // Is square x,y attacked by 'colors' queens ?
46302e64 605 isAttackedByQueen(sq, colors)
1d184b4c 606 {
a37076f1
BA
607 const V = VariantRules;
608 return this.isAttackedBySlideNJump(sq, colors, V.QUEEN,
609 V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
1d184b4c
BA
610 }
611
dda21a71 612 // Is square x,y attacked by 'colors' king(s) ?
46302e64 613 isAttackedByKing(sq, colors)
1d184b4c 614 {
a37076f1
BA
615 const V = VariantRules;
616 return this.isAttackedBySlideNJump(sq, colors, V.KING,
617 V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep");
1d184b4c
BA
618 }
619
1221ac47 620 // Generic method for non-pawn pieces ("sliding or jumping"):
dda21a71 621 // is x,y attacked by a piece of color in array 'colors' ?
46302e64 622 isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
1d184b4c 623 {
efb20746 624 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
625 for (let step of steps)
626 {
627 let rx = x+step[0], ry = y+step[1];
efb20746
BA
628 while (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
629 && this.board[rx][ry] == VariantRules.EMPTY && !oneStep)
1d184b4c
BA
630 {
631 rx += step[0];
632 ry += step[1];
633 }
efb20746
BA
634 if (rx>=0 && rx<sizeX && ry>=0 && ry<sizeY
635 && this.board[rx][ry] != VariantRules.EMPTY
46302e64 636 && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
1d184b4c
BA
637 {
638 return true;
639 }
640 }
641 return false;
642 }
643
dda21a71 644 // Is current player under check after his move ?
46302e64 645 underCheck(move)
1d184b4c 646 {
46302e64 647 const color = this.turn;
1d184b4c 648 this.play(move);
cf130369 649 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]);
1d184b4c
BA
650 this.undo(move);
651 return res;
652 }
653
dda21a71 654 // On which squares is opponent under check after our move ?
46302e64 655 getCheckSquares(move)
4b5fe306
BA
656 {
657 this.play(move);
204e289b 658 const color = this.turn; //opponent
cf130369 659 let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)])
46302e64 660 ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
4b5fe306
BA
661 : [ ];
662 this.undo(move);
663 return res;
664 }
665
1d184b4c
BA
666 // Apply a move on board
667 static PlayOnBoard(board, move)
668 {
669 for (let psq of move.vanish)
670 board[psq.x][psq.y] = VariantRules.EMPTY;
671 for (let psq of move.appear)
672 board[psq.x][psq.y] = psq.c + psq.p;
673 }
674 // Un-apply the played move
675 static UndoOnBoard(board, move)
676 {
677 for (let psq of move.appear)
678 board[psq.x][psq.y] = VariantRules.EMPTY;
679 for (let psq of move.vanish)
680 board[psq.x][psq.y] = psq.c + psq.p;
681 }
682
d3334c3a 683 // Before move is played, update variables + flags
1d184b4c
BA
684 updateVariables(move)
685 {
686 const piece = this.getPiece(move.start.x,move.start.y);
687 const c = this.getColor(move.start.x,move.start.y);
c6052161
BA
688 const [sizeX,sizeY] = VariantRules.size;
689 const firstRank = (c == "w" ? sizeX-1 : 0);
1d184b4c
BA
690
691 // Update king position + flags
692 if (piece == VariantRules.KING && move.appear.length > 0)
693 {
694 this.kingPos[c][0] = move.appear[0].x;
695 this.kingPos[c][1] = move.appear[0].y;
2526c041 696 this.castleFlags[c] = [false,false];
1d184b4c
BA
697 return;
698 }
699 const oppCol = this.getOppCol(c);
c6052161 700 const oppFirstRank = (sizeX-1) - firstRank;
1d184b4c
BA
701 if (move.start.x == firstRank //our rook moves?
702 && this.INIT_COL_ROOK[c].includes(move.start.y))
703 {
2526c041
BA
704 const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
705 this.castleFlags[c][flagIdx] = false;
1d184b4c
BA
706 }
707 else if (move.end.x == oppFirstRank //we took opponent rook?
aea1443e 708 && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
1d184b4c 709 {
2526c041
BA
710 const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
711 this.castleFlags[oppCol][flagIdx] = false;
1d184b4c
BA
712 }
713 }
714
dda21a71
BA
715 // After move is undo-ed, un-update variables (flags are reset)
716 // TODO: more symmetry, by storing flags increment in move...
d3334c3a 717 unupdateVariables(move)
1d184b4c 718 {
d3334c3a
BA
719 // (Potentially) Reset king position
720 const c = this.getColor(move.start.x,move.start.y);
721 if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
722 this.kingPos[c] = [move.start.x, move.start.y];
723 }
1d184b4c 724
d3334c3a
BA
725 play(move, ingame)
726 {
dfb4afc1 727 if (!!ingame)
6752407b 728 move.notation = [this.getNotation(move), this.getLongNotation(move)];
dfb4afc1 729
2526c041 730 move.flags = JSON.stringify(this.flags); //save flags (for undo)
d3334c3a
BA
731 this.updateVariables(move);
732 this.moves.push(move);
1d184b4c
BA
733 this.epSquares.push( this.getEpSquare(move) );
734 VariantRules.PlayOnBoard(this.board, move);
1d184b4c
BA
735 }
736
cd4cad04 737 undo(move)
1d184b4c
BA
738 {
739 VariantRules.UndoOnBoard(this.board, move);
740 this.epSquares.pop();
d3334c3a
BA
741 this.moves.pop();
742 this.unupdateVariables(move);
2526c041 743 this.parseFlags(JSON.parse(move.flags));
1d184b4c
BA
744 }
745
746 //////////////
747 // END OF GAME
748
dda21a71 749 // Basic check for 3 repetitions (in the last moves only)
1af36beb 750 checkRepetition()
1d184b4c 751 {
1d184b4c
BA
752 if (this.moves.length >= 8)
753 {
1d184b4c
BA
754 const L = this.moves.length;
755 if (_.isEqual(this.moves[L-1], this.moves[L-5]) &&
756 _.isEqual(this.moves[L-2], this.moves[L-6]) &&
757 _.isEqual(this.moves[L-3], this.moves[L-7]) &&
758 _.isEqual(this.moves[L-4], this.moves[L-8]))
759 {
1af36beb 760 return true;
1d184b4c
BA
761 }
762 }
1af36beb
BA
763 return false;
764 }
1d184b4c 765
dda21a71 766 // Is game over ? And if yes, what is the score ?
1af36beb
BA
767 checkGameOver()
768 {
769 if (this.checkRepetition())
770 return "1/2";
771
772 if (this.atLeastOneMove()) // game not over
1d184b4c 773 return "*";
1d184b4c
BA
774
775 // Game over
46302e64 776 return this.checkGameEnd();
1d184b4c
BA
777 }
778
46302e64
BA
779 // No moves are possible: compute score
780 checkGameEnd()
1d184b4c 781 {
46302e64 782 const color = this.turn;
1d184b4c 783 // No valid move: stalemate or checkmate?
cf130369 784 if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)]))
1d184b4c
BA
785 return "1/2";
786 // OK, checkmate
787 return color == "w" ? "0-1" : "1-0";
788 }
789
790 ////////
791 //ENGINE
792
793 // Pieces values
794 static get VALUES() {
795 return {
796 'p': 1,
797 'r': 5,
798 'n': 3,
799 'b': 3,
800 'q': 9,
801 'k': 1000
802 };
803 }
804
9e42b4dd
BA
805 static get INFINITY() {
806 return 9999; //"checkmate" (unreachable eval)
807 }
808
809 static get THRESHOLD_MATE() {
810 // At this value or above, the game is over
811 return VariantRules.INFINITY;
812 }
813
3c09dc49
BA
814 static get SEARCH_DEPTH() {
815 return 3; //2 for high branching factor, 4 for small (Loser chess)
816 }
817
1d184b4c 818 // Assumption: at least one legal move
a6abf094
BA
819 // NOTE: works also for extinction chess because depth is 3...
820 getComputerMove()
1d184b4c 821 {
3c09dc49 822 this.shouldReturn = false;
9e42b4dd 823 const maxeval = VariantRules.INFINITY;
46302e64 824 const color = this.turn;
15952ada
BA
825 // Some variants may show a bigger moves list to the human (Switching),
826 // thus the argument "computer" below (which is generally ignored)
827 let moves1 = this.getAllValidMoves("computer");
a6abf094
BA
828
829 // Can I mate in 1 ? (for Magnetic & Extinction)
830 for (let i of _.shuffle(_.range(moves1.length)))
831 {
832 this.play(moves1[i]);
833 const finish = (Math.abs(this.evalPosition()) >= VariantRules.THRESHOLD_MATE);
834 this.undo(moves1[i]);
835 if (finish)
836 return moves1[i];
837 }
1d184b4c 838
06ddfe34 839 // Rank moves using a min-max at depth 2
1d184b4c
BA
840 for (let i=0; i<moves1.length; i++)
841 {
9e42b4dd 842 moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; //very low, I'm checkmated
1d184b4c 843 this.play(moves1[i]);
68f5ccc8
BA
844 let eval2 = undefined;
845 if (this.atLeastOneMove())
1d184b4c 846 {
68f5ccc8
BA
847 eval2 = (color=="w" ? 1 : -1) * maxeval; //initialized with checkmate value
848 // Second half-move:
15952ada 849 let moves2 = this.getAllValidMoves("computer");
68f5ccc8
BA
850 for (let j=0; j<moves2.length; j++)
851 {
852 this.play(moves2[j]);
853 let evalPos = undefined;
854 if (this.atLeastOneMove())
855 evalPos = this.evalPosition()
856 else
857 {
858 // Work with scores for Loser variant
859 const score = this.checkGameEnd();
860 evalPos = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
861 }
862 if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
863 eval2 = evalPos;
864 this.undo(moves2[j]);
865 }
866 }
867 else
868 {
869 const score = this.checkGameEnd();
870 eval2 = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1d184b4c
BA
871 }
872 if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval))
873 moves1[i].eval = eval2;
874 this.undo(moves1[i]);
875 }
876 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
11a31682 877 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1d184b4c 878
3c09dc49
BA
879 let candidates = [0]; //indices of candidates moves
880 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
881 candidates.push(j);
882 let currentBest = moves1[_.sample(candidates, 1)];
883
a6abf094 884 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
3c09dc49
BA
885 if (VariantRules.SEARCH_DEPTH >= 3
886 && Math.abs(moves1[0].eval) < VariantRules.THRESHOLD_MATE)
e64a4eff 887 {
9e42b4dd
BA
888 for (let i=0; i<moves1.length; i++)
889 {
3c09dc49
BA
890 if (this.shouldReturn)
891 return currentBest; //depth-2, minimum
9e42b4dd
BA
892 this.play(moves1[i]);
893 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
3c09dc49
BA
894 moves1[i].eval = 0.1*moves1[i].eval +
895 this.alphabeta(VariantRules.SEARCH_DEPTH-1, -maxeval, maxeval);
9e42b4dd
BA
896 this.undo(moves1[i]);
897 }
898 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
e64a4eff 899 }
3c09dc49
BA
900 else
901 return currentBest;
68f5ccc8 902 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1d184b4c 903
3c09dc49 904 candidates = [0];
1d184b4c
BA
905 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
906 candidates.push(j);
1d184b4c
BA
907 return moves1[_.sample(candidates, 1)];
908 }
909
46302e64 910 alphabeta(depth, alpha, beta)
1d184b4c 911 {
9e42b4dd 912 const maxeval = VariantRules.INFINITY;
46302e64
BA
913 const color = this.turn;
914 if (!this.atLeastOneMove())
1d184b4c 915 {
46302e64 916 switch (this.checkGameEnd())
1d184b4c 917 {
68f5ccc8
BA
918 case "1/2":
919 return 0;
920 default:
921 const score = this.checkGameEnd();
922 return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval);
1d184b4c
BA
923 }
924 }
925 if (depth == 0)
926 return this.evalPosition();
15952ada 927 const moves = this.getAllValidMoves("computer");
9e42b4dd 928 let v = color=="w" ? -maxeval : maxeval;
1d184b4c
BA
929 if (color == "w")
930 {
931 for (let i=0; i<moves.length; i++)
932 {
933 this.play(moves[i]);
46302e64 934 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
1d184b4c
BA
935 this.undo(moves[i]);
936 alpha = Math.max(alpha, v);
937 if (alpha >= beta)
938 break; //beta cutoff
939 }
940 }
941 else //color=="b"
942 {
943 for (let i=0; i<moves.length; i++)
944 {
945 this.play(moves[i]);
46302e64 946 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
1d184b4c
BA
947 this.undo(moves[i]);
948 beta = Math.min(beta, v);
949 if (alpha >= beta)
950 break; //alpha cutoff
951 }
952 }
953 return v;
954 }
955
956 evalPosition()
957 {
958 const [sizeX,sizeY] = VariantRules.size;
959 let evaluation = 0;
a6abf094 960 // Just count material for now
1d184b4c
BA
961 for (let i=0; i<sizeX; i++)
962 {
963 for (let j=0; j<sizeY; j++)
964 {
965 if (this.board[i][j] != VariantRules.EMPTY)
966 {
967 const sign = this.getColor(i,j) == "w" ? 1 : -1;
968 evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)];
969 }
970 }
971 }
972 return evaluation;
973 }
974
975 ////////////
976 // FEN utils
977
dda21a71 978 // Setup the initial random (assymetric) position
1d184b4c
BA
979 static GenRandInitFen()
980 {
981 let pieces = [new Array(8), new Array(8)];
982 // Shuffle pieces on first and last rank
983 for (let c = 0; c <= 1; c++)
984 {
985 let positions = _.range(8);
986
987 // Get random squares for bishops
988 let randIndex = 2 * _.random(3);
989 let bishop1Pos = positions[randIndex];
990 // The second bishop must be on a square of different color
991 let randIndex_tmp = 2 * _.random(3) + 1;
992 let bishop2Pos = positions[randIndex_tmp];
993 // Remove chosen squares
994 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
995 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
996
997 // Get random squares for knights
998 randIndex = _.random(5);
999 let knight1Pos = positions[randIndex];
1000 positions.splice(randIndex, 1);
1001 randIndex = _.random(4);
1002 let knight2Pos = positions[randIndex];
1003 positions.splice(randIndex, 1);
1004
1005 // Get random square for queen
1006 randIndex = _.random(3);
1007 let queenPos = positions[randIndex];
1008 positions.splice(randIndex, 1);
1009
1010 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
1011 let rook1Pos = positions[0];
1012 let kingPos = positions[1];
1013 let rook2Pos = positions[2];
1014
1015 // Finally put the shuffled pieces in the board array
1016 pieces[c][rook1Pos] = 'r';
1017 pieces[c][knight1Pos] = 'n';
1018 pieces[c][bishop1Pos] = 'b';
1019 pieces[c][queenPos] = 'q';
1020 pieces[c][kingPos] = 'k';
1021 pieces[c][bishop2Pos] = 'b';
1022 pieces[c][knight2Pos] = 'n';
1023 pieces[c][rook2Pos] = 'r';
1024 }
1025 let fen = pieces[0].join("") +
1026 "/pppppppp/8/8/8/8/PPPPPPPP/" +
1027 pieces[1].join("").toUpperCase() +
f3802fcd 1028 " 1111"; //add flags
1d184b4c
BA
1029 return fen;
1030 }
1031
1032 // Return current fen according to pieces+colors state
1033 getFen()
1034 {
f3802fcd 1035 return this.getBaseFen() + " " + this.getFlagsFen();
1d184b4c
BA
1036 }
1037
dda21a71 1038 // Position part of the FEN string
1d184b4c
BA
1039 getBaseFen()
1040 {
1041 let fen = "";
1042 let [sizeX,sizeY] = VariantRules.size;
1043 for (let i=0; i<sizeX; i++)
1044 {
1045 let emptyCount = 0;
1046 for (let j=0; j<sizeY; j++)
1047 {
1048 if (this.board[i][j] == VariantRules.EMPTY)
1049 emptyCount++;
1050 else
1051 {
1052 if (emptyCount > 0)
1053 {
1054 // Add empty squares in-between
1055 fen += emptyCount;
1056 emptyCount = 0;
1057 }
1058 fen += VariantRules.board2fen(this.board[i][j]);
1059 }
1060 }
1061 if (emptyCount > 0)
1062 {
1063 // "Flush remainder"
1064 fen += emptyCount;
1065 }
1066 if (i < sizeX - 1)
1067 fen += "/"; //separate rows
1068 }
1069 return fen;
1070 }
1071
dda21a71 1072 // Flags part of the FEN string
1d184b4c
BA
1073 getFlagsFen()
1074 {
1075 let fen = "";
1076 // Add castling flags
1077 for (let i of ['w','b'])
1078 {
1079 for (let j=0; j<2; j++)
77e1ec78 1080 fen += (this.castleFlags[i][j] ? '1' : '0');
1d184b4c
BA
1081 }
1082 return fen;
1083 }
1084
1085 // Context: just before move is played, turn hasn't changed
1086 getNotation(move)
1087 {
15952ada
BA
1088 if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING) //castle
1089 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
1d184b4c
BA
1090
1091 // Translate final square
270968d6 1092 const finalSquare =
1d184b4c
BA
1093 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1094
270968d6 1095 const piece = this.getPiece(move.start.x, move.start.y);
1d184b4c
BA
1096 if (piece == VariantRules.PAWN)
1097 {
1098 // Pawn move
1099 let notation = "";
5bfb0956 1100 if (move.vanish.length > move.appear.length)
1d184b4c
BA
1101 {
1102 // Capture
270968d6 1103 const startColumn = String.fromCharCode(97 + move.start.y);
1d184b4c
BA
1104 notation = startColumn + "x" + finalSquare;
1105 }
1106 else //no capture
1107 notation = finalSquare;
1108 if (move.appear.length > 0 && piece != move.appear[0].p) //promotion
1109 notation += "=" + move.appear[0].p.toUpperCase();
1110 return notation;
1111 }
1112
1113 else
1114 {
1115 // Piece movement
f3c10e18
BA
1116 return piece.toUpperCase() +
1117 (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
1d184b4c
BA
1118 }
1119 }
dfb4afc1 1120
6752407b
BA
1121 // Complete the usual notation, may be required for de-ambiguification
1122 getLongNotation(move)
1123 {
1124 const startSquare =
1125 String.fromCharCode(97 + move.start.y) + (VariantRules.size[0]-move.start.x);
1126 const finalSquare =
1127 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1128 return startSquare + finalSquare; //not encoding move. But short+long is enough
1129 }
1130
dfb4afc1 1131 // The score is already computed when calling this function
01a135e2 1132 getPGN(mycolor, score, fenStart, mode)
dfb4afc1 1133 {
16984853 1134 const zeroPad = x => { return (x<10 ? "0" : "") + x; };
dfb4afc1
BA
1135 let pgn = "";
1136 pgn += '[Site "vchess.club"]<br>';
1137 const d = new Date();
5e622704 1138 const opponent = mode=="human" ? "Anonymous" : "Computer";
0f51ef98 1139 pgn += '[Variant "' + variant + '"]<br>';
16984853 1140 pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + zeroPad(d.getDate()) + '"]<br>';
01a135e2
BA
1141 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1142 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
04449c97
BA
1143 pgn += '[FenStart "' + fenStart + '"]<br>';
1144 pgn += '[Fen "' + this.getFen() + '"]<br>';
762b7c9c 1145 pgn += '[Result "' + score + '"]<br><br>';
dfb4afc1 1146
6752407b 1147 // Standard PGN
dfb4afc1
BA
1148 for (let i=0; i<this.moves.length; i++)
1149 {
1150 if (i % 2 == 0)
1151 pgn += ((i/2)+1) + ".";
6752407b 1152 pgn += this.moves[i].notation[0] + " ";
dfb4afc1 1153 }
97fc8bf7 1154 pgn += "<br><br>";
dfb4afc1 1155
6752407b
BA
1156 // "Complete moves" PGN (helping in ambiguous cases)
1157 for (let i=0; i<this.moves.length; i++)
1158 {
1159 if (i % 2 == 0)
1160 pgn += ((i/2)+1) + ".";
1161 pgn += this.moves[i].notation[1] + " ";
1162 }
6752407b 1163
dfb4afc1
BA
1164 return pgn;
1165 }
1d184b4c 1166}