0868a3670178e8a855786f9b422f9d38ca52478b
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 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 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 thing on square1 take thing on square2
194 canTake([x1
,y1
], [x2
,y2
])
196 return this.getColor(x1
,y1
) != this.getColor(x2
,y2
);
202 // All possible moves from selected square (assumption: color is OK)
203 getPotentialMovesFrom([x
,y
])
205 switch (this.getPiece(x
,y
))
207 case VariantRules
.PAWN:
208 return this.getPotentialPawnMoves([x
,y
]);
209 case VariantRules
.ROOK:
210 return this.getPotentialRookMoves([x
,y
]);
211 case VariantRules
.KNIGHT:
212 return this.getPotentialKnightMoves([x
,y
]);
213 case VariantRules
.BISHOP:
214 return this.getPotentialBishopMoves([x
,y
]);
215 case VariantRules
.QUEEN:
216 return this.getPotentialQueenMoves([x
,y
]);
217 case VariantRules
.KING:
218 return this.getPotentialKingMoves([x
,y
]);
222 // Build a regular move from its initial and destination squares; tr: transformation
223 getBasicMove([sx
,sy
], [ex
,ey
], tr
)
230 c: !!tr
? tr
.c : this.getColor(sx
,sy
),
231 p: !!tr
? tr
.p : this.getPiece(sx
,sy
)
238 c: this.getColor(sx
,sy
),
239 p: this.getPiece(sx
,sy
)
244 // The opponent piece disappears if we take it
245 if (this.board
[ex
][ey
] != VariantRules
.EMPTY
)
251 c: this.getColor(ex
,ey
),
252 p: this.getPiece(ex
,ey
)
259 // Generic method to find possible moves of non-pawn pieces ("sliding or jumping")
260 getSlideNJumpMoves([x
,y
], steps
, oneStep
)
262 const color
= this.getColor(x
,y
);
264 const [sizeX
,sizeY
] = VariantRules
.size
;
266 for (let step
of steps
)
270 while (i
>=0 && i
<sizeX
&& j
>=0 && j
<sizeY
&& this.board
[i
][j
] == VariantRules
.EMPTY
)
272 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
273 if (oneStep
!== undefined)
278 if (i
>=0 && i
<8 && j
>=0 && j
<8 && this.canTake([x
,y
], [i
,j
]))
279 moves
.push(this.getBasicMove([x
,y
], [i
,j
]));
284 // What are the pawn moves from square x,y considering color "color" ?
285 getPotentialPawnMoves([x
,y
])
287 const color
= this.getColor(x
,y
);
289 var V
= VariantRules
;
290 const [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([x
,y
], [x
+shift
,y
-1]) && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
309 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1]));
310 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1]) && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
311 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1]));
314 if (x
+shift
== lastRank
)
317 let promotionPieces
= [V
.ROOK
,V
.KNIGHT
,V
.BISHOP
,V
.QUEEN
];
318 promotionPieces
.forEach(p
=> {
320 if (this.board
[x
+shift
][y
] == V
.EMPTY
)
321 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
], {c:color
,p:p
}));
323 if (y
>0 && this.canTake([x
,y
], [x
+shift
,y
-1]) && this.board
[x
+shift
][y
-1] != V
.EMPTY
)
324 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
-1], {c:color
,p:p
}));
325 if (y
<sizeY
-1 && this.canTake([x
,y
], [x
+shift
,y
+1]) && this.board
[x
+shift
][y
+1] != V
.EMPTY
)
326 moves
.push(this.getBasicMove([x
,y
], [x
+shift
,y
+1], {c:color
,p:p
}));
331 const Lep
= this.epSquares
.length
;
332 const epSquare
= Lep
>0 ? this.epSquares
[Lep
-1] : undefined;
333 if (!!epSquare
&& epSquare
.x
== x
+shift
&& Math
.abs(epSquare
.y
- y
) == 1)
335 let epStep
= epSquare
.y
- y
;
336 var enpassantMove
= this.getBasicMove([x
,y
], [x
+shift
,y
+epStep
]);
337 enpassantMove
.vanish
.push({
341 c: this.getColor(x
,y
+epStep
)
343 moves
.push(enpassantMove
);
349 // What are the rook moves from square x,y ?
350 getPotentialRookMoves(sq
)
352 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.ROOK
]);
355 // What are the knight moves from square x,y ?
356 getPotentialKnightMoves(sq
)
358 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
361 // What are the bishop moves from square x,y ?
362 getPotentialBishopMoves(sq
)
364 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.BISHOP
]);
367 // What are the queen moves from square x,y ?
368 getPotentialQueenMoves(sq
)
370 return this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.QUEEN
]);
373 // What are the king moves from square x,y ?
374 getPotentialKingMoves(sq
)
376 // Initialize with normal moves
377 let moves
= this.getSlideNJumpMoves(sq
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
378 return moves
.concat(this.getCastleMoves(sq
));
381 getCastleMoves([x
,y
])
383 const c
= this.getColor(x
,y
);
384 if (x
!= (c
=="w" ? 7 : 0) || y
!= this.INIT_COL_KING
[c
])
385 return []; //x isn't first rank, or king has moved (shortcut)
387 const V
= VariantRules
;
390 const oppCol
= this.getOppCol(c
);
393 const finalSquares
= [ [2,3], [6,5] ]; //king, then rook
395 for (let castleSide
=0; castleSide
< 2; castleSide
++) //large, then small
397 if (!this.flags
[c
][castleSide
])
399 // If this code is reached, rooks and king are on initial position
401 // Nothing on the path of the king (and no checks; OK also if y==finalSquare)?
402 let step
= finalSquares
[castleSide
][0] < y
? -1 : 1;
403 for (i
=y
; i
!=finalSquares
[castleSide
][0]; i
+=step
)
405 if (this.isAttacked([x
,i
], oppCol
) || (this.board
[x
][i
] != V
.EMPTY
&&
406 // NOTE: next check is enough, because of chessboard constraints
407 (this.getColor(x
,i
) != c
|| ![V
.KING
,V
.ROOK
].includes(this.getPiece(x
,i
)))))
409 continue castlingCheck
;
413 // Nothing on the path to the rook?
414 step
= castleSide
== 0 ? -1 : 1;
415 for (i
= y
+ step
; i
!= this.INIT_COL_ROOK
[c
][castleSide
]; i
+= step
)
417 if (this.board
[x
][i
] != V
.EMPTY
)
418 continue castlingCheck
;
420 const rookPos
= this.INIT_COL_ROOK
[c
][castleSide
];
422 // Nothing on final squares, except maybe king and castling rook?
425 if (this.board
[x
][finalSquares
[castleSide
][i
]] != V
.EMPTY
&&
426 this.getPiece(x
,finalSquares
[castleSide
][i
]) != V
.KING
&&
427 finalSquares
[castleSide
][i
] != rookPos
)
429 continue castlingCheck
;
433 // If this code is reached, castle is valid
434 moves
.push( new Move({
436 new PiPo({x:x
,y:finalSquares
[castleSide
][0],p:V
.KING
,c:c
}),
437 new PiPo({x:x
,y:finalSquares
[castleSide
][1],p:V
.ROOK
,c:c
})],
439 new PiPo({x:x
,y:y
,p:V
.KING
,c:c
}),
440 new PiPo({x:x
,y:rookPos
,p:V
.ROOK
,c:c
})],
441 end: Math
.abs(y
- rookPos
) <= 2
443 : {x:x
, y:y
+ 2 * (castleSide
==0 ? -1 : 1)}
453 canIplay(side
, [x
,y
])
455 return ((side
=='w' && this.moves
.length
%2==0) || (side
=='b' && this.moves
.length
%2==1))
456 && this.getColor(x
,y
) == side
;
459 getPossibleMovesFrom(sq
)
461 // Assuming color is right (already checked)
462 return this.filterValid( this.getPotentialMovesFrom(sq
) );
465 // TODO: once a promotion is filtered, the others results are same: useless computations
468 if (moves
.length
== 0)
470 let color
= this.turn
;
471 return moves
.filter(m
=> { return !this.underCheck(m
, color
); });
474 // Search for all valid moves considering current turn (for engine and game end)
477 const color
= this.turn
;
478 const oppCol
= this.getOppCol(color
);
479 var potentialMoves
= [];
480 let [sizeX
,sizeY
] = VariantRules
.size
;
481 for (var i
=0; i
<sizeX
; i
++)
483 for (var j
=0; j
<sizeY
; j
++)
485 // Next condition ... != oppCol is a little HACK to work with checkered variant
486 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
487 Array
.prototype.push
.apply(potentialMoves
, this.getPotentialMovesFrom([i
,j
]));
490 // NOTE: prefer lazy undercheck tests, letting the king being taken?
491 // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals
492 return this.filterValid(potentialMoves
);
495 // Stop at the first move found
498 const color
= this.turn
;
499 const oppCol
= this.getOppCol(color
);
500 let [sizeX
,sizeY
] = VariantRules
.size
;
501 for (var i
=0; i
<sizeX
; i
++)
503 for (var j
=0; j
<sizeY
; j
++)
505 if (this.board
[i
][j
] != VariantRules
.EMPTY
&& this.getColor(i
,j
) != oppCol
)
507 const moves
= this.getPotentialMovesFrom([i
,j
]);
508 if (moves
.length
> 0)
510 for (let i
=0; i
<moves
.length
; i
++)
512 if (this.filterValid([moves
[i
]]).length
> 0)
522 // Check if pieces of color 'colors' are attacking square x,y
523 isAttacked(sq
, colors
)
525 return (this.isAttackedByPawn(sq
, colors
)
526 || this.isAttackedByRook(sq
, colors
)
527 || this.isAttackedByKnight(sq
, colors
)
528 || this.isAttackedByBishop(sq
, colors
)
529 || this.isAttackedByQueen(sq
, colors
)
530 || this.isAttackedByKing(sq
, colors
));
533 // Is square x,y attacked by pawns of color c ?
534 isAttackedByPawn([x
,y
], colors
)
536 for (let c
of colors
)
538 let pawnShift
= (c
=="w" ? 1 : -1);
539 if (x
+pawnShift
>=0 && x
+pawnShift
<8)
541 for (let i
of [-1,1])
543 if (y
+i
>=0 && y
+i
<8 && this.getPiece(x
+pawnShift
,y
+i
)==VariantRules
.PAWN
544 && this.getColor(x
+pawnShift
,y
+i
)==c
)
554 // Is square x,y attacked by rooks of color c ?
555 isAttackedByRook(sq
, colors
)
557 return this.isAttackedBySlideNJump(sq
, colors
,
558 VariantRules
.ROOK
, VariantRules
.steps
[VariantRules
.ROOK
]);
561 // Is square x,y attacked by knights of color c ?
562 isAttackedByKnight(sq
, colors
)
564 return this.isAttackedBySlideNJump(sq
, colors
,
565 VariantRules
.KNIGHT
, VariantRules
.steps
[VariantRules
.KNIGHT
], "oneStep");
568 // Is square x,y attacked by bishops of color c ?
569 isAttackedByBishop(sq
, colors
)
571 return this.isAttackedBySlideNJump(sq
, colors
,
572 VariantRules
.BISHOP
, VariantRules
.steps
[VariantRules
.BISHOP
]);
575 // Is square x,y attacked by queens of color c ?
576 isAttackedByQueen(sq
, colors
)
578 return this.isAttackedBySlideNJump(sq
, colors
,
579 VariantRules
.QUEEN
, VariantRules
.steps
[VariantRules
.QUEEN
]);
582 // Is square x,y attacked by king of color c ?
583 isAttackedByKing(sq
, colors
)
585 return this.isAttackedBySlideNJump(sq
, colors
,
586 VariantRules
.KING
, VariantRules
.steps
[VariantRules
.QUEEN
], "oneStep");
589 // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ?
590 isAttackedBySlideNJump([x
,y
], colors
, piece
, steps
, oneStep
)
592 for (let step
of steps
)
594 let rx
= x
+step
[0], ry
= y
+step
[1];
595 while (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] == VariantRules
.EMPTY
601 if (rx
>=0 && rx
<8 && ry
>=0 && ry
<8 && this.board
[rx
][ry
] != VariantRules
.EMPTY
602 && this.getPiece(rx
,ry
) == piece
&& colors
.includes(this.getColor(rx
,ry
)))
610 // Is color c under check after move ?
613 const color
= this.turn
;
615 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
));
620 // On which squares is color c under check (after move) ?
621 getCheckSquares(move)
624 const color
= this.turn
;
625 let res
= this.isAttacked(this.kingPos
[color
], this.getOppCol(color
))
626 ? [ JSON
.parse(JSON
.stringify(this.kingPos
[color
])) ] //need to duplicate!
632 // Apply a move on board
633 static PlayOnBoard(board
, move)
635 for (let psq
of move.vanish
)
636 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
637 for (let psq
of move.appear
)
638 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
640 // Un-apply the played move
641 static UndoOnBoard(board
, move)
643 for (let psq
of move.appear
)
644 board
[psq
.x
][psq
.y
] = VariantRules
.EMPTY
;
645 for (let psq
of move.vanish
)
646 board
[psq
.x
][psq
.y
] = psq
.c
+ psq
.p
;
649 // Before move is played, update variables + flags
650 updateVariables(move)
652 const piece
= this.getPiece(move.start
.x
,move.start
.y
);
653 const c
= this.getColor(move.start
.x
,move.start
.y
);
654 const firstRank
= (c
== "w" ? 7 : 0);
656 // Update king position + flags
657 if (piece
== VariantRules
.KING
&& move.appear
.length
> 0)
659 this.kingPos
[c
][0] = move.appear
[0].x
;
660 this.kingPos
[c
][1] = move.appear
[0].y
;
661 this.flags
[c
] = [false,false];
664 const oppCol
= this.getOppCol(c
);
665 const oppFirstRank
= 7 - firstRank
;
666 if (move.start
.x
== firstRank
//our rook moves?
667 && this.INIT_COL_ROOK
[c
].includes(move.start
.y
))
669 const flagIdx
= move.start
.y
== this.INIT_COL_ROOK
[c
][0] ? 0 : 1;
670 this.flags
[c
][flagIdx
] = false;
672 else if (move.end
.x
== oppFirstRank
//we took opponent rook?
673 && this.INIT_COL_ROOK
[c
].includes(move.end
.y
))
675 const flagIdx
= move.end
.y
== this.INIT_COL_ROOK
[oppCol
][0] ? 0 : 1;
676 this.flags
[oppCol
][flagIdx
] = false;
680 unupdateVariables(move)
682 // (Potentially) Reset king position
683 const c
= this.getColor(move.start
.x
,move.start
.y
);
684 if (this.getPiece(move.start
.x
,move.start
.y
) == VariantRules
.KING
)
685 this.kingPos
[c
] = [move.start
.x
, move.start
.y
];
691 move.notation
= this.getNotation(move);
693 // Save flags (for undo)
694 move.flags
= JSON
.stringify(this.flags
); //TODO: less costly?
695 this.updateVariables(move);
696 this.moves
.push(move);
697 this.epSquares
.push( this.getEpSquare(move) );
698 VariantRules
.PlayOnBoard(this.board
, move);
703 VariantRules
.UndoOnBoard(this.board
, move);
704 this.epSquares
.pop();
706 this.unupdateVariables(move);
707 this.flags
= JSON
.parse(move.flags
);
715 // Check for 3 repetitions
716 if (this.moves
.length
>= 8)
718 // NOTE: crude detection, only moves repetition
719 const L
= this.moves
.length
;
720 if (_
.isEqual(this.moves
[L
-1], this.moves
[L
-5]) &&
721 _
.isEqual(this.moves
[L
-2], this.moves
[L
-6]) &&
722 _
.isEqual(this.moves
[L
-3], this.moves
[L
-7]) &&
723 _
.isEqual(this.moves
[L
-4], this.moves
[L
-8]))
725 return "1/2 (repetition)";
729 if (this.atLeastOneMove())
736 return this.checkGameEnd();
739 // No moves are possible: compute score
742 const color
= this.turn
;
743 // No valid move: stalemate or checkmate?
744 if (!this.isAttacked(this.kingPos
[color
], this.getOppCol(color
)))
747 return color
== "w" ? "0-1" : "1-0";
754 static get VALUES() {
765 // Assumption: at least one legal move
768 const color
= this.turn
;
770 // Rank moves using a min-max at depth 2
771 let moves1
= this.getAllValidMoves();
773 for (let i
=0; i
<moves1
.length
; i
++)
775 moves1
[i
].eval
= (color
=="w" ? -1 : 1) * 1000; //very low, I'm checkmated
776 let eval2
= (color
=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value
777 this.play(moves1
[i
]);
779 let moves2
= this.getAllValidMoves();
780 // If no possible moves AND underCheck, eval2 is correct.
781 // If !underCheck, eval2 is 0 (stalemate).
782 if (moves2
.length
== 0 && this.checkGameEnd() == "1/2")
784 for (let j
=0; j
<moves2
.length
; j
++)
786 this.play(moves2
[j
]);
787 let evalPos
= this.evalPosition();
788 if ((color
== "w" && evalPos
< eval2
) || (color
=="b" && evalPos
> eval2
))
790 this.undo(moves2
[j
]);
792 if ((color
=="w" && eval2
> moves1
[i
].eval
) || (color
=="b" && eval2
< moves1
[i
].eval
))
793 moves1
[i
].eval
= eval2
;
794 this.undo(moves1
[i
]);
796 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
798 // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0])
799 for (let i
=0; i
<moves1
.length
; i
++)
801 this.play(moves1
[i
]);
802 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
803 moves1
[i
].eval
= 0.1*moves1
[i
].eval
+ this.alphabeta(2, -1000, 1000);
804 this.undo(moves1
[i
]);
806 moves1
.sort( (a
,b
) => { return (color
=="w" ? 1 : -1) * (b
.eval
- a
.eval
); });
808 let candidates
= [0]; //indices of candidates moves
809 for (let j
=1; j
<moves1
.length
&& moves1
[j
].eval
== moves1
[0].eval
; j
++)
812 //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
813 return moves1
[_
.sample(candidates
, 1)];
816 alphabeta(depth
, alpha
, beta
)
818 const color
= this.turn
;
819 if (!this.atLeastOneMove())
821 switch (this.checkGameEnd())
823 case "1/2": return 0;
824 default: return color
=="w" ? -1000 : 1000;
828 return this.evalPosition();
829 const moves
= this.getAllValidMoves();
830 let v
= color
=="w" ? -1000 : 1000;
833 for (let i
=0; i
<moves
.length
; i
++)
836 v
= Math
.max(v
, this.alphabeta(depth
-1, alpha
, beta
));
838 alpha
= Math
.max(alpha
, v
);
845 for (let i
=0; i
<moves
.length
; i
++)
848 v
= Math
.min(v
, this.alphabeta(depth
-1, alpha
, beta
));
850 beta
= Math
.min(beta
, v
);
852 break; //alpha cutoff
860 const [sizeX
,sizeY
] = VariantRules
.size
;
862 //Just count material for now
863 for (let i
=0; i
<sizeX
; i
++)
865 for (let j
=0; j
<sizeY
; j
++)
867 if (this.board
[i
][j
] != VariantRules
.EMPTY
)
869 const sign
= this.getColor(i
,j
) == "w" ? 1 : -1;
870 evaluation
+= sign
* VariantRules
.VALUES
[this.getPiece(i
,j
)];
881 static GenRandInitFen()
883 let pieces
= [new Array(8), new Array(8)];
884 // Shuffle pieces on first and last rank
885 for (let c
= 0; c
<= 1; c
++)
887 let positions
= _
.range(8);
889 // Get random squares for bishops
890 let randIndex
= 2 * _
.random(3);
891 let bishop1Pos
= positions
[randIndex
];
892 // The second bishop must be on a square of different color
893 let randIndex_tmp
= 2 * _
.random(3) + 1;
894 let bishop2Pos
= positions
[randIndex_tmp
];
895 // Remove chosen squares
896 positions
.splice(Math
.max(randIndex
,randIndex_tmp
), 1);
897 positions
.splice(Math
.min(randIndex
,randIndex_tmp
), 1);
899 // Get random squares for knights
900 randIndex
= _
.random(5);
901 let knight1Pos
= positions
[randIndex
];
902 positions
.splice(randIndex
, 1);
903 randIndex
= _
.random(4);
904 let knight2Pos
= positions
[randIndex
];
905 positions
.splice(randIndex
, 1);
907 // Get random square for queen
908 randIndex
= _
.random(3);
909 let queenPos
= positions
[randIndex
];
910 positions
.splice(randIndex
, 1);
912 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
913 let rook1Pos
= positions
[0];
914 let kingPos
= positions
[1];
915 let rook2Pos
= positions
[2];
917 // Finally put the shuffled pieces in the board array
918 pieces
[c
][rook1Pos
] = 'r';
919 pieces
[c
][knight1Pos
] = 'n';
920 pieces
[c
][bishop1Pos
] = 'b';
921 pieces
[c
][queenPos
] = 'q';
922 pieces
[c
][kingPos
] = 'k';
923 pieces
[c
][bishop2Pos
] = 'b';
924 pieces
[c
][knight2Pos
] = 'n';
925 pieces
[c
][rook2Pos
] = 'r';
927 let fen
= pieces
[0].join("") +
928 "/pppppppp/8/8/8/8/PPPPPPPP/" +
929 pieces
[1].join("").toUpperCase() +
934 // Return current fen according to pieces+colors state
937 return this.getBaseFen() + " " + this.getFlagsFen();
943 let [sizeX
,sizeY
] = VariantRules
.size
;
944 for (let i
=0; i
<sizeX
; i
++)
947 for (let j
=0; j
<sizeY
; j
++)
949 if (this.board
[i
][j
] == VariantRules
.EMPTY
)
955 // Add empty squares in-between
959 fen
+= VariantRules
.board2fen(this.board
[i
][j
]);
968 fen
+= "/"; //separate rows
977 // Add castling flags
978 for (let i
of ['w','b'])
980 for (let j
=0; j
<2; j
++)
981 fen
+= this.flags
[i
][j
] ? '1' : '0';
986 // Context: just before move is played, turn hasn't changed
989 if (move.appear
.length
== 2)
992 if (move.end
.y
< move.start
.y
)
998 // Translate final square
1000 String
.fromCharCode(97 + move.end
.y
) + (VariantRules
.size
[0]-move.end
.x
);
1002 let piece
= this.getPiece(move.start
.x
, move.start
.y
);
1003 if (piece
== VariantRules
.PAWN
)
1007 if (move.vanish
.length
> 1)
1010 let startColumn
= String
.fromCharCode(97 + move.start
.y
);
1011 notation
= startColumn
+ "x" + finalSquare
;
1014 notation
= finalSquare
;
1015 if (move.appear
.length
> 0 && piece
!= move.appear
[0].p
) //promotion
1016 notation
+= "=" + move.appear
[0].p
.toUpperCase();
1023 return piece
.toUpperCase() + (move.vanish
.length
> 1 ? "x" : "") + finalSquare
;
1027 // The score is already computed when calling this function
1028 getPGN(mycolor
, score
, fenStart
, mode
)
1031 pgn
+= '[Site "vchess.club"]<br>';
1032 const d
= new Date();
1033 const opponent
= this.mode
=="human" ? "Anonymous" : "Computer";
1034 pgn
+= '[Date "' + d
.getFullYear() + '-' + (d
.getMonth()+1) + '-' + d
.getDate() + '"]<br>';
1035 pgn
+= '[White "' + (mycolor
=='w'?'Myself':opponent
) + '"]<br>';
1036 pgn
+= '[Black "' + (mycolor
=='b'?'Myself':opponent
) + '"]<br>';
1037 pgn
+= '[Fen "' + fenStart
+ '"]<br>';
1038 pgn
+= '[Result "' + score
+ '"]<br><br>';
1040 for (let i
=0; i
<this.moves
.length
; i
++)
1043 pgn
+= ((i
/2)+1) + ".";
1044 pgn
+= this.moves
[i
].notation
+ " ";