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