1 class PiPo
//Piece+Position
3 // o: {piece[p], color[c], posX[x], posY[y]}
15 // o: {appear, vanish, [start,] [end,]}
16 // appear,vanish = arrays of PiPo
17 // start,end = coordinates to apply to trigger move visually (think castle)
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
};
27 // NOTE: x coords = top to bottom; y = left to right (from white player perspective)
33 return b
; //usual pieces in pieces/ folder
35 // Turn "wb" into "B" (for FEN)
38 return b
[0]=='w' ? b
[1].toUpperCase() : b
[1];
40 // Turn "p" into "bp" (for board)
43 return f
.charCodeAt()<=90 ? "w"+f
.toLowerCase() : "b"+f
;
49 // fen = "position flags epSquare movesCount"
50 constructor(fen
, moves
)
53 // Use fen string to initialize variables, flags and board
54 this.initVariables(fen
);
55 this.flags
= VariantRules
.GetFlags(fen
);
56 this.board
= VariantRules
.GetBoard(fen
);
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
++)
69 while (j
< position
[i
].length
)
71 switch (position
[i
].charAt(j
))
74 this.kingPos
['b'] = [i
,j
];
75 this.INIT_COL_KING
['b'] = j
;
78 this.kingPos
['w'] = [i
,j
];
79 this.INIT_COL_KING
['w'] = j
;
82 if (this.INIT_COL_ROOK
['b'][0] < 0)
83 this.INIT_COL_ROOK
['b'][0] = j
;
85 this.INIT_COL_ROOK
['b'][1] = j
;
88 if (this.INIT_COL_ROOK
['w'][0] < 0)
89 this.INIT_COL_ROOK
['w'][0] = j
;
91 this.INIT_COL_ROOK
['w'][1] = j
;
94 let num
= parseInt(position
[i
].charAt(j
));
101 // TODO: since we keep moves stack, next 2 are redundant
102 let epSq
= undefined;
103 if (fenParts
[2] != "-")
105 const digits
= fenParts
[2].split(","); //3,2 ...
106 epSq
= { x:Number
.parseInt(digits
[0]), y:Number
.parseInt(digits
[1]) };
108 this.epSquares
= [ epSq
];
109 this.movesCount
= Number
.parseInt(fenParts
[3]);
112 // Turn diagram fen into double array ["wb","wp","bk",...]
115 let rows
= fen
.split(" ")[0].split("/");
116 let [sizeX
,sizeY
] = VariantRules
.size
;
117 let board
= doubleArray(sizeX
, sizeY
, "");
118 for (let i
=0; i
<rows
.length
; i
++)
121 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
123 let character
= rows
[i
][indexInRow
];
124 let num
= parseInt(character
);
126 j
+= num
; //just shift j
127 else //something at position i,j
128 board
[i
][j
++] = VariantRules
.fen2board(character
);
134 // Overridable: flags can change a lot
137 // white a-castle, h-castle, black a-castle, h-castle
138 let flags
= {'w': new Array(2), 'b': new Array(2)};
139 let fenFlags
= fen
.split(" ")[1]; //flags right after position
140 for (let i
=0; i
<4; i
++)
141 flags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenFlags
.charAt(i
) == '1');
148 // Simple useful getters
149 static get size() { return [8,8]; }
150 // Two next functions return 'undefined' if called on empty square
151 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
152 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
155 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
158 const L
= this.moves
.length
;
159 return L
>0 ? this.moves
[L
-1] : null;
162 return this.movesCount
%2==0 ? 'w' : 'b';
166 static get PAWN() { return 'p'; }
167 static get ROOK() { return 'r'; }
168 static get KNIGHT() { return 'n'; }
169 static get BISHOP() { return 'b'; }
170 static get QUEEN() { return 'q'; }
171 static get KING() { return 'k'; }
174 static get EMPTY() { return ''; }
176 // Some pieces movements
179 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
180 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
181 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
182 'q': [ [-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1] ]
186 // En-passant square, if any
189 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
190 if (this.getPiece(sx
,sy
) == VariantRules
.PAWN
&& Math
.abs(sx
- ex
) == 2)
197 return undefined; //default
200 // can color1 take color2?
201 canTake(color1
, color2
)
203 return color1
!= color2
;
209 // All possible moves from selected square (assumption: color is OK)
210 getPotentialMovesFrom([x
,y
])
212 let c
= this.getColor(x
,y
);
213 // Fill possible moves according to piece type
214 switch (this.getPiece(x
,y
))
216 case VariantRules
.PAWN:
217 return this.getPotentialPawnMoves(x
,y
,c
);
218 case VariantRules
.ROOK:
219 return this.getPotentialRookMoves(x
,y
,c
);
220 case VariantRules
.KNIGHT:
221 return this.getPotentialKnightMoves(x
,y
,c
);
222 case VariantRules
.BISHOP:
223 return this.getPotentialBishopMoves(x
,y
,c
);
224 case VariantRules
.QUEEN:
225 return this.getPotentialQueenMoves(x
,y
,c
);
226 case VariantRules
.KING:
227 return this.getPotentialKingMoves(x
,y
,c
);
231 // Build a regular move from its initial and destination squares; tr: transformation
232 getBasicMove(sx
, sy
, ex
, ey
, tr
)
239 c: this.getColor(sx
,sy
),
240 p: !!tr
? tr : this.getPiece(sx
,sy
)
247 c: this.getColor(sx
,sy
),
248 p: this.getPiece(sx
,sy
)
253 // The opponent piece disappears if we take it
254 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
260 c: this.getColor(ex
,ey
),
261 p: this.getPiece(ex
,ey
)
268 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
269 getSlideNJumpMoves(x
, y
, color
, steps
, oneStep
)
272 let [sizeX
,sizeY
] = VariantRules
.size
;
274 for (let step
of steps
)
278 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
279 && this.board
[i
][j
] == VariantRules
.EMPTY
)
281 moves
.push(this.getBasicMove(x
, y
, i
, j
));
282 if (oneStep
!== undefined)
287 if (i
>=0 && i
<8 && j
>=0 && j
<8 && this.canTake(color
, this.getColor(i
,j
)))
288 moves
.push(this.getBasicMove(x
, y
, i
, j
));
293 // What are the pawn moves from square x,y considering color "color" ?
294 getPotentialPawnMoves(x
, y
, color
)
297 var V
= VariantRules
;
298 let [sizeX
,sizeY
] = VariantRules
.size
;
299 let shift
= (color
== "w" ? -1 : 1);
300 let startRank
= (color
== "w" ? sizeY
-2 : 1);
301 let lastRank
= (color
== "w" ? 0 : sizeY
-1);
303 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
306 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
308 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
));
309 if (x
==startRank
&& this.board
[x
+2*shift
][y
] == V
.EMPTY
)
312 moves
.push(this.getBasicMove(x
, y
, x
+2*shift
, y
));
316 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
317 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
319 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1));
321 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
322 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
324 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1));
328 if (x
+shift
== lastRank
)
331 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
332 promotionPieces
.forEach(p
=> {
334 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
335 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
, p
));
337 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
338 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
340 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1, p
));
342 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
343 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
345 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1, p
));
351 const Lep
= this.epSquares
.length
;
352 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
353 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
355 let epStep
= epSquare
.y
- y
;
356 var enpassantMove
= this.getBasicMove(x
, y
, x
+shift
, y
+epStep
);
357 enpassantMove
.vanish
.push({
361 c: this.getColor(x
,y
+epStep
)
363 moves
.push(enpassantMove
);
369 // What are the rook moves from square x,y ?
370 getPotentialRookMoves(x
, y
, color
)
372 return this.getSlideNJumpMoves(
373 x
, y
, color
, VariantRules
.steps
[VariantRules
.ROOK
]);
376 // What are the knight moves from square x,y ?
377 getPotentialKnightMoves(x
, y
, color
)
379 return this.getSlideNJumpMoves(
380 x
, y
, color
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
383 // What are the bishop moves from square x,y ?
384 getPotentialBishopMoves(x
, y
, color
)
386 return this.getSlideNJumpMoves(
387 x
, y
, color
, VariantRules
.steps
[VariantRules
.BISHOP
]);
390 // What are the queen moves from square x,y ?
391 getPotentialQueenMoves(x
, y
, color
)
393 return this.getSlideNJumpMoves(
394 x
, y
, color
, VariantRules
.steps
[VariantRules
.QUEEN
]);
397 // What are the king moves from square x,y ?
398 getPotentialKingMoves(x
, y
, c
)
400 // Initialize with normal moves
401 var moves
= this.getSlideNJumpMoves(x
, y
, c
,
402 VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
404 return moves
.concat(this.getCastleMoves(x
,y
,c
));
407 getCastleMoves(x
,y
,c
)
409 if (x
!= (c
=="w" ? 7 : 0) || y
!= this.INIT_COL_KING
[c
])
410 return []; //x isn't first rank, or king has moved (shortcut)
412 const V
= VariantRules
;
415 const oppCol
= this.getOppCol(c
);
418 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
420 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
422 if (!this.flags
[c
][castleSide
])
424 // If this code is reached, rooks and king are on initial position
426 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
427 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
428 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
430 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
431 // NOTE: next check is enough, because of chessboard constraints
432 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
434 continue castlingCheck
;
438 // Nothing on the path to the rook?
439 step
= castleSide
== 0 ? -1 : 1;
440 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
442 if (this.board
[x
][i
] != V
.EMPTY
)
443 continue castlingCheck
;
445 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
447 // Nothing on final squares, except maybe king and castling rook?
450 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
451 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
452 finalSquares
[castleSide
][i
] != rookPos
)
454 continue castlingCheck
;
458 // If this code is reached, castle is valid
459 moves
.push( new Move({
461 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
462 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
464 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
465 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
466 end: Math
.abs(y
- rookPos
) <= 2
468 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
480 return ((color
=='w' && this.movesCount
%2==0)
481 || (color
=='b' && this.movesCount
%2==1))
482 && this.getColor(sq
[0], sq
[1]) == color
;
485 getPossibleMovesFrom(sq
)
487 // Assuming color is right (already checked)
488 return this.filterValid( this.getPotentialMovesFrom(sq
) );
491 // TODO: once a promotion is filtered, the others results are same: useless computations
494 if (moves
.length
== 0)
496 let color
= this.getColor( moves
[0].start
.x
, moves
[0].start
.y
);
497 return moves
.filter(m
=> {
498 return !this.underCheck(m
, color
);
502 // Search for all valid moves considering current turn (for engine and game end)
503 getAllValidMoves(color
)
505 const oppCol
= this.getOppCol(color
);
506 var potentialMoves
= [];
507 let [sizeX
,sizeY
] = VariantRules
.size
;
508 for (var i
=0; i
<sizeX
; i
++)
510 for (var j
=0; j
<sizeY
; j
++)
512 // Next condition ... != oppCol is a little HACK to work with checkered variant
513 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
514 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
517 // NOTE: prefer lazy undercheck tests, letting the king being taken?
518 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
519 return this.filterValid(potentialMoves
);
522 // Stop at the first move found
523 atLeastOneMove(color
)
525 const oppCol
= this.getOppCol(color
);
526 let [sizeX
,sizeY
] = VariantRules
.size
;
527 for (var i
=0; i
<sizeX
; i
++)
529 for (var j
=0; j
<sizeY
; j
++)
531 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
533 const moves
= this.getPotentialMovesFrom([i
,j
]);
534 if (moves
.length
> 0)
536 for (let i
=0; i
<moves
.length
; i
++)
538 if (this.filterValid([moves
[i
]]).length
> 0)
548 // Check if pieces of color 'color' are attacking square x,y
549 isAttacked(sq
, color
)
551 return (this.isAttackedByPawn(sq
, color
)
552 || this.isAttackedByRook(sq
, color
)
553 || this.isAttackedByKnight(sq
, color
)
554 || this.isAttackedByBishop(sq
, color
)
555 || this.isAttackedByQueen(sq
, color
)
556 || this.isAttackedByKing(sq
, color
));
559 // Is square x,y attacked by pawns of color c ?
560 isAttackedByPawn([x
,y
], c
)
562 let pawnShift
= (c
=="w" ? 1 : -1);
563 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
565 for (let i
of [-1,1])
567 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
568 && this.getColor(x
+pawnShift
,y
+i
)==c
)
577 // Is square x,y attacked by rooks of color c ?
578 isAttackedByRook(sq
, color
)
580 return this.isAttackedBySlideNJump(sq
, color
,
581 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
584 // Is square x,y attacked by knights of color c ?
585 isAttackedByKnight(sq
, color
)
587 return this.isAttackedBySlideNJump(sq
, color
,
588 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
591 // Is square x,y attacked by bishops of color c ?
592 isAttackedByBishop(sq
, color
)
594 return this.isAttackedBySlideNJump(sq
, color
,
595 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
598 // Is square x,y attacked by queens of color c ?
599 isAttackedByQueen(sq
, color
)
601 return this.isAttackedBySlideNJump(sq
, color
,
602 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
605 // Is square x,y attacked by king of color c ?
606 isAttackedByKing(sq
, color
)
608 return this.isAttackedBySlideNJump(sq
, color
,
609 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
612 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
613 isAttackedBySlideNJump([x
,y
], c
,piece
,steps
,oneStep
)
615 for (let step
of steps
)
617 let rx
= x
+step
[0], ry
= y
+step
[1];
618 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
624 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
625 && this.getPiece(rx
,ry
) == piece
&& this.getColor(rx
,ry
) == c
)
633 // Is color c under check after move ?
637 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
));
642 // On which squares is color c under check (after move) ?
643 getCheckSquares(move, c
)
646 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
))
647 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[c
])) ] //need to duplicate!
653 // Apply a move on board
654 static PlayOnBoard(board
, move)
656 for (let psq
of move.vanish
)
657 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
658 for (let psq
of move.appear
)
659 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
661 // Un-apply the played move
662 static UndoOnBoard(board
, move)
664 for (let psq
of move.appear
)
665 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
666 for (let psq
of move.vanish
)
667 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
670 // Before move is played:
671 updateVariables(move)
673 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
674 const c
= this.getColor(move.start
.x
,move.start
.y
);
675 const firstRank
= (c
== "w" ? 7 : 0);
677 // Update king position + flags
678 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
680 this.kingPos
[c
][0] = move.appear
[0].x
;
681 this.kingPos
[c
][1] = move.appear
[0].y
;
682 this.flags
[c
] = [false,false];
685 const oppCol
= this.getOppCol(c
);
686 const oppFirstRank
= 7 - firstRank
;
687 if (move.start
.x
== firstRank
//our rook moves?
688 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
690 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
691 this.flags
[c
][flagIdx
] = false;
693 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
694 && this.INIT_COL_ROOK
[c
].includes(move.end
.y
))
696 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
697 this.flags
[oppCol
][flagIdx
] = false;
703 // Save flags (for undo)
704 move.flags
= JSON
.stringify(this.flags
); //TODO: less costly
705 this.updateVariables(move);
709 move.notation
= this.getNotation(move);
710 this.moves
.push(move);
713 this.epSquares
.push( this.getEpSquare(move) );
714 VariantRules
.PlayOnBoard(this.board
, move);
720 VariantRules
.UndoOnBoard(this.board
, move);
721 this.epSquares
.pop();
727 // Update king position, and reset stored/computed flags
728 const c
= this.getColor(move.start
.x
,move.start
.y
);
729 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
730 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
732 this.flags
= JSON
.parse(move.flags
);
740 // Check for 3 repetitions
741 if (this.moves
.length
>= 8)
743 // NOTE: crude detection, only moves repetition
744 const L
= this.moves
.length
;
745 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
746 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
747 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
748 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
750 return "1/2 (repetition)";
754 if (this.atLeastOneMove(color
))
761 return this.checkGameEnd(color
);
764 // Useful stand-alone for engine
767 // No valid move: stalemate or checkmate?
768 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
771 return color
== "w" ? "0-1" : "1-0";
778 static get VALUES() {
789 // Assumption: at least one legal move
790 getComputerMove(color
)
792 const oppCol
= this.getOppCol(color
);
794 // Rank moves using a min-max at depth 2
795 let moves1
= this.getAllValidMoves(color
);
797 for (let i
=0; i
<moves1
.length
; i
++)
799 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
800 let eval2
= (color
=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
801 this.play(moves1
[i
]);
803 let moves2
= this.getAllValidMoves(oppCol
);
804 // If no possible moves AND underCheck, eval2 is correct.
805 // If !underCheck, eval2 is 0 (stalemate).
806 if (moves2
.length
== 0 && this.checkGameEnd(oppCol
) == "1/2")
808 for (let j
=0; j
<moves2
.length
; j
++)
810 this.play(moves2
[j
]);
811 let evalPos
= this.evalPosition();
812 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
814 this.undo(moves2
[j
]);
816 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
817 moves1
[i
].eval
= eval2
;
818 this.undo(moves1
[i
]);
820 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
822 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
823 for (let i
=0; i
<moves1
.length
; i
++)
825 this.play(moves1
[i
]);
826 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
827 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+ this.alphabeta(oppCol
, color
, 2, -1000, 1000);
828 this.undo(moves1
[i
]);
830 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
832 let candidates
= [0]; //indices of candidates moves
833 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
836 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
837 return moves1
[_
.sample(candidates
, 1)];
840 alphabeta(color
, oppCol
, depth
, alpha
, beta
)
842 if (!this.atLeastOneMove(color
))
844 switch (this.checkGameEnd(color
))
846 case "1/2": return 0;
847 default: return color
=="w" ? -1000 : 1000;
851 return this.evalPosition();
852 const moves
= this.getAllValidMoves(color
);
853 let v
= color
=="w" ? -1000 : 1000;
856 for (let i
=0; i
<moves
.length
; i
++)
859 v
= Math
.max(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
861 alpha
= Math
.max(alpha
, v
);
868 for (let i
=0; i
<moves
.length
; i
++)
871 v
= Math
.min(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
873 beta
= Math
.min(beta
, v
);
875 break; //alpha cutoff
883 const [sizeX
,sizeY
] = VariantRules
.size
;
885 //Just count material for now
886 for (let i
=0; i
<sizeX
; i
++)
888 for (let j
=0; j
<sizeY
; j
++)
890 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
892 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
893 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
904 static GenRandInitFen()
906 let pieces
= [new Array(8), new Array(8)];
907 // Shuffle pieces on first and last rank
908 for (let c
= 0; c
<= 1; c
++)
910 let positions
= _
.range(8);
912 // Get random squares for bishops
913 let randIndex
= 2 * _
.random(3);
914 let bishop1Pos
= positions
[randIndex
];
915 // The second bishop must be on a square of different color
916 let randIndex_tmp
= 2 * _
.random(3) + 1;
917 let bishop2Pos
= positions
[randIndex_tmp
];
918 // Remove chosen squares
919 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
920 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
922 // Get random squares for knights
923 randIndex
= _
.random(5);
924 let knight1Pos
= positions
[randIndex
];
925 positions
.splice(randIndex
, 1);
926 randIndex
= _
.random(4);
927 let knight2Pos
= positions
[randIndex
];
928 positions
.splice(randIndex
, 1);
930 // Get random square for queen
931 randIndex
= _
.random(3);
932 let queenPos
= positions
[randIndex
];
933 positions
.splice(randIndex
, 1);
935 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
936 let rook1Pos
= positions
[0];
937 let kingPos
= positions
[1];
938 let rook2Pos
= positions
[2];
940 // Finally put the shuffled pieces in the board array
941 pieces
[c
][rook1Pos
] = 'r';
942 pieces
[c
][knight1Pos
] = 'n';
943 pieces
[c
][bishop1Pos
] = 'b';
944 pieces
[c
][queenPos
] = 'q';
945 pieces
[c
][kingPos
] = 'k';
946 pieces
[c
][bishop2Pos
] = 'b';
947 pieces
[c
][knight2Pos
] = 'n';
948 pieces
[c
][rook2Pos
] = 'r';
950 let fen
= pieces
[0].join("") +
951 "/pppppppp/8/8/8/8/PPPPPPPP/" +
952 pieces
[1].join("").toUpperCase() +
953 " 1111 - 0"; //flags + enPassant + movesCount
957 // Return current fen according to pieces+colors state
960 const L
= this.epSquares
.length
;
961 const epSq
= this.epSquares
[L
-1]===undefined
963 : this.epSquares
[L
-1].x
+","+this.epSquares
[L
-1].y
;
964 return this.getBaseFen() + " " + this.getFlagsFen()
965 + " " + epSq
+ " " + this.movesCount
;
971 let [sizeX
,sizeY
] = VariantRules
.size
;
972 for (let i
=0; i
<sizeX
; i
++)
975 for (let j
=0; j
<sizeY
; j
++)
977 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
983 // Add empty squares in-between
987 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
996 fen
+= "/"; //separate rows
1005 // Add castling flags
1006 for (let i
of ['w','b'])
1008 for (let j
=0; j
<2; j
++)
1009 fen
+= this.flags
[i
][j
] ? '1' : '0';
1014 // Context: just before move is played, turn hasn't changed
1017 if (move.appear
.length
== 2)
1020 if (move.end
.y
< move.start
.y
)
1026 // Translate final square
1028 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1030 let piece
= this.getPiece(move.start
.x
, move.start
.y
);
1031 if (piece
== VariantRules
.PAWN
)
1035 if (move.vanish
.length
> 1)
1038 let startColumn
= String
.fromCharCode(97 + move.start
.y
);
1039 notation
= startColumn
+ "x" + finalSquare
;
1042 notation
= finalSquare
;
1043 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1044 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1051 return piece
.toUpperCase() + (move.vanish
.length
> 1 ? "x" : "") + finalSquare
;
1055 // The score is already computed when calling this function
1056 getPGN(mycolor
, score
, fenStart
)
1059 pgn
+= '[Site "vchess.club"]<br>';
1060 const d
= new Date();
1061 pgn
+= '[Date "' + d
.getFullYear() + '-' + d
.getMonth() + '-' + d
.getDate() + '"]<br>';
1062 pgn
+= '[White "' + (mycolor
=='w'?'Myself':'Anonymous') + '"]<br>';
1063 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':'Anonymous') + '"]<br>';
1064 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1065 pgn
+= '[Result "' + score
+ '"]<br><br>';
1067 for (let i
=0; i
<this.moves
.length
; i
++)
1070 pgn
+= ((i
/2)+1) + ".";
1071 pgn
+= this.moves
[i
].notation
+ " ";