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 let epSq
= undefined;
102 if (fenParts
[2] != "-")
104 const digits
= fenParts
[2].split(","); //3,2 ...
105 epSq
= { x:Number
.parseInt(digits
[0]), y:Number
.parseInt(digits
[1]) };
107 this.epSquares
= [ epSq
];
108 this.movesCount
= Number
.parseInt(fenParts
[3]);
111 // Turn diagram fen into double array ["wb","wp","bk",...]
114 let rows
= fen
.split(" ")[0].split("/");
115 let [sizeX
,sizeY
] = VariantRules
.size
;
116 let board
= doubleArray(sizeX
, sizeY
, "");
117 for (let i
=0; i
<rows
.length
; i
++)
120 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
122 let character
= rows
[i
][indexInRow
];
123 let num
= parseInt(character
);
125 j
+= num
; //just shift j
126 else //something at position i,j
127 board
[i
][j
++] = VariantRules
.fen2board(character
);
133 // Overridable: flags can change a lot
136 // white a-castle, h-castle, black a-castle, h-castle
137 let flags
= {'w': new Array(2), 'b': new Array(2)};
138 let fenFlags
= fen
.split(" ")[1]; //flags right after position
139 for (let i
=0; i
<4; i
++)
140 flags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenFlags
.charAt(i
) == '1');
147 // Simple useful getters
148 static get size() { return [8,8]; }
149 // Two next functions return 'undefined' if called on empty square
150 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
151 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
154 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
157 const L
= this.moves
.length
;
158 return L
>0 ? this.moves
[L
-1] : null;
161 return this.movesCount
%2==0 ? 'w' : 'b';
165 static get PAWN() { return 'p'; }
166 static get ROOK() { return 'r'; }
167 static get KNIGHT() { return 'n'; }
168 static get BISHOP() { return 'b'; }
169 static get QUEEN() { return 'q'; }
170 static get KING() { return 'k'; }
173 static get EMPTY() { return ''; }
175 // Some pieces movements
178 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
179 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
180 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
181 'q': [ [-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1] ]
185 // En-passant square, if any
188 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
189 if (this.getPiece(sx
,sy
) == VariantRules
.PAWN
&& Math
.abs(sx
- ex
) == 2)
196 return undefined; //default
199 // can color1 take color2?
200 canTake(color1
, color2
)
202 return color1
!= color2
;
208 // All possible moves from selected square (assumption: color is OK)
209 getPotentialMovesFrom([x
,y
])
211 let c
= this.getColor(x
,y
);
212 // Fill possible moves according to piece type
213 switch (this.getPiece(x
,y
))
215 case VariantRules
.PAWN:
216 return this.getPotentialPawnMoves(x
,y
,c
);
217 case VariantRules
.ROOK:
218 return this.getPotentialRookMoves(x
,y
,c
);
219 case VariantRules
.KNIGHT:
220 return this.getPotentialKnightMoves(x
,y
,c
);
221 case VariantRules
.BISHOP:
222 return this.getPotentialBishopMoves(x
,y
,c
);
223 case VariantRules
.QUEEN:
224 return this.getPotentialQueenMoves(x
,y
,c
);
225 case VariantRules
.KING:
226 return this.getPotentialKingMoves(x
,y
,c
);
230 // Build a regular move from its initial and destination squares; tr: transformation
231 getBasicMove(sx
, sy
, ex
, ey
, tr
)
238 c: this.getColor(sx
,sy
),
239 p: !!tr
? tr : this.getPiece(sx
,sy
)
246 c: this.getColor(sx
,sy
),
247 p: this.getPiece(sx
,sy
)
252 // The opponent piece disappears if we take it
253 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
259 c: this.getColor(ex
,ey
),
260 p: this.getPiece(ex
,ey
)
267 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
268 getSlideNJumpMoves(x
, y
, color
, steps
, oneStep
)
271 let [sizeX
,sizeY
] = VariantRules
.size
;
273 for (let step
of steps
)
277 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
278 && this.board
[i
][j
] == VariantRules
.EMPTY
)
280 moves
.push(this.getBasicMove(x
, y
, i
, j
));
281 if (oneStep
!== undefined)
286 if (i
>=0 && i
<8 && j
>=0 && j
<8 && this.canTake(color
, this.getColor(i
,j
)))
287 moves
.push(this.getBasicMove(x
, y
, i
, j
));
292 // What are the pawn moves from square x,y considering color "color" ?
293 getPotentialPawnMoves(x
, y
, color
)
296 var V
= VariantRules
;
297 let [sizeX
,sizeY
] = VariantRules
.size
;
298 let shift
= (color
== "w" ? -1 : 1);
299 let startRank
= (color
== "w" ? sizeY
-2 : 1);
300 let lastRank
= (color
== "w" ? 0 : sizeY
-1);
302 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
305 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
307 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
));
308 if (x
==startRank
&& this.board
[x
+2*shift
][y
] == V
.EMPTY
)
311 moves
.push(this.getBasicMove(x
, y
, x
+2*shift
, y
));
315 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
316 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
318 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1));
320 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
321 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
323 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1));
327 if (x
+shift
== lastRank
)
330 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
331 promotionPieces
.forEach(p
=> {
333 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
334 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
, p
));
336 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
337 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
339 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1, p
));
341 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
342 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
344 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1, p
));
350 const Lep
= this.epSquares
.length
;
351 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
352 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
354 let epStep
= epSquare
.y
- y
;
355 var enpassantMove
= this.getBasicMove(x
, y
, x
+shift
, y
+epStep
);
356 enpassantMove
.vanish
.push({
360 c: this.getColor(x
,y
+epStep
)
362 moves
.push(enpassantMove
);
368 // What are the rook moves from square x,y ?
369 getPotentialRookMoves(x
, y
, color
)
371 return this.getSlideNJumpMoves(
372 x
, y
, color
, VariantRules
.steps
[VariantRules
.ROOK
]);
375 // What are the knight moves from square x,y ?
376 getPotentialKnightMoves(x
, y
, color
)
378 return this.getSlideNJumpMoves(
379 x
, y
, color
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
382 // What are the bishop moves from square x,y ?
383 getPotentialBishopMoves(x
, y
, color
)
385 return this.getSlideNJumpMoves(
386 x
, y
, color
, VariantRules
.steps
[VariantRules
.BISHOP
]);
389 // What are the queen moves from square x,y ?
390 getPotentialQueenMoves(x
, y
, color
)
392 return this.getSlideNJumpMoves(
393 x
, y
, color
, VariantRules
.steps
[VariantRules
.QUEEN
]);
396 // What are the king moves from square x,y ?
397 getPotentialKingMoves(x
, y
, c
)
399 // Initialize with normal moves
400 var moves
= this.getSlideNJumpMoves(x
, y
, c
,
401 VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
403 return moves
.concat(this.getCastleMoves(x
,y
,c
));
406 getCastleMoves(x
,y
,c
)
408 if (x
!= (c
=="w" ? 7 : 0) || y
!= this.INIT_COL_KING
[c
])
409 return []; //x isn't first rank, or king has moved (shortcut)
411 const V
= VariantRules
;
414 const oppCol
= this.getOppCol(c
);
417 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
419 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
421 if (!this.flags
[c
][castleSide
])
423 // If this code is reached, rooks and king are on initial position
425 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
426 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
427 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
429 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
430 // NOTE: next check is enough, because of chessboard constraints
431 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
433 continue castlingCheck
;
437 // Nothing on the path to the rook?
438 step
= castleSide
== 0 ? -1 : 1;
439 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
441 if (this.board
[x
][i
] != V
.EMPTY
)
442 continue castlingCheck
;
444 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
446 // Nothing on final squares, except maybe king and castling rook?
449 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
450 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
451 finalSquares
[castleSide
][i
] != rookPos
)
453 continue castlingCheck
;
457 // If this code is reached, castle is valid
458 moves
.push( new Move({
460 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
461 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
463 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
464 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
465 end: Math
.abs(y
- rookPos
) <= 2
467 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
479 return ((color
=='w' && this.movesCount
%2==0)
480 || (color
=='b' && this.movesCount
%2==1))
481 && this.getColor(sq
[0], sq
[1]) == color
;
484 getPossibleMovesFrom(sq
)
486 // Assuming color is right (already checked)
487 return this.filterValid( this.getPotentialMovesFrom(sq
) );
490 // TODO: once a promotion is filtered, the others results are same: useless computations
493 if (moves
.length
== 0)
495 let color
= this.getColor( moves
[0].start
.x
, moves
[0].start
.y
);
496 return moves
.filter(m
=> {
497 return !this.underCheck(m
, color
);
501 // Search for all valid moves considering current turn (for engine and game end)
502 getAllValidMoves(color
)
504 const oppCol
= this.getOppCol(color
);
505 var potentialMoves
= [];
506 let [sizeX
,sizeY
] = VariantRules
.size
;
507 for (var i
=0; i
<sizeX
; i
++)
509 for (var j
=0; j
<sizeY
; j
++)
511 // Next condition ... != oppCol is a little HACK to work with checkered variant
512 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
513 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
516 // NOTE: prefer lazy undercheck tests, letting the king being taken?
517 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
518 return this.filterValid(potentialMoves
);
521 // Stop at the first move found
522 atLeastOneMove(color
)
524 const oppCol
= this.getOppCol(color
);
525 let [sizeX
,sizeY
] = VariantRules
.size
;
526 for (var i
=0; i
<sizeX
; i
++)
528 for (var j
=0; j
<sizeY
; j
++)
530 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
532 const moves
= this.getPotentialMovesFrom([i
,j
]);
533 if (moves
.length
> 0)
535 for (let i
=0; i
<moves
.length
; i
++)
537 if (this.filterValid([moves
[i
]]).length
> 0)
547 // Check if pieces of color 'color' are attacking square x,y
548 isAttacked(sq
, color
)
550 return (this.isAttackedByPawn(sq
, color
)
551 || this.isAttackedByRook(sq
, color
)
552 || this.isAttackedByKnight(sq
, color
)
553 || this.isAttackedByBishop(sq
, color
)
554 || this.isAttackedByQueen(sq
, color
)
555 || this.isAttackedByKing(sq
, color
));
558 // Is square x,y attacked by pawns of color c ?
559 isAttackedByPawn([x
,y
], c
)
561 let pawnShift
= (c
=="w" ? 1 : -1);
562 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
564 for (let i
of [-1,1])
566 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
567 && this.getColor(x
+pawnShift
,y
+i
)==c
)
576 // Is square x,y attacked by rooks of color c ?
577 isAttackedByRook(sq
, color
)
579 return this.isAttackedBySlideNJump(sq
, color
,
580 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
583 // Is square x,y attacked by knights of color c ?
584 isAttackedByKnight(sq
, color
)
586 return this.isAttackedBySlideNJump(sq
, color
,
587 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
590 // Is square x,y attacked by bishops of color c ?
591 isAttackedByBishop(sq
, color
)
593 return this.isAttackedBySlideNJump(sq
, color
,
594 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
597 // Is square x,y attacked by queens of color c ?
598 isAttackedByQueen(sq
, color
)
600 return this.isAttackedBySlideNJump(sq
, color
,
601 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
604 // Is square x,y attacked by king of color c ?
605 isAttackedByKing(sq
, color
)
607 return this.isAttackedBySlideNJump(sq
, color
,
608 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
611 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
612 isAttackedBySlideNJump([x
,y
], c
,piece
,steps
,oneStep
)
614 for (let step
of steps
)
616 let rx
= x
+step
[0], ry
= y
+step
[1];
617 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
623 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
624 && this.getPiece(rx
,ry
) == piece
&& this.getColor(rx
,ry
) == c
)
632 // Is color c under check after move ?
636 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
));
641 // On which squares is color c under check (after move) ?
642 getCheckSquares(move, c
)
645 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
))
646 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[c
])) ] //need to duplicate!
652 // Apply a move on board
653 static PlayOnBoard(board
, move)
655 for (let psq
of move.vanish
)
656 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
657 for (let psq
of move.appear
)
658 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
660 // Un-apply the played move
661 static UndoOnBoard(board
, move)
663 for (let psq
of move.appear
)
664 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
665 for (let psq
of move.vanish
)
666 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
669 // Before move is played:
670 updateVariables(move)
672 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
673 const c
= this.getColor(move.start
.x
,move.start
.y
);
674 const firstRank
= (c
== "w" ? 7 : 0);
676 // Update king position + flags
677 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
679 this.kingPos
[c
][0] = move.appear
[0].x
;
680 this.kingPos
[c
][1] = move.appear
[0].y
;
681 this.flags
[c
] = [false,false];
684 const oppCol
= this.getOppCol(c
);
685 const oppFirstRank
= 7 - firstRank
;
686 if (move.start
.x
== firstRank
//our rook moves?
687 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
689 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
690 this.flags
[c
][flagIdx
] = false;
692 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
693 && this.INIT_COL_ROOK
[c
].includes(move.end
.y
))
695 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
696 this.flags
[oppCol
][flagIdx
] = false;
702 // Save flags (for undo)
703 move.flags
= JSON
.stringify(this.flags
); //TODO: less costly
704 this.updateVariables(move);
708 move.notation
= this.getNotation(move);
709 this.moves
.push(move);
712 this.epSquares
.push( this.getEpSquare(move) );
713 VariantRules
.PlayOnBoard(this.board
, move);
719 VariantRules
.UndoOnBoard(this.board
, move);
720 this.epSquares
.pop();
726 // Update king position, and reset stored/computed flags
727 const c
= this.getColor(move.start
.x
,move.start
.y
);
728 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
729 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
731 this.flags
= JSON
.parse(move.flags
);
739 // Check for 3 repetitions
740 if (this.moves
.length
>= 8)
742 // NOTE: crude detection, only moves repetition
743 const L
= this.moves
.length
;
744 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
745 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
746 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
747 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
749 return "1/2 (repetition)";
753 if (this.atLeastOneMove(color
))
760 return this.checkGameEnd(color
);
763 // Useful stand-alone for engine
766 // No valid move: stalemate or checkmate?
767 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
770 return color
== "w" ? "0-1" : "1-0";
777 static get VALUES() {
788 // Assumption: at least one legal move
789 getComputerMove(color
)
791 const oppCol
= this.getOppCol(color
);
793 // Rank moves using a min-max at depth 2
794 let moves1
= this.getAllValidMoves(color
);
796 for (let i
=0; i
<moves1
.length
; i
++)
798 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
799 let eval2
= (color
=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
800 this.play(moves1
[i
]);
802 let moves2
= this.getAllValidMoves(oppCol
);
803 // If no possible moves AND underCheck, eval2 is correct.
804 // If !underCheck, eval2 is 0 (stalemate).
805 if (moves2
.length
== 0 && this.checkGameEnd(oppCol
) == "1/2")
807 for (let j
=0; j
<moves2
.length
; j
++)
809 this.play(moves2
[j
]);
810 let evalPos
= this.evalPosition();
811 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
813 this.undo(moves2
[j
]);
815 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
816 moves1
[i
].eval
= eval2
;
817 this.undo(moves1
[i
]);
819 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
821 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
822 for (let i
=0; i
<moves1
.length
; i
++)
824 this.play(moves1
[i
]);
825 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
826 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+ this.alphabeta(oppCol
, color
, 2, -1000, 1000);
827 this.undo(moves1
[i
]);
829 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
831 let candidates
= [0]; //indices of candidates moves
832 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
835 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
836 return moves1
[_
.sample(candidates
, 1)];
839 alphabeta(color
, oppCol
, depth
, alpha
, beta
)
841 const moves
= this.getAllValidMoves(color
);
842 if (moves
.length
== 0)
844 switch (this.checkGameEnd(color
))
846 case "1/2": return 0;
847 default: return color
=="w" ? -1000 : 1000;
851 return this.evalPosition();
852 let v
= color
=="w" ? -1000 : 1000;
855 for (let i
=0; i
<moves
.length
; i
++)
858 v
= Math
.max(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
860 alpha
= Math
.max(alpha
, v
);
867 for (let i
=0; i
<moves
.length
; i
++)
870 v
= Math
.min(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
872 beta
= Math
.min(beta
, v
);
874 break; //alpha cutoff
882 const [sizeX
,sizeY
] = VariantRules
.size
;
884 //Just count material for now
885 for (let i
=0; i
<sizeX
; i
++)
887 for (let j
=0; j
<sizeY
; j
++)
889 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
891 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
892 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
903 static GenRandInitFen()
905 let pieces
= [new Array(8), new Array(8)];
906 // Shuffle pieces on first and last rank
907 for (let c
= 0; c
<= 1; c
++)
909 let positions
= _
.range(8);
911 // Get random squares for bishops
912 let randIndex
= 2 * _
.random(3);
913 let bishop1Pos
= positions
[randIndex
];
914 // The second bishop must be on a square of different color
915 let randIndex_tmp
= 2 * _
.random(3) + 1;
916 let bishop2Pos
= positions
[randIndex_tmp
];
917 // Remove chosen squares
918 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
919 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
921 // Get random squares for knights
922 randIndex
= _
.random(5);
923 let knight1Pos
= positions
[randIndex
];
924 positions
.splice(randIndex
, 1);
925 randIndex
= _
.random(4);
926 let knight2Pos
= positions
[randIndex
];
927 positions
.splice(randIndex
, 1);
929 // Get random square for queen
930 randIndex
= _
.random(3);
931 let queenPos
= positions
[randIndex
];
932 positions
.splice(randIndex
, 1);
934 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
935 let rook1Pos
= positions
[0];
936 let kingPos
= positions
[1];
937 let rook2Pos
= positions
[2];
939 // Finally put the shuffled pieces in the board array
940 pieces
[c
][rook1Pos
] = 'r';
941 pieces
[c
][knight1Pos
] = 'n';
942 pieces
[c
][bishop1Pos
] = 'b';
943 pieces
[c
][queenPos
] = 'q';
944 pieces
[c
][kingPos
] = 'k';
945 pieces
[c
][bishop2Pos
] = 'b';
946 pieces
[c
][knight2Pos
] = 'n';
947 pieces
[c
][rook2Pos
] = 'r';
949 let fen
= pieces
[0].join("") +
950 "/pppppppp/8/8/8/8/PPPPPPPP/" +
951 pieces
[1].join("").toUpperCase() +
952 " 1111 - 0"; //flags + enPassant + movesCount
956 // Return current fen according to pieces+colors state
959 const L
= this.epSquares
.length
;
960 const epSq
= this.epSquares
[L
-1]===undefined
962 : this.epSquares
[L
-1].x
+","+this.epSquares
[L
-1].y
;
963 return this.getBaseFen() + " " + this.getFlagsFen()
964 + " " + epSq
+ " " + this.movesCount
;
970 let [sizeX
,sizeY
] = VariantRules
.size
;
971 for (let i
=0; i
<sizeX
; i
++)
974 for (let j
=0; j
<sizeY
; j
++)
976 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
982 // Add empty squares in-between
986 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
995 fen
+= "/"; //separate rows
1004 // Add castling flags
1005 for (let i
of ['w','b'])
1007 for (let j
=0; j
<2; j
++)
1008 fen
+= this.flags
[i
][j
] ? '1' : '0';
1013 // Context: just before move is played, turn hasn't changed
1016 if (move.appear
.length
== 2)
1019 if (move.end
.y
< move.start
.y
)
1025 // Translate final square
1027 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1029 let piece
= this.getPiece(move.start
.x
, move.start
.y
);
1030 if (piece
== VariantRules
.PAWN
)
1034 if (move.vanish
.length
> 1)
1037 let startColumn
= String
.fromCharCode(97 + move.start
.y
);
1038 notation
= startColumn
+ "x" + finalSquare
;
1041 notation
= finalSquare
;
1042 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1043 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1050 return piece
.toUpperCase() + (move.vanish
.length
> 1 ? "x" : "") + finalSquare
;
1054 // The score is already computed when calling this function
1055 getPGN(mycolor
, score
, fenStart
)
1058 pgn
+= '[Site "vchess.club"]<br>';
1059 const d
= new Date();
1060 pgn
+= '[Date "' + d
.getFullYear() + '-' + d
.getMonth() + '-' + d
.getDate() + '"]<br>';
1061 pgn
+= '[White "' + (mycolor
=='w'?'Myself':'Anonymous') + '"]<br>';
1062 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':'Anonymous') + '"]<br>';
1063 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1064 pgn
+= '[Result "' + score
+ '"]<br><br>';
1066 for (let i
=0; i
<this.moves
.length
; i
++)
1069 pgn
+= ((i
/2)+1) + ".";
1070 pgn
+= this.moves
[i
].notation
+ " ";