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"
50 constructor(fen
, moves
)
53 // Use fen string to initialize variables, flags and board
54 this.initVariables(fen
);
55 this.board
= VariantRules
.GetBoard(fen
);
56 this.flags
= VariantRules
.GetFlags(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 const epSq
= this.moves
.length
> 0 ? this.getEpSquare(this.lastMove
) : undefined;
102 this.epSquares
= [ epSq
];
105 // Turn diagram fen into double array ["wb","wp","bk",...]
108 let rows
= fen
.split(" ")[0].split("/");
109 let [sizeX
,sizeY
] = VariantRules
.size
;
110 let board
= doubleArray(sizeX
, sizeY
, "");
111 for (let i
=0; i
<rows
.length
; i
++)
114 for (let indexInRow
= 0; indexInRow
< rows
[i
].length
; indexInRow
++)
116 let character
= rows
[i
][indexInRow
];
117 let num
= parseInt(character
);
119 j
+= num
; //just shift j
120 else //something at position i,j
121 board
[i
][j
++] = VariantRules
.fen2board(character
);
127 // Overridable: flags can change a lot
130 // white a-castle, h-castle, black a-castle, h-castle
131 let flags
= {'w': new Array(2), 'b': new Array(2)};
132 let fenFlags
= fen
.split(" ")[1]; //flags right after position
133 for (let i
=0; i
<4; i
++)
134 flags
[i
< 2 ? 'w' : 'b'][i
%2] = (fenFlags
.charAt(i
) == '1');
141 // Simple useful getters
142 static get size() { return [8,8]; }
143 // Two next functions return 'undefined' if called on empty square
144 getColor(i
,j
) { return this.board
[i
][j
].charAt(0); }
145 getPiece(i
,j
) { return this.board
[i
][j
].charAt(1); }
148 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
151 const L
= this.moves
.length
;
152 return L
>0 ? this.moves
[L
-1] : null;
155 return this.moves
.length
%2==0 ? 'w' : 'b';
159 static get PAWN() { return 'p'; }
160 static get ROOK() { return 'r'; }
161 static get KNIGHT() { return 'n'; }
162 static get BISHOP() { return 'b'; }
163 static get QUEEN() { return 'q'; }
164 static get KING() { return 'k'; }
167 static get EMPTY() { return ''; }
169 // Some pieces movements
172 'r': [ [-1,0],[1,0],[0,-1],[0,1] ],
173 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ],
174 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ],
175 'q': [ [-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1] ]
179 // En-passant square, if any
182 const [sx
,sy
,ex
] = [move.start
.x
,move.start
.y
,move.end
.x
];
183 if (this.getPiece(sx
,sy
) == VariantRules
.PAWN
&& Math
.abs(sx
- ex
) == 2)
190 return undefined; //default
193 // can color1 take color2?
194 canTake(color1
, color2
)
196 return color1
!= color2
;
202 // All possible moves from selected square (assumption: color is OK)
203 getPotentialMovesFrom([x
,y
])
205 let c
= this.getColor(x
,y
);
206 // Fill possible moves according to piece type
207 switch (this.getPiece(x
,y
))
209 case VariantRules
.PAWN:
210 return this.getPotentialPawnMoves(x
,y
,c
);
211 case VariantRules
.ROOK:
212 return this.getPotentialRookMoves(x
,y
,c
);
213 case VariantRules
.KNIGHT:
214 return this.getPotentialKnightMoves(x
,y
,c
);
215 case VariantRules
.BISHOP:
216 return this.getPotentialBishopMoves(x
,y
,c
);
217 case VariantRules
.QUEEN:
218 return this.getPotentialQueenMoves(x
,y
,c
);
219 case VariantRules
.KING:
220 return this.getPotentialKingMoves(x
,y
,c
);
224 // Build a regular move from its initial and destination squares; tr: transformation
225 getBasicMove(sx
, sy
, ex
, ey
, tr
)
232 c: this.getColor(sx
,sy
),
233 p: !!tr
? tr : this.getPiece(sx
,sy
)
240 c: this.getColor(sx
,sy
),
241 p: this.getPiece(sx
,sy
)
246 // The opponent piece disappears if we take it
247 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
253 c: this.getColor(ex
,ey
),
254 p: this.getPiece(ex
,ey
)
261 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
262 getSlideNJumpMoves(x
, y
, color
, steps
, oneStep
)
265 let [sizeX
,sizeY
] = VariantRules
.size
;
267 for (let step
of steps
)
271 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
272 && this.board
[i
][j
] == VariantRules
.EMPTY
)
274 moves
.push(this.getBasicMove(x
, y
, i
, j
));
275 if (oneStep
!== undefined)
280 if (i
>=0 && i
<8 && j
>=0 && j
<8 && this.canTake(color
, this.getColor(i
,j
)))
281 moves
.push(this.getBasicMove(x
, y
, i
, j
));
286 // What are the pawn moves from square x,y considering color "color" ?
287 getPotentialPawnMoves(x
, y
, color
)
290 var V
= VariantRules
;
291 let [sizeX
,sizeY
] = VariantRules
.size
;
292 let shift
= (color
== "w" ? -1 : 1);
293 let startRank
= (color
== "w" ? sizeY
-2 : 1);
294 let lastRank
= (color
== "w" ? 0 : sizeY
-1);
296 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
299 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
301 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
));
302 if (x
==startRank
&& this.board
[x
+2*shift
][y
] == V
.EMPTY
)
305 moves
.push(this.getBasicMove(x
, y
, x
+2*shift
, y
));
309 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
310 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
312 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1));
314 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
315 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
317 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1));
321 if (x
+shift
== lastRank
)
324 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
325 promotionPieces
.forEach(p
=> {
327 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
328 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
, p
));
330 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
331 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
333 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1, p
));
335 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
336 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
338 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1, p
));
344 const Lep
= this.epSquares
.length
;
345 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
346 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
348 let epStep
= epSquare
.y
- y
;
349 var enpassantMove
= this.getBasicMove(x
, y
, x
+shift
, y
+epStep
);
350 enpassantMove
.vanish
.push({
354 c: this.getColor(x
,y
+epStep
)
356 moves
.push(enpassantMove
);
362 // What are the rook moves from square x,y ?
363 getPotentialRookMoves(x
, y
, color
)
365 return this.getSlideNJumpMoves(
366 x
, y
, color
, VariantRules
.steps
[VariantRules
.ROOK
]);
369 // What are the knight moves from square x,y ?
370 getPotentialKnightMoves(x
, y
, color
)
372 return this.getSlideNJumpMoves(
373 x
, y
, color
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
376 // What are the bishop moves from square x,y ?
377 getPotentialBishopMoves(x
, y
, color
)
379 return this.getSlideNJumpMoves(
380 x
, y
, color
, VariantRules
.steps
[VariantRules
.BISHOP
]);
383 // What are the queen moves from square x,y ?
384 getPotentialQueenMoves(x
, y
, color
)
386 return this.getSlideNJumpMoves(
387 x
, y
, color
, VariantRules
.steps
[VariantRules
.QUEEN
]);
390 // What are the king moves from square x,y ?
391 getPotentialKingMoves(x
, y
, c
)
393 // Initialize with normal moves
394 var moves
= this.getSlideNJumpMoves(x
, y
, c
,
395 VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
397 return moves
.concat(this.getCastleMoves(x
,y
,c
));
400 getCastleMoves(x
,y
,c
)
402 if (x
!= (c
=="w" ? 7 : 0) || y
!= this.INIT_COL_KING
[c
])
403 return []; //x isn't first rank, or king has moved (shortcut)
405 const V
= VariantRules
;
408 const oppCol
= this.getOppCol(c
);
411 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
413 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
415 if (!this.flags
[c
][castleSide
])
417 // If this code is reached, rooks and king are on initial position
419 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
420 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
421 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
423 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
424 // NOTE: next check is enough, because of chessboard constraints
425 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
427 continue castlingCheck
;
431 // Nothing on the path to the rook?
432 step
= castleSide
== 0 ? -1 : 1;
433 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
435 if (this.board
[x
][i
] != V
.EMPTY
)
436 continue castlingCheck
;
438 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
440 // Nothing on final squares, except maybe king and castling rook?
443 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
444 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
445 finalSquares
[castleSide
][i
] != rookPos
)
447 continue castlingCheck
;
451 // If this code is reached, castle is valid
452 moves
.push( new Move({
454 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
455 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
457 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
458 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
459 end: Math
.abs(y
- rookPos
) <= 2
461 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
473 return ((color
=='w' && this.moves
.length
%2==0)
474 || (color
=='b' && this.moves
.length
%2==1))
475 && this.getColor(sq
[0], sq
[1]) == color
;
478 getPossibleMovesFrom(sq
)
480 // Assuming color is right (already checked)
481 return this.filterValid( this.getPotentialMovesFrom(sq
) );
484 // TODO: once a promotion is filtered, the others results are same: useless computations
487 if (moves
.length
== 0)
489 let color
= this.getColor( moves
[0].start
.x
, moves
[0].start
.y
);
490 return moves
.filter(m
=> {
491 return !this.underCheck(m
, color
);
495 // Search for all valid moves considering current turn (for engine and game end)
496 getAllValidMoves(color
)
498 const oppCol
= this.getOppCol(color
);
499 var potentialMoves
= [];
500 let [sizeX
,sizeY
] = VariantRules
.size
;
501 for (var i
=0; i
<sizeX
; i
++)
503 for (var j
=0; j
<sizeY
; j
++)
505 // Next condition ... != oppCol is a little HACK to work with checkered variant
506 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
507 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
510 // NOTE: prefer lazy undercheck tests, letting the king being taken?
511 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
512 return this.filterValid(potentialMoves
);
515 // Stop at the first move found
516 atLeastOneMove(color
)
518 const oppCol
= this.getOppCol(color
);
519 let [sizeX
,sizeY
] = VariantRules
.size
;
520 for (var i
=0; i
<sizeX
; i
++)
522 for (var j
=0; j
<sizeY
; j
++)
524 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
526 const moves
= this.getPotentialMovesFrom([i
,j
]);
527 if (moves
.length
> 0)
529 for (let i
=0; i
<moves
.length
; i
++)
531 if (this.filterValid([moves
[i
]]).length
> 0)
541 // Check if pieces of color 'color' are attacking square x,y
542 isAttacked(sq
, color
)
544 return (this.isAttackedByPawn(sq
, color
)
545 || this.isAttackedByRook(sq
, color
)
546 || this.isAttackedByKnight(sq
, color
)
547 || this.isAttackedByBishop(sq
, color
)
548 || this.isAttackedByQueen(sq
, color
)
549 || this.isAttackedByKing(sq
, color
));
552 // Is square x,y attacked by pawns of color c ?
553 isAttackedByPawn([x
,y
], c
)
555 let pawnShift
= (c
=="w" ? 1 : -1);
556 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
558 for (let i
of [-1,1])
560 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
561 && this.getColor(x
+pawnShift
,y
+i
)==c
)
570 // Is square x,y attacked by rooks of color c ?
571 isAttackedByRook(sq
, color
)
573 return this.isAttackedBySlideNJump(sq
, color
,
574 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
577 // Is square x,y attacked by knights of color c ?
578 isAttackedByKnight(sq
, color
)
580 return this.isAttackedBySlideNJump(sq
, color
,
581 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
584 // Is square x,y attacked by bishops of color c ?
585 isAttackedByBishop(sq
, color
)
587 return this.isAttackedBySlideNJump(sq
, color
,
588 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
591 // Is square x,y attacked by queens of color c ?
592 isAttackedByQueen(sq
, color
)
594 return this.isAttackedBySlideNJump(sq
, color
,
595 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
598 // Is square x,y attacked by king of color c ?
599 isAttackedByKing(sq
, color
)
601 return this.isAttackedBySlideNJump(sq
, color
,
602 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
605 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
606 isAttackedBySlideNJump([x
,y
], c
,piece
,steps
,oneStep
)
608 for (let step
of steps
)
610 let rx
= x
+step
[0], ry
= y
+step
[1];
611 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
617 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
618 && this.getPiece(rx
,ry
) == piece
&& this.getColor(rx
,ry
) == c
)
626 // Is color c under check after move ?
630 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
));
635 // On which squares is color c under check (after move) ?
636 getCheckSquares(move, c
)
639 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
))
640 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[c
])) ] //need to duplicate!
646 // Apply a move on board
647 static PlayOnBoard(board
, move)
649 for (let psq
of move.vanish
)
650 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
651 for (let psq
of move.appear
)
652 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
654 // Un-apply the played move
655 static UndoOnBoard(board
, move)
657 for (let psq
of move.appear
)
658 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
659 for (let psq
of move.vanish
)
660 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
663 // Before move is played, update variables + flags
664 updateVariables(move)
666 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
667 const c
= this.getColor(move.start
.x
,move.start
.y
);
668 const firstRank
= (c
== "w" ? 7 : 0);
670 // Update king position + flags
671 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
673 this.kingPos
[c
][0] = move.appear
[0].x
;
674 this.kingPos
[c
][1] = move.appear
[0].y
;
675 this.flags
[c
] = [false,false];
678 const oppCol
= this.getOppCol(c
);
679 const oppFirstRank
= 7 - firstRank
;
680 if (move.start
.x
== firstRank
//our rook moves?
681 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
683 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
684 this.flags
[c
][flagIdx
] = false;
686 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
687 && this.INIT_COL_ROOK
[c
].includes(move.end
.y
))
689 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
690 this.flags
[oppCol
][flagIdx
] = false;
694 unupdateVariables(move)
696 // (Potentially) Reset king position
697 const c
= this.getColor(move.start
.x
,move.start
.y
);
698 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
699 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
705 move.notation
= this.getNotation(move);
707 // Save flags (for undo)
708 move.flags
= JSON
.stringify(this.flags
); //TODO: less costly?
709 this.updateVariables(move);
710 this.moves
.push(move);
711 this.epSquares
.push( this.getEpSquare(move) );
712 VariantRules
.PlayOnBoard(this.board
, move);
717 VariantRules
.UndoOnBoard(this.board
, move);
718 this.epSquares
.pop();
720 this.unupdateVariables(move);
721 this.flags
= JSON
.parse(move.flags
);
729 // Check for 3 repetitions
730 if (this.moves
.length
>= 8)
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]))
739 return "1/2 (repetition)";
743 if (this.atLeastOneMove(color
))
750 return this.checkGameEnd(color
);
753 // Useful stand-alone for engine
756 // No valid move: stalemate or checkmate?
757 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
760 return color
== "w" ? "0-1" : "1-0";
767 static get VALUES() {
778 // Assumption: at least one legal move
779 getComputerMove(color
)
781 const oppCol
= this.getOppCol(color
);
783 // Rank moves using a min-max at depth 2
784 let moves1
= this.getAllValidMoves(color
);
786 for (let i
=0; i
<moves1
.length
; i
++)
788 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
789 let eval2
= (color
=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
790 this.play(moves1
[i
]);
792 let moves2
= this.getAllValidMoves(oppCol
);
793 // If no possible moves AND underCheck, eval2 is correct.
794 // If !underCheck, eval2 is 0 (stalemate).
795 if (moves2
.length
== 0 && this.checkGameEnd(oppCol
) == "1/2")
797 for (let j
=0; j
<moves2
.length
; j
++)
799 this.play(moves2
[j
]);
800 let evalPos
= this.evalPosition();
801 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
803 this.undo(moves2
[j
]);
805 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
806 moves1
[i
].eval
= eval2
;
807 this.undo(moves1
[i
]);
809 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
811 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
812 for (let i
=0; i
<moves1
.length
; i
++)
814 this.play(moves1
[i
]);
815 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
816 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+ this.alphabeta(oppCol
, color
, 2, -1000, 1000);
817 this.undo(moves1
[i
]);
819 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
821 let candidates
= [0]; //indices of candidates moves
822 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
825 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
826 return moves1
[_
.sample(candidates
, 1)];
829 alphabeta(color
, oppCol
, depth
, alpha
, beta
)
831 if (!this.atLeastOneMove(color
))
833 switch (this.checkGameEnd(color
))
835 case "1/2": return 0;
836 default: return color
=="w" ? -1000 : 1000;
840 return this.evalPosition();
841 const moves
= this.getAllValidMoves(color
);
842 let v
= color
=="w" ? -1000 : 1000;
845 for (let i
=0; i
<moves
.length
; i
++)
848 v
= Math
.max(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
850 alpha
= Math
.max(alpha
, v
);
857 for (let i
=0; i
<moves
.length
; i
++)
860 v
= Math
.min(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
862 beta
= Math
.min(beta
, v
);
864 break; //alpha cutoff
872 const [sizeX
,sizeY
] = VariantRules
.size
;
874 //Just count material for now
875 for (let i
=0; i
<sizeX
; i
++)
877 for (let j
=0; j
<sizeY
; j
++)
879 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
881 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
882 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
893 static GenRandInitFen()
895 let pieces
= [new Array(8), new Array(8)];
896 // Shuffle pieces on first and last rank
897 for (let c
= 0; c
<= 1; c
++)
899 let positions
= _
.range(8);
901 // Get random squares for bishops
902 let randIndex
= 2 * _
.random(3);
903 let bishop1Pos
= positions
[randIndex
];
904 // The second bishop must be on a square of different color
905 let randIndex_tmp
= 2 * _
.random(3) + 1;
906 let bishop2Pos
= positions
[randIndex_tmp
];
907 // Remove chosen squares
908 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
909 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
911 // Get random squares for knights
912 randIndex
= _
.random(5);
913 let knight1Pos
= positions
[randIndex
];
914 positions
.splice(randIndex
, 1);
915 randIndex
= _
.random(4);
916 let knight2Pos
= positions
[randIndex
];
917 positions
.splice(randIndex
, 1);
919 // Get random square for queen
920 randIndex
= _
.random(3);
921 let queenPos
= positions
[randIndex
];
922 positions
.splice(randIndex
, 1);
924 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
925 let rook1Pos
= positions
[0];
926 let kingPos
= positions
[1];
927 let rook2Pos
= positions
[2];
929 // Finally put the shuffled pieces in the board array
930 pieces
[c
][rook1Pos
] = 'r';
931 pieces
[c
][knight1Pos
] = 'n';
932 pieces
[c
][bishop1Pos
] = 'b';
933 pieces
[c
][queenPos
] = 'q';
934 pieces
[c
][kingPos
] = 'k';
935 pieces
[c
][bishop2Pos
] = 'b';
936 pieces
[c
][knight2Pos
] = 'n';
937 pieces
[c
][rook2Pos
] = 'r';
939 let fen
= pieces
[0].join("") +
940 "/pppppppp/8/8/8/8/PPPPPPPP/" +
941 pieces
[1].join("").toUpperCase() +
946 // Return current fen according to pieces+colors state
949 return this.getBaseFen() + " " + this.getFlagsFen();
955 let [sizeX
,sizeY
] = VariantRules
.size
;
956 for (let i
=0; i
<sizeX
; i
++)
959 for (let j
=0; j
<sizeY
; j
++)
961 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
967 // Add empty squares in-between
971 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
980 fen
+= "/"; //separate rows
989 // Add castling flags
990 for (let i
of ['w','b'])
992 for (let j
=0; j
<2; j
++)
993 fen
+= this.flags
[i
][j
] ? '1' : '0';
998 // Context: just before move is played, turn hasn't changed
1001 if (move.appear
.length
== 2)
1004 if (move.end
.y
< move.start
.y
)
1010 // Translate final square
1012 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1014 let piece
= this.getPiece(move.start
.x
, move.start
.y
);
1015 if (piece
== VariantRules
.PAWN
)
1019 if (move.vanish
.length
> 1)
1022 let startColumn
= String
.fromCharCode(97 + move.start
.y
);
1023 notation
= startColumn
+ "x" + finalSquare
;
1026 notation
= finalSquare
;
1027 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1028 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1035 return piece
.toUpperCase() + (move.vanish
.length
> 1 ? "x" : "") + finalSquare
;
1039 // The score is already computed when calling this function
1040 getPGN(mycolor
, score
, fenStart
)
1043 pgn
+= '[Site "vchess.club"]<br>';
1044 const d
= new Date();
1045 pgn
+= '[Date "' + d
.getFullYear() + '-' + d
.getMonth() + '-' + d
.getDate() + '"]<br>';
1046 pgn
+= '[White "' + (mycolor
=='w'?'Myself':'Anonymous') + '"]<br>';
1047 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':'Anonymous') + '"]<br>';
1048 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1049 pgn
+= '[Result "' + score
+ '"]<br><br>';
1051 for (let i
=0; i
<this.moves
.length
; i
++)
1054 pgn
+= ((i
/2)+1) + ".";
1055 pgn
+= this.moves
[i
].notation
+ " ";