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
);
55 this.flags
= VariantRules
.GetFlags(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
++)
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
&& this.board
[i
][j
] == VariantRules
.EMPTY
)
273 moves
.push(this.getBasicMove(x
, y
, i
, j
));
274 if (oneStep
!== undefined)
279 if (i
>=0 && i
<8 && j
>=0 && j
<8 && this.canTake(color
, this.getColor(i
,j
)))
280 moves
.push(this.getBasicMove(x
, y
, i
, j
));
285 // What are the pawn moves from square x,y considering color "color" ?
286 getPotentialPawnMoves(x
, y
, color
)
289 var V
= VariantRules
;
290 let [sizeX
,sizeY
] = VariantRules
.size
;
291 let shift
= (color
== "w" ? -1 : 1);
292 let startRank
= (color
== "w" ? sizeY
-2 : 1);
293 let lastRank
= (color
== "w" ? 0 : sizeY
-1);
295 if (x
+shift
>= 0 && x
+shift
< sizeX
&& x
+shift
!= lastRank
)
298 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
300 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
));
301 if (x
==startRank
&& this.board
[x
+2*shift
][y
] == V
.EMPTY
)
304 moves
.push(this.getBasicMove(x
, y
, x
+2*shift
, y
));
308 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
309 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
311 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1));
313 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
314 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
316 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1));
320 if (x
+shift
== lastRank
)
323 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
324 promotionPieces
.forEach(p
=> {
326 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
327 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
, p
));
329 if (y
>0 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
-1))
330 && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
332 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
-1, p
));
334 if (y
<sizeY
-1 && this.canTake(this.getColor(x
,y
), this.getColor(x
+shift
,y
+1))
335 && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
337 moves
.push(this.getBasicMove(x
, y
, x
+shift
, y
+1, 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(x
, y
, color
)
364 return this.getSlideNJumpMoves(
365 x
, y
, color
, VariantRules
.steps
[VariantRules
.ROOK
]);
368 // What are the knight moves from square x,y ?
369 getPotentialKnightMoves(x
, y
, color
)
371 return this.getSlideNJumpMoves(
372 x
, y
, color
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
375 // What are the bishop moves from square x,y ?
376 getPotentialBishopMoves(x
, y
, color
)
378 return this.getSlideNJumpMoves(
379 x
, y
, color
, VariantRules
.steps
[VariantRules
.BISHOP
]);
382 // What are the queen moves from square x,y ?
383 getPotentialQueenMoves(x
, y
, color
)
385 return this.getSlideNJumpMoves(
386 x
, y
, color
, VariantRules
.steps
[VariantRules
.QUEEN
]);
389 // What are the king moves from square x,y ?
390 getPotentialKingMoves(x
, y
, c
)
392 // Initialize with normal moves
393 var moves
= this.getSlideNJumpMoves(x
, y
, c
,
394 VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
396 return moves
.concat(this.getCastleMoves(x
,y
,c
));
399 getCastleMoves(x
,y
,c
)
401 if (x
!= (c
=="w" ? 7 : 0) || y
!= this.INIT_COL_KING
[c
])
402 return []; //x isn't first rank, or king has moved (shortcut)
404 const V
= VariantRules
;
407 const oppCol
= this.getOppCol(c
);
410 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
412 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
414 if (!this.flags
[c
][castleSide
])
416 // If this code is reached, rooks and king are on initial position
418 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
419 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
420 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
422 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
423 // NOTE: next check is enough, because of chessboard constraints
424 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
426 continue castlingCheck
;
430 // Nothing on the path to the rook?
431 step
= castleSide
== 0 ? -1 : 1;
432 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
434 if (this.board
[x
][i
] != V
.EMPTY
)
435 continue castlingCheck
;
437 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
439 // Nothing on final squares, except maybe king and castling rook?
442 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
443 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
444 finalSquares
[castleSide
][i
] != rookPos
)
446 continue castlingCheck
;
450 // If this code is reached, castle is valid
451 moves
.push( new Move({
453 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
454 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
456 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
457 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
458 end: Math
.abs(y
- rookPos
) <= 2
460 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
472 return ((color
=='w' && this.moves
.length
%2==0)
473 || (color
=='b' && this.moves
.length
%2==1))
474 && this.getColor(sq
[0], sq
[1]) == color
;
477 getPossibleMovesFrom(sq
)
479 // Assuming color is right (already checked)
480 return this.filterValid( this.getPotentialMovesFrom(sq
) );
483 // TODO: once a promotion is filtered, the others results are same: useless computations
486 if (moves
.length
== 0)
488 let color
= this.getColor( moves
[0].start
.x
, moves
[0].start
.y
);
489 return moves
.filter(m
=> {
490 return !this.underCheck(m
, color
);
494 // Search for all valid moves considering current turn (for engine and game end)
495 getAllValidMoves(color
)
497 const oppCol
= this.getOppCol(color
);
498 var potentialMoves
= [];
499 let [sizeX
,sizeY
] = VariantRules
.size
;
500 for (var i
=0; i
<sizeX
; i
++)
502 for (var j
=0; j
<sizeY
; j
++)
504 // Next condition ... != oppCol is a little HACK to work with checkered variant
505 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
506 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
509 // NOTE: prefer lazy undercheck tests, letting the king being taken?
510 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
511 return this.filterValid(potentialMoves
);
514 // Stop at the first move found
515 atLeastOneMove(color
)
517 const oppCol
= this.getOppCol(color
);
518 let [sizeX
,sizeY
] = VariantRules
.size
;
519 for (var i
=0; i
<sizeX
; i
++)
521 for (var j
=0; j
<sizeY
; j
++)
523 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
525 const moves
= this.getPotentialMovesFrom([i
,j
]);
526 if (moves
.length
> 0)
528 for (let i
=0; i
<moves
.length
; i
++)
530 if (this.filterValid([moves
[i
]]).length
> 0)
540 // Check if pieces of color 'color' are attacking square x,y
541 isAttacked(sq
, color
)
543 return (this.isAttackedByPawn(sq
, color
)
544 || this.isAttackedByRook(sq
, color
)
545 || this.isAttackedByKnight(sq
, color
)
546 || this.isAttackedByBishop(sq
, color
)
547 || this.isAttackedByQueen(sq
, color
)
548 || this.isAttackedByKing(sq
, color
));
551 // Is square x,y attacked by pawns of color c ?
552 isAttackedByPawn([x
,y
], c
)
554 let pawnShift
= (c
=="w" ? 1 : -1);
555 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
557 for (let i
of [-1,1])
559 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
560 && this.getColor(x
+pawnShift
,y
+i
)==c
)
569 // Is square x,y attacked by rooks of color c ?
570 isAttackedByRook(sq
, color
)
572 return this.isAttackedBySlideNJump(sq
, color
,
573 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
576 // Is square x,y attacked by knights of color c ?
577 isAttackedByKnight(sq
, color
)
579 return this.isAttackedBySlideNJump(sq
, color
,
580 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
583 // Is square x,y attacked by bishops of color c ?
584 isAttackedByBishop(sq
, color
)
586 return this.isAttackedBySlideNJump(sq
, color
,
587 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
590 // Is square x,y attacked by queens of color c ?
591 isAttackedByQueen(sq
, color
)
593 return this.isAttackedBySlideNJump(sq
, color
,
594 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
597 // Is square x,y attacked by king of color c ?
598 isAttackedByKing(sq
, color
)
600 return this.isAttackedBySlideNJump(sq
, color
,
601 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
604 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
605 isAttackedBySlideNJump([x
,y
], c
,piece
,steps
,oneStep
)
607 for (let step
of steps
)
609 let rx
= x
+step
[0], ry
= y
+step
[1];
610 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
616 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
617 && this.getPiece(rx
,ry
) == piece
&& this.getColor(rx
,ry
) == c
)
625 // Is color c under check after move ?
629 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
));
634 // On which squares is color c under check (after move) ?
635 getCheckSquares(move, c
)
638 let res
= this.isAttacked(this.kingPos
[c
], this.getOppCol(c
))
639 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[c
])) ] //need to duplicate!
645 // Apply a move on board
646 static PlayOnBoard(board
, move)
648 for (let psq
of move.vanish
)
649 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
650 for (let psq
of move.appear
)
651 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
653 // Un-apply the played move
654 static UndoOnBoard(board
, move)
656 for (let psq
of move.appear
)
657 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
658 for (let psq
of move.vanish
)
659 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
662 // Before move is played, update variables + flags
663 updateVariables(move)
665 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
666 const c
= this.getColor(move.start
.x
,move.start
.y
);
667 const firstRank
= (c
== "w" ? 7 : 0);
669 // Update king position + flags
670 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
672 this.kingPos
[c
][0] = move.appear
[0].x
;
673 this.kingPos
[c
][1] = move.appear
[0].y
;
674 this.flags
[c
] = [false,false];
677 const oppCol
= this.getOppCol(c
);
678 const oppFirstRank
= 7 - firstRank
;
679 if (move.start
.x
== firstRank
//our rook moves?
680 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
682 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
683 this.flags
[c
][flagIdx
] = false;
685 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
686 && this.INIT_COL_ROOK
[c
].includes(move.end
.y
))
688 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
689 this.flags
[oppCol
][flagIdx
] = false;
693 unupdateVariables(move)
695 // (Potentially) Reset king position
696 const c
= this.getColor(move.start
.x
,move.start
.y
);
697 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
698 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
704 move.notation
= this.getNotation(move);
706 // Save flags (for undo)
707 move.flags
= JSON
.stringify(this.flags
); //TODO: less costly?
708 this.updateVariables(move);
709 this.moves
.push(move);
710 this.epSquares
.push( this.getEpSquare(move) );
711 VariantRules
.PlayOnBoard(this.board
, move);
716 VariantRules
.UndoOnBoard(this.board
, move);
717 this.epSquares
.pop();
719 this.unupdateVariables(move);
720 this.flags
= JSON
.parse(move.flags
);
728 // Check for 3 repetitions
729 if (this.moves
.length
>= 8)
731 // NOTE: crude detection, only moves repetition
732 const L
= this.moves
.length
;
733 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
734 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
735 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
736 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
738 return "1/2 (repetition)";
742 if (this.atLeastOneMove(color
))
749 return this.checkGameEnd(color
);
752 // Useful stand-alone for engine
755 // No valid move: stalemate or checkmate?
756 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
759 return color
== "w" ? "0-1" : "1-0";
766 static get VALUES() {
777 // Assumption: at least one legal move
778 getComputerMove(color
)
780 const oppCol
= this.getOppCol(color
);
782 // Rank moves using a min-max at depth 2
783 let moves1
= this.getAllValidMoves(color
);
785 for (let i
=0; i
<moves1
.length
; i
++)
787 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
788 let eval2
= (color
=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
789 this.play(moves1
[i
]);
791 let moves2
= this.getAllValidMoves(oppCol
);
792 // If no possible moves AND underCheck, eval2 is correct.
793 // If !underCheck, eval2 is 0 (stalemate).
794 if (moves2
.length
== 0 && this.checkGameEnd(oppCol
) == "1/2")
796 for (let j
=0; j
<moves2
.length
; j
++)
798 this.play(moves2
[j
]);
799 let evalPos
= this.evalPosition();
800 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
802 this.undo(moves2
[j
]);
804 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
805 moves1
[i
].eval
= eval2
;
806 this.undo(moves1
[i
]);
808 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
810 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
811 for (let i
=0; i
<moves1
.length
; i
++)
813 this.play(moves1
[i
]);
814 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
815 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+ this.alphabeta(oppCol
, color
, 2, -1000, 1000);
816 this.undo(moves1
[i
]);
818 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
820 let candidates
= [0]; //indices of candidates moves
821 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
824 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
825 return moves1
[_
.sample(candidates
, 1)];
828 alphabeta(color
, oppCol
, depth
, alpha
, beta
)
830 if (!this.atLeastOneMove(color
))
832 switch (this.checkGameEnd(color
))
834 case "1/2": return 0;
835 default: return color
=="w" ? -1000 : 1000;
839 return this.evalPosition();
840 const moves
= this.getAllValidMoves(color
);
841 let v
= color
=="w" ? -1000 : 1000;
844 for (let i
=0; i
<moves
.length
; i
++)
847 v
= Math
.max(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
849 alpha
= Math
.max(alpha
, v
);
856 for (let i
=0; i
<moves
.length
; i
++)
859 v
= Math
.min(v
, this.alphabeta(oppCol
, color
, depth
-1, alpha
, beta
));
861 beta
= Math
.min(beta
, v
);
863 break; //alpha cutoff
871 const [sizeX
,sizeY
] = VariantRules
.size
;
873 //Just count material for now
874 for (let i
=0; i
<sizeX
; i
++)
876 for (let j
=0; j
<sizeY
; j
++)
878 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
880 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
881 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
892 static GenRandInitFen()
894 let pieces
= [new Array(8), new Array(8)];
895 // Shuffle pieces on first and last rank
896 for (let c
= 0; c
<= 1; c
++)
898 let positions
= _
.range(8);
900 // Get random squares for bishops
901 let randIndex
= 2 * _
.random(3);
902 let bishop1Pos
= positions
[randIndex
];
903 // The second bishop must be on a square of different color
904 let randIndex_tmp
= 2 * _
.random(3) + 1;
905 let bishop2Pos
= positions
[randIndex_tmp
];
906 // Remove chosen squares
907 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
908 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
910 // Get random squares for knights
911 randIndex
= _
.random(5);
912 let knight1Pos
= positions
[randIndex
];
913 positions
.splice(randIndex
, 1);
914 randIndex
= _
.random(4);
915 let knight2Pos
= positions
[randIndex
];
916 positions
.splice(randIndex
, 1);
918 // Get random square for queen
919 randIndex
= _
.random(3);
920 let queenPos
= positions
[randIndex
];
921 positions
.splice(randIndex
, 1);
923 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
924 let rook1Pos
= positions
[0];
925 let kingPos
= positions
[1];
926 let rook2Pos
= positions
[2];
928 // Finally put the shuffled pieces in the board array
929 pieces
[c
][rook1Pos
] = 'r';
930 pieces
[c
][knight1Pos
] = 'n';
931 pieces
[c
][bishop1Pos
] = 'b';
932 pieces
[c
][queenPos
] = 'q';
933 pieces
[c
][kingPos
] = 'k';
934 pieces
[c
][bishop2Pos
] = 'b';
935 pieces
[c
][knight2Pos
] = 'n';
936 pieces
[c
][rook2Pos
] = 'r';
938 let fen
= pieces
[0].join("") +
939 "/pppppppp/8/8/8/8/PPPPPPPP/" +
940 pieces
[1].join("").toUpperCase() +
945 // Return current fen according to pieces+colors state
948 return this.getBaseFen() + " " + this.getFlagsFen();
954 let [sizeX
,sizeY
] = VariantRules
.size
;
955 for (let i
=0; i
<sizeX
; i
++)
958 for (let j
=0; j
<sizeY
; j
++)
960 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
966 // Add empty squares in-between
970 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
979 fen
+= "/"; //separate rows
988 // Add castling flags
989 for (let i
of ['w','b'])
991 for (let j
=0; j
<2; j
++)
992 fen
+= this.flags
[i
][j
] ? '1' : '0';
997 // Context: just before move is played, turn hasn't changed
1000 if (move.appear
.length
== 2)
1003 if (move.end
.y
< move.start
.y
)
1009 // Translate final square
1011 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1013 let piece
= this.getPiece(move.start
.x
, move.start
.y
);
1014 if (piece
== VariantRules
.PAWN
)
1018 if (move.vanish
.length
> 1)
1021 let startColumn
= String
.fromCharCode(97 + move.start
.y
);
1022 notation
= startColumn
+ "x" + finalSquare
;
1025 notation
= finalSquare
;
1026 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1027 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1034 return piece
.toUpperCase() + (move.vanish
.length
> 1 ? "x" : "") + finalSquare
;
1038 // The score is already computed when calling this function
1039 getPGN(mycolor
, score
, fenStart
, mode
)
1042 pgn
+= '[Site "vchess.club"]<br>';
1043 const d
= new Date();
1044 const opponent
= this.mode
=="human" ? "Anonymous" : "Computer";
1045 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) + '-' + d
.getDate() + '"]<br>';
1046 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1047 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<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
+ " ";