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