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