eb82bb55e1ae598ecf40bfcb6039a94d13b8daf9
1 import { ChessRules
} from "@/base_rules";
2 import { randInt
} from "@/utils/alea";
4 export class SynchroneRules
extends ChessRules
{
5 static get CanAnalyze() {
9 static get ShowMoves() {
13 static IsGoodFen(fen
) {
14 if (!ChessRules
.IsGoodFen(fen
)) return false;
15 const fenParsed
= V
.ParseFen(fen
);
19 fenParsed
.turn
== "b" &&
20 // NOTE: do not check really JSON stringified move...
21 (!fenParsed
.whiteMove
|| fenParsed
.whiteMove
== "-")
24 (fenParsed
.turn
== "w" && fenParsed
.whiteMove
!= "-")
31 static IsGoodEnpassant(enpassant
) {
32 const epArray
= enpassant
.split(",");
33 if (![2, 3].includes(epArray
.length
)) return false;
34 epArray
.forEach(epsq
=> {
36 const ep
= V
.SquareToCoords(epsq
);
37 if (isNaN(ep
.x
) || !V
.OnBoard(ep
)) return false;
43 static ParseFen(fen
) {
44 const fenParts
= fen
.split(" ");
46 ChessRules
.ParseFen(fen
),
47 { whiteMove: fenParts
[5] }
51 static GenRandInitFen(randomness
) {
52 return ChessRules
.GenRandInitFen(randomness
).slice(0, -1) + "-,- -";
56 return super.getFen() + " " + this.getWhitemoveFen();
60 return super.getFenForRepeat() + "_" + this.getWhitemoveFen();
63 setOtherVariables(fen
) {
64 const parsedFen
= V
.ParseFen(fen
);
65 this.setFlags(parsedFen
.flags
);
66 const epArray
= parsedFen
.enpassant
.split(",");
68 epArray
.forEach(epsq
=> this.epSquares
.push(this.getEpSquare(epsq
)));
70 // Also init whiteMove
72 parsedFen
.whiteMove
!= "-"
73 ? JSON
.parse(parsedFen
.whiteMove
)
77 // After undo(): no need to re-set INIT_COL_KING
79 this.kingPos
= { w: [-1, -1], b: [-1, -1] };
80 for (let i
= 0; i
< V
.size
.x
; i
++) {
81 for (let j
= 0; j
< V
.size
.y
; j
++) {
82 if (this.getPiece(i
, j
) == V
.KING
)
83 this.kingPos
[this.getColor(i
, j
)] = [i
, j
];
89 const L
= this.epSquares
.length
;
91 const start
= L
- 2 - (this.turn
== 'b' ? 1 : 0);
92 for (let i
=start
; i
< L
; i
++) {
93 if (!this.epSquares
[i
]) res
+= "-,";
94 else res
+= V
.CoordsToSquare(this.epSquares
[i
]) + ",";
96 return res
.slice(0, -1);
100 if (!this.whiteMove
) return "-";
101 return JSON
.stringify({
102 start: this.whiteMove
.start
,
103 end: this.whiteMove
.end
,
104 appear: this.whiteMove
.appear
,
105 vanish: this.whiteMove
.vanish
109 getPossibleMovesFrom([x
, y
]) {
111 this.filterValid(super.getPotentialMovesFrom([x
, y
]))
112 // Augment with potential recaptures:
113 .concat(this.getRecaptures())
117 // Aux function used to find opponent and self captures
118 getCaptures(x
, y
, color
) {
119 const sliderAttack
= (xx
, yy
, allowedSteps
) => {
120 const deltaX
= xx
- x
,
121 absDeltaX
= Math
.abs(deltaX
);
122 const deltaY
= yy
- y
,
123 absDeltaY
= Math
.abs(deltaY
);
124 const step
= [ deltaX
/ absDeltaX
|| 0, deltaY
/ absDeltaY
|| 0 ];
126 // Check that the step is a priori valid:
127 (absDeltaX
!= absDeltaY
&& deltaX
!= 0 && deltaY
!= 0) ||
128 allowedSteps
.every(st
=> st
[0] != step
[0] || st
[1] != step
[1])
132 let sq
= [ x
+ step
[0], y
+ step
[1] ];
133 while (sq
[0] != xx
|| sq
[1] != yy
) {
134 // NOTE: no need to check OnBoard in this special case
135 if (this.board
[sq
[0]][sq
[1]] != V
.EMPTY
) return null;
139 return this.getBasicMove([xx
, yy
], [x
, y
]);
141 // Can I take on the square [x, y] ?
142 // If yes, return the (list of) capturing move(s)
144 for (let i
=0; i
<8; i
++) {
145 for (let j
=0; j
<8; j
++) {
146 if (this.getColor(i
, j
) == color
) {
147 switch (this.getPiece(i
, j
)) {
149 // Pushed pawns move as enemy pawns
150 const shift
= (color
== 'w' ? 1 : -1);
151 if (x
+ shift
== i
&& Math
.abs(y
- j
) == 1)
152 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
156 const deltaX
= Math
.abs(i
- x
);
157 const deltaY
= Math
.abs(j
- y
);
159 deltaX
+ deltaY
== 3 &&
160 [1, 2].includes(deltaX
) &&
161 [1, 2].includes(deltaY
)
163 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
168 if (Math
.abs(i
- x
) <= 1 && Math
.abs(j
- y
) <= 1)
169 moves
.push(this.getBasicMove([i
, j
], [x
, y
]));
172 const mv
= sliderAttack(i
, j
, V
.steps
[V
.ROOK
]);
173 if (!!mv
) moves
.push(mv
);
177 const mv
= sliderAttack(i
, j
, V
.steps
[V
.BISHOP
]);
178 if (!!mv
) moves
.push(mv
);
182 const mv
= sliderAttack(
183 i
, j
, V
.steps
[V
.ROOK
].concat(V
.steps
[V
.BISHOP
]));
184 if (!!mv
) moves
.push(mv
);
191 return this.filterValid(moves
);
195 // 1) Generate all opponent's capturing moves
196 let oppCaptureMoves
= [];
197 const color
= this.turn
;
198 const oppCol
= V
.GetOppCol(color
);
199 for (let i
=0; i
<8; i
++) {
200 for (let j
=0; j
<8; j
++) {
202 this.getColor(i
, j
) == color
&&
203 // Do not consider king captures: self-captures of king are forbidden
204 this.getPiece(i
, j
) != V
.KING
206 Array
.prototype.push
.apply(
208 this.getCaptures(i
, j
, oppCol
)
213 // 2) Play each opponent's capture, and see if back-captures are possible:
214 // Lookup table to quickly decide if a move is already in list:
217 oppCaptureMoves
.forEach(m
=> {
218 // If another opponent capture with same endpoint already processed, skip:
219 const mHash
= "m" + m
.end
.x
+ m
.end
.y
;
220 if (!moveSet
[mHash
]) {
221 moveSet
[mHash
] = true;
222 // Just make enemy piece disappear, to clear potential path:
223 const justDisappear
= {
225 vanish: [m
.vanish
[0]]
227 V
.PlayOnBoard(this.board
, justDisappear
);
228 // Can I take on [m.end.x, m.end.y] ? If yes, add to list:
229 this.getCaptures(m
.end
.x
, m
.end
.y
, color
).forEach(cm
=> moves
.push(cm
));
230 V
.UndoOnBoard(this.board
, justDisappear
);
237 // Return possible moves + potential recaptures
238 return super.getAllValidMoves().concat(this.getRecaptures());
242 if (moves
.length
== 0) return [];
243 // filterValid can be called when it's "not our turn":
244 const color
= moves
[0].vanish
[0].c
;
245 return moves
.filter(m
=> {
246 const piece
= m
.vanish
[0].p
;
247 if (piece
== V
.KING
) {
248 this.kingPos
[color
][0] = m
.appear
[0].x
;
249 this.kingPos
[color
][1] = m
.appear
[0].y
;
251 V
.PlayOnBoard(this.board
, m
);
252 let res
= !this.underCheck(color
);
253 V
.UndoOnBoard(this.board
, m
);
254 if (piece
== V
.KING
) this.kingPos
[color
] = [m
.start
.x
, m
.start
.y
];
259 atLeastOneMove(color
) {
260 const curTurn
= this.turn
;
262 const res
= super.atLeastOneMove();
267 // White and black (partial) moves were played: merge
268 resolveSynchroneMove(move) {
269 const m1
= this.whiteMove
;
271 // For PlayOnBoard (no need for start / end, irrelevant)
279 if ((m1
.end
.x
!= m2
.end
.x
) || (m1
.end
.y
!= m2
.end
.y
)) {
280 // Easy case: two independant moves (which may (self-)capture)
281 smove
.appear
.push(m1
.appear
[0]);
282 smove
.appear
.push(m2
.appear
[0]);
283 // "Captured" pieces may have moved:
284 if (m1
.appear
.length
== 2) {
286 smove
.appear
.push(m1
.appear
[1]);
287 smove
.vanish
.push(m1
.vanish
[1]);
289 m1
.vanish
.length
== 2 &&
291 m1
.vanish
[1].x
!= m2
.start
.x
||
292 m1
.vanish
[1].y
!= m2
.start
.y
295 smove
.vanish
.push(m1
.vanish
[1]);
297 if (m2
.appear
.length
== 2) {
299 smove
.appear
.push(m2
.appear
[1]);
300 smove
.vanish
.push(m2
.vanish
[1]);
302 m2
.vanish
.length
== 2 &&
304 m2
.vanish
[1].x
!= m1
.start
.x
||
305 m2
.vanish
[1].y
!= m1
.start
.y
308 smove
.vanish
.push(m2
.vanish
[1]);
312 if (m1
.vanish
.length
== 1 && m2
.vanish
.length
== 1) {
313 // Easy case: both disappear except if one is a king
314 const p1
= m1
.vanish
[0].p
;
315 const p2
= m2
.vanish
[0].p
;
316 if ([p1
, p2
].includes(V
.KING
)) {
321 c: (p1
== V
.KING
? 'w' : 'b')
325 // One move is a self-capture and the other a normal capture:
326 // only the self-capture appears
327 const selfCaptureMove
=
328 m1
.vanish
[1].c
== m1
.vanish
[0].c
334 p: selfCaptureMove
.appear
[0].p
,
335 c: selfCaptureMove
.vanish
[0].c
340 p: selfCaptureMove
.vanish
[1].p
,
341 c: selfCaptureMove
.vanish
[0].c
349 move.flags
= JSON
.stringify(this.aggregateFlags()); //save flags (for undo)
350 this.epSquares
.push(this.getEpSquare(move));
351 // Do not play on board (would reveal the move...)
352 this.turn
= V
.GetOppCol(this.turn
);
357 updateCastleFlags(move) {
358 const firstRank
= { 'w': V
.size
.x
- 1, 'b': 0 };
359 move.appear
.concat(move.vanish
).forEach(av
=> {
360 for (let c
of ['w', 'b']) {
361 if (av
.x
== firstRank
[c
] && this.castleFlags
[c
].includes(av
.y
)) {
362 const flagIdx
= (av
.y
== this.castleFlags
[c
][0] ? 0 : 1);
363 this.castleFlags
[c
][flagIdx
] = 8;
370 if (this.turn
== 'b') {
371 // NOTE: whiteMove is used read-only, so no need to copy
372 this.whiteMove
= move;
376 // A full turn just ended:
377 const smove
= this.resolveSynchroneMove(move);
378 V
.PlayOnBoard(this.board
, smove
);
379 move.whiteMove
= this.whiteMove
; //for undo
380 this.whiteMove
= null;
382 // Update king position + flags
383 let kingAppear
= { 'w': false, 'b': false };
384 for (let i
=0; i
<smove
.appear
.length
; i
++) {
385 if (smove
.appear
[i
].p
== V
.KING
) {
386 const c
= smove
.appear
[i
].c
;
387 kingAppear
[c
] = true;
388 this.kingPos
[c
][0] = smove
.appear
[i
].x
;
389 this.kingPos
[c
][1] = smove
.appear
[i
].y
;
392 for (let i
=0; i
<smove
.vanish
.length
; i
++) {
393 if (smove
.vanish
[i
].p
== V
.KING
) {
394 const c
= smove
.vanish
[i
].c
;
395 if (!kingAppear
[c
]) {
396 this.kingPos
[c
][0] = -1;
397 this.kingPos
[c
][1] = -1;
402 this.updateCastleFlags(smove
);
407 this.epSquares
.pop();
408 this.disaggregateFlags(JSON
.parse(move.flags
));
409 if (this.turn
== 'w')
410 // Back to the middle of the move
411 V
.UndoOnBoard(this.board
, move.smove
);
412 this.turn
= V
.GetOppCol(this.turn
);
418 if (this.turn
== 'w') {
419 // Reset king positions: scan board
421 // Also reset whiteMove
422 this.whiteMove
= null;
423 } else this.whiteMove
= move.whiteMove
;
426 getCheckSquares(color
) {
428 // kingPos must be reset for appropriate highlighting:
429 var lastMove
= JSON
.parse(JSON
.stringify(this.whiteMove
));
430 this.undo(lastMove
); //will erase whiteMove, thus saved above
433 if (this.kingPos
['w'][0] >= 0 && this.underCheck('w'))
434 res
.push(JSON
.parse(JSON
.stringify(this.kingPos
['w'])));
435 if (this.kingPos
['b'][0] >= 0 && this.underCheck('b'))
436 res
.push(JSON
.parse(JSON
.stringify(this.kingPos
['b'])));
437 if (color
== 'b') this.play(lastMove
);
442 if (this.turn
== 'b')
443 // Turn (white + black) not over yet
445 // Was a king captured?
446 if (this.kingPos
['w'][0] < 0) return "0-1";
447 if (this.kingPos
['b'][0] < 0) return "1-0";
448 const whiteCanMove
= this.atLeastOneMove('w');
449 const blackCanMove
= this.atLeastOneMove('b');
450 if (whiteCanMove
&& blackCanMove
) return "*";
452 const whiteInCheck
= this.underCheck('w');
453 const blackInCheck
= this.underCheck('b');
455 (whiteCanMove
&& !this.underCheck('b')) ||
456 (blackCanMove
&& !this.underCheck('w'))
460 // Checkmate: could be mutual
461 if (!whiteCanMove
&& !blackCanMove
) return "1/2";
462 return (whiteCanMove
? "1-0" : "0-1");
466 const maxeval
= V
.INFINITY
;
467 const color
= this.turn
;
468 let moves
= this.getAllValidMoves();
469 if (moves
.length
== 0)
470 // TODO: this situation should not happen
473 if (Math
.random() < 0.5)
474 // Return a random move
475 return moves
[randInt(moves
.length
)];
477 // Rank moves at depth 1:
478 // try to capture something (not re-capturing)
480 V
.PlayOnBoard(this.board
, m
);
481 m
.eval
= this.evalPosition();
482 V
.UndoOnBoard(this.board
, m
);
484 moves
.sort((a
, b
) => {
485 return (color
== "w" ? 1 : -1) * (b
.eval
- a
.eval
);
487 let candidates
= [0];
488 for (let i
= 1; i
< moves
.length
&& moves
[i
].eval
== moves
[0].eval
; i
++)
490 return moves
[candidates
[randInt(candidates
.length
)]];
494 if (move.appear
.length
== 2 && move.appear
[0].p
== V
.KING
)
496 return move.end
.y
< move.start
.y
? "0-0-0" : "0-0";
497 // Basic system: piece + init + dest square
499 move.vanish
[0].p
.toUpperCase() +
500 V
.CoordsToSquare(move.start
) +
501 V
.CoordsToSquare(move.end
)