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 // Also, the pushed/pulled piece must exit the board.
162 isAprioriValidExit([x1
, y1
], [x2
, y2
], color2
) {
163 const color1
= this.getColor(x1
, y1
);
164 const pawnShift
= (color1
== 'w' ? -1 : 1);
165 const lastRank
= (color1
== 'w' ? 0 : 7);
166 const deltaX
= Math
.abs(x1
- x2
);
167 const deltaY
= Math
.abs(y1
- y2
);
168 const checkSlider
= () => {
169 const dir
= this.getNormalizedDirection([x2
- x1
, y2
- y1
]);
170 let [i
, j
] = [x1
+ dir
[0], y1
+ dir
[1]];
171 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
175 return !V
.OnBoard(i
, j
);
177 switch (this.getPiece(x1
, y1
)) {
180 x1
+ pawnShift
== x2
&&
182 (color1
== color2
&& x2
== lastRank
&& y1
== y2
) ||
183 (color1
!= color2
&& deltaY
== 1 && !V
.OnBoard(x2
, 2 * y2
- y1
))
187 if (x1
!= x2
&& y1
!= y2
) return false;
188 return checkSlider();
191 deltaX
+ deltaY
== 3 &&
192 (deltaX
== 1 || deltaY
== 1) &&
193 !V
.OnBoard(2 * x2
- x1
, 2 * y2
- y1
)
196 if (deltaX
!= deltaY
) return false;
197 return checkSlider();
199 if (deltaX
!= 0 && deltaY
!= 0 && deltaX
!= deltaY
) return false;
200 return checkSlider();
205 !V
.OnBoard(2 * x2
- x1
, 2 * y2
- y1
)
211 isAprioriValidVertical([x1
, y1
], x2
) {
212 const piece
= this.getPiece(x1
, y1
);
213 const deltaX
= Math
.abs(x1
- x2
);
214 const startRank
= (this.getColor(x1
, y1
) == 'w' ? 6 : 1);
216 [V
.QUEEN
, V
.ROOK
].includes(piece
) ||
218 [V
.KING
, V
.PAWN
].includes(piece
) &&
221 (deltaX
== 2 && piece
== V
.PAWN
&& x1
== startRank
)
227 // NOTE: for pushes, play the pushed piece first.
228 // for pulls: play the piece doing the action first
229 // NOTE: to push a piece out of the board, make it slide until its king
230 getPotentialMovesFrom([x
, y
]) {
231 const color
= this.turn
;
232 const sqCol
= this.getColor(x
, y
);
233 if (this.subTurn
== 1) {
234 const getMoveHash
= (m
) => {
235 return V
.CoordsToSquare(m
.start
) + V
.CoordsToSquare(m
.end
);
237 const addMoves
= (dir
, nbSteps
) => {
239 this.getMovesInDirection([x
, y
], [-dir
[0], -dir
[1]], nbSteps
)
240 .filter(m
=> !movesHash
[getMoveHash(m
)]);
241 newMoves
.forEach(m
=> { movesHash
[getMoveHash(m
)] = true; });
242 Array
.prototype.push
.apply(moves
, newMoves
);
244 // Free to play any move (if piece of my color):
247 ? super.getPotentialMovesFrom([x
, y
])
249 // There may be several suicide moves: keep only one
251 moves
= moves
.filter(m
=> {
252 const suicide
= (m
.appear
.length
== 0);
254 if (hasExit
) return false;
259 const pawnShift
= (color
== 'w' ? -1 : 1);
260 const pawnStartRank
= (color
== 'w' ? 6 : 1);
261 // Structure to avoid adding moves twice (can be action & move)
263 moves
.forEach(m
=> { movesHash
[getMoveHash(m
)] = true; });
264 // [x, y] is pushed by 'color'
265 for (let step
of V
.steps
[V
.KNIGHT
]) {
266 const [i
, j
] = [x
+ step
[0], y
+ step
[1]];
269 this.board
[i
][j
] != V
.EMPTY
&&
270 this.getColor(i
, j
) == color
&&
271 this.getPiece(i
, j
) == V
.KNIGHT
276 for (let step
of V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
])) {
277 let [i
, j
] = [x
+ step
[0], y
+ step
[1]];
278 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
284 this.board
[i
][j
] != V
.EMPTY
&&
285 this.getColor(i
, j
) == color
287 const deltaX
= Math
.abs(i
- x
);
288 const deltaY
= Math
.abs(j
- y
);
289 switch (this.getPiece(i
, j
)) {
292 (x
- i
) / deltaX
== pawnShift
&&
296 if (sqCol
== color
&& deltaY
== 0) {
298 const maxSteps
= (i
== pawnStartRank
&& deltaX
== 1 ? 2 : 1);
299 addMoves(step
, maxSteps
);
301 else if (sqCol
!= color
&& deltaY
== 1 && deltaX
== 1)
307 if (deltaX
== 0 || deltaY
== 0) addMoves(step
);
310 if (deltaX
== deltaY
) addMoves(step
);
313 // All steps are valid for a queen:
317 if (deltaX
<= 1 && deltaY
<= 1) addMoves(step
, 1);
324 // If subTurn == 2 then we should have a first move,
325 // which restrict what we can play now: only in the first move direction
326 // NOTE: no need for knight or pawn checks, because the move will be
327 // naturally limited in those cases.
328 const L
= this.firstMove
.length
;
329 const fm
= this.firstMove
[L
-1];
331 (fm
.appear
.length
== 2 && fm
.vanish
.length
== 2) ||
332 (fm
.vanish
[0].c
== sqCol
&& sqCol
!= color
)
334 // Castle or again opponent color: no move playable then.
337 if (fm
.appear
.length
== 0) {
338 // Piece at subTurn 1 just exited the board.
339 // Can I be a piece which caused the exit?
341 this.isAprioriValidExit(
343 [fm
.start
.x
, fm
.start
.y
],
348 const dir
= this.getNormalizedDirection(
349 [fm
.start
.x
- x
, fm
.start
.y
- y
]);
350 return this.getMovesInDirection([x
, y
], dir
);
354 const dirM
= this.getNormalizedDirection(
355 [fm
.end
.x
- fm
.start
.x
, fm
.end
.y
- fm
.start
.y
]);
356 const dir
= this.getNormalizedDirection(
357 [fm
.start
.x
- x
, fm
.start
.y
- y
]);
358 // Normalized directions should match
359 if (dir
[0] == dirM
[0] && dir
[1] == dirM
[1]) {
360 // If first move is a pawn move, only a queen, rook, or maybe king or
361 // pawn can follow (need vertical movement option).
363 fm
.vanish
[0].p
== V
.PAWN
&&
364 fm
.vanish
[0].c
== color
&&
365 !this.isAprioriValidVertical([x
, y
], fm
.start
.x
)
369 // And nothing should stand between [x, y] and the square fm.start
370 let [i
, j
] = [x
+ dir
[0], y
+ dir
[1]];
372 (i
!= fm
.start
.x
|| j
!= fm
.start
.y
) &&
373 this.board
[i
][j
] == V
.EMPTY
378 if (i
== fm
.start
.x
&& j
== fm
.start
.y
)
379 return this.getMovesInDirection([x
, y
], dir
);
385 getSlideNJumpMoves([x
, y
], steps
, oneStep
) {
387 const c
= this.getColor(x
, y
);
388 const piece
= this.getPiece(x
, y
);
389 outerLoop: for (let step
of steps
) {
392 while (V
.OnBoard(i
, j
) && this.board
[i
][j
] == V
.EMPTY
) {
393 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
394 if (oneStep
) continue outerLoop
;
398 if (V
.OnBoard(i
, j
)) {
399 if (this.canTake([x
, y
], [i
, j
]))
400 moves
.push(this.getBasicMove([x
, y
], [i
, j
]));
403 // Add potential board exit (suicide), except for the king
404 if (piece
!= V
.KING
) {
406 start: { x: x
, y: y
},
407 end: { x: this.kingPos
[c
][0], y: this.kingPos
[c
][1] },
424 // Does m2 un-do m1 ? (to disallow undoing actions)
425 oppositeMoves(m1
, m2
) {
426 const isEqual
= (av1
, av2
) => {
427 // Precondition: av1 and av2 length = 2
428 for (let av
of av1
) {
429 const avInAv2
= av2
.find(elt
=> {
437 if (!avInAv2
) return false;
442 m1
.appear
.length
== 2 &&
443 m2
.appear
.length
== 2 &&
444 m1
.vanish
.length
== 2 &&
445 m2
.vanish
.length
== 2 &&
446 isEqual(m1
.appear
, m2
.vanish
) &&
447 isEqual(m1
.vanish
, m2
.appear
)
451 getAmove(move1
, move2
) {
452 // Just merge (one is action one is move, one may be empty)
454 appear: move1
.appear
.concat(move2
.appear
),
455 vanish: move1
.vanish
.concat(move2
.vanish
)
460 const color
= this.turn
;
461 if (this.subTurn
== 1) {
462 return moves
.filter(m
=> {
463 // A move is valid either if it doesn't result in a check,
464 // or if a second move is possible to counter the check
465 // (not undoing a potential move + action of the opponent)
467 let res
= this.underCheck(color
);
469 const moves2
= this.getAllPotentialMoves();
470 for (let m2
of moves2
) {
472 const res2
= this.underCheck(color
);
484 const Lf
= this.firstMove
.length
;
485 const La
= this.amoves
.length
;
486 if (La
== 0) return super.filterValid(moves
);
490 // Move shouldn't undo another:
491 const amove
= this.getAmove(this.firstMove
[Lf
-1], m
);
492 return !this.oppositeMoves(this.amoves
[La
-1], amove
);
498 isAttackedBySlideNJump([x
, y
], color
, piece
, steps
, oneStep
) {
499 for (let step
of steps
) {
500 let rx
= x
+ step
[0],
502 while (V
.OnBoard(rx
, ry
) && this.board
[rx
][ry
] == V
.EMPTY
&& !oneStep
) {
508 this.getPiece(rx
, ry
) == piece
&&
509 this.getColor(rx
, ry
) == color
511 // Continue some steps in the same direction (pull)
516 this.board
[rx
][ry
] == V
.EMPTY
&&
522 if (!V
.OnBoard(rx
, ry
)) return true;
523 // Step in the other direction (push)
528 this.board
[rx
][ry
] == V
.EMPTY
&&
534 if (!V
.OnBoard(rx
, ry
)) return true;
540 isAttackedByPawn([x
, y
], color
) {
541 const lastRank
= (color
== 'w' ? 0 : 7);
543 // The king can be pushed out by a pawn only on last rank
545 const pawnShift
= (color
== "w" ? 1 : -1);
546 for (let i
of [-1, 1]) {
550 this.getPiece(x
+ pawnShift
, y
+ i
) == V
.PAWN
&&
551 this.getColor(x
+ pawnShift
, y
+ i
) == color
559 // No consideration of color: all pieces could be played
560 getAllPotentialMoves() {
561 let potentialMoves
= [];
562 for (let i
= 0; i
< V
.size
.x
; i
++) {
563 for (let j
= 0; j
< V
.size
.y
; j
++) {
564 if (this.board
[i
][j
] != V
.EMPTY
) {
565 Array
.prototype.push
.apply(
567 this.getPotentialMovesFrom([i
, j
])
572 return potentialMoves
;
576 if (this.subTurn
== 2)
579 return super.getCurrentScore();
583 // If subTurn == 2 && square is empty && !underCheck,
584 // then return an empty move, allowing to "pass" subTurn2
587 this.board
[square
[0]][square
[1]] == V
.EMPTY
&&
588 !this.underCheck(this.turn
)
591 start: { x: -1, y: -1 },
592 end: { x: -1, y: -1 },
601 move.flags
= JSON
.stringify(this.aggregateFlags());
602 V
.PlayOnBoard(this.board
, move);
603 if (this.subTurn
== 2) {
604 const L
= this.firstMove
.length
;
605 this.amoves
.push(this.getAmove(this.firstMove
[L
-1], move));
606 this.turn
= V
.GetOppCol(this.turn
);
609 else this.firstMove
.push(move);
610 this.subTurn
= 3 - this.subTurn
;
615 if (move.start
.x
< 0) return;
616 for (let a
of move.appear
)
617 if (a
.p
== V
.KING
) this.kingPos
[a
.c
] = [a
.x
, a
.y
];
618 this.updateCastleFlags(move);
621 updateCastleFlags(move) {
622 const firstRank
= { 'w': V
.size
.x
- 1, 'b': 0 };
623 for (let v
of move.vanish
) {
624 if (v
.p
== V
.KING
) this.castleFlags
[v
.c
] = [V
.size
.y
, V
.size
.y
];
625 else if (v
.x
== firstRank
[v
.c
] && this.castleFlags
[v
.c
].includes(v
.y
)) {
626 const flagIdx
= (v
.y
== this.castleFlags
[v
.c
][0] ? 0 : 1);
627 this.castleFlags
[v
.c
][flagIdx
] = V
.size
.y
;
633 this.disaggregateFlags(JSON
.parse(move.flags
));
634 V
.UndoOnBoard(this.board
, move);
635 if (this.subTurn
== 1) {
636 this.turn
= V
.GetOppCol(this.turn
);
639 else this.firstMove
.pop();
640 this.subTurn
= 3 - this.subTurn
;
645 // (Potentially) Reset king position
646 for (let v
of move.vanish
)
647 if (v
.p
== V
.KING
) this.kingPos
[v
.c
] = [v
.x
, v
.y
];
651 let moves
= this.getAllValidMoves();
652 if (moves
.length
== 0) return null;
653 // "Search" at depth 1 for now
654 const maxeval
= V
.INFINITY
;
655 const color
= this.turn
;
657 start: { x: -1, y: -1 },
658 end: { x: -1, y: -1 },
664 m
.eval
= (color
== "w" ? -1 : 1) * maxeval
;
665 const moves2
= this.getAllValidMoves().concat([emptyMove
]);
667 moves2
.forEach(m2
=> {
669 const score
= this.getCurrentScore();
671 if (score
!= "1/2") {
672 if (score
!= "*") mvEval
= (score
== "1-0" ? 1 : -1) * maxeval
;
673 else mvEval
= this.evalPosition();
676 (color
== 'w' && mvEval
> m
.eval
) ||
677 (color
== 'b' && mvEval
< m
.eval
)
686 moves
.sort((a
, b
) => {
687 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
689 let candidates
= [0];
690 for (let i
= 1; i
< moves
.length
&& moves
[i
].eval
== moves
[0].eval
; i
++)
692 const mIdx
= candidates
[randInt(candidates
.length
)];
693 const move2
= moves
[mIdx
].next
;
694 delete moves
[mIdx
]["next"];
695 return [moves
[mIdx
], move2
];
699 if (move.start
.x
< 0)
700 // A second move is always required, but may be empty
702 const initialSquare
= V
.CoordsToSquare(move.start
);
703 const finalSquare
= V
.CoordsToSquare(move.end
);
704 if (move.appear
.length
== 0)
705 // Pushed or pulled out of the board
706 return initialSquare
+ "R";
707 return move.appear
[0].p
.toUpperCase() + initialSquare
+ finalSquare
;