Add Fugue variant
[vchess.git] / client / src / variants / Checkered2.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2
3 export class Checkered2Rules extends ChessRules {
4
5 static board2fen(b) {
6 const checkered_codes = {
7 p: "s",
8 q: "t",
9 r: "u",
10 b: "c",
11 n: "o"
12 };
13 if (b[0] == "c") return checkered_codes[b[1]];
14 return ChessRules.board2fen(b);
15 }
16
17 static fen2board(f) {
18 // Tolerate upper-case versions of checkered pieces (why not?)
19 const checkered_pieces = {
20 s: "p",
21 S: "p",
22 t: "q",
23 T: "q",
24 u: "r",
25 U: "r",
26 c: "b",
27 C: "b",
28 o: "n",
29 O: "n"
30 };
31 if (Object.keys(checkered_pieces).includes(f))
32 return "c" + checkered_pieces[f];
33 return ChessRules.fen2board(f);
34 }
35
36 static get PIECES() {
37 return ChessRules.PIECES.concat(["s", "t", "u", "c", "o"]);
38 }
39
40 getPpath(b) {
41 return (b[0] == "c" ? "Checkered/" : "") + b;
42 }
43
44 setOtherVariables(fen) {
45 super.setOtherVariables(fen);
46 // Local stack of non-capturing checkered moves:
47 this.cmoves = [];
48 const cmove = V.ParseFen(fen).cmove;
49 if (cmove == "-") this.cmoves.push(null);
50 else {
51 this.cmoves.push({
52 start: ChessRules.SquareToCoords(cmove.substr(0, 2)),
53 end: ChessRules.SquareToCoords(cmove.substr(2))
54 });
55 }
56 }
57
58 static IsGoodFen(fen) {
59 if (!ChessRules.IsGoodFen(fen)) return false;
60 const fenParts = fen.split(" ");
61 if (fenParts.length != 6) return false;
62 if (fenParts[5] != "-" && !fenParts[5].match(/^([a-h][1-8]){2}$/))
63 return false;
64 return true;
65 }
66
67 static IsGoodFlags(flags) {
68 // 4 for castle + 16 for pawns
69 return !!flags.match(/^[a-z]{4,4}[01]{16,16}$/);
70 }
71
72 setFlags(fenflags) {
73 super.setFlags(fenflags); //castleFlags
74 this.pawnFlags = {
75 w: [...Array(8)], //pawns can move 2 squares?
76 b: [...Array(8)]
77 };
78 const flags = fenflags.substr(4); //skip first 4 letters, for castle
79 for (let c of ["w", "b"]) {
80 for (let i = 0; i < 8; i++)
81 this.pawnFlags[c][i] = flags.charAt((c == "w" ? 0 : 8) + i) == "1";
82 }
83 }
84
85 aggregateFlags() {
86 return [this.castleFlags, this.pawnFlags];
87 }
88
89 disaggregateFlags(flags) {
90 this.castleFlags = flags[0];
91 this.pawnFlags = flags[1];
92 }
93
94 getEpSquare(moveOrSquare) {
95 if (typeof moveOrSquare !== "object" || moveOrSquare.appear[0].c != 'c')
96 return super.getEpSquare(moveOrSquare);
97 // Checkered move: no en-passant
98 return undefined;
99 }
100
101 getCmove(move) {
102 if (move.appear[0].c == "c" && move.vanish.length == 1)
103 return { start: move.start, end: move.end };
104 return null;
105 }
106
107 canTake([x1, y1], [x2, y2]) {
108 const color1 = this.getColor(x1, y1);
109 const color2 = this.getColor(x2, y2);
110 // Checkered aren't captured
111 return (
112 color1 != color2 &&
113 color2 != "c" &&
114 (color1 != "c" || color2 != this.turn)
115 );
116 }
117
118 // Post-processing: apply "checkerization" of standard moves
119 getPotentialMovesFrom([x, y]) {
120 let standardMoves = super.getPotentialMovesFrom([x, y]);
121 const lastRank = this.turn == "w" ? 0 : 7;
122 // King is treated differently: it never turn checkered
123 if (this.getPiece(x, y) == V.KING) return standardMoves;
124 let moves = [];
125 standardMoves.forEach(m => {
126 if (m.vanish[0].p == V.PAWN) {
127 if (
128 Math.abs(m.end.x - m.start.x) == 2 &&
129 !this.pawnFlags[this.turn][m.start.y]
130 ) {
131 return; //skip forbidden 2-squares jumps
132 }
133 if (
134 this.board[m.end.x][m.end.y] == V.EMPTY &&
135 m.vanish.length == 2 &&
136 this.getColor(m.start.x, m.start.y) == "c"
137 ) {
138 return; //checkered pawns cannot take en-passant
139 }
140 }
141 if (m.vanish.length == 1)
142 // No capture
143 moves.push(m);
144 else {
145 // A capture occured (m.vanish.length == 2)
146 m.appear[0].c = "c";
147 moves.push(m);
148 if (
149 // Avoid promotions (already treated):
150 m.appear[0].p != m.vanish[1].p &&
151 (m.vanish[0].p != V.PAWN || m.end.x != lastRank)
152 ) {
153 // Add transformation into captured piece
154 let m2 = JSON.parse(JSON.stringify(m));
155 m2.appear[0].p = m.vanish[1].p;
156 moves.push(m2);
157 }
158 }
159 });
160 return moves;
161 }
162
163 getPotentialPawnMoves([x, y]) {
164 let moves = super.getPotentialPawnMoves([x, y]);
165 // Post-process: set right color for checkered moves
166 if (this.getColor(x, y) == 'c') {
167 moves.forEach(m => {
168 m.appear[0].c = 'c'; //may be done twice if capture
169 m.vanish[0].c = 'c';
170 });
171 }
172 return moves;
173 }
174
175 canIplay(side, [x, y]) {
176 return side == this.turn && [side, "c"].includes(this.getColor(x, y));
177 }
178
179 // Does m2 un-do m1 ? (to disallow undoing checkered moves)
180 oppositeMoves(m1, m2) {
181 return (
182 !!m1 &&
183 m2.appear[0].c == "c" &&
184 m2.appear.length == 1 &&
185 m2.vanish.length == 1 &&
186 m1.start.x == m2.end.x &&
187 m1.end.x == m2.start.x &&
188 m1.start.y == m2.end.y &&
189 m1.end.y == m2.start.y
190 );
191 }
192
193 filterValid(moves) {
194 if (moves.length == 0) return [];
195 const color = this.turn;
196 const L = this.cmoves.length; //at least 1: init from FEN
197 return moves.filter(m => {
198 if (this.oppositeMoves(this.cmoves[L - 1], m)) return false;
199 this.play(m);
200 const res = !this.underCheck(color);
201 this.undo(m);
202 return res;
203 });
204 }
205
206 getAllValidMoves() {
207 const oppCol = V.GetOppCol(this.turn);
208 let potentialMoves = [];
209 for (let i = 0; i < V.size.x; i++) {
210 for (let j = 0; j < V.size.y; j++) {
211 // NOTE: just testing == color isn't enough because of checkered pieces
212 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) {
213 Array.prototype.push.apply(
214 potentialMoves,
215 this.getPotentialMovesFrom([i, j])
216 );
217 }
218 }
219 }
220 return this.filterValid(potentialMoves);
221 }
222
223 atLeastOneMove() {
224 const oppCol = V.GetOppCol(this.turn);
225 for (let i = 0; i < V.size.x; i++) {
226 for (let j = 0; j < V.size.y; j++) {
227 // NOTE: just testing == color isn't enough because of checkered pieces
228 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) {
229 const moves = this.getPotentialMovesFrom([i, j]);
230 if (moves.length > 0) {
231 for (let k = 0; k < moves.length; k++) {
232 if (this.filterValid([moves[k]]).length > 0) return true;
233 }
234 }
235 }
236 }
237 }
238 return false;
239 }
240
241 // colors: array, generally 'w' and 'c' or 'b' and 'c'
242 isAttacked(sq, colors) {
243 if (!Array.isArray(colors)) colors = [colors];
244 return (
245 this.isAttackedByPawn(sq, colors) ||
246 this.isAttackedByRook(sq, colors) ||
247 this.isAttackedByKnight(sq, colors) ||
248 this.isAttackedByBishop(sq, colors) ||
249 this.isAttackedByQueen(sq, colors) ||
250 this.isAttackedByKing(sq, colors)
251 );
252 }
253
254 isAttackedByPawn([x, y], colors) {
255 for (let c of colors) {
256 const color = (c == "c" ? this.turn : c);
257 let pawnShift = color == "w" ? 1 : -1;
258 if (x + pawnShift >= 0 && x + pawnShift < 8) {
259 for (let i of [-1, 1]) {
260 if (
261 y + i >= 0 &&
262 y + i < 8 &&
263 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
264 this.getColor(x + pawnShift, y + i) == c
265 ) {
266 return true;
267 }
268 }
269 }
270 }
271 return false;
272 }
273
274 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
275 for (let step of steps) {
276 let rx = x + step[0],
277 ry = y + step[1];
278 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
279 rx += step[0];
280 ry += step[1];
281 }
282 if (
283 V.OnBoard(rx, ry) &&
284 this.getPiece(rx, ry) === piece &&
285 colors.includes(this.getColor(rx, ry))
286 ) {
287 return true;
288 }
289 }
290 return false;
291 }
292
293 isAttackedByRook(sq, colors) {
294 return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
295 }
296
297 isAttackedByKnight(sq, colors) {
298 return this.isAttackedBySlideNJump(
299 sq,
300 colors,
301 V.KNIGHT,
302 V.steps[V.KNIGHT],
303 "oneStep"
304 );
305 }
306
307 isAttackedByBishop(sq, colors) {
308 return this.isAttackedBySlideNJump(
309 sq, colors, V.BISHOP, V.steps[V.BISHOP]);
310 }
311
312 isAttackedByQueen(sq, colors) {
313 return this.isAttackedBySlideNJump(
314 sq,
315 colors,
316 V.QUEEN,
317 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
318 );
319 }
320
321 isAttackedByKing(sq, colors) {
322 return this.isAttackedBySlideNJump(
323 sq,
324 colors,
325 V.KING,
326 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
327 "oneStep"
328 );
329 }
330
331 underCheck(color) {
332 return this.isAttacked(this.kingPos[color], [V.GetOppCol(color), "c"]);
333 }
334
335 getCheckSquares() {
336 const color = this.turn;
337 // Artifically change turn, for checkered pawns
338 this.turn = V.GetOppCol(color);
339 const kingAttacked =
340 this.isAttacked(
341 this.kingPos[color],
342 [this.turn, 'c']
343 );
344 let res = kingAttacked
345 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
346 : [];
347 this.turn = color;
348 return res;
349 }
350
351 postPlay(move) {
352 super.postPlay(move);
353 // Does this move turn off a 2-squares pawn flag?
354 if ([1, 6].includes(move.start.x) && move.vanish[0].p == V.PAWN)
355 this.pawnFlags[move.start.x == 6 ? "w" : "b"][move.start.y] = false;
356 this.cmoves.push(this.getCmove(move));
357 }
358
359 postUndo(move) {
360 super.postUndo(move);
361 this.cmoves.pop();
362 }
363
364 getCurrentScore() {
365 if (this.atLeastOneMove()) return "*";
366 const color = this.turn;
367 // Artifically change turn, for checkered pawns
368 this.turn = V.GetOppCol(this.turn);
369 const res = this.isAttacked(this.kingPos[color], [V.GetOppCol(color), "c"])
370 ? color == "w"
371 ? "0-1"
372 : "1-0"
373 : "1/2";
374 this.turn = V.GetOppCol(this.turn);
375 return res;
376 }
377
378 evalPosition() {
379 let evaluation = 0;
380 // Just count material for now, considering checkered neutral (...)
381 for (let i = 0; i < V.size.x; i++) {
382 for (let j = 0; j < V.size.y; j++) {
383 if (this.board[i][j] != V.EMPTY) {
384 const sqColor = this.getColor(i, j);
385 if (["w","b"].includes(sqColor)) {
386 const sign = sqColor == "w" ? 1 : -1;
387 evaluation += sign * V.VALUES[this.getPiece(i, j)];
388 }
389 }
390 }
391 }
392 return evaluation;
393 }
394
395 static GenRandInitFen(randomness) {
396 // Add 16 pawns flags + empty cmove:
397 return ChessRules.GenRandInitFen(randomness)
398 .slice(0, -2) + "1111111111111111 - -";
399 }
400
401 static ParseFen(fen) {
402 return Object.assign(
403 ChessRules.ParseFen(fen),
404 { cmove: fen.split(" ")[5] }
405 );
406 }
407
408 getCmoveFen() {
409 const L = this.cmoves.length;
410 return (
411 !this.cmoves[L - 1]
412 ? "-"
413 : ChessRules.CoordsToSquare(this.cmoves[L - 1].start) +
414 ChessRules.CoordsToSquare(this.cmoves[L - 1].end)
415 );
416 }
417
418 getFen() {
419 return super.getFen() + " " + this.getCmoveFen();
420 }
421
422 getFenForRepeat() {
423 return super.getFenForRepeat() + "_" + this.getCmoveFen();
424 }
425
426 getFlagsFen() {
427 let fen = super.getFlagsFen();
428 // Add pawns flags
429 for (let c of ["w", "b"])
430 for (let i = 0; i < 8; i++) fen += (this.pawnFlags[c][i] ? "1" : "0");
431 return fen;
432 }
433
434 static get SEARCH_DEPTH() {
435 return 2;
436 }
437
438 getNotation(move) {
439 if (move.appear.length == 2) {
440 // Castle
441 if (move.end.y < move.start.y) return "0-0-0";
442 return "0-0";
443 }
444
445 const finalSquare = V.CoordsToSquare(move.end);
446 const piece = this.getPiece(move.start.x, move.start.y);
447 let notation = "";
448 if (piece == V.PAWN) {
449 // Pawn move
450 if (move.vanish.length > 1) {
451 // Capture
452 const startColumn = V.CoordToColumn(move.start.y);
453 notation = startColumn + "x" + finalSquare;
454 } else notation = finalSquare;
455 } else {
456 // Piece movement
457 notation =
458 piece.toUpperCase() +
459 (move.vanish.length > 1 ? "x" : "") +
460 finalSquare;
461 }
462 if (move.appear[0].p != move.vanish[0].p)
463 notation += "=" + move.appear[0].p.toUpperCase();
464 return notation;
465 }
466
467 };