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