Fix Synchrone variant
[vchess.git] / client / src / variants / Synchrone.js
1 import { ChessRules } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export class SynchroneRules extends ChessRules {
5 static get CanAnalyze() {
6 return false;
7 }
8
9 static get ShowMoves() {
10 return "byrow";
11 }
12
13 static IsGoodFen(fen) {
14 if (!ChessRules.IsGoodFen(fen)) return false;
15 const fenParsed = V.ParseFen(fen);
16 // 5) Check whiteMove
17 if (
18 (
19 fenParsed.turn == "w" &&
20 // NOTE: do not check really JSON stringified move...
21 (!fenParsed.whiteMove || fenParsed.whiteMove == "-")
22 )
23 ||
24 (fenParsed.turn == "b" && fenParsed.whiteMove != "-")
25 ) {
26 return false;
27 }
28 return true;
29 }
30
31 static IsGoodEnpassant(enpassant) {
32 const epArray = enpassant.split(",");
33 if (![2, 3].includes(epArray.length)) return false;
34 epArray.forEach(epsq => {
35 if (epsq != "-") {
36 const ep = V.SquareToCoords(epsq);
37 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
38 }
39 });
40 return true;
41 }
42
43 static ParseFen(fen) {
44 const fenParts = fen.split(" ");
45 return Object.assign(
46 ChessRules.ParseFen(fen),
47 { whiteMove: fenParts[5] }
48 );
49 }
50
51 static GenRandInitFen(randomness) {
52 return ChessRules.GenRandInitFen(randomness).slice(0, -1) + "-,- -";
53 }
54
55 getFen() {
56 return super.getFen() + " " + this.getWhitemoveFen();
57 }
58
59 getFenForRepeat() {
60 return super.getFenForRepeat() + "_" + this.getWhitemoveFen();
61 }
62
63 setOtherVariables(fen) {
64 const parsedFen = V.ParseFen(fen);
65 this.setFlags(parsedFen.flags);
66 const epArray = parsedFen.enpassant.split(",");
67 this.epSquares = [];
68 epArray.forEach(epsq => this.epSquares.push(this.getEpSquare(epsq)));
69 super.scanKings(fen);
70 // Also init whiteMove
71 this.whiteMove =
72 parsedFen.whiteMove != "-"
73 ? JSON.parse(parsedFen.whiteMove)
74 : null;
75 }
76
77 // After undo(): no need to re-set INIT_COL_KING
78 scanKings() {
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];
84 }
85 }
86 }
87
88 getEnpassantFen() {
89 const L = this.epSquares.length;
90 let res = "";
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]) + ",";
95 }
96 return res.slice(0, -1);
97 }
98
99 getWhitemoveFen() {
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
106 });
107 }
108
109 // NOTE: lazy unefficient implementation (for now. TODO?)
110 getPossibleMovesFrom([x, y]) {
111 const moves = this.getAllValidMoves();
112 return moves.filter(m => {
113 return m.start.x == x && m.start.y == y;
114 });
115 }
116
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 ];
125 if (
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])
129 ) {
130 return null;
131 }
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;
136 sq[0] += step[0];
137 sq[1] += step[1];
138 }
139 return this.getBasicMove([xx, yy], [x, y]);
140 };
141 // Can I take on the square [x, y] ?
142 // If yes, return the (list of) capturing move(s)
143 let moves = [];
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)) {
148 case V.PAWN: {
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]));
153 break;
154 }
155 case V.KNIGHT: {
156 const deltaX = Math.abs(i - x);
157 const deltaY = Math.abs(j - y);
158 if (
159 deltaX + deltaY == 3 &&
160 [1, 2].includes(deltaX) &&
161 [1, 2].includes(deltaY)
162 ) {
163 moves.push(this.getBasicMove([i, j], [x, y]));
164 }
165 break;
166 }
167 case V.KING:
168 if (Math.abs(i - x) <= 1 && Math.abs(j - y) <= 1)
169 moves.push(this.getBasicMove([i, j], [x, y]));
170 break;
171 case V.ROOK: {
172 const mv = sliderAttack(i, j, V.steps[V.ROOK]);
173 if (!!mv) moves.push(mv);
174 break;
175 }
176 case V.BISHOP: {
177 const mv = sliderAttack(i, j, V.steps[V.BISHOP]);
178 if (!!mv) moves.push(mv);
179 break;
180 }
181 case V.QUEEN: {
182 const mv = sliderAttack(
183 i, j, V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
184 if (!!mv) moves.push(mv);
185 break;
186 }
187 }
188 }
189 }
190 }
191 return this.filterValid(moves);
192 }
193
194 getAllValidMoves() {
195 const color = this.turn;
196 // 0) Generate our possible moves
197 let myMoves = super.getAllValidMoves();
198 // 1) Generate all opponent's capturing moves
199 let oppCaptureMoves = [];
200 const oppCol = V.GetOppCol(color);
201 for (let i=0; i<8; i++) {
202 for (let j=0; j<8; j++) {
203 if (
204 this.getColor(i, j) == color &&
205 // Do not consider king captures: self-captures of king are forbidden
206 this.getPiece(i, j) != V.KING
207 ) {
208 Array.prototype.push.apply(
209 oppCaptureMoves,
210 this.getCaptures(i, j, oppCol)
211 );
212 }
213 }
214 }
215 // 2) Play each opponent's capture, and see if back-captures are possible:
216 // Lookup table to quickly decide if a move is already in list:
217 let moveSet = {};
218 oppCaptureMoves.forEach(m => {
219 // If another opponent capture with same endpoint already processed, skip:
220 const mHash = "m" + m.end.x + m.end.y;
221 if (!moveSet[mHash]) {
222 moveSet[mHash] = true;
223 // Just make enemy piece disappear, to clear potential path:
224 const justDisappear = {
225 appear: [],
226 vanish: [m.vanish[0]]
227 };
228 V.PlayOnBoard(this.board, justDisappear);
229 // Can I take on [m.end.x, m.end.y] ? If yes, add to list:
230 this.getCaptures(m.end.x, m.end.y, color).forEach(cm => myMoves.push(cm));
231 V.UndoOnBoard(this.board, justDisappear);
232 }
233 });
234 return myMoves;
235 }
236
237 filterValid(moves) {
238 if (moves.length == 0) return [];
239 // filterValid can be called when it's "not our turn":
240 const color = moves[0].vanish[0].c;
241 return moves.filter(m => {
242 const piece = m.vanish[0].p;
243 if (piece == V.KING) {
244 this.kingPos[color][0] = m.appear[0].x;
245 this.kingPos[color][1] = m.appear[0].y;
246 }
247 V.PlayOnBoard(this.board, m);
248 let res = !this.underCheck(color);
249 V.UndoOnBoard(this.board, m);
250 if (piece == V.KING) this.kingPos[color] = [m.start.x, m.start.y];
251 return res;
252 });
253 }
254
255 atLeastOneMove(color) {
256 const curTurn = this.turn;
257 this.turn = color;
258 const res = super.atLeastOneMove();
259 this.turn = curTurn;
260 return res;
261 }
262
263 // White and black (partial) moves were played: merge
264 resolveSynchroneMove(move) {
265 const m1 = this.whiteMove;
266 const m2 = move;
267 // For PlayOnBoard (no need for start / end, irrelevant)
268 let smove = {
269 appear: [],
270 vanish: [
271 m1.vanish[0],
272 m2.vanish[0]
273 ]
274 };
275 if ((m1.end.x != m2.end.x) || (m1.end.y != m2.end.y)) {
276 // Easy case: two independant moves (which may (self-)capture)
277 smove.appear.push(m1.appear[0]);
278 smove.appear.push(m2.appear[0]);
279 // "Captured" pieces may have moved:
280 if (m1.appear.length == 2) {
281 // Castle
282 smove.appear.push(m1.appear[1]);
283 smove.vanish.push(m1.vanish[1]);
284 } else if (
285 m1.vanish.length == 2 &&
286 (
287 m1.vanish[1].x != m2.start.x ||
288 m1.vanish[1].y != m2.start.y
289 )
290 ) {
291 smove.vanish.push(m1.vanish[1]);
292 }
293 if (m2.appear.length == 2) {
294 // Castle
295 smove.appear.push(m2.appear[1]);
296 smove.vanish.push(m2.vanish[1]);
297 } else if (
298 m2.vanish.length == 2 &&
299 (
300 m2.vanish[1].x != m1.start.x ||
301 m2.vanish[1].y != m1.start.y
302 )
303 ) {
304 smove.vanish.push(m2.vanish[1]);
305 }
306 } else {
307 // Collision:
308 if (m1.vanish.length == 1 && m2.vanish.length == 1) {
309 // Easy case: both disappear except if one is a king
310 const p1 = m1.vanish[0].p;
311 const p2 = m2.vanish[0].p;
312 if ([p1, p2].includes(V.KING)) {
313 smove.appear.push({
314 x: m1.end.x,
315 y: m1.end.y,
316 p: V.KING,
317 c: (p1 == V.KING ? 'w' : 'b')
318 });
319 }
320 } else {
321 // One move is a self-capture and the other a normal capture:
322 // only the self-capture appears
323 const selfCaptureMove =
324 m1.vanish[1].c == m1.vanish[0].c
325 ? m1
326 : m2;
327 smove.appear.push({
328 x: m1.end.x,
329 y: m1.end.y,
330 p: selfCaptureMove.appear[0].p,
331 c: selfCaptureMove.vanish[0].c
332 });
333 smove.vanish.push({
334 x: m1.end.x,
335 y: m1.end.y,
336 p: selfCaptureMove.vanish[1].p,
337 c: selfCaptureMove.vanish[0].c
338 });
339 }
340 }
341 return smove;
342 }
343
344 play(move) {
345 move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo)
346 this.epSquares.push(this.getEpSquare(move));
347 // Do not play on board (would reveal the move...)
348 this.turn = V.GetOppCol(this.turn);
349 this.movesCount++;
350 this.postPlay(move);
351 }
352
353 updateCastleFlags(move) {
354 const firstRank = { 'w': V.size.x - 1, 'b': 0 };
355 move.appear.concat(move.vanish).forEach(av => {
356 for (let c of ['w', 'b']) {
357 if (av.x == firstRank[c] && this.castleFlags[c].includes(av.y)) {
358 const flagIdx = (av.y == this.castleFlags[c][0] ? 0 : 1);
359 this.castleFlags[c][flagIdx] = 8;
360 }
361 }
362 });
363 }
364
365 postPlay(move) {
366 if (this.turn == 'b') {
367 // NOTE: whiteMove is used read-only, so no need to copy
368 this.whiteMove = move;
369 return;
370 }
371
372 // A full turn just ended:
373 const smove = this.resolveSynchroneMove(move);
374 V.PlayOnBoard(this.board, smove);
375 move.whiteMove = this.whiteMove; //for undo
376 this.whiteMove = null;
377
378 // Update king position + flags
379 let kingAppear = { 'w': false, 'b': false };
380 for (let i=0; i<smove.appear.length; i++) {
381 if (smove.appear[i].p == V.KING) {
382 const c = smove.appear[i].c;
383 kingAppear[c] = true;
384 this.kingPos[c][0] = smove.appear[i].x;
385 this.kingPos[c][1] = smove.appear[i].y;
386 }
387 }
388 for (let i=0; i<smove.vanish.length; i++) {
389 if (smove.vanish[i].p == V.KING) {
390 const c = smove.vanish[i].c;
391 if (!kingAppear[c]) {
392 this.kingPos[c][0] = -1;
393 this.kingPos[c][1] = -1;
394 }
395 break;
396 }
397 }
398 this.updateCastleFlags(smove);
399 move.smove = smove;
400 }
401
402 undo(move) {
403 this.epSquares.pop();
404 this.disaggregateFlags(JSON.parse(move.flags));
405 if (this.turn == 'w')
406 // Back to the middle of the move
407 V.UndoOnBoard(this.board, move.smove);
408 this.turn = V.GetOppCol(this.turn);
409 this.movesCount--;
410 this.postUndo(move);
411 }
412
413 postUndo(move) {
414 if (this.turn == 'w') {
415 // Reset king positions: scan board
416 this.scanKings();
417 // Also reset whiteMove
418 this.whiteMove = null;
419 } else this.whiteMove = move.whiteMove;
420 }
421
422 getCheckSquares(color) {
423 if (color == 'b') {
424 // kingPos must be reset for appropriate highlighting:
425 var lastMove = JSON.parse(JSON.stringify(this.whiteMove));
426 this.undo(lastMove); //will erase whiteMove, thus saved above
427 }
428 let res = [];
429 if (this.underCheck('w'))
430 res.push(JSON.parse(JSON.stringify(this.kingPos['w'])));
431 if (this.underCheck('b'))
432 res.push(JSON.parse(JSON.stringify(this.kingPos['b'])));
433 if (color == 'b') this.play(lastMove);
434 return res;
435 }
436
437 getCurrentScore() {
438 if (this.turn == 'b')
439 // Turn (white + black) not over yet
440 return "*";
441 // Was a king captured?
442 if (this.kingPos['w'][0] < 0) return "0-1";
443 if (this.kingPos['b'][0] < 0) return "1-0";
444 const whiteCanMove = this.atLeastOneMove('w');
445 const blackCanMove = this.atLeastOneMove('b');
446 if (whiteCanMove && blackCanMove) return "*";
447 // Game over
448 const whiteInCheck = this.underCheck('w');
449 const blackInCheck = this.underCheck('b');
450 if (
451 (whiteCanMove && !this.underCheck('b')) ||
452 (blackCanMove && !this.underCheck('w'))
453 ) {
454 return "1/2";
455 }
456 // Checkmate: could be mutual
457 if (!whiteCanMove && !blackCanMove) return "1/2";
458 return (whiteCanMove ? "1-0" : "0-1");
459 }
460
461 getComputerMove() {
462 const maxeval = V.INFINITY;
463 const color = this.turn;
464 let moves = this.getAllValidMoves();
465 if (moves.length == 0)
466 // TODO: this situation should not happen
467 return null;
468
469 if (Math.random() < 0.5)
470 // Return a random move
471 return moves[randInt(moves.length)];
472
473 // Rank moves at depth 1:
474 // try to capture something (not re-capturing)
475 moves.forEach(m => {
476 V.PlayOnBoard(this.board, m);
477 m.eval = this.evalPosition();
478 V.UndoOnBoard(this.board, m);
479 });
480 moves.sort((a, b) => {
481 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
482 });
483 let candidates = [0];
484 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
485 candidates.push(i);
486 return moves[candidates[randInt(candidates.length)]];
487 }
488
489 getNotation(move) {
490 if (move.appear.length == 2 && move.appear[0].p == V.KING)
491 // Castle
492 return move.end.y < move.start.y ? "0-0-0" : "0-0";
493 // Basic system: piece + init + dest square
494 return (
495 move.vanish[0].p.toUpperCase() +
496 V.CoordsToSquare(move.start) +
497 V.CoordsToSquare(move.end)
498 );
499 }
500 };