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