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.board
= VariantRules
.GetBoard(fen
);
56 this.initVariables(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
++)
68 let k
= 0; //column index on board
69 for (let j
=0; j
<position
[i
].length
; j
++)
71 switch (position
[i
].charAt(j
))
74 this.kingPos
['b'] = [i
,k
];
75 this.INIT_COL_KING
['b'] = k
;
78 this.kingPos
['w'] = [i
,k
];
79 this.INIT_COL_KING
['w'] = k
;
82 if (this.INIT_COL_ROOK
['b'][0] < 0)
83 this.INIT_COL_ROOK
['b'][0] = k
;
85 this.INIT_COL_ROOK
['b'][1] = k
;
88 if (this.INIT_COL_ROOK
['w'][0] < 0)
89 this.INIT_COL_ROOK
['w'][0] = k
;
91 this.INIT_COL_ROOK
['w'][1] = k
;
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 const [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 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');
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); }
147 getOppCol(color
) { return color
=="w" ? "b" : "w"; }
150 const L
= this.moves
.length
;
151 return L
>0 ? this.moves
[L
-1] : null;
154 return this.moves
.length
%2==0 ? 'w' : 'b';
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'; }
166 static get EMPTY() { return ''; }
168 // Some pieces movements
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] ]
178 // Aggregates flags into one object
180 return this.castleFlags
;
186 this.castleFlags
= flags
;
189 // En-passant square, if any
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)
200 return undefined; //default
203 // can thing on square1 take thing on square2
204 canTake([x1
,y1
], [x2
,y2
])
206 return this.getColor(x1
,y1
) != this.getColor(x2
,y2
);
212 // All possible moves from selected square (assumption: color is OK)
213 getPotentialMovesFrom([x
,y
])
215 switch (this.getPiece(x
,y
))
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
]);
232 // Build a regular move from its initial and destination squares; tr: transformation
233 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
240 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
241 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
248 c: this.getColor(sx
,sy
),
249 p: this.getPiece(sx
,sy
)
254 // The opponent piece disappears if we take it
255 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
261 c: this.getColor(ex
,ey
),
262 p: this.getPiece(ex
,ey
)
269 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
270 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
272 const color
= this.getColor(x
,y
);
274 const [sizeX
,sizeY
] = VariantRules
.size
;
276 for (let step
of steps
)
280 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
&& this.board
[i
][j
] == VariantRules
.EMPTY
)
282 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
283 if (oneStep
!== undefined)
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
]));
294 // What are the pawn moves from square x,y considering color "color" ?
295 getPotentialPawnMoves([x
,y
])
297 const color
= this.turn
;
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);
306 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
309 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
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
)
316 moves
.push(this.getBasicMove([x
,y
], [x
+2*shift
,y
]));
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]));
326 if (x
+shift
== lastRank
)
329 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
330 promotionPieces
.forEach(p
=> {
332 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
333 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:color
,p:p
}));
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
}));
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)
347 let epStep
= epSquare
.y
- y
;
348 var enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
349 enpassantMove
.vanish
.push({
353 c: this.getColor(x
,y
+epStep
)
355 moves
.push(enpassantMove
);
361 // What are the rook moves from square x,y ?
362 getPotentialRookMoves(sq
)
364 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.ROOK
]);
367 // What are the knight moves from square x,y ?
368 getPotentialKnightMoves(sq
)
370 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
373 // What are the bishop moves from square x,y ?
374 getPotentialBishopMoves(sq
)
376 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.BISHOP
]);
379 // What are the queen moves from square x,y ?
380 getPotentialQueenMoves(sq
)
382 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.QUEEN
]);
385 // What are the king moves from square x,y ?
386 getPotentialKingMoves(sq
)
388 // Initialize with normal moves
389 let moves
= this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
390 return moves
.concat(this.getCastleMoves(sq
));
393 getCastleMoves([x
,y
])
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)
399 const V
= VariantRules
;
402 const oppCol
= this.getOppCol(c
);
405 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
407 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
409 if (!this.castleFlags
[c
][castleSide
])
411 // If this code is reached, rooks and king are on initial position
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
)
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
)))))
421 continue castlingCheck
;
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
)
429 if (this.board
[x
][i
] != V
.EMPTY
)
430 continue castlingCheck
;
432 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
434 // Nothing on final squares, except maybe king and castling rook?
437 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
438 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
439 finalSquares
[castleSide
][i
] != rookPos
)
441 continue castlingCheck
;
445 // If this code is reached, castle is valid
446 moves
.push( new Move({
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
})],
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
455 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
465 canIplay(side
, [x
,y
])
467 return ((side
=='w' && this.moves
.length
%2==0) || (side
=='b' && this.moves
.length
%2==1))
468 && this.getColor(x
,y
) == side
;
471 getPossibleMovesFrom(sq
)
473 // Assuming color is right (already checked)
474 return this.filterValid( this.getPotentialMovesFrom(sq
) );
477 // TODO: once a promotion is filtered, the others results are same: useless computations
480 if (moves
.length
== 0)
482 return moves
.filter(m
=> { return !this.underCheck(m
); });
485 // Search for all valid moves considering current turn (for engine and game end)
488 const color
= this.turn
;
489 const oppCol
= this.getOppCol(color
);
490 var potentialMoves
= [];
491 let [sizeX
,sizeY
] = VariantRules
.size
;
492 for (var i
=0; i
<sizeX
; i
++)
494 for (var j
=0; j
<sizeY
; j
++)
496 // Next condition ... != oppCol is a little HACK to work with checkered variant
497 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
498 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
501 // NOTE: prefer lazy undercheck tests, letting the king being taken?
502 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
503 return this.filterValid(potentialMoves
);
506 // Stop at the first move found
509 const color
= this.turn
;
510 const oppCol
= this.getOppCol(color
);
511 let [sizeX
,sizeY
] = VariantRules
.size
;
512 for (let i
=0; i
<sizeX
; i
++)
514 for (let j
=0; j
<sizeY
; j
++)
516 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
518 const moves
= this.getPotentialMovesFrom([i
,j
]);
519 if (moves
.length
> 0)
521 for (let k
=0; k
<moves
.length
; k
++)
523 if (this.filterValid([moves
[k
]]).length
> 0)
533 // Check if pieces of color 'colors' are attacking square x,y
534 isAttacked(sq
, colors
)
536 return (this.isAttackedByPawn(sq
, colors
)
537 || this.isAttackedByRook(sq
, colors
)
538 || this.isAttackedByKnight(sq
, colors
)
539 || this.isAttackedByBishop(sq
, colors
)
540 || this.isAttackedByQueen(sq
, colors
)
541 || this.isAttackedByKing(sq
, colors
));
544 // Is square x,y attacked by pawns of color c ?
545 isAttackedByPawn([x
,y
], colors
)
547 for (let c
of colors
)
549 let pawnShift
= (c
=="w" ? 1 : -1);
550 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
552 for (let i
of [-1,1])
554 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
555 && this.getColor(x
+pawnShift
,y
+i
)==c
)
565 // Is square x,y attacked by rooks of color c ?
566 isAttackedByRook(sq
, colors
)
568 return this.isAttackedBySlideNJump(sq
, colors
,
569 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
572 // Is square x,y attacked by knights of color c ?
573 isAttackedByKnight(sq
, colors
)
575 return this.isAttackedBySlideNJump(sq
, colors
,
576 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
579 // Is square x,y attacked by bishops of color c ?
580 isAttackedByBishop(sq
, colors
)
582 return this.isAttackedBySlideNJump(sq
, colors
,
583 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
586 // Is square x,y attacked by queens of color c ?
587 isAttackedByQueen(sq
, colors
)
589 return this.isAttackedBySlideNJump(sq
, colors
,
590 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
593 // Is square x,y attacked by king of color c ?
594 isAttackedByKing(sq
, colors
)
596 return this.isAttackedBySlideNJump(sq
, colors
,
597 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
600 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
601 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
603 for (let step
of steps
)
605 let rx
= x
+step
[0], ry
= y
+step
[1];
606 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
612 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
613 && this.getPiece(rx
,ry
) == piece
&& colors
.includes(this.getColor(rx
,ry
)))
621 // Is color c under check after move ?
624 const color
= this.turn
;
626 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
));
631 // On which squares is color c under check (after move) ?
632 getCheckSquares(move)
635 const color
= this.turn
; //opponent
636 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
))
637 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
643 // Apply a move on board
644 static PlayOnBoard(board
, move)
646 for (let psq
of move.vanish
)
647 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
648 for (let psq
of move.appear
)
649 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
651 // Un-apply the played move
652 static UndoOnBoard(board
, move)
654 for (let psq
of move.appear
)
655 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
656 for (let psq
of move.vanish
)
657 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
660 // Before move is played, update variables + flags
661 updateVariables(move)
663 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
664 const c
= this.getColor(move.start
.x
,move.start
.y
);
665 const firstRank
= (c
== "w" ? 7 : 0);
667 // Update king position + flags
668 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
670 this.kingPos
[c
][0] = move.appear
[0].x
;
671 this.kingPos
[c
][1] = move.appear
[0].y
;
672 this.castleFlags
[c
] = [false,false];
675 const oppCol
= this.getOppCol(c
);
676 const oppFirstRank
= 7 - firstRank
;
677 if (move.start
.x
== firstRank
//our rook moves?
678 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
680 const flagIdx
= (move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1);
681 this.castleFlags
[c
][flagIdx
] = false;
683 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
684 && this.INIT_COL_ROOK
[oppCol
].includes(move.end
.y
))
686 const flagIdx
= (move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1);
687 this.castleFlags
[oppCol
][flagIdx
] = false;
691 unupdateVariables(move)
693 // (Potentially) Reset king position
694 const c
= this.getColor(move.start
.x
,move.start
.y
);
695 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
696 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
702 move.notation
= this.getNotation(move);
704 move.flags
= JSON
.stringify(this.flags
); //save flags (for undo)
705 this.updateVariables(move);
706 this.moves
.push(move);
707 this.epSquares
.push( this.getEpSquare(move) );
708 VariantRules
.PlayOnBoard(this.board
, move);
713 VariantRules
.UndoOnBoard(this.board
, move);
714 this.epSquares
.pop();
716 this.unupdateVariables(move);
717 this.parseFlags(JSON
.parse(move.flags
));
725 // Check for 3 repetitions
726 if (this.moves
.length
>= 8)
728 // NOTE: crude detection, only moves repetition
729 const L
= this.moves
.length
;
730 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
731 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
732 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
733 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
743 if (this.checkRepetition())
746 if (this.atLeastOneMove()) // game not over
750 return this.checkGameEnd();
753 // No moves are possible: compute score
756 const color
= this.turn
;
757 // No valid move: stalemate or checkmate?
758 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
761 return color
== "w" ? "0-1" : "1-0";
768 static get VALUES() {
779 // Assumption: at least one legal move
782 const color
= this.turn
;
783 let moves1
= this.getAllValidMoves();
785 // Rank moves using a min-max at depth 2
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();
793 // If no possible moves AND underCheck, eval2 is correct.
794 // If !underCheck, eval2 is 0 (stalemate).
795 if (moves2
.length
== 0 && this.checkGameEnd() == "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(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(depth
, alpha
, beta
)
831 const color
= this.turn
;
832 if (!this.atLeastOneMove())
834 switch (this.checkGameEnd())
836 case "1/2": return 0;
837 default: return color
=="w" ? -1000 : 1000;
841 return this.evalPosition();
842 const moves
= this.getAllValidMoves();
843 let v
= color
=="w" ? -1000 : 1000;
846 for (let i
=0; i
<moves
.length
; i
++)
849 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
851 alpha
= Math
.max(alpha
, v
);
858 for (let i
=0; i
<moves
.length
; i
++)
861 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
863 beta
= Math
.min(beta
, v
);
865 break; //alpha cutoff
873 const [sizeX
,sizeY
] = VariantRules
.size
;
875 //Just count material for now
876 for (let i
=0; i
<sizeX
; i
++)
878 for (let j
=0; j
<sizeY
; j
++)
880 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
882 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
883 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
894 static GenRandInitFen()
896 let pieces
= [new Array(8), new Array(8)];
897 // Shuffle pieces on first and last rank
898 for (let c
= 0; c
<= 1; c
++)
900 let positions
= _
.range(8);
902 // Get random squares for bishops
903 let randIndex
= 2 * _
.random(3);
904 let bishop1Pos
= positions
[randIndex
];
905 // The second bishop must be on a square of different color
906 let randIndex_tmp
= 2 * _
.random(3) + 1;
907 let bishop2Pos
= positions
[randIndex_tmp
];
908 // Remove chosen squares
909 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
910 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
912 // Get random squares for knights
913 randIndex
= _
.random(5);
914 let knight1Pos
= positions
[randIndex
];
915 positions
.splice(randIndex
, 1);
916 randIndex
= _
.random(4);
917 let knight2Pos
= positions
[randIndex
];
918 positions
.splice(randIndex
, 1);
920 // Get random square for queen
921 randIndex
= _
.random(3);
922 let queenPos
= positions
[randIndex
];
923 positions
.splice(randIndex
, 1);
925 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
926 let rook1Pos
= positions
[0];
927 let kingPos
= positions
[1];
928 let rook2Pos
= positions
[2];
930 // Finally put the shuffled pieces in the board array
931 pieces
[c
][rook1Pos
] = 'r';
932 pieces
[c
][knight1Pos
] = 'n';
933 pieces
[c
][bishop1Pos
] = 'b';
934 pieces
[c
][queenPos
] = 'q';
935 pieces
[c
][kingPos
] = 'k';
936 pieces
[c
][bishop2Pos
] = 'b';
937 pieces
[c
][knight2Pos
] = 'n';
938 pieces
[c
][rook2Pos
] = 'r';
940 let fen
= pieces
[0].join("") +
941 "/pppppppp/8/8/8/8/PPPPPPPP/" +
942 pieces
[1].join("").toUpperCase() +
947 // Return current fen according to pieces+colors state
950 return this.getBaseFen() + " " + this.getFlagsFen();
956 let [sizeX
,sizeY
] = VariantRules
.size
;
957 for (let i
=0; i
<sizeX
; i
++)
960 for (let j
=0; j
<sizeY
; j
++)
962 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
968 // Add empty squares in-between
972 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
981 fen
+= "/"; //separate rows
990 // Add castling flags
991 for (let i
of ['w','b'])
993 for (let j
=0; j
<2; j
++)
994 fen
+= this.castleFlags
[i
][j
] ? '1' : '0';
999 // Context: just before move is played, turn hasn't changed
1002 if (move.appear
.length
== 2 && move.appear
[0].p
== VariantRules
.KING
)
1005 if (move.end
.y
< move.start
.y
)
1011 // Translate final square
1013 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1015 const piece
= this.getPiece(move.start
.x
, move.start
.y
);
1016 if (piece
== VariantRules
.PAWN
)
1020 if (move.vanish
.length
> move.appear
.length
)
1023 const startColumn
= String
.fromCharCode(97 + move.start
.y
);
1024 notation
= startColumn
+ "x" + finalSquare
;
1027 notation
= finalSquare
;
1028 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1029 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1036 return piece
.toUpperCase() +
1037 (move.vanish
.length
> move.appear
.length
? "x" : "") + finalSquare
;
1041 // The score is already computed when calling this function
1042 getPGN(mycolor
, score
, fenStart
, mode
)
1045 pgn
+= '[Site "vchess.club"]<br>';
1046 const d
= new Date();
1047 const opponent
= mode
=="human" ? "Anonymous" : "Computer";
1048 pgn
+= '[Variant "' + variant
+ '"]<br>';
1049 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) + '-' + d
.getDate() + '"]<br>';
1050 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1051 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1052 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1053 pgn
+= '[Result "' + score
+ '"]<br><br>';
1055 for (let i
=0; i
<this.moves
.length
; i
++)
1058 pgn
+= ((i
/2)+1) + ".";
1059 pgn
+= this.moves
[i
].notation
+ " ";