Fix Chakart when landing piece on invisible queen + reserve pieces ordering
[vchess.git] / client / src / variants / Doublemove2.js
1 import { ChessRules } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export class Doublemove2Rules extends ChessRules {
5 static IsGoodEnpassant(enpassant) {
6 const squares = enpassant.split(",");
7 if (squares.length > 2) return false;
8 for (let sq of squares) {
9 if (sq != "-") {
10 const ep = V.SquareToCoords(sq);
11 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
12 }
13 }
14 return true;
15 }
16
17 // There may be 2 enPassant squares (if 2 pawns jump 2 squares in same turn)
18 getEnpassantFen() {
19 return this.epSquares[this.epSquares.length - 1].map(
20 epsq => epsq === undefined
21 ? "-" //no en-passant
22 : V.CoordsToSquare(epsq)
23 ).join(",");
24 }
25
26 setOtherVariables(fen) {
27 const parsedFen = V.ParseFen(fen);
28 this.setFlags(parsedFen.flags);
29 this.epSquares = [parsedFen.enpassant.split(",").map(sq => {
30 if (sq != "-") return V.SquareToCoords(sq);
31 return undefined;
32 })];
33 this.scanKings(fen);
34 // Extract subTurn from turn indicator: "w" (first move), or
35 // "w1" or "w2" white subturn 1 or 2, and same for black
36 this.turn = parsedFen.turn;
37 this.subTurn = 1;
38 }
39
40 getEnpassantCaptures([x, y], shiftX) {
41 let moves = [];
42 // En passant: always OK if subturn 1,
43 // OK on subturn 2 only if enPassant was played at subturn 1
44 // (and if there are two e.p. squares available).
45 const Lep = this.epSquares.length;
46 const epSquares = this.epSquares[Lep - 1]; //always at least one element
47 let epSqs = [];
48 epSquares.forEach(sq => {
49 if (sq) epSqs.push(sq);
50 });
51 if (epSqs.length == 0) return moves;
52 const oppCol = V.GetOppCol(this.getColor(x, y));
53 for (let sq of epSqs) {
54 if (
55 this.subTurn == 1 ||
56 (epSqs.length == 2 &&
57 // Was this en-passant capture already played at subturn 1 ?
58 // (Or maybe the opponent filled the en-passant square with a piece)
59 this.board[epSqs[0].x][epSqs[0].y] != V.EMPTY)
60 ) {
61 if (
62 sq.x == x + shiftX &&
63 Math.abs(sq.y - y) == 1 &&
64 // Add condition "enemy pawn must be present"
65 this.getPiece(x, sq.y) == V.PAWN &&
66 this.getColor(x, sq.y) == oppCol
67 ) {
68 let epMove = this.getBasicMove([x, y], [sq.x, sq.y]);
69 epMove.vanish.push({
70 x: x,
71 y: sq.y,
72 p: "p",
73 c: oppCol
74 });
75 moves.push(epMove);
76 }
77 }
78 }
79 return moves;
80 }
81
82 isAttacked() {
83 // Goal is king capture => no checks
84 return false;
85 }
86
87 filterValid(moves) {
88 return moves;
89 }
90
91 getCheckSquares() {
92 return [];
93 }
94
95 getCurrentScore() {
96 const color = this.turn;
97 if (this.kingPos[color][0] < 0) return (color == 'w' ? "0-1" : "1-0");
98 return "*";
99 }
100
101 play(move) {
102 move.flags = JSON.stringify(this.aggregateFlags());
103 V.PlayOnBoard(this.board, move);
104 const epSq = this.getEpSquare(move);
105 if (this.subTurn == 2) {
106 let lastEpsq = this.epSquares[this.epSquares.length - 1];
107 lastEpsq.push(epSq);
108 this.turn = V.GetOppCol(this.turn);
109 }
110 else {
111 this.epSquares.push([epSq]);
112 this.movesCount++;
113 if (this.movesCount == 1) this.turn = "b";
114 }
115 if (this.movesCount > 1) this.subTurn = 3 - this.subTurn;
116 this.postPlay(move);
117 }
118
119 postPlay(move) {
120 const c = move.vanish[0].c;
121 const piece = move.vanish[0].p;
122 const firstRank = c == "w" ? V.size.x - 1 : 0;
123
124 if (piece == V.KING && move.appear.length > 0) {
125 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
126 this.castleFlags[c] = [V.size.y, V.size.y];
127 return;
128 }
129 const oppCol = V.GetOppCol(c);
130 if (move.vanish.length == 2 && move.vanish[1].p == V.KING)
131 // Opponent's king is captured, game over
132 this.kingPos[oppCol] = [-1, -1];
133 const oppFirstRank = V.size.x - 1 - firstRank;
134 if (
135 move.start.x == firstRank && //our rook moves?
136 this.castleFlags[c].includes(move.start.y)
137 ) {
138 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
139 this.castleFlags[c][flagIdx] = V.size.y;
140 }
141 else if (
142 move.end.x == oppFirstRank && //we took opponent rook?
143 this.castleFlags[oppCol].includes(move.end.y)
144 ) {
145 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
146 this.castleFlags[oppCol][flagIdx] = V.size.y;
147 }
148 }
149
150 undo(move) {
151 this.disaggregateFlags(JSON.parse(move.flags));
152 V.UndoOnBoard(this.board, move);
153 if (this.subTurn == 2 || this.movesCount == 1) {
154 this.epSquares.pop();
155 this.movesCount--;
156 if (this.movesCount == 0) this.turn = "w";
157 }
158 else {
159 let lastEpsq = this.epSquares[this.epSquares.length - 1];
160 lastEpsq.pop();
161 this.turn = V.GetOppCol(this.turn);
162 }
163 if (this.movesCount > 0) this.subTurn = 3 - this.subTurn;
164 this.postUndo(move);
165 }
166
167 postUndo(move) {
168 if (move.vanish.length == 2 && move.vanish[1].p == V.KING)
169 // Opponent's king was captured
170 this.kingPos[move.vanish[1].c] = [move.vanish[1].x, move.vanish[1].y];
171 super.postUndo(move);
172 }
173
174 // No alpha-beta here, just adapted min-max at depth 2(+1)
175 getComputerMove() {
176 const maxeval = V.INFINITY;
177 const color = this.turn;
178 const oppCol = V.GetOppCol(this.turn);
179
180 // Search best (half) move for opponent turn
181 const getBestMoveEval = () => {
182 let score = this.getCurrentScore();
183 if (score != "*") return maxeval * (score == "1-0" ? 1 : -1);
184 let moves = this.getAllValidMoves();
185 let res = oppCol == "w" ? -maxeval : maxeval;
186 for (let m of moves) {
187 this.play(m);
188 score = this.getCurrentScore();
189 if (score != "*") {
190 // King captured
191 this.undo(m);
192 return maxeval * (score == "1-0" ? 1 : -1);
193 }
194 const evalPos = this.evalPosition();
195 res = oppCol == "w" ? Math.max(res, evalPos) : Math.min(res, evalPos);
196 this.undo(m);
197 }
198 return res;
199 };
200
201 const moves11 = this.getAllValidMoves();
202 if (this.movesCount == 0)
203 // First white move at random:
204 return moves11[randInt(moves11.length)];
205 let doubleMoves = [];
206 // Rank moves using a min-max at depth 2
207 for (let i = 0; i < moves11.length; i++) {
208 this.play(moves11[i]);
209 const moves12 = this.getAllValidMoves();
210 for (let j = 0; j < moves12.length; j++) {
211 this.play(moves12[j]);
212 doubleMoves.push({
213 moves: [moves11[i], moves12[j]],
214 // Small fluctuations to uniformize play a little
215 eval: getBestMoveEval() + 0.05 - Math.random() / 10
216 });
217 this.undo(moves12[j]);
218 }
219 this.undo(moves11[i]);
220 }
221
222 doubleMoves.sort((a, b) => {
223 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
224 });
225 let candidates = [0]; //indices of candidates moves
226 for (
227 let i = 1;
228 i < doubleMoves.length && doubleMoves[i].eval == doubleMoves[0].eval;
229 i++
230 ) {
231 candidates.push(i);
232 }
233 return doubleMoves[randInt(candidates.length)].moves;
234 }
235 };