Fix games download/upload + Dynamo variant
[vchess.git] / client / src / variants / Dynamo.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export class DynamoRules extends ChessRules {
5 // TODO: later, allow to push out pawns on a and h files
6 static get HasEnpassant() {
7 return false;
8 }
9
10 canIplay(side, [x, y]) {
11 // Sometimes opponent's pieces can be moved directly
12 return this.turn == side;
13 }
14
15 setOtherVariables(fen) {
16 super.setOtherVariables(fen);
17 this.subTurn = 1;
18 // Local stack of "action moves"
19 this.amoves = [];
20 const amove = V.ParseFen(fen).amove;
21 if (amove != "-") {
22 const amoveParts = amove.split("/");
23 let move = {
24 // No need for start & end
25 appear: [],
26 vanish: []
27 };
28 [0, 1].map(i => {
29 if (amoveParts[i] != "-") {
30 amoveParts[i].split(".").forEach(av => {
31 // Format is "bpe3"
32 const xy = V.SquareToCoords(av.substr(2));
33 move[i == 0 ? "appear" : "vanish"].push(
34 new PiPo({
35 x: xy.x,
36 y: xy.y,
37 c: av[0],
38 p: av[1]
39 })
40 );
41 });
42 }
43 });
44 this.amoves.push(move);
45 }
46 this.subTurn = 1;
47 // Stack "first moves" (on subTurn 1) to merge and check opposite moves
48 this.firstMove = [];
49 }
50
51 static ParseFen(fen) {
52 return Object.assign(
53 ChessRules.ParseFen(fen),
54 { amove: fen.split(" ")[4] }
55 );
56 }
57
58 static IsGoodFen(fen) {
59 if (!ChessRules.IsGoodFen(fen)) return false;
60 const fenParts = fen.split(" ");
61 if (fenParts.length != 5) return false;
62 if (fenParts[4] != "-") {
63 // TODO: a single regexp instead.
64 // Format is [bpa2[.wpd3]] || '-'/[bbc3[.wrd5]] || '-'
65 const amoveParts = fenParts[4].split("/");
66 if (amoveParts.length != 2) return false;
67 for (let part of amoveParts) {
68 if (part != "-") {
69 for (let psq of part.split("."))
70 if (!psq.match(/^[a-r]{3}[1-8]$/)) return false;
71 }
72 }
73 }
74 return true;
75 }
76
77 getFen() {
78 return super.getFen() + " " + this.getAmoveFen();
79 }
80
81 getFenForRepeat() {
82 return super.getFenForRepeat() + "_" + this.getAmoveFen();
83 }
84
85 getAmoveFen() {
86 const L = this.amoves.length;
87 if (L == 0) return "-";
88 return (
89 ["appear","vanish"].map(
90 mpart => {
91 if (this.amoves[L-1][mpart].length == 0) return "-";
92 return (
93 this.amoves[L-1][mpart].map(
94 av => {
95 const square = V.CoordsToSquare({ x: av.x, y: av.y });
96 return av.c + av.p + square;
97 }
98 ).join(".")
99 );
100 }
101 ).join("/")
102 );
103 }
104
105 canTake() {
106 // Captures don't occur (only pulls & pushes)
107 return false;
108 }
109
110 // Step is right, just add (push/pull) moves in this direction
111 // Direction is assumed normalized.
112 getMovesInDirection([x, y], [dx, dy], nbSteps) {
113 nbSteps = nbSteps || 8; //max 8 steps anyway
114 let [i, j] = [x + dx, y + dy];
115 let moves = [];
116 const color = this.getColor(x, y);
117 const piece = this.getPiece(x, y);
118 const lastRank = (color == 'w' ? 0 : 7);
119 let counter = 1;
120 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
121 if (i == lastRank && piece == V.PAWN) {
122 // Promotion by push or pull
123 V.PawnSpecs.promotions.forEach(p => {
124 let move = super.getBasicMove([x, y], [i, j], { c: color, p: p });
125 moves.push(move);
126 });
127 }
128 else moves.push(super.getBasicMove([x, y], [i, j]));
129 if (++counter > nbSteps) break;
130 i += dx;
131 j += dy;
132 }
133 if (!V.OnBoard(i, j) && piece != V.KING) {
134 // Add special "exit" move, by "taking king"
135 moves.push(
136 new Move({
137 start: { x: x, y: y },
138 end: { x: this.kingPos[color][0], y: this.kingPos[color][1] },
139 appear: [],
140 vanish: [{ x: x, y: y, c: color, p: piece }]
141 })
142 );
143 }
144 return moves;
145 }
146
147 // Normalize direction to know the step
148 getNormalizedDirection([dx, dy]) {
149 const absDir = [Math.abs(dx), Math.abs(dy)];
150 let divisor = 0;
151 if (absDir[0] != 0 && absDir[1] != 0 && absDir[0] != absDir[1])
152 // Knight
153 divisor = Math.min(absDir[0], absDir[1]);
154 else
155 // Standard slider (or maybe a pawn or king: same)
156 divisor = Math.max(absDir[0], absDir[1]);
157 return [dx / divisor, dy / divisor];
158 }
159
160 // There was something on x2,y2, maybe our color, pushed/pulled.
161 isAprioriValidExit([x1, y1], [x2, y2], color2) {
162 const color1 = this.getColor(x1, y1);
163 const pawnShift = (color1 == 'w' ? -1 : 1);
164 const lastRank = (color1 == 'w' ? 0 : 7);
165 const deltaX = Math.abs(x1 - x2);
166 const deltaY = Math.abs(y1 - y2);
167 const checkSlider = () => {
168 const dir = this.getNormalizedDirection([x2 - x1, y2 - y1]);
169 let [i, j] = [x1 + dir[0], y1 + dir[1]];
170 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
171 i += dir[0];
172 j += dir[1];
173 }
174 return !V.OnBoard(i, j);
175 };
176 switch (this.getPiece(x1, y1)) {
177 case V.PAWN:
178 return (
179 x1 + pawnShift == x2 &&
180 (
181 (color1 == color2 && x2 == lastRank && y1 == y2) ||
182 (color1 != color2 && deltaY == 1 && !V.OnBoard(x2, 2 * y2 - y1))
183 )
184 );
185 case V.ROOK:
186 if (x1 != x2 && y1 != y2) return false;
187 return checkSlider();
188 case V.KNIGHT:
189 return (
190 deltaX + deltaY == 3 &&
191 (deltaX == 1 || deltaY == 1) &&
192 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
193 );
194 case V.BISHOP:
195 if (deltaX != deltaY) return false;
196 return checkSlider();
197 case V.QUEEN:
198 if (deltaX != 0 && deltaY != 0 && deltaX != deltaY) return false;
199 return checkSlider();
200 case V.KING:
201 return (
202 deltaX <= 1 &&
203 deltaY <= 1 &&
204 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
205 );
206 }
207 return false;
208 }
209
210 isAprioriValidVertical([x1, y1], x2) {
211 const piece = this.getPiece(x1, y1);
212 const deltaX = Math.abs(x1 - x2);
213 const startRank = (this.getColor(x1, y1) == 'w' ? 6 : 1);
214 return (
215 [V.QUEEN, V.ROOK].includes(piece) ||
216 (
217 [V.KING, V.PAWN].includes(piece) &&
218 (
219 deltaX == 1 ||
220 (deltaX == 2 && piece == V.PAWN && x1 == startRank)
221 )
222 )
223 );
224 }
225
226 // NOTE: for pushes, play the pushed piece first.
227 // for pulls: play the piece doing the action first
228 // NOTE: to push a piece out of the board, make it slide until its king
229 getPotentialMovesFrom([x, y]) {
230 const color = this.turn;
231 const sqCol = this.getColor(x, y);
232 if (this.subTurn == 1) {
233 const getMoveHash = (m) => {
234 return V.CoordsToSquare(m.start) + V.CoordsToSquare(m.end);
235 };
236 const addMoves = (dir, nbSteps) => {
237 const newMoves =
238 this.getMovesInDirection([x, y], [-dir[0], -dir[1]], nbSteps)
239 .filter(m => !movesHash[getMoveHash(m)]);
240 newMoves.forEach(m => { movesHash[getMoveHash(m)] = true; });
241 Array.prototype.push.apply(moves, newMoves);
242 };
243 // Free to play any move (if piece of my color):
244 let moves =
245 sqCol == color
246 ? super.getPotentialMovesFrom([x, y])
247 : [];
248 // There may be several suicide moves: keep only one
249 let hasExit = false;
250 moves = moves.filter(m => {
251 const suicide = (m.appear.length == 0);
252 if (suicide) {
253 if (hasExit) return false;
254 hasExit = true;
255 }
256 return true;
257 });
258 const pawnShift = (color == 'w' ? -1 : 1);
259 const pawnStartRank = (color == 'w' ? 6 : 1);
260 // Structure to avoid adding moves twice (can be action & move)
261 let movesHash = {};
262 moves.forEach(m => { movesHash[getMoveHash(m)] = true; });
263 // [x, y] is pushed by 'color'
264 for (let step of V.steps[V.KNIGHT]) {
265 const [i, j] = [x + step[0], y + step[1]];
266 if (
267 V.OnBoard(i, j) &&
268 this.board[i][j] != V.EMPTY &&
269 this.getColor(i, j) == color &&
270 this.getPiece(i, j) == V.KNIGHT
271 ) {
272 addMoves(step, 1);
273 }
274 }
275 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
276 let [i, j] = [x + step[0], y + step[1]];
277 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
278 i += step[0];
279 j += step[1];
280 }
281 if (
282 V.OnBoard(i, j) &&
283 this.board[i][j] != V.EMPTY &&
284 this.getColor(i, j) == color
285 ) {
286 const deltaX = Math.abs(i - x);
287 const deltaY = Math.abs(j - y);
288 switch (this.getPiece(i, j)) {
289 case V.PAWN:
290 if (
291 (x - i) / deltaX == pawnShift &&
292 deltaX <= 2 &&
293 deltaY <= 1
294 ) {
295 if (sqCol == color && deltaY == 0) {
296 // Pushed forward
297 const maxSteps = (i == pawnStartRank && deltaX == 1 ? 2 : 1);
298 addMoves(step, maxSteps);
299 }
300 else if (sqCol != color && deltaY == 1 && deltaX == 1)
301 // Pushed diagonally
302 addMoves(step, 1);
303 }
304 break;
305 case V.ROOK:
306 if (deltaX == 0 || deltaY == 0) addMoves(step);
307 break;
308 case V.BISHOP:
309 if (deltaX == deltaY) addMoves(step);
310 break;
311 case V.QUEEN:
312 // All steps are valid for a queen:
313 addMoves(step);
314 break;
315 case V.KING:
316 if (deltaX <= 1 && deltaY <= 1) addMoves(step, 1);
317 break;
318 }
319 }
320 }
321 return moves;
322 }
323 // If subTurn == 2 then we should have a first move,
324 // which restrict what we can play now: only in the first move direction
325 // NOTE: no need for knight or pawn checks, because the move will be
326 // naturally limited in those cases.
327 const L = this.firstMove.length;
328 const fm = this.firstMove[L-1];
329 if (
330 (fm.appear.length == 2 && fm.vanish.length == 2) ||
331 (fm.vanish[0].c == sqCol && sqCol != color)
332 ) {
333 // Castle or again opponent color: no move playable then.
334 return [];
335 }
336 if (fm.appear.length == 0) {
337 // Piece at subTurn 1 just exited the board.
338 // Can I be a piece which caused the exit?
339 if (
340 // Only "turn" color can do actions
341 sqCol == color &&
342 this.isAprioriValidExit(
343 [x, y],
344 [fm.start.x, fm.start.y],
345 fm.vanish[0].c
346 )
347 ) {
348 // Seems so:
349 const dir = this.getNormalizedDirection(
350 [fm.start.x - x, fm.start.y - y]);
351 const nbSteps =
352 ([V.PAWN,V.KING,V.KNIGHT].includes(this.getPiece(x, y)) ? 1 : null);
353 return this.getMovesInDirection([x, y], dir, nbSteps);
354 }
355 }
356 else {
357 const dirM = this.getNormalizedDirection(
358 [fm.end.x - fm.start.x, fm.end.y - fm.start.y]);
359 const dir = this.getNormalizedDirection(
360 [fm.start.x - x, fm.start.y - y]);
361 // Normalized directions should match
362 if (dir[0] == dirM[0] && dir[1] == dirM[1]) {
363 // If first move is a pawn move, only a queen, rook, or maybe king or
364 // pawn can follow (need vertical movement option).
365 if (
366 fm.vanish[0].p == V.PAWN &&
367 fm.vanish[0].c == color &&
368 !this.isAprioriValidVertical([x, y], fm.start.x)
369 ) {
370 return [];
371 }
372 // And nothing should stand between [x, y] and the square fm.start
373 let [i, j] = [x + dir[0], y + dir[1]];
374 while (
375 (i != fm.start.x || j != fm.start.y) &&
376 this.board[i][j] == V.EMPTY
377 ) {
378 i += dir[0];
379 j += dir[1];
380 }
381 if (i == fm.start.x && j == fm.start.y)
382 return this.getMovesInDirection([x, y], dir);
383 }
384 }
385 return [];
386 }
387
388 getSlideNJumpMoves([x, y], steps, oneStep) {
389 let moves = [];
390 const c = this.getColor(x, y);
391 const piece = this.getPiece(x, y);
392 outerLoop: for (let step of steps) {
393 let i = x + step[0];
394 let j = y + step[1];
395 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
396 moves.push(this.getBasicMove([x, y], [i, j]));
397 if (oneStep) continue outerLoop;
398 i += step[0];
399 j += step[1];
400 }
401 if (V.OnBoard(i, j)) {
402 if (this.canTake([x, y], [i, j]))
403 moves.push(this.getBasicMove([x, y], [i, j]));
404 }
405 else {
406 // Add potential board exit (suicide), except for the king
407 if (piece != V.KING) {
408 moves.push({
409 start: { x: x, y: y},
410 end: { x: this.kingPos[c][0], y: this.kingPos[c][1] },
411 appear: [],
412 vanish: [
413 new PiPo({
414 x: x,
415 y: y,
416 c: c,
417 p: piece
418 })
419 ]
420 });
421 }
422 }
423 }
424 return moves;
425 }
426
427 // Does m2 un-do m1 ? (to disallow undoing actions)
428 oppositeMoves(m1, m2) {
429 const isEqual = (av1, av2) => {
430 // Precondition: av1 and av2 length = 2
431 for (let av of av1) {
432 const avInAv2 = av2.find(elt => {
433 return (
434 elt.x == av.x &&
435 elt.y == av.y &&
436 elt.c == av.c &&
437 elt.p == av.p
438 );
439 });
440 if (!avInAv2) return false;
441 }
442 return true;
443 };
444 return (
445 m1.appear.length == 2 &&
446 m2.appear.length == 2 &&
447 m1.vanish.length == 2 &&
448 m2.vanish.length == 2 &&
449 isEqual(m1.appear, m2.vanish) &&
450 isEqual(m1.vanish, m2.appear)
451 );
452 }
453
454 getAmove(move1, move2) {
455 // Just merge (one is action one is move, one may be empty)
456 return {
457 appear: move1.appear.concat(move2.appear),
458 vanish: move1.vanish.concat(move2.vanish)
459 }
460 }
461
462 filterValid(moves) {
463 const color = this.turn;
464 if (this.subTurn == 1) {
465 return moves.filter(m => {
466 // A move is valid either if it doesn't result in a check,
467 // or if a second move is possible to counter the check
468 // (not undoing a potential move + action of the opponent)
469 this.play(m);
470 let res = this.underCheck(color);
471 if (res) {
472 const moves2 = this.getAllPotentialMoves();
473 for (let m2 of moves2) {
474 this.play(m2);
475 const res2 = this.underCheck(color);
476 this.undo(m2);
477 if (!res2) {
478 res = false;
479 break;
480 }
481 }
482 }
483 this.undo(m);
484 return !res;
485 });
486 }
487 const Lf = this.firstMove.length;
488 const La = this.amoves.length;
489 if (La == 0) return super.filterValid(moves);
490 return (
491 super.filterValid(
492 moves.filter(m => {
493 // Move shouldn't undo another:
494 const amove = this.getAmove(this.firstMove[Lf-1], m);
495 return !this.oppositeMoves(this.amoves[La-1], amove);
496 })
497 )
498 );
499 }
500
501 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
502 for (let step of steps) {
503 let rx = x + step[0],
504 ry = y + step[1];
505 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
506 rx += step[0];
507 ry += step[1];
508 }
509 if (
510 V.OnBoard(rx, ry) &&
511 this.getPiece(rx, ry) == piece &&
512 this.getColor(rx, ry) == color
513 ) {
514 // Continue some steps in the same direction (pull)
515 rx += step[0];
516 ry += step[1];
517 while (
518 V.OnBoard(rx, ry) &&
519 this.board[rx][ry] == V.EMPTY &&
520 !oneStep
521 ) {
522 rx += step[0];
523 ry += step[1];
524 }
525 if (!V.OnBoard(rx, ry)) return true;
526 // Step in the other direction (push)
527 rx = x - step[0];
528 ry = y - step[1];
529 while (
530 V.OnBoard(rx, ry) &&
531 this.board[rx][ry] == V.EMPTY &&
532 !oneStep
533 ) {
534 rx -= step[0];
535 ry -= step[1];
536 }
537 if (!V.OnBoard(rx, ry)) return true;
538 }
539 }
540 return false;
541 }
542
543 isAttackedByPawn([x, y], color) {
544 const lastRank = (color == 'w' ? 0 : 7);
545 if (x != lastRank)
546 // The king can be pushed out by a pawn only on last rank
547 return false;
548 const pawnShift = (color == "w" ? 1 : -1);
549 for (let i of [-1, 1]) {
550 if (
551 y + i >= 0 &&
552 y + i < V.size.y &&
553 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
554 this.getColor(x + pawnShift, y + i) == color
555 ) {
556 return true;
557 }
558 }
559 return false;
560 }
561
562 // No consideration of color: all pieces could be played
563 getAllPotentialMoves() {
564 let potentialMoves = [];
565 for (let i = 0; i < V.size.x; i++) {
566 for (let j = 0; j < V.size.y; j++) {
567 if (this.board[i][j] != V.EMPTY) {
568 Array.prototype.push.apply(
569 potentialMoves,
570 this.getPotentialMovesFrom([i, j])
571 );
572 }
573 }
574 }
575 return potentialMoves;
576 }
577
578 getCurrentScore() {
579 if (this.subTurn == 2)
580 // Move not over
581 return "*";
582 return super.getCurrentScore();
583 }
584
585 doClick(square) {
586 // If subTurn == 2 && square is empty && !underCheck,
587 // then return an empty move, allowing to "pass" subTurn2
588 if (
589 this.subTurn == 2 &&
590 this.board[square[0]][square[1]] == V.EMPTY &&
591 !this.underCheck(this.turn)
592 ) {
593 return {
594 start: { x: -1, y: -1 },
595 end: { x: -1, y: -1 },
596 appear: [],
597 vanish: []
598 };
599 }
600 return null;
601 }
602
603 play(move) {
604 move.flags = JSON.stringify(this.aggregateFlags());
605 V.PlayOnBoard(this.board, move);
606 if (this.subTurn == 2) {
607 const L = this.firstMove.length;
608 this.amoves.push(this.getAmove(this.firstMove[L-1], move));
609 this.turn = V.GetOppCol(this.turn);
610 this.movesCount++;
611 }
612 else this.firstMove.push(move);
613 this.subTurn = 3 - this.subTurn;
614 this.postPlay(move);
615 }
616
617 postPlay(move) {
618 if (move.start.x < 0) return;
619 for (let a of move.appear)
620 if (a.p == V.KING) this.kingPos[a.c] = [a.x, a.y];
621 this.updateCastleFlags(move);
622 }
623
624 updateCastleFlags(move) {
625 const firstRank = { 'w': V.size.x - 1, 'b': 0 };
626 for (let v of move.vanish) {
627 if (v.p == V.KING) this.castleFlags[v.c] = [V.size.y, V.size.y];
628 else if (v.x == firstRank[v.c] && this.castleFlags[v.c].includes(v.y)) {
629 const flagIdx = (v.y == this.castleFlags[v.c][0] ? 0 : 1);
630 this.castleFlags[v.c][flagIdx] = V.size.y;
631 }
632 }
633 }
634
635 undo(move) {
636 this.disaggregateFlags(JSON.parse(move.flags));
637 V.UndoOnBoard(this.board, move);
638 if (this.subTurn == 1) {
639 this.turn = V.GetOppCol(this.turn);
640 this.movesCount--;
641 }
642 else this.firstMove.pop();
643 this.subTurn = 3 - this.subTurn;
644 this.postUndo(move);
645 }
646
647 postUndo(move) {
648 // (Potentially) Reset king position
649 for (let v of move.vanish)
650 if (v.p == V.KING) this.kingPos[v.c] = [v.x, v.y];
651 }
652
653 getComputerMove() {
654 let moves = this.getAllValidMoves();
655 if (moves.length == 0) return null;
656 // "Search" at depth 1 for now
657 const maxeval = V.INFINITY;
658 const color = this.turn;
659 const emptyMove = {
660 start: { x: -1, y: -1 },
661 end: { x: -1, y: -1 },
662 appear: [],
663 vanish: []
664 };
665 moves.forEach(m => {
666 this.play(m);
667 m.eval = (color == "w" ? -1 : 1) * maxeval;
668 const moves2 = this.getAllValidMoves().concat([emptyMove]);
669 m.next = moves2[0];
670 moves2.forEach(m2 => {
671 this.play(m2);
672 const score = this.getCurrentScore();
673 let mvEval = 0;
674 if (score != "1/2") {
675 if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
676 else mvEval = this.evalPosition();
677 }
678 if (
679 (color == 'w' && mvEval > m.eval) ||
680 (color == 'b' && mvEval < m.eval)
681 ) {
682 m.eval = mvEval;
683 m.next = m2;
684 }
685 this.undo(m2);
686 });
687 this.undo(m);
688 });
689 moves.sort((a, b) => {
690 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
691 });
692 let candidates = [0];
693 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
694 candidates.push(i);
695 const mIdx = candidates[randInt(candidates.length)];
696 const move2 = moves[mIdx].next;
697 delete moves[mIdx]["next"];
698 return [moves[mIdx], move2];
699 }
700
701 getNotation(move) {
702 if (move.start.x < 0)
703 // A second move is always required, but may be empty
704 return "-";
705 const initialSquare = V.CoordsToSquare(move.start);
706 const finalSquare = V.CoordsToSquare(move.end);
707 if (move.appear.length == 0)
708 // Pushed or pulled out of the board
709 return initialSquare + "R";
710 return move.appear[0].p.toUpperCase() + initialSquare + finalSquare;
711 }
712 };