Fix Alice rules (en passant)
[vchess.git] / client / src / variants / Alice.js
1 import { ChessRules } from "@/base_rules";
2 import { ArrayFun } from "@/utils/array";
3
4 // NOTE: alternative implementation, probably cleaner = use only 1 board
5 // TODO? atLeastOneMove() would be more efficient if rewritten here
6 // (less sideBoard computations)
7 export class AliceRules extends ChessRules {
8 static get ALICE_PIECES() {
9 return {
10 s: "p",
11 t: "q",
12 u: "r",
13 c: "b",
14 o: "n",
15 l: "k"
16 };
17 }
18 static get ALICE_CODES() {
19 return {
20 p: "s",
21 q: "t",
22 r: "u",
23 b: "c",
24 n: "o",
25 k: "l"
26 };
27 }
28
29 static get PIECES() {
30 return ChessRules.PIECES.concat(Object.keys(V.ALICE_PIECES));
31 }
32
33 getPpath(b) {
34 return (Object.keys(V.ALICE_PIECES).includes(b[1]) ? "Alice/" : "") + b;
35 }
36
37 getEpSquare(moveOrSquare) {
38 if (!moveOrSquare) return undefined;
39 if (typeof moveOrSquare === "string") {
40 const square = moveOrSquare;
41 if (square == "-") return undefined;
42 return V.SquareToCoords(square);
43 }
44 // Argument is a move:
45 const move = moveOrSquare;
46 const s = move.start,
47 e = move.end;
48 if (
49 s.y == e.y &&
50 Math.abs(s.x - e.x) == 2 &&
51 // Special conditions: a pawn can be on the other side
52 ['p','s'].includes(move.appear[0].p) &&
53 ['p','s'].includes(move.vanish[0].p)
54 ) {
55 return {
56 x: (s.x + e.x) / 2,
57 y: s.y
58 };
59 }
60 return undefined; //default
61 }
62
63 setOtherVariables(fen) {
64 super.setOtherVariables(fen);
65 const rows = V.ParseFen(fen).position.split("/");
66 if (this.kingPos["w"][0] < 0 || this.kingPos["b"][0] < 0) {
67 // INIT_COL_XXX won't be required if Alice kings are found
68 // (it means 'king moved')
69 for (let i = 0; i < rows.length; i++) {
70 let k = 0; //column index on board
71 for (let j = 0; j < rows[i].length; j++) {
72 switch (rows[i].charAt(j)) {
73 case "l":
74 this.kingPos["b"] = [i, k];
75 break;
76 case "L":
77 this.kingPos["w"] = [i, k];
78 break;
79 default: {
80 const num = parseInt(rows[i].charAt(j));
81 if (!isNaN(num)) k += num - 1;
82 }
83 }
84 k++;
85 }
86 }
87 }
88 }
89
90 // Return the (standard) color+piece notation at a square for a board
91 getSquareOccupation(i, j, mirrorSide) {
92 const piece = this.getPiece(i, j);
93 if (mirrorSide == 1 && Object.keys(V.ALICE_CODES).includes(piece))
94 return this.board[i][j];
95 if (mirrorSide == 2 && Object.keys(V.ALICE_PIECES).includes(piece))
96 return this.getColor(i, j) + V.ALICE_PIECES[piece];
97 return "";
98 }
99
100 // Build board of the given (mirror)side
101 getSideBoard(mirrorSide) {
102 // Build corresponding board from complete board
103 let sideBoard = ArrayFun.init(V.size.x, V.size.y, "");
104 for (let i = 0; i < V.size.x; i++) {
105 for (let j = 0; j < V.size.y; j++)
106 sideBoard[i][j] = this.getSquareOccupation(i, j, mirrorSide);
107 }
108 return sideBoard;
109 }
110
111 // NOTE: castle & enPassant
112 // https://www.chessvariants.com/other.dir/alice.html
113 getPotentialMovesFrom([x, y], sideBoard) {
114 const pieces = Object.keys(V.ALICE_CODES);
115 const codes = Object.keys(V.ALICE_PIECES);
116 const mirrorSide = pieces.includes(this.getPiece(x, y)) ? 1 : 2;
117 if (!sideBoard) sideBoard = [this.getSideBoard(1), this.getSideBoard(2)];
118 const color = this.getColor(x, y);
119
120 // Search valid moves on sideBoard
121 const saveBoard = this.board;
122 this.board = sideBoard[mirrorSide - 1];
123 const moves = super.getPotentialMovesFrom([x, y]).filter(m => {
124 // Filter out king moves which result in under-check position on
125 // current board (before mirror traversing)
126 let aprioriValid = true;
127 if (m.appear[0].p == V.KING) {
128 this.play(m);
129 if (this.underCheck(color, sideBoard)) aprioriValid = false;
130 this.undo(m);
131 }
132 return aprioriValid;
133 });
134 this.board = saveBoard;
135
136 // Finally filter impossible moves
137 const res = moves.filter(m => {
138 if (m.appear.length == 2) {
139 // Castle: appear[i] must be an empty square on the other board
140 for (let psq of m.appear) {
141 if (
142 this.getSquareOccupation(psq.x, psq.y, 3 - mirrorSide) != V.EMPTY
143 ) {
144 return false;
145 }
146 }
147 } else if (this.board[m.end.x][m.end.y] != V.EMPTY) {
148 // Attempt to capture
149 const piece = this.getPiece(m.end.x, m.end.y);
150 if (
151 (mirrorSide == 1 && codes.includes(piece)) ||
152 (mirrorSide == 2 && pieces.includes(piece))
153 ) {
154 return false;
155 }
156 }
157 // If the move is computed on board1, m.appear change for Alice pieces.
158 if (mirrorSide == 1) {
159 m.appear.forEach(psq => {
160 // forEach: castling taken into account
161 psq.p = V.ALICE_CODES[psq.p]; //goto board2
162 });
163 }
164 else {
165 // Move on board2: mark vanishing pieces as Alice
166 m.vanish.forEach(psq => {
167 psq.p = V.ALICE_CODES[psq.p];
168 });
169 }
170 // Fix en-passant captures
171 if (
172 m.vanish[0].p == V.PAWN &&
173 m.vanish.length == 2 &&
174 this.board[m.end.x][m.end.y] == V.EMPTY
175 ) {
176 m.vanish[1].c = V.GetOppCol(this.turn);
177 const [epX, epY] = [m.vanish[1].x, m.vanish[1].y];
178 m.vanish[1].p = this.getPiece(epX, epY);
179 }
180 return true;
181 });
182 return res;
183 }
184
185 filterValid(moves, sideBoard) {
186 if (moves.length == 0) return [];
187 if (!sideBoard) sideBoard = [this.getSideBoard(1), this.getSideBoard(2)];
188 const color = this.turn;
189 return moves.filter(m => {
190 this.playSide(m, sideBoard); //no need to track flags
191 const res = !this.underCheck(color, sideBoard);
192 this.undoSide(m, sideBoard);
193 return res;
194 });
195 }
196
197 getAllValidMoves() {
198 const color = this.turn;
199 let potentialMoves = [];
200 const sideBoard = [this.getSideBoard(1), this.getSideBoard(2)];
201 for (var i = 0; i < V.size.x; i++) {
202 for (var j = 0; j < V.size.y; j++) {
203 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
204 Array.prototype.push.apply(
205 potentialMoves,
206 this.getPotentialMovesFrom([i, j], sideBoard)
207 );
208 }
209 }
210 }
211 return this.filterValid(potentialMoves, sideBoard);
212 }
213
214 // Play on sideboards [TODO: only one sideBoard required]
215 playSide(move, sideBoard) {
216 const pieces = Object.keys(V.ALICE_CODES);
217 move.vanish.forEach(psq => {
218 const mirrorSide = pieces.includes(psq.p) ? 1 : 2;
219 sideBoard[mirrorSide - 1][psq.x][psq.y] = V.EMPTY;
220 });
221 move.appear.forEach(psq => {
222 const mirrorSide = pieces.includes(psq.p) ? 1 : 2;
223 const piece = mirrorSide == 1 ? psq.p : V.ALICE_PIECES[psq.p];
224 sideBoard[mirrorSide - 1][psq.x][psq.y] = psq.c + piece;
225 if (piece == V.KING) this.kingPos[psq.c] = [psq.x, psq.y];
226 });
227 }
228
229 // Undo on sideboards
230 undoSide(move, sideBoard) {
231 const pieces = Object.keys(V.ALICE_CODES);
232 move.appear.forEach(psq => {
233 const mirrorSide = pieces.includes(psq.p) ? 1 : 2;
234 sideBoard[mirrorSide - 1][psq.x][psq.y] = V.EMPTY;
235 });
236 move.vanish.forEach(psq => {
237 const mirrorSide = pieces.includes(psq.p) ? 1 : 2;
238 const piece = mirrorSide == 1 ? psq.p : V.ALICE_PIECES[psq.p];
239 sideBoard[mirrorSide - 1][psq.x][psq.y] = psq.c + piece;
240 if (piece == V.KING) this.kingPos[psq.c] = [psq.x, psq.y];
241 });
242 }
243
244 // sideBoard: arg containing both boards (see getAllValidMoves())
245 underCheck(color, sideBoard) {
246 const kp = this.kingPos[color];
247 const mirrorSide = sideBoard[0][kp[0]][kp[1]] != V.EMPTY ? 1 : 2;
248 let saveBoard = this.board;
249 this.board = sideBoard[mirrorSide - 1];
250 let res = this.isAttacked(kp, [V.GetOppCol(color)]);
251 this.board = saveBoard;
252 return res;
253 }
254
255 getCheckSquares() {
256 const color = this.turn;
257 const pieces = Object.keys(V.ALICE_CODES);
258 const kp = this.kingPos[color];
259 const mirrorSide = pieces.includes(this.getPiece(kp[0], kp[1])) ? 1 : 2;
260 let sideBoard = this.getSideBoard(mirrorSide);
261 let saveBoard = this.board;
262 this.board = sideBoard;
263 let res = this.isAttacked(this.kingPos[color], [V.GetOppCol(color)])
264 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
265 : [];
266 this.board = saveBoard;
267 return res;
268 }
269
270 postPlay(move) {
271 super.postPlay(move); //standard king
272 const piece = move.vanish[0].p;
273 const c = move.vanish[0].c;
274 // "l" = Alice king
275 if (piece == "l") {
276 this.kingPos[c][0] = move.appear[0].x;
277 this.kingPos[c][1] = move.appear[0].y;
278 this.castleFlags[c] = [8, 8];
279 }
280 }
281
282 postUndo(move) {
283 super.postUndo(move);
284 const c = move.vanish[0].c;
285 if (move.vanish[0].p == "l")
286 this.kingPos[c] = [move.start.x, move.start.y];
287 }
288
289 getCurrentScore() {
290 if (this.atLeastOneMove()) return "*";
291 const pieces = Object.keys(V.ALICE_CODES);
292 const color = this.turn;
293 const kp = this.kingPos[color];
294 const mirrorSide = pieces.includes(this.getPiece(kp[0], kp[1])) ? 1 : 2;
295 let sideBoard = this.getSideBoard(mirrorSide);
296 let saveBoard = this.board;
297 this.board = sideBoard;
298 let res = "*";
299 if (!this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]))
300 res = "1/2";
301 else res = color == "w" ? "0-1" : "1-0";
302 this.board = saveBoard;
303 return res;
304 }
305
306 static get VALUES() {
307 return Object.assign(
308 {
309 s: 1,
310 u: 5,
311 o: 3,
312 c: 3,
313 t: 9,
314 l: 1000
315 },
316 ChessRules.VALUES
317 );
318 }
319
320 static get SEARCH_DEPTH() {
321 return 2;
322 }
323
324 getNotation(move) {
325 if (move.appear.length == 2 && move.appear[0].p == V.KING) {
326 if (move.end.y < move.start.y) return "0-0-0";
327 return "0-0";
328 }
329
330 const finalSquare = V.CoordsToSquare(move.end);
331 const piece = this.getPiece(move.start.x, move.start.y);
332
333 const captureMark = move.vanish.length > move.appear.length ? "x" : "";
334 let pawnMark = "";
335 if (["p", "s"].includes(piece) && captureMark.length == 1)
336 pawnMark = V.CoordToColumn(move.start.y); //start column
337
338 // Piece or pawn movement
339 let notation = piece.toUpperCase() + pawnMark + captureMark + finalSquare;
340 if (["s", "p"].includes(piece) && !["s", "p"].includes(move.appear[0].p)) {
341 // Promotion
342 notation += "=" + move.appear[0].p.toUpperCase();
343 }
344 return notation;
345 }
346 };