Alice rules implemented, but unfinished and with bugs...
[vchess.git] / public / javascripts / base_rules.js
1 class 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
13 class 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)
28 class 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
49 // fen == "position flags"
50 constructor(fen, moves)
51 {
52 this.moves = moves;
53 // Use fen string to initialize variables, flags and board
54 this.board = VariantRules.GetBoard(fen);
55 this.setFlags(fen);
56 this.initVariables(fen);
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 {
68 let k = 0; //column index on board
69 for (let j=0; j<position[i].length; j++)
70 {
71 switch (position[i].charAt(j))
72 {
73 case 'k':
74 this.kingPos['b'] = [i,k];
75 this.INIT_COL_KING['b'] = k;
76 break;
77 case 'K':
78 this.kingPos['w'] = [i,k];
79 this.INIT_COL_KING['w'] = k;
80 break;
81 case 'r':
82 if (this.INIT_COL_ROOK['b'][0] < 0)
83 this.INIT_COL_ROOK['b'][0] = k;
84 else
85 this.INIT_COL_ROOK['b'][1] = k;
86 break;
87 case 'R':
88 if (this.INIT_COL_ROOK['w'][0] < 0)
89 this.INIT_COL_ROOK['w'][0] = k;
90 else
91 this.INIT_COL_ROOK['w'][1] = k;
92 break;
93 default:
94 let num = parseInt(position[i].charAt(j));
95 if (!isNaN(num))
96 k += (num-1);
97 }
98 k++;
99 }
100 }
101 const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined;
102 this.epSquares = [ epSq ];
103 }
104
105 // Turn diagram fen into double array ["wb","wp","bk",...]
106 static GetBoard(fen)
107 {
108 let rows = fen.split(" ")[0].split("/");
109 const [sizeX,sizeY] = VariantRules.size;
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
128 setFlags(fen)
129 {
130 // white a-castle, h-castle, black a-castle, h-castle
131 this.castleFlags = {'w': new Array(2), 'b': new Array(2)};
132 let flags = fen.split(" ")[1]; //flags right after position
133 for (let i=0; i<4; i++)
134 this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (flags.charAt(i) == '1');
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() {
154 return this.moves.length%2==0 ? 'w' : 'b';
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
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
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
203 // can thing on square1 take thing on square2
204 canTake([x1,y1], [x2,y2])
205 {
206 return this.getColor(x1,y1) != this.getColor(x2,y2);
207 }
208
209 ///////////////////
210 // MOVES GENERATION
211
212 // All possible moves from selected square (assumption: color is OK)
213 getPotentialMovesFrom([x,y])
214 {
215 switch (this.getPiece(x,y))
216 {
217 case VariantRules.PAWN:
218 return this.getPotentialPawnMoves([x,y]);
219 case VariantRules.ROOK:
220 return this.getPotentialRookMoves([x,y]);
221 case VariantRules.KNIGHT:
222 return this.getPotentialKnightMoves([x,y]);
223 case VariantRules.BISHOP:
224 return this.getPotentialBishopMoves([x,y]);
225 case VariantRules.QUEEN:
226 return this.getPotentialQueenMoves([x,y]);
227 case VariantRules.KING:
228 return this.getPotentialKingMoves([x,y]);
229 }
230 }
231
232 // Build a regular move from its initial and destination squares; tr: transformation
233 getBasicMove([sx,sy], [ex,ey], tr)
234 {
235 let mv = new Move({
236 appear: [
237 new PiPo({
238 x: ex,
239 y: ey,
240 c: !!tr ? tr.c : this.getColor(sx,sy),
241 p: !!tr ? tr.p : this.getPiece(sx,sy)
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")
270 getSlideNJumpMoves([x,y], steps, oneStep)
271 {
272 const color = this.getColor(x,y);
273 let moves = [];
274 const [sizeX,sizeY] = VariantRules.size;
275 outerLoop:
276 for (let step of steps)
277 {
278 let i = x + step[0];
279 let j = y + step[1];
280 while (i>=0 && i<sizeX && j>=0 && j<sizeY && this.board[i][j] == VariantRules.EMPTY)
281 {
282 moves.push(this.getBasicMove([x,y], [i,j]));
283 if (oneStep !== undefined)
284 continue outerLoop;
285 i += step[0];
286 j += step[1];
287 }
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]));
290 }
291 return moves;
292 }
293
294 // What are the pawn moves from square x,y considering color "color" ?
295 getPotentialPawnMoves([x,y])
296 {
297 const color = this.turn;
298 let moves = [];
299 const V = VariantRules;
300 const [sizeX,sizeY] = VariantRules.size;
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);
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 {
311 moves.push(this.getBasicMove([x,y], [x+shift,y]));
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)
314 {
315 // Two squares jump
316 moves.push(this.getBasicMove([x,y], [x+2*shift,y]));
317 }
318 }
319 // Captures
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]));
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)
333 moves.push(this.getBasicMove([x,y], [x+shift,y], {c:color,p:p}));
334 // Captures
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}));
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;
348 var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]);
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 ?
362 getPotentialRookMoves(sq)
363 {
364 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]);
365 }
366
367 // What are the knight moves from square x,y ?
368 getPotentialKnightMoves(sq)
369 {
370 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
371 }
372
373 // What are the bishop moves from square x,y ?
374 getPotentialBishopMoves(sq)
375 {
376 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]);
377 }
378
379 // What are the queen moves from square x,y ?
380 getPotentialQueenMoves(sq)
381 {
382 return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.QUEEN]);
383 }
384
385 // What are the king moves from square x,y ?
386 getPotentialKingMoves(sq)
387 {
388 // Initialize with normal moves
389 let moves = this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.QUEEN], "oneStep");
390 return moves.concat(this.getCastleMoves(sq));
391 }
392
393 getCastleMoves([x,y])
394 {
395 const c = this.getColor(x,y);
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 {
409 if (!this.castleFlags[c][castleSide])
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
465 canIplay(side, [x,y])
466 {
467 return ((side=='w' && this.moves.length%2==0) || (side=='b' && this.moves.length%2==1))
468 && this.getColor(x,y) == side;
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 [];
482 let color = this.turn;
483 return moves.filter(m => { return !this.underCheck(m, color); });
484 }
485
486 // Search for all valid moves considering current turn (for engine and game end)
487 getAllValidMoves()
488 {
489 const color = this.turn;
490 const oppCol = this.getOppCol(color);
491 var potentialMoves = [];
492 let [sizeX,sizeY] = VariantRules.size;
493 for (var i=0; i<sizeX; i++)
494 {
495 for (var j=0; j<sizeY; j++)
496 {
497 // Next condition ... != oppCol is a little HACK to work with checkered variant
498 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
499 Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j]));
500 }
501 }
502 // NOTE: prefer lazy undercheck tests, letting the king being taken?
503 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
504 return this.filterValid(potentialMoves);
505 }
506
507 // Stop at the first move found
508 atLeastOneMove()
509 {
510 const color = this.turn;
511 const oppCol = this.getOppCol(color);
512 let [sizeX,sizeY] = VariantRules.size;
513 for (var i=0; i<sizeX; i++)
514 {
515 for (var j=0; j<sizeY; j++)
516 {
517 if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol)
518 {
519 const moves = this.getPotentialMovesFrom([i,j]);
520 if (moves.length > 0)
521 {
522 for (let i=0; i<moves.length; i++)
523 {
524 if (this.filterValid([moves[i]]).length > 0)
525 return true;
526 }
527 }
528 }
529 }
530 }
531 return false;
532 }
533
534 // Check if pieces of color 'colors' are attacking square x,y
535 isAttacked(sq, colors)
536 {
537 return (this.isAttackedByPawn(sq, colors)
538 || this.isAttackedByRook(sq, colors)
539 || this.isAttackedByKnight(sq, colors)
540 || this.isAttackedByBishop(sq, colors)
541 || this.isAttackedByQueen(sq, colors)
542 || this.isAttackedByKing(sq, colors));
543 }
544
545 // Is square x,y attacked by pawns of color c ?
546 isAttackedByPawn([x,y], colors)
547 {
548 for (let c of colors)
549 {
550 let pawnShift = (c=="w" ? 1 : -1);
551 if (x+pawnShift>=0 && x+pawnShift<8)
552 {
553 for (let i of [-1,1])
554 {
555 if (y+i>=0 && y+i<8 && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN
556 && this.getColor(x+pawnShift,y+i)==c)
557 {
558 return true;
559 }
560 }
561 }
562 }
563 return false;
564 }
565
566 // Is square x,y attacked by rooks of color c ?
567 isAttackedByRook(sq, colors)
568 {
569 return this.isAttackedBySlideNJump(sq, colors,
570 VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]);
571 }
572
573 // Is square x,y attacked by knights of color c ?
574 isAttackedByKnight(sq, colors)
575 {
576 return this.isAttackedBySlideNJump(sq, colors,
577 VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep");
578 }
579
580 // Is square x,y attacked by bishops of color c ?
581 isAttackedByBishop(sq, colors)
582 {
583 return this.isAttackedBySlideNJump(sq, colors,
584 VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]);
585 }
586
587 // Is square x,y attacked by queens of color c ?
588 isAttackedByQueen(sq, colors)
589 {
590 return this.isAttackedBySlideNJump(sq, colors,
591 VariantRules.QUEEN, VariantRules.steps[VariantRules.QUEEN]);
592 }
593
594 // Is square x,y attacked by king of color c ?
595 isAttackedByKing(sq, colors)
596 {
597 return this.isAttackedBySlideNJump(sq, colors,
598 VariantRules.KING, VariantRules.steps[VariantRules.QUEEN], "oneStep");
599 }
600
601 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
602 isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep)
603 {
604 for (let step of steps)
605 {
606 let rx = x+step[0], ry = y+step[1];
607 while (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] == VariantRules.EMPTY
608 && !oneStep)
609 {
610 rx += step[0];
611 ry += step[1];
612 }
613 if (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] != VariantRules.EMPTY
614 && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry)))
615 {
616 return true;
617 }
618 }
619 return false;
620 }
621
622 // Is color c under check after move ?
623 underCheck(move)
624 {
625 const color = this.turn;
626 this.play(move);
627 let res = this.isAttacked(this.kingPos[color], this.getOppCol(color));
628 this.undo(move);
629 return res;
630 }
631
632 // On which squares is color c under check (after move) ?
633 getCheckSquares(move)
634 {
635 this.play(move);
636 const color = this.turn; //opponent
637 let res = this.isAttacked(this.kingPos[color], this.getOppCol(color))
638 ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate!
639 : [ ];
640 this.undo(move);
641 return res;
642 }
643
644 // Apply a move on board
645 static PlayOnBoard(board, move)
646 {
647 for (let psq of move.vanish)
648 board[psq.x][psq.y] = VariantRules.EMPTY;
649 for (let psq of move.appear)
650 board[psq.x][psq.y] = psq.c + psq.p;
651 }
652 // Un-apply the played move
653 static UndoOnBoard(board, move)
654 {
655 for (let psq of move.appear)
656 board[psq.x][psq.y] = VariantRules.EMPTY;
657 for (let psq of move.vanish)
658 board[psq.x][psq.y] = psq.c + psq.p;
659 }
660
661 // Before move is played, update variables + flags
662 updateVariables(move)
663 {
664 const piece = this.getPiece(move.start.x,move.start.y);
665 const c = this.getColor(move.start.x,move.start.y);
666 const firstRank = (c == "w" ? 7 : 0);
667
668 // Update king position + flags
669 if (piece == VariantRules.KING && move.appear.length > 0)
670 {
671 this.kingPos[c][0] = move.appear[0].x;
672 this.kingPos[c][1] = move.appear[0].y;
673 this.castleFlags[c] = [false,false];
674 return;
675 }
676 const oppCol = this.getOppCol(c);
677 const oppFirstRank = 7 - firstRank;
678 if (move.start.x == firstRank //our rook moves?
679 && this.INIT_COL_ROOK[c].includes(move.start.y))
680 {
681 const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1);
682 this.castleFlags[c][flagIdx] = false;
683 }
684 else if (move.end.x == oppFirstRank //we took opponent rook?
685 && this.INIT_COL_ROOK[oppCol].includes(move.end.y))
686 {
687 const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1);
688 this.castleFlags[oppCol][flagIdx] = false;
689 }
690 }
691
692 unupdateVariables(move)
693 {
694 // (Potentially) Reset king position
695 const c = this.getColor(move.start.x,move.start.y);
696 if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING)
697 this.kingPos[c] = [move.start.x, move.start.y];
698 }
699
700 play(move, ingame)
701 {
702 console.log("play " + this.getNotation(move));
703 console.log(JSON.stringify(move));
704 if (!!ingame)
705 move.notation = this.getNotation(move);
706
707 move.flags = JSON.stringify(this.flags); //save flags (for undo)
708 this.updateVariables(move);
709 this.moves.push(move);
710 this.epSquares.push( this.getEpSquare(move) );
711 VariantRules.PlayOnBoard(this.board, move);
712 }
713
714 undo(move)
715 {
716 VariantRules.UndoOnBoard(this.board, move);
717 this.epSquares.pop();
718 this.moves.pop();
719 this.unupdateVariables(move);
720 this.parseFlags(JSON.parse(move.flags));
721 console.log("undo " + this.getNotation(move));
722 }
723
724 //////////////
725 // END OF GAME
726
727 checkRepetition()
728 {
729 // Check for 3 repetitions
730 if (this.moves.length >= 8)
731 {
732 // NOTE: crude detection, only moves repetition
733 const L = this.moves.length;
734 if (_.isEqual(this.moves[L-1], this.moves[L-5]) &&
735 _.isEqual(this.moves[L-2], this.moves[L-6]) &&
736 _.isEqual(this.moves[L-3], this.moves[L-7]) &&
737 _.isEqual(this.moves[L-4], this.moves[L-8]))
738 {
739 return true;
740 }
741 }
742 return false;
743 }
744
745 checkGameOver()
746 {
747 if (this.checkRepetition())
748 return "1/2";
749
750 if (this.atLeastOneMove()) // game not over
751 return "*";
752
753 // Game over
754 return this.checkGameEnd();
755 }
756
757 // No moves are possible: compute score
758 checkGameEnd()
759 {
760 const color = this.turn;
761 // No valid move: stalemate or checkmate?
762 if (!this.isAttacked(this.kingPos[color], this.getOppCol(color)))
763 return "1/2";
764 // OK, checkmate
765 return color == "w" ? "0-1" : "1-0";
766 }
767
768 ////////
769 //ENGINE
770
771 // Pieces values
772 static get VALUES() {
773 return {
774 'p': 1,
775 'r': 5,
776 'n': 3,
777 'b': 3,
778 'q': 9,
779 'k': 1000
780 };
781 }
782
783 // Assumption: at least one legal move
784 getComputerMove()
785 {
786 const color = this.turn;
787
788 // Rank moves using a min-max at depth 2
789 let moves1 = this.getAllValidMoves();
790
791 for (let i=0; i<moves1.length; i++)
792 {
793 moves1[i].eval = (color=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
794 let eval2 = (color=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
795 this.play(moves1[i]);
796 // Second half-move:
797 let moves2 = this.getAllValidMoves();
798 // If no possible moves AND underCheck, eval2 is correct.
799 // If !underCheck, eval2 is 0 (stalemate).
800 if (moves2.length == 0 && this.checkGameEnd() == "1/2")
801 eval2 = 0;
802 for (let j=0; j<moves2.length; j++)
803 {
804 this.play(moves2[j]);
805 let evalPos = this.evalPosition();
806 if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2))
807 eval2 = evalPos;
808 this.undo(moves2[j]);
809 }
810 if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval))
811 moves1[i].eval = eval2;
812 this.undo(moves1[i]);
813 }
814 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
815
816 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
817 for (let i=0; i<moves1.length; i++)
818 {
819 this.play(moves1[i]);
820 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
821 moves1[i].eval = 0.1*moves1[i].eval + this.alphabeta(2, -1000, 1000);
822 this.undo(moves1[i]);
823 }
824 moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); });
825
826 let candidates = [0]; //indices of candidates moves
827 for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++)
828 candidates.push(j);
829
830 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
831 return moves1[_.sample(candidates, 1)];
832 }
833
834 alphabeta(depth, alpha, beta)
835 {
836 const color = this.turn;
837 if (!this.atLeastOneMove())
838 {
839 switch (this.checkGameEnd())
840 {
841 case "1/2": return 0;
842 default: return color=="w" ? -1000 : 1000;
843 }
844 }
845 if (depth == 0)
846 return this.evalPosition();
847 const moves = this.getAllValidMoves();
848 let v = color=="w" ? -1000 : 1000;
849 if (color == "w")
850 {
851 for (let i=0; i<moves.length; i++)
852 {
853 this.play(moves[i]);
854 v = Math.max(v, this.alphabeta(depth-1, alpha, beta));
855 this.undo(moves[i]);
856 alpha = Math.max(alpha, v);
857 if (alpha >= beta)
858 break; //beta cutoff
859 }
860 }
861 else //color=="b"
862 {
863 for (let i=0; i<moves.length; i++)
864 {
865 this.play(moves[i]);
866 v = Math.min(v, this.alphabeta(depth-1, alpha, beta));
867 this.undo(moves[i]);
868 beta = Math.min(beta, v);
869 if (alpha >= beta)
870 break; //alpha cutoff
871 }
872 }
873 return v;
874 }
875
876 evalPosition()
877 {
878 const [sizeX,sizeY] = VariantRules.size;
879 let evaluation = 0;
880 //Just count material for now
881 for (let i=0; i<sizeX; i++)
882 {
883 for (let j=0; j<sizeY; j++)
884 {
885 if (this.board[i][j] != VariantRules.EMPTY)
886 {
887 const sign = this.getColor(i,j) == "w" ? 1 : -1;
888 evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)];
889 }
890 }
891 }
892 return evaluation;
893 }
894
895 ////////////
896 // FEN utils
897
898 // Overridable..
899 static GenRandInitFen()
900 {
901 let pieces = [new Array(8), new Array(8)];
902 // Shuffle pieces on first and last rank
903 for (let c = 0; c <= 1; c++)
904 {
905 let positions = _.range(8);
906
907 // Get random squares for bishops
908 let randIndex = 2 * _.random(3);
909 let bishop1Pos = positions[randIndex];
910 // The second bishop must be on a square of different color
911 let randIndex_tmp = 2 * _.random(3) + 1;
912 let bishop2Pos = positions[randIndex_tmp];
913 // Remove chosen squares
914 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
915 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
916
917 // Get random squares for knights
918 randIndex = _.random(5);
919 let knight1Pos = positions[randIndex];
920 positions.splice(randIndex, 1);
921 randIndex = _.random(4);
922 let knight2Pos = positions[randIndex];
923 positions.splice(randIndex, 1);
924
925 // Get random square for queen
926 randIndex = _.random(3);
927 let queenPos = positions[randIndex];
928 positions.splice(randIndex, 1);
929
930 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
931 let rook1Pos = positions[0];
932 let kingPos = positions[1];
933 let rook2Pos = positions[2];
934
935 // Finally put the shuffled pieces in the board array
936 pieces[c][rook1Pos] = 'r';
937 pieces[c][knight1Pos] = 'n';
938 pieces[c][bishop1Pos] = 'b';
939 pieces[c][queenPos] = 'q';
940 pieces[c][kingPos] = 'k';
941 pieces[c][bishop2Pos] = 'b';
942 pieces[c][knight2Pos] = 'n';
943 pieces[c][rook2Pos] = 'r';
944 }
945 let fen = pieces[0].join("") +
946 "/pppppppp/8/8/8/8/PPPPPPPP/" +
947 pieces[1].join("").toUpperCase() +
948 " 1111"; //add flags
949 return fen;
950 }
951
952 // Return current fen according to pieces+colors state
953 getFen()
954 {
955 return this.getBaseFen() + " " + this.getFlagsFen();
956 }
957
958 getBaseFen()
959 {
960 let fen = "";
961 let [sizeX,sizeY] = VariantRules.size;
962 for (let i=0; i<sizeX; i++)
963 {
964 let emptyCount = 0;
965 for (let j=0; j<sizeY; j++)
966 {
967 if (this.board[i][j] == VariantRules.EMPTY)
968 emptyCount++;
969 else
970 {
971 if (emptyCount > 0)
972 {
973 // Add empty squares in-between
974 fen += emptyCount;
975 emptyCount = 0;
976 }
977 fen += VariantRules.board2fen(this.board[i][j]);
978 }
979 }
980 if (emptyCount > 0)
981 {
982 // "Flush remainder"
983 fen += emptyCount;
984 }
985 if (i < sizeX - 1)
986 fen += "/"; //separate rows
987 }
988 return fen;
989 }
990
991 // Overridable..
992 getFlagsFen()
993 {
994 let fen = "";
995 // Add castling flags
996 for (let i of ['w','b'])
997 {
998 for (let j=0; j<2; j++)
999 fen += this.castleFlags[i][j] ? '1' : '0';
1000 }
1001 return fen;
1002 }
1003
1004 // Context: just before move is played, turn hasn't changed
1005 getNotation(move)
1006 {
1007 if (move.appear.length == 2 && move.appear[0].p == VariantRules.KING)
1008 {
1009 // Castle
1010 if (move.end.y < move.start.y)
1011 return "0-0-0";
1012 else
1013 return "0-0";
1014 }
1015
1016 // Translate final square
1017 const finalSquare =
1018 String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x);
1019
1020 const piece = this.getPiece(move.start.x, move.start.y);
1021 if (piece == VariantRules.PAWN)
1022 {
1023 // Pawn move
1024 let notation = "";
1025 if (move.vanish.length > move.appear.length)
1026 {
1027 // Capture
1028 const startColumn = String.fromCharCode(97 + move.start.y);
1029 notation = startColumn + "x" + finalSquare;
1030 }
1031 else //no capture
1032 notation = finalSquare;
1033 if (move.appear.length > 0 && piece != move.appear[0].p) //promotion
1034 notation += "=" + move.appear[0].p.toUpperCase();
1035 return notation;
1036 }
1037
1038 else
1039 {
1040 // Piece movement
1041 return piece.toUpperCase() +
1042 (move.vanish.length > move.appear.length ? "x" : "") + finalSquare;
1043 }
1044 }
1045
1046 // The score is already computed when calling this function
1047 getPGN(mycolor, score, fenStart, mode)
1048 {
1049 let pgn = "";
1050 pgn += '[Site "vchess.club"]<br>';
1051 const d = new Date();
1052 const opponent = mode=="human" ? "Anonymous" : "Computer";
1053 pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate() + '"]<br>';
1054 pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>';
1055 pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>';
1056 pgn += '[Fen "' + fenStart + '"]<br>';
1057 pgn += '[Result "' + score + '"]<br><br>';
1058
1059 for (let i=0; i<this.moves.length; i++)
1060 {
1061 if (i % 2 == 0)
1062 pgn += ((i/2)+1) + ".";
1063 pgn += this.moves[i].notation + " ";
1064 }
1065
1066 pgn += score;
1067 return pgn;
1068 }
1069 }