1 import { ChessRules
, Move
, PiPo
} from "@/base_rules";
2 import { randInt
} from "@/utils/alea";
4 export class DynamoRules
extends ChessRules
{
5 // TODO: later, allow to push out pawns on a and h files
6 static get HasEnpassant() {
10 canIplay(side
, [x
, y
]) {
11 // Sometimes opponent's pieces can be moved directly
12 return this.turn
== side
;
15 setOtherVariables(fen
) {
16 super.setOtherVariables(fen
);
18 // Local stack of "action moves"
20 const amove
= V
.ParseFen(fen
).amove
;
22 const amoveParts
= amove
.split("/");
24 // No need for start & end
29 if (amoveParts
[i
] != "-") {
30 amoveParts
[i
].split(".").forEach(av
=> {
32 const xy
= V
.SquareToCoords(av
.substr(2));
33 move[i
== 0 ? "appear" : "vanish"].push(
44 this.amoves
.push(move);
47 // Stack "first moves" (on subTurn 1) to merge and check opposite moves
51 static ParseFen(fen
) {
53 ChessRules
.ParseFen(fen
),
54 { amove: fen
.split(" ")[4] }
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
) {
69 for (let psq
of part
.split("."))
70 if (!psq
.match(/^[a-r]{3}[1-8]$/)) return false;
78 return super.getFen() + " " + this.getAmoveFen();
82 return super.getFenForRepeat() + "_" + this.getAmoveFen();
86 const L
= this.amoves
.length
;
87 if (L
== 0) return "-";
89 ["appear","vanish"].map(
91 if (this.amoves
[L
-1][mpart
].length
== 0) return "-";
93 this.amoves
[L
-1][mpart
].map(
95 const square
= V
.CoordsToSquare({ x: av
.x
, y: av
.y
});
96 return av
.c
+ av
.p
+ square
;
106 // Captures don't occur (only pulls & pushes)
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
];
116 const color
= this.getColor(x
, y
);
117 const piece
= this.getPiece(x
, y
);
118 const lastRank
= (color
== 'w' ? 0 : 7);
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
});
128 else moves
.push(super.getBasicMove([x
, y
], [i
, j
]));
129 if (++counter
> nbSteps
) break;
133 if (!V
.OnBoard(i
, j
) && piece
!= V
.KING
) {
134 // Add special "exit" move, by "taking king"
137 start: { x: x
, y: y
},
138 end: { x: this.kingPos
[color
][0], y: this.kingPos
[color
][1] },
140 vanish: [{ x: x
, y: y
, c: color
, p: piece
}]
147 // Normalize direction to know the step
148 getNormalizedDirection([dx
, dy
]) {
149 const absDir
= [Math
.abs(dx
), Math
.abs(dy
)];
151 if (absDir
[0] != 0 && absDir
[1] != 0 && absDir
[0] != absDir
[1])
153 divisor
= Math
.min(absDir
[0], absDir
[1]);
155 // Standard slider (or maybe a pawn or king: same)
156 divisor
= Math
.max(absDir
[0], absDir
[1]);
157 return [dx
/ divisor
, dy
/ divisor
];
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
) {
174 return !V
.OnBoard(i
, j
);
176 switch (this.getPiece(x1
, y1
)) {
179 x1
+ pawnShift
== x2
&&
181 (color1
== color2
&& x2
== lastRank
&& y1
== y2
) ||
182 (color1
!= color2
&& deltaY
== 1 && !V
.OnBoard(x2
, 2 * y2
- y1
))
186 if (x1
!= x2
&& y1
!= y2
) return false;
187 return checkSlider();
190 deltaX
+ deltaY
== 3 &&
191 (deltaX
== 1 || deltaY
== 1) &&
192 !V
.OnBoard(2 * x2
- x1
, 2 * y2
- y1
)
195 if (deltaX
!= deltaY
) return false;
196 return checkSlider();
198 if (deltaX
!= 0 && deltaY
!= 0 && deltaX
!= deltaY
) return false;
199 return checkSlider();
204 !V
.OnBoard(2 * x2
- x1
, 2 * y2
- y1
)
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);
215 [V
.QUEEN
, V
.ROOK
].includes(piece
) ||
217 [V
.KING
, V
.PAWN
].includes(piece
) &&
220 (deltaX
== 2 && piece
== V
.PAWN
&& x1
== startRank
)
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
);
236 const addMoves
= (dir
, nbSteps
) => {
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
);
243 // Free to play any move (if piece of my color):
246 ? super.getPotentialMovesFrom([x
, y
])
248 // There may be several suicide moves: keep only one
250 moves
= moves
.filter(m
=> {
251 const suicide
= (m
.appear
.length
== 0);
253 if (hasExit
) return false;
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)
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]];
268 this.board
[i
][j
] != V
.EMPTY
&&
269 this.getColor(i
, j
) == color
&&
270 this.getPiece(i
, j
) == V
.KNIGHT
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
) {
283 this.board
[i
][j
] != V
.EMPTY
&&
284 this.getColor(i
, j
) == color
286 const deltaX
= Math
.abs(i
- x
);
287 const deltaY
= Math
.abs(j
- y
);
288 switch (this.getPiece(i
, j
)) {
291 (x
- i
) / deltaX
== pawnShift
&&
295 if (sqCol
== color
&& deltaY
== 0) {
297 const maxSteps
= (i
== pawnStartRank
&& deltaX
== 1 ? 2 : 1);
298 addMoves(step
, maxSteps
);
300 else if (sqCol
!= color
&& deltaY
== 1 && deltaX
== 1)
306 if (deltaX
== 0 || deltaY
== 0) addMoves(step
);
309 if (deltaX
== deltaY
) addMoves(step
);
312 // All steps are valid for a queen:
316 if (deltaX
<= 1 && deltaY
<= 1) addMoves(step
, 1);
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];
330 (fm
.appear
.length
== 2 && fm
.vanish
.length
== 2) ||
331 (fm
.vanish
[0].c
== sqCol
&& sqCol
!= color
)
333 // Castle or again opponent color: no move playable then.
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?
340 // Only "turn" color can do actions
342 this.isAprioriValidExit(
344 [fm
.start
.x
, fm
.start
.y
],
349 const dir
= this.getNormalizedDirection(
350 [fm
.start
.x
- x
, fm
.start
.y
- y
]);
352 ([V
.PAWN
,V
.KING
,V
.KNIGHT
].includes(this.getPiece(x
, y
)) ? 1 : null);
353 return this.getMovesInDirection([x
, y
], dir
, nbSteps
);
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).
366 fm
.vanish
[0].p
== V
.PAWN
&&
367 fm
.vanish
[0].c
== color
&&
368 !this.isAprioriValidVertical([x
, y
], fm
.start
.x
)
372 // And nothing should stand between [x, y] and the square fm.start
373 let [i
, j
] = [x
+ dir
[0], y
+ dir
[1]];
375 (i
!= fm
.start
.x
|| j
!= fm
.start
.y
) &&
376 this.board
[i
][j
] == V
.EMPTY
381 if (i
== fm
.start
.x
&& j
== fm
.start
.y
)
382 return this.getMovesInDirection([x
, y
], dir
);
388 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
390 const c
= this.getColor(x
, y
);
391 const piece
= this.getPiece(x
, y
);
392 outerLoop: for (let step
of steps
) {
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
;
401 if (V
.OnBoard(i
, j
)) {
402 if (this.canTake([x
, y
], [i
, j
]))
403 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
406 // Add potential board exit (suicide), except for the king
407 if (piece
!= V
.KING
) {
409 start: { x: x
, y: y
},
410 end: { x: this.kingPos
[c
][0], y: this.kingPos
[c
][1] },
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
=> {
440 if (!avInAv2
) return false;
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
)
454 getAmove(move1
, move2
) {
455 // Just merge (one is action one is move, one may be empty)
457 appear: move1
.appear
.concat(move2
.appear
),
458 vanish: move1
.vanish
.concat(move2
.vanish
)
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)
470 let res
= this.underCheck(color
);
472 const moves2
= this.getAllPotentialMoves();
473 for (let m2
of moves2
) {
475 const res2
= this.underCheck(color
);
487 const Lf
= this.firstMove
.length
;
488 const La
= this.amoves
.length
;
489 if (La
== 0) return super.filterValid(moves
);
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
);
501 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
502 for (let step
of steps
) {
503 let rx
= x
+ step
[0],
505 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
511 this.getPiece(rx
, ry
) == piece
&&
512 this.getColor(rx
, ry
) == color
514 // Continue some steps in the same direction (pull)
519 this.board
[rx
][ry
] == V
.EMPTY
&&
525 if (!V
.OnBoard(rx
, ry
)) return true;
526 // Step in the other direction (push)
531 this.board
[rx
][ry
] == V
.EMPTY
&&
537 if (!V
.OnBoard(rx
, ry
)) return true;
543 isAttackedByPawn([x
, y
], color
) {
544 const lastRank
= (color
== 'w' ? 0 : 7);
546 // The king can be pushed out by a pawn only on last rank
548 const pawnShift
= (color
== "w" ? 1 : -1);
549 for (let i
of [-1, 1]) {
553 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
554 this.getColor(x
+ pawnShift
, y
+ i
) == color
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(
570 this.getPotentialMovesFrom([i
, j
])
575 return potentialMoves
;
579 if (this.subTurn
== 2)
582 return super.getCurrentScore();
586 // If subTurn == 2 && square is empty && !underCheck,
587 // then return an empty move, allowing to "pass" subTurn2
590 this.board
[square
[0]][square
[1]] == V
.EMPTY
&&
591 !this.underCheck(this.turn
)
594 start: { x: -1, y: -1 },
595 end: { x: -1, y: -1 },
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
);
612 else this.firstMove
.push(move);
613 this.subTurn
= 3 - this.subTurn
;
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);
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
;
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
);
642 else this.firstMove
.pop();
643 this.subTurn
= 3 - this.subTurn
;
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
];
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
;
660 start: { x: -1, y: -1 },
661 end: { x: -1, y: -1 },
667 m
.eval
= (color
== "w" ? -1 : 1) * maxeval
;
668 const moves2
= this.getAllValidMoves().concat([emptyMove
]);
670 moves2
.forEach(m2
=> {
672 const score
= this.getCurrentScore();
674 if (score
!= "1/2") {
675 if (score
!= "*") mvEval
= (score
== "1-0" ? 1 : -1) * maxeval
;
676 else mvEval
= this.evalPosition();
679 (color
== 'w' && mvEval
> m
.eval
) ||
680 (color
== 'b' && mvEval
< m
.eval
)
689 moves
.sort((a
, b
) => {
690 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
692 let candidates
= [0];
693 for (let i
= 1; i
< moves
.length
&& moves
[i
].eval
== moves
[0].eval
; i
++)
695 const mIdx
= candidates
[randInt(candidates
.length
)];
696 const move2
= moves
[mIdx
].next
;
697 delete moves
[mIdx
]["next"];
698 return [moves
[mIdx
], move2
];
702 if (move.start
.x
< 0)
703 // A second move is always required, but may be empty
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
;