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