Typo
[vchess.git] / client / src / variants / Checkered1.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2
3 export class Checkered1Rules 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 // Stage 1: as Checkered2. Stage 2: checkered pieces are autonomous
57 const stageInfo = V.ParseFen(fen).stage;
58 this.stage = parseInt(stageInfo[0], 10);
59 this.sideCheckered = (this.stage == 2 ? stageInfo[1] : undefined);
60 }
61
62 static IsGoodFen(fen) {
63 if (!ChessRules.IsGoodFen(fen)) return false;
64 const fenParts = fen.split(" ");
65 if (fenParts.length != 7) return false;
66 if (fenParts[5] != "-" && !fenParts[5].match(/^([a-h][1-8]){2}$/))
67 return false;
68 if (!fenParts[6].match(/^[12][wb]?$/)) return false;
69 return true;
70 }
71
72 static IsGoodFlags(flags) {
73 // 4 for castle + 16 for pawns
74 return !!flags.match(/^[a-z]{4,4}[01]{16,16}$/);
75 }
76
77 setFlags(fenflags) {
78 super.setFlags(fenflags); //castleFlags
79 this.pawnFlags = {
80 w: [...Array(8)], //pawns can move 2 squares?
81 b: [...Array(8)]
82 };
83 const flags = fenflags.substr(4); //skip first 4 letters, for castle
84 for (let c of ["w", "b"]) {
85 for (let i = 0; i < 8; i++)
86 this.pawnFlags[c][i] = flags.charAt((c == "w" ? 0 : 8) + i) == "1";
87 }
88 }
89
90 aggregateFlags() {
91 return [this.castleFlags, this.pawnFlags];
92 }
93
94 disaggregateFlags(flags) {
95 this.castleFlags = flags[0];
96 this.pawnFlags = flags[1];
97 }
98
99 getEpSquare(moveOrSquare) {
100 // At stage 2, all pawns can be captured en-passant
101 if (
102 this.stage == 2 ||
103 typeof moveOrSquare !== "object" ||
104 (moveOrSquare.appear.length > 0 && moveOrSquare.appear[0].c != 'c')
105 )
106 return super.getEpSquare(moveOrSquare);
107 // Checkered or switch move: no en-passant
108 return undefined;
109 }
110
111 getCmove(move) {
112 // No checkered move to undo at stage 2:
113 if (this.stage == 1 && move.vanish.length == 1 && move.appear[0].c == "c")
114 return { start: move.start, end: move.end };
115 return null;
116 }
117
118 canTake([x1, y1], [x2, y2]) {
119 const color1 = this.getColor(x1, y1);
120 const color2 = this.getColor(x2, y2);
121 if (this.stage == 2) {
122 // Black & White <-- takes --> Checkered
123 const color1 = this.getColor(x1, y1);
124 const color2 = this.getColor(x2, y2);
125 return color1 != color2 && [color1, color2].includes('c');
126 }
127 // Checkered aren't captured
128 return (
129 color1 != color2 &&
130 color2 != "c" &&
131 (color1 != "c" || color2 != this.turn)
132 );
133 }
134
135 getPotentialMovesFrom([x, y], noswitch) {
136 let standardMoves = super.getPotentialMovesFrom([x, y]);
137 if (this.stage == 1) {
138 const color = this.turn;
139 // Post-processing: apply "checkerization" of standard moves
140 const lastRank = (color == "w" ? 0 : 7);
141 let moves = [];
142 // King is treated differently: it never turn checkered
143 if (this.getPiece(x, y) == V.KING) {
144 // If at least one checkered piece, allow switching:
145 if (
146 !noswitch &&
147 this.board.some(b => b.some(cell => cell[0] == 'c'))
148 ) {
149 const oppCol = V.GetOppCol(color);
150 moves.push(
151 new Move({
152 start: { x: x, y: y },
153 end: { x: this.kingPos[oppCol][0], y: this.kingPos[oppCol][1] },
154 appear: [],
155 vanish: []
156 })
157 );
158 }
159 return standardMoves.concat(moves);
160 }
161 standardMoves.forEach(m => {
162 if (m.vanish[0].p == V.PAWN) {
163 if (
164 Math.abs(m.end.x - m.start.x) == 2 &&
165 !this.pawnFlags[this.turn][m.start.y]
166 ) {
167 return; //skip forbidden 2-squares jumps
168 }
169 if (
170 this.board[m.end.x][m.end.y] == V.EMPTY &&
171 m.vanish.length == 2 &&
172 this.getColor(m.start.x, m.start.y) == "c"
173 ) {
174 return; //checkered pawns cannot take en-passant
175 }
176 }
177 if (m.vanish.length == 1)
178 // No capture
179 moves.push(m);
180 else {
181 // A capture occured (m.vanish.length == 2)
182 m.appear[0].c = "c";
183 moves.push(m);
184 if (
185 // Avoid promotions (already treated):
186 m.appear[0].p != m.vanish[1].p &&
187 (m.vanish[0].p != V.PAWN || m.end.x != lastRank)
188 ) {
189 // Add transformation into captured piece
190 let m2 = JSON.parse(JSON.stringify(m));
191 m2.appear[0].p = m.vanish[1].p;
192 moves.push(m2);
193 }
194 }
195 });
196 return moves;
197 }
198 return standardMoves;
199 }
200
201 getPotentialPawnMoves([x, y]) {
202 const color = this.getColor(x, y);
203 if (this.stage == 2) {
204 const saveTurn = this.turn;
205 if (this.sideCheckered == this.turn) {
206 // Cannot change PawnSpecs.bidirectional, so cheat a little:
207 this.turn = 'w';
208 const wMoves = super.getPotentialPawnMoves([x, y]);
209 this.turn = 'b';
210 const bMoves = super.getPotentialPawnMoves([x, y]);
211 this.turn = saveTurn;
212 return wMoves.concat(bMoves);
213 }
214 // Playing with both colors:
215 this.turn = color;
216 const moves = super.getPotentialPawnMoves([x, y]);
217 this.turn = saveTurn;
218 return moves;
219 }
220 let moves = super.getPotentialPawnMoves([x, y]);
221 // Post-process: set right color for checkered moves
222 if (color == 'c') {
223 moves.forEach(m => {
224 m.appear[0].c = 'c'; //may be done twice if capture
225 m.vanish[0].c = 'c';
226 });
227 }
228 return moves;
229 }
230
231 canIplay(side, [x, y]) {
232 if (this.stage == 2) {
233 const color = this.getColor(x, y);
234 return (
235 this.turn == this.sideCheckered
236 ? color == 'c'
237 : ['w', 'b'].includes(color)
238 );
239 }
240 return side == this.turn && [side, "c"].includes(this.getColor(x, y));
241 }
242
243 // Does m2 un-do m1 ? (to disallow undoing checkered moves)
244 oppositeMoves(m1, m2) {
245 return (
246 !!m1 &&
247 m2.appear[0].c == "c" &&
248 m2.appear.length == 1 &&
249 m2.vanish.length == 1 &&
250 m1.start.x == m2.end.x &&
251 m1.end.x == m2.start.x &&
252 m1.start.y == m2.end.y &&
253 m1.end.y == m2.start.y
254 );
255 }
256
257 filterValid(moves) {
258 if (moves.length == 0) return [];
259 const color = this.turn;
260 const oppCol = V.GetOppCol(color);
261 const L = this.cmoves.length; //at least 1: init from FEN
262 const stage = this.stage; //may change if switch
263 return moves.filter(m => {
264 // Checkered cannot be under check (no king)
265 if (stage == 2 && this.sideCheckered == color) return true;
266 this.play(m);
267 let res = true;
268 if (stage == 1) {
269 if (m.appear.length == 0 && m.vanish.length == 0) {
270 // Special "switch" move: kings must not be attacked by checkered.
271 // Not checking for oppositeMoves here: checkered are autonomous
272 res = (
273 !this.isAttacked(this.kingPos['w'], ['c']) &&
274 !this.isAttacked(this.kingPos['b'], ['c']) &&
275 this.getAllPotentialMoves().length > 0
276 );
277 }
278 else res = !this.oppositeMoves(this.cmoves[L - 1], m);
279 }
280 if (res && m.appear.length > 0) res = !this.underCheck(color);
281 // At stage 2, side with B & W can be undercheck with both kings:
282 if (res && stage == 2) res = !this.underCheck(oppCol);
283 this.undo(m);
284 return res;
285 });
286 }
287
288 getAllPotentialMoves() {
289 const color = this.turn;
290 const oppCol = V.GetOppCol(color);
291 let potentialMoves = [];
292 for (let i = 0; i < V.size.x; i++) {
293 for (let j = 0; j < V.size.y; j++) {
294 const colIJ = this.getColor(i, j);
295 if (
296 this.board[i][j] != V.EMPTY &&
297 (
298 (this.stage == 1 && colIJ != oppCol) ||
299 (this.stage == 2 &&
300 (
301 (this.sideCheckered == color && colIJ == 'c') ||
302 (this.sideCheckered != color && ['w', 'b'].includes(colIJ))
303 )
304 )
305 )
306 ) {
307 Array.prototype.push.apply(
308 potentialMoves,
309 this.getPotentialMovesFrom([i, j])
310 );
311 }
312 }
313 }
314 return potentialMoves;
315 }
316
317 atLeastOneMove() {
318 const color = this.turn;
319 const oppCol = V.GetOppCol(color);
320 for (let i = 0; i < V.size.x; i++) {
321 for (let j = 0; j < V.size.y; j++) {
322 const colIJ = this.getColor(i, j);
323 if (
324 this.board[i][j] != V.EMPTY &&
325 (
326 (this.stage == 1 && colIJ != oppCol) ||
327 (this.stage == 2 &&
328 (
329 (this.sideCheckered == color && colIJ == 'c') ||
330 (this.sideCheckered != color && ['w', 'b'].includes(colIJ))
331 )
332 )
333 )
334 ) {
335 const moves = this.getPotentialMovesFrom([i, j], "noswitch");
336 if (moves.length > 0) {
337 for (let k = 0; k < moves.length; k++)
338 if (this.filterValid([moves[k]]).length > 0) return true;
339 }
340 }
341 }
342 }
343 return false;
344 }
345
346 // colors: array, 'w' and 'c' or 'b' and 'c' at stage 1,
347 // just 'c' (or unused) at stage 2
348 isAttacked(sq, colors) {
349 if (!Array.isArray(colors)) colors = [colors];
350 return (
351 this.isAttackedByPawn(sq, colors) ||
352 this.isAttackedByRook(sq, colors) ||
353 this.isAttackedByKnight(sq, colors) ||
354 this.isAttackedByBishop(sq, colors) ||
355 this.isAttackedByQueen(sq, colors) ||
356 this.isAttackedByKing(sq, colors)
357 );
358 }
359
360 isAttackedByPawn([x, y], colors) {
361 for (let c of colors) {
362 let shifts = [];
363 if (this.stage == 1) {
364 const color = (c == "c" ? this.turn : c);
365 shifts = [color == "w" ? 1 : -1];
366 }
367 else {
368 // Stage 2: checkered pawns are bidirectional
369 if (c == 'c') shifts = [-1, 1];
370 else shifts = [c == "w" ? 1 : -1];
371 }
372 for (let pawnShift of shifts) {
373 if (x + pawnShift >= 0 && x + pawnShift < 8) {
374 for (let i of [-1, 1]) {
375 if (
376 y + i >= 0 &&
377 y + i < 8 &&
378 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
379 this.getColor(x + pawnShift, y + i) == c
380 ) {
381 return true;
382 }
383 }
384 }
385 }
386 }
387 return false;
388 }
389
390 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
391 for (let step of steps) {
392 let rx = x + step[0],
393 ry = y + step[1];
394 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
395 rx += step[0];
396 ry += step[1];
397 }
398 if (
399 V.OnBoard(rx, ry) &&
400 this.getPiece(rx, ry) === piece &&
401 colors.includes(this.getColor(rx, ry))
402 ) {
403 return true;
404 }
405 }
406 return false;
407 }
408
409 isAttackedByRook(sq, colors) {
410 return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
411 }
412
413 isAttackedByKnight(sq, colors) {
414 return this.isAttackedBySlideNJump(
415 sq,
416 colors,
417 V.KNIGHT,
418 V.steps[V.KNIGHT],
419 "oneStep"
420 );
421 }
422
423 isAttackedByBishop(sq, colors) {
424 return this.isAttackedBySlideNJump(
425 sq, colors, V.BISHOP, V.steps[V.BISHOP]);
426 }
427
428 isAttackedByQueen(sq, colors) {
429 return this.isAttackedBySlideNJump(
430 sq,
431 colors,
432 V.QUEEN,
433 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
434 );
435 }
436
437 isAttackedByKing(sq, colors) {
438 return this.isAttackedBySlideNJump(
439 sq,
440 colors,
441 V.KING,
442 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
443 "oneStep"
444 );
445 }
446
447 underCheck(color) {
448 if (this.stage == 1)
449 return this.isAttacked(this.kingPos[color], [V.GetOppCol(color), "c"]);
450 if (color == this.sideCheckered) return false;
451 return (
452 this.isAttacked(this.kingPos['w'], ["c"]) ||
453 this.isAttacked(this.kingPos['b'], ["c"])
454 );
455 }
456
457 getCheckSquares() {
458 const color = this.turn;
459 if (this.stage == 1) {
460 // Artifically change turn, for checkered pawns
461 this.turn = V.GetOppCol(color);
462 const kingAttacked =
463 this.isAttacked(
464 this.kingPos[color],
465 [V.GetOppCol(color), "c"]
466 );
467 let res = kingAttacked
468 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
469 : [];
470 this.turn = color;
471 return res;
472 }
473 if (this.sideCheckered == color) return [];
474 let res = [];
475 for (let c of ['w', 'b']) {
476 if (this.isAttacked(this.kingPos[c], ['c']))
477 res.push(JSON.parse(JSON.stringify(this.kingPos[c])));
478 }
479 return res;
480 }
481
482 play(move) {
483 move.flags = JSON.stringify(this.aggregateFlags());
484 this.epSquares.push(this.getEpSquare(move));
485 V.PlayOnBoard(this.board, move);
486 if (move.appear.length > 0 || move.vanish.length > 0)
487 {
488 this.turn = V.GetOppCol(this.turn);
489 this.movesCount++;
490 }
491 this.postPlay(move);
492 }
493
494 postPlay(move) {
495 if (move.appear.length == 0 && move.vanish.length == 0) {
496 this.stage = 2;
497 this.sideCheckered = this.turn;
498 }
499 else {
500 const c = move.vanish[0].c;
501 const piece = move.vanish[0].p;
502 if (piece == V.KING) {
503 this.kingPos[c][0] = move.appear[0].x;
504 this.kingPos[c][1] = move.appear[0].y;
505 }
506 super.updateCastleFlags(move, piece);
507 if (
508 [1, 6].includes(move.start.x) &&
509 move.vanish[0].p == V.PAWN &&
510 Math.abs(move.end.x - move.start.x) == 2
511 ) {
512 // This move turns off a 2-squares pawn flag
513 this.pawnFlags[move.start.x == 6 ? "w" : "b"][move.start.y] = false;
514 }
515 }
516 this.cmoves.push(this.getCmove(move));
517 }
518
519 undo(move) {
520 this.epSquares.pop();
521 this.disaggregateFlags(JSON.parse(move.flags));
522 V.UndoOnBoard(this.board, move);
523 if (move.appear.length > 0 || move.vanish.length > 0)
524 {
525 this.turn = V.GetOppCol(this.turn);
526 this.movesCount--;
527 }
528 this.postUndo(move);
529 }
530
531 postUndo(move) {
532 if (move.appear.length == 0 && move.vanish.length == 0) this.stage = 1;
533 else super.postUndo(move);
534 this.cmoves.pop();
535 }
536
537 getCurrentScore() {
538 const color = this.turn;
539 if (this.stage == 1) {
540 if (this.atLeastOneMove()) return "*";
541 // Artifically change turn, for checkered pawns
542 this.turn = V.GetOppCol(this.turn);
543 const res =
544 this.isAttacked(this.kingPos[color], [V.GetOppCol(color), "c"])
545 ? color == "w"
546 ? "0-1"
547 : "1-0"
548 : "1/2";
549 this.turn = V.GetOppCol(this.turn);
550 return res;
551 }
552 // Stage == 2:
553 if (this.sideCheckered == this.turn) {
554 // Check if remaining checkered pieces: if none, I lost
555 if (this.board.some(b => b.some(cell => cell[0] == 'c'))) {
556 if (!this.atLeastOneMove()) return "1/2";
557 return "*";
558 }
559 return color == 'w' ? "0-1" : "1-0";
560 }
561 if (this.atLeastOneMove()) return "*";
562 let res = this.isAttacked(this.kingPos['w'], ["c"]);
563 if (!res) res = this.isAttacked(this.kingPos['b'], ["c"]);
564 if (res) return color == 'w' ? "0-1" : "1-0";
565 return "1/2";
566 }
567
568 evalPosition() {
569 let evaluation = 0;
570 // Just count material for now, considering checkered neutral at stage 1.
571 const baseSign = (this.turn == 'w' ? 1 : -1);
572 for (let i = 0; i < V.size.x; i++) {
573 for (let j = 0; j < V.size.y; j++) {
574 if (this.board[i][j] != V.EMPTY) {
575 const sqColor = this.getColor(i, j);
576 if (this.stage == 1) {
577 if (["w", "b"].includes(sqColor)) {
578 const sign = sqColor == "w" ? 1 : -1;
579 evaluation += sign * V.VALUES[this.getPiece(i, j)];
580 }
581 }
582 else {
583 const sign =
584 this.sideCheckered == this.turn
585 ? (sqColor == 'c' ? 1 : -1) * baseSign
586 : (sqColor == 'c' ? -1 : 1) * baseSign;
587 evaluation += sign * V.VALUES[this.getPiece(i, j)];
588 }
589 }
590 }
591 }
592 return evaluation;
593 }
594
595 static GenRandInitFen(randomness) {
596 // Add 16 pawns flags + empty cmove + stage == 1:
597 return ChessRules.GenRandInitFen(randomness)
598 .slice(0, -2) + "1111111111111111 - - 1";
599 }
600
601 static ParseFen(fen) {
602 const fenParts = fen.split(" ");
603 return Object.assign(
604 ChessRules.ParseFen(fen),
605 {
606 cmove: fenParts[5],
607 stage: fenParts[6]
608 }
609 );
610 }
611
612 getCmoveFen() {
613 const L = this.cmoves.length;
614 return (
615 !this.cmoves[L - 1]
616 ? "-"
617 : ChessRules.CoordsToSquare(this.cmoves[L - 1].start) +
618 ChessRules.CoordsToSquare(this.cmoves[L - 1].end)
619 );
620 }
621
622 getStageFen() {
623 return (this.stage == 1 ? "1" : "2" + this.sideCheckered);
624 }
625
626 getFen() {
627 return (
628 super.getFen() + " " + this.getCmoveFen() + " " + this.getStageFen()
629 );
630 }
631
632 getFenForRepeat() {
633 return (
634 super.getFenForRepeat() + "_" +
635 this.getCmoveFen() + "_" + this.getStageFen()
636 );
637 }
638
639 getFlagsFen() {
640 let fen = super.getFlagsFen();
641 // Add pawns flags
642 for (let c of ["w", "b"])
643 for (let i = 0; i < 8; i++) fen += (this.pawnFlags[c][i] ? "1" : "0");
644 return fen;
645 }
646
647 static get SEARCH_DEPTH() {
648 return 2;
649 }
650
651 getComputerMove() {
652 // To simplify, prevent the bot from switching (TODO...)
653 return (
654 super.getComputerMove(
655 this.getAllValidMoves().filter(m => m.appear.length > 0)
656 )
657 );
658 }
659
660 getNotation(move) {
661 if (move.appear.length == 0 && move.vanish.length == 0) return "S";
662 if (move.appear.length == 2) {
663 // Castle
664 if (move.end.y < move.start.y) return "0-0-0";
665 return "0-0";
666 }
667
668 const finalSquare = V.CoordsToSquare(move.end);
669 const piece = this.getPiece(move.start.x, move.start.y);
670 let notation = "";
671 if (piece == V.PAWN) {
672 if (move.vanish.length > 1) {
673 const startColumn = V.CoordToColumn(move.start.y);
674 notation = startColumn + "x" + finalSquare;
675 } else notation = finalSquare;
676 } else {
677 // Piece movement
678 notation =
679 piece.toUpperCase() +
680 (move.vanish.length > 1 ? "x" : "") +
681 finalSquare;
682 }
683 if (move.appear[0].p != move.vanish[0].p)
684 notation += "=" + move.appear[0].p.toUpperCase();
685 return notation;
686 }
687
688 };