Fix rules implementation and translations for Allmate1
[vchess.git] / client / src / variants / Dynamo.js
CommitLineData
b866a62a 1import { ChessRules, Move, PiPo } from "@/base_rules";
ad1e629e 2import { randInt } from "@/utils/alea";
b866a62a 3
0d5335de 4export class DynamoRules extends ChessRules {
becbc692 5 // TODO? later, allow to push out pawns on a and h files
61656127
BA
6 static get HasEnpassant() {
7 return false;
8 }
9
c7550017
BA
10 canIplay(side, [x, y]) {
11 // Sometimes opponent's pieces can be moved directly
e78633db 12 return this.turn == side;
c7550017
BA
13 }
14
61656127
BA
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;
93ce6119 21 if (amove != "-") {
61656127 22 const amoveParts = amove.split("/");
ad1e629e 23 let move = {
61656127
BA
24 // No need for start & end
25 appear: [],
26 vanish: []
27 };
28 [0, 1].map(i => {
ad1e629e
BA
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 }
61656127
BA
43 });
44 this.amoves.push(move);
c7550017 45 }
7b53b5a7 46 this.subTurn = 1;
a443d256
BA
47 // Stack "first moves" (on subTurn 1) to merge and check opposite moves
48 this.firstMove = [];
c7550017
BA
49 }
50
61656127
BA
51 static ParseFen(fen) {
52 return Object.assign(
53 ChessRules.ParseFen(fen),
93ce6119 54 { amove: fen.split(" ")[4] }
61656127
BA
55 );
56 }
57
58 static IsGoodFen(fen) {
59 if (!ChessRules.IsGoodFen(fen)) return false;
60 const fenParts = fen.split(" ");
ad1e629e
BA
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 }
61656127
BA
74 return true;
75 }
76
93ce6119
BA
77 getFen() {
78 return super.getFen() + " " + this.getAmoveFen();
61656127
BA
79 }
80
93ce6119
BA
81 getFenForRepeat() {
82 return super.getFenForRepeat() + "_" + this.getAmoveFen();
83 }
84
85 getAmoveFen() {
86 const L = this.amoves.length;
7b53b5a7 87 if (L == 0) return "-";
93ce6119
BA
88 return (
89 ["appear","vanish"].map(
90 mpart => {
156986e6 91 if (this.amoves[L-1][mpart].length == 0) return "-";
93ce6119
BA
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 );
61656127
BA
103 }
104
105 canTake() {
106 // Captures don't occur (only pulls & pushes)
107 return false;
108 }
109
b2655276
BA
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];
61656127 115 let moves = [];
b2655276
BA
116 const color = this.getColor(x, y);
117 const piece = this.getPiece(x, y);
118 const lastRank = (color == 'w' ? 0 : 7);
7b53b5a7 119 let counter = 1;
b2655276
BA
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]));
7b53b5a7
BA
129 if (++counter > nbSteps) break;
130 i += dx;
131 j += dy;
b2655276
BA
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 },
7b53b5a7 138 end: { x: this.kingPos[color][0], y: this.kingPos[color][1] },
b2655276
BA
139 appear: [],
140 vanish: [{ x: x, y: y, c: color, p: piece }]
141 })
142 );
143 }
61656127
BA
144 return moves;
145 }
146
b2655276
BA
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
becbc692
BA
160 // There was something on x2,y2, maybe our color, pushed or (self)pulled
161 isAprioriValidExit([x1, y1], [x2, y2], color2, piece2) {
b2655276 162 const color1 = this.getColor(x1, y1);
b2655276 163 const pawnShift = (color1 == 'w' ? -1 : 1);
ad1e629e 164 const lastRank = (color1 == 'w' ? 0 : 7);
b2655276
BA
165 const deltaX = Math.abs(x1 - x2);
166 const deltaY = Math.abs(y1 - y2);
ad1e629e
BA
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 };
becbc692 176 switch (piece2 || this.getPiece(x1, y1)) {
b2655276
BA
177 case V.PAWN:
178 return (
ad1e629e 179 x1 + pawnShift == x2 &&
b2655276 180 (
ad1e629e 181 (color1 == color2 && x2 == lastRank && y1 == y2) ||
becbc692
BA
182 (
183 color1 != color2 &&
184 deltaY == 1 &&
185 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
186 )
b2655276
BA
187 )
188 );
189 case V.ROOK:
ad1e629e
BA
190 if (x1 != x2 && y1 != y2) return false;
191 return checkSlider();
192 case V.KNIGHT:
193 return (
194 deltaX + deltaY == 3 &&
195 (deltaX == 1 || deltaY == 1) &&
196 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
197 );
b2655276 198 case V.BISHOP:
ad1e629e
BA
199 if (deltaX != deltaY) return false;
200 return checkSlider();
b2655276 201 case V.QUEEN:
ad1e629e
BA
202 if (deltaX != 0 && deltaY != 0 && deltaX != deltaY) return false;
203 return checkSlider();
204 case V.KING:
b2655276 205 return (
ad1e629e
BA
206 deltaX <= 1 &&
207 deltaY <= 1 &&
208 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
b2655276 209 );
93ce6119 210 }
b2655276 211 return false;
b866a62a
BA
212 }
213
05d37cc7
BA
214 isAprioriValidVertical([x1, y1], x2) {
215 const piece = this.getPiece(x1, y1);
216 const deltaX = Math.abs(x1 - x2);
217 const startRank = (this.getColor(x1, y1) == 'w' ? 6 : 1);
218 return (
219 [V.QUEEN, V.ROOK].includes(piece) ||
220 (
221 [V.KING, V.PAWN].includes(piece) &&
222 (
223 deltaX == 1 ||
224 (deltaX == 2 && piece == V.PAWN && x1 == startRank)
225 )
226 )
227 );
228 }
229
93ce6119 230 // NOTE: for pushes, play the pushed piece first.
61656127 231 // for pulls: play the piece doing the action first
b2655276 232 // NOTE: to push a piece out of the board, make it slide until its king
b866a62a
BA
233 getPotentialMovesFrom([x, y]) {
234 const color = this.turn;
81e74ee5 235 const sqCol = this.getColor(x, y);
becbc692
BA
236 const pawnShift = (color == 'w' ? -1 : 1);
237 const pawnStartRank = (color == 'w' ? 6 : 1);
238 const getMoveHash = (m) => {
239 return V.CoordsToSquare(m.start) + V.CoordsToSquare(m.end);
240 };
93ce6119 241 if (this.subTurn == 1) {
b2655276
BA
242 const addMoves = (dir, nbSteps) => {
243 const newMoves =
244 this.getMovesInDirection([x, y], [-dir[0], -dir[1]], nbSteps)
245 .filter(m => !movesHash[getMoveHash(m)]);
7b53b5a7 246 newMoves.forEach(m => { movesHash[getMoveHash(m)] = true; });
b2655276
BA
247 Array.prototype.push.apply(moves, newMoves);
248 };
8c267d0c 249 // Free to play any move (if piece of my color):
cfceecba 250 let moves =
81e74ee5 251 sqCol == color
8c267d0c
BA
252 ? super.getPotentialMovesFrom([x, y])
253 : [];
cfceecba
BA
254 // There may be several suicide moves: keep only one
255 let hasExit = false;
256 moves = moves.filter(m => {
257 const suicide = (m.appear.length == 0);
258 if (suicide) {
259 if (hasExit) return false;
260 hasExit = true;
261 }
262 return true;
263 });
7b53b5a7
BA
264 // Structure to avoid adding moves twice (can be action & move)
265 let movesHash = {};
266 moves.forEach(m => { movesHash[getMoveHash(m)] = true; });
b2655276
BA
267 // [x, y] is pushed by 'color'
268 for (let step of V.steps[V.KNIGHT]) {
269 const [i, j] = [x + step[0], y + step[1]];
7b53b5a7
BA
270 if (
271 V.OnBoard(i, j) &&
272 this.board[i][j] != V.EMPTY &&
273 this.getColor(i, j) == color &&
274 this.getPiece(i, j) == V.KNIGHT
275 ) {
276 addMoves(step, 1);
b2655276
BA
277 }
278 }
7b53b5a7 279 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
b2655276
BA
280 let [i, j] = [x + step[0], y + step[1]];
281 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
282 i += step[0];
283 j += step[1];
284 }
285 if (
286 V.OnBoard(i, j) &&
287 this.board[i][j] != V.EMPTY &&
288 this.getColor(i, j) == color
289 ) {
290 const deltaX = Math.abs(i - x);
291 const deltaY = Math.abs(j - y);
b2655276
BA
292 switch (this.getPiece(i, j)) {
293 case V.PAWN:
ad1e629e
BA
294 if (
295 (x - i) / deltaX == pawnShift &&
296 deltaX <= 2 &&
297 deltaY <= 1
298 ) {
81e74ee5 299 if (sqCol == color && deltaY == 0) {
b2655276
BA
300 // Pushed forward
301 const maxSteps = (i == pawnStartRank && deltaX == 1 ? 2 : 1);
302 addMoves(step, maxSteps);
303 }
81e74ee5 304 else if (sqCol != color && deltaY == 1 && deltaX == 1)
b2655276
BA
305 // Pushed diagonally
306 addMoves(step, 1);
307 }
308 break;
309 case V.ROOK:
310 if (deltaX == 0 || deltaY == 0) addMoves(step);
311 break;
b2655276
BA
312 case V.BISHOP:
313 if (deltaX == deltaY) addMoves(step);
314 break;
315 case V.QUEEN:
cfceecba
BA
316 // All steps are valid for a queen:
317 addMoves(step);
b2655276
BA
318 break;
319 case V.KING:
320 if (deltaX <= 1 && deltaY <= 1) addMoves(step, 1);
321 break;
322 }
323 }
324 }
325 return moves;
b866a62a 326 }
93ce6119 327 // If subTurn == 2 then we should have a first move,
b2655276 328 // which restrict what we can play now: only in the first move direction
93ce6119
BA
329 const L = this.firstMove.length;
330 const fm = this.firstMove[L-1];
81e74ee5
BA
331 if (
332 (fm.appear.length == 2 && fm.vanish.length == 2) ||
333 (fm.vanish[0].c == sqCol && sqCol != color)
334 ) {
335 // Castle or again opponent color: no move playable then.
b2655276 336 return [];
81e74ee5 337 }
becbc692
BA
338 const piece = this.getPiece(x, y);
339 const getPushExit = () => {
340 // Piece at subTurn 1 exited: can I have caused the exit?
ad1e629e
BA
341 if (
342 this.isAprioriValidExit(
343 [x, y],
344 [fm.start.x, fm.start.y],
345 fm.vanish[0].c
346 )
347 ) {
b2655276
BA
348 // Seems so:
349 const dir = this.getNormalizedDirection(
350 [fm.start.x - x, fm.start.y - y]);
6e0c0bcb 351 const nbSteps =
becbc692
BA
352 [V.PAWN, V.KING, V.KNIGHT].includes(piece)
353 ? 1
354 : null;
6e0c0bcb 355 return this.getMovesInDirection([x, y], dir, nbSteps);
b2655276 356 }
becbc692 357 return [];
93ce6119 358 }
becbc692
BA
359 const getPushMoves = () => {
360 // Piece from subTurn 1 is still on board:
b2655276
BA
361 const dirM = this.getNormalizedDirection(
362 [fm.end.x - fm.start.x, fm.end.y - fm.start.y]);
363 const dir = this.getNormalizedDirection(
364 [fm.start.x - x, fm.start.y - y]);
ad1e629e
BA
365 // Normalized directions should match
366 if (dir[0] == dirM[0] && dir[1] == dirM[1]) {
becbc692
BA
367 // We don't know if first move is a pushed piece or normal move,
368 // so still must check if the push is valid.
369 const deltaX = Math.abs(fm.start.x - x);
370 const deltaY = Math.abs(fm.start.y - y);
371 switch (piece) {
372 case V.PAWN:
373 if (x == pawnStartRank) {
374 if (
375 (fm.start.x - x) * pawnShift < 0 ||
376 deltaX >= 3 ||
377 deltaY >= 2 ||
378 (fm.vanish[0].c == color && deltaY > 0) ||
379 (fm.vanish[0].c != color && deltaY == 0) ||
380 Math.abs(fm.end.x - fm.start.x) > deltaX ||
381 fm.end.y - fm.start.y != fm.start.y - y
382 ) {
383 return [];
384 }
385 }
386 else {
387 if (
388 fm.start.x - x != pawnShift ||
389 deltaY >= 2 ||
390 (fm.vanish[0].c == color && deltaY == 1) ||
391 (fm.vanish[0].c != color && deltaY == 0) ||
392 fm.end.x - fm.start.x != pawnShift ||
393 fm.end.y - fm.start.y != fm.start.y - y
394 ) {
395 return [];
396 }
397 }
398 break;
399 case V.KNIGHT:
400 if (
401 (deltaX + deltaY != 3 || (deltaX == 0 && deltaY == 0)) ||
402 (fm.end.x - fm.start.x != fm.start.x - x) ||
403 (fm.end.y - fm.start.y != fm.start.y - y)
404 ) {
405 return [];
406 }
407 break;
408 case V.KING:
409 if (
410 (deltaX >= 2 || deltaY >= 2) ||
411 (fm.end.x - fm.start.x != fm.start.x - x) ||
412 (fm.end.y - fm.start.y != fm.start.y - y)
413 ) {
414 return [];
415 }
416 break;
417 case V.BISHOP:
418 if (deltaX != deltaY) return [];
419 break;
420 case V.ROOK:
421 if (deltaX != 0 && deltaY != 0) return [];
422 break;
423 case V.QUEEN:
424 if (deltaX != deltaY && deltaX != 0 && deltaY != 0) return [];
425 break;
426 }
427 // Nothing should stand between [x, y] and the square fm.start
428 let [i, j] = [x + dir[0], y + dir[1]];
429 while (
430 (i != fm.start.x || j != fm.start.y) &&
431 this.board[i][j] == V.EMPTY
432 ) {
433 i += dir[0];
434 j += dir[1];
435 }
436 if (i == fm.start.x && j == fm.start.y)
437 return this.getMovesInDirection([x, y], dir);
438 }
439 return [];
440 }
441 const getPullExit = () => {
442 // Piece at subTurn 1 exited: can I be pulled?
443 // Note: pawns and kings cannot suicide,
444 // so fm.vanish[0].p is neither PAWN or KING
445 if (
446 this.isAprioriValidExit(
447 [x, y],
448 [fm.start.x, fm.start.y],
449 fm.vanish[0].c,
450 fm.vanish[0].p
451 )
452 ) {
453 // Seems so:
454 const dir = this.getNormalizedDirection(
455 [fm.start.x - x, fm.start.y - y]);
456 const nbSteps = (fm.vanish[0].p == V.KNIGHT ? 1 : null);
457 return this.getMovesInDirection([x, y], dir, nbSteps);
458 }
459 return [];
460 };
461 const getPullMoves = () => {
462 if (fm.vanish[0].p == V.PAWN)
463 // pawns cannot pull
464 return [];
465 const dirM = this.getNormalizedDirection(
466 [fm.end.x - fm.start.x, fm.end.y - fm.start.y]);
467 const dir = this.getNormalizedDirection(
468 [fm.start.x - x, fm.start.y - y]);
469 // Normalized directions should match
470 if (dir[0] == dirM[0] && dir[1] == dirM[1]) {
471 // Am I at the right distance?
472 const deltaX = Math.abs(x - fm.start.x);
473 const deltaY = Math.abs(y - fm.start.y);
05d37cc7 474 if (
becbc692
BA
475 (fm.vanish[0].p == V.KING && (deltaX > 1 || deltaY > 1)) ||
476 (fm.vanish[0].p == V.KNIGHT &&
477 (deltaX + deltaY != 3 || deltaX == 0 || deltaY == 0))
05d37cc7
BA
478 ) {
479 return [];
480 }
becbc692 481 // Nothing should stand between [x, y] and the square fm.start
ad1e629e
BA
482 let [i, j] = [x + dir[0], y + dir[1]];
483 while (
484 (i != fm.start.x || j != fm.start.y) &&
485 this.board[i][j] == V.EMPTY
486 ) {
487 i += dir[0];
488 j += dir[1];
489 }
490 if (i == fm.start.x && j == fm.start.y)
491 return this.getMovesInDirection([x, y], dir);
492 }
becbc692
BA
493 return [];
494 };
495 if (fm.vanish[0].c != color) {
496 // Only possible action is a push:
497 if (fm.appear.length == 0) return getPushExit();
498 return getPushMoves();
499 }
500 else if (sqCol != color) {
501 // Only possible action is a pull, considering moving piece abilities
502 if (fm.appear.length == 0) return getPullExit();
503 return getPullMoves();
504 }
505 else {
506 // My color + my color: both actions possible
507 // Structure to avoid adding moves twice (can be action & move)
508 let movesHash = {};
509 if (fm.appear.length == 0) {
510 const pushes = getPushExit();
511 pushes.forEach(m => { movesHash[getMoveHash(m)] = true; });
512 return (
513 pushes.concat(getPullExit().filter(m => !movesHash[getMoveHash(m)]))
514 );
515 }
516 const pushes = getPushMoves();
517 pushes.forEach(m => { movesHash[getMoveHash(m)] = true; });
518 return (
519 pushes.concat(getPullMoves().filter(m => !movesHash[getMoveHash(m)]))
520 );
93ce6119 521 }
b2655276 522 return [];
61656127
BA
523 }
524
cfceecba
BA
525 getSlideNJumpMoves([x, y], steps, oneStep) {
526 let moves = [];
81e74ee5
BA
527 const c = this.getColor(x, y);
528 const piece = this.getPiece(x, y);
cfceecba
BA
529 outerLoop: for (let step of steps) {
530 let i = x + step[0];
531 let j = y + step[1];
532 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
533 moves.push(this.getBasicMove([x, y], [i, j]));
534 if (oneStep) continue outerLoop;
535 i += step[0];
536 j += step[1];
537 }
538 if (V.OnBoard(i, j)) {
539 if (this.canTake([x, y], [i, j]))
540 moves.push(this.getBasicMove([x, y], [i, j]));
541 }
542 else {
543 // Add potential board exit (suicide), except for the king
cfceecba 544 if (piece != V.KING) {
cfceecba
BA
545 moves.push({
546 start: { x: x, y: y},
547 end: { x: this.kingPos[c][0], y: this.kingPos[c][1] },
548 appear: [],
549 vanish: [
550 new PiPo({
551 x: x,
552 y: y,
553 c: c,
554 p: piece
555 })
556 ]
557 });
558 }
559 }
560 }
561 return moves;
562 }
563
61656127
BA
564 // Does m2 un-do m1 ? (to disallow undoing actions)
565 oppositeMoves(m1, m2) {
566 const isEqual = (av1, av2) => {
61656127
BA
567 for (let av of av1) {
568 const avInAv2 = av2.find(elt => {
569 return (
570 elt.x == av.x &&
571 elt.y == av.y &&
572 elt.c == av.c &&
573 elt.p == av.p
574 );
575 });
576 if (!avInAv2) return false;
577 }
578 return true;
579 };
266fba4a
BA
580 // All appear and vanish arrays must have the same length
581 const mL = m1.appear.length;
61656127 582 return (
266fba4a
BA
583 m2.appear.length == mL &&
584 m1.vanish.length == mL &&
585 m2.vanish.length == mL &&
61656127
BA
586 isEqual(m1.appear, m2.vanish) &&
587 isEqual(m1.vanish, m2.appear)
588 );
589 }
590
93ce6119
BA
591 getAmove(move1, move2) {
592 // Just merge (one is action one is move, one may be empty)
593 return {
594 appear: move1.appear.concat(move2.appear),
595 vanish: move1.vanish.concat(move2.vanish)
596 }
597 }
598
61656127 599 filterValid(moves) {
93ce6119 600 const color = this.turn;
2e29e0e3 601 const La = this.amoves.length;
93ce6119
BA
602 if (this.subTurn == 1) {
603 return moves.filter(m => {
604 // A move is valid either if it doesn't result in a check,
605 // or if a second move is possible to counter the check
606 // (not undoing a potential move + action of the opponent)
607 this.play(m);
608 let res = this.underCheck(color);
2e29e0e3
BA
609 let isOpposite = La > 0 && this.oppositeMoves(this.amoves[La-1], m);
610 if (res || isOpposite) {
93ce6119 611 const moves2 = this.getAllPotentialMoves();
ad1e629e 612 for (let m2 of moves2) {
93ce6119
BA
613 this.play(m2);
614 const res2 = this.underCheck(color);
2e29e0e3
BA
615 const amove = this.getAmove(m, m2);
616 isOpposite =
617 La > 0 && this.oppositeMoves(this.amoves[La-1], amove);
93ce6119 618 this.undo(m2);
2e29e0e3 619 if (!res2 && !isOpposite) {
93ce6119
BA
620 res = false;
621 break;
622 }
623 }
624 }
625 this.undo(m);
626 return !res;
627 });
628 }
629 const Lf = this.firstMove.length;
93ce6119 630 if (La == 0) return super.filterValid(moves);
a443d256 631 return (
93ce6119 632 super.filterValid(
a443d256
BA
633 moves.filter(m => {
634 // Move shouldn't undo another:
93ce6119
BA
635 const amove = this.getAmove(this.firstMove[Lf-1], m);
636 return !this.oppositeMoves(this.amoves[La-1], amove);
a443d256
BA
637 })
638 )
639 );
b866a62a
BA
640 }
641
c7550017
BA
642 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
643 for (let step of steps) {
644 let rx = x + step[0],
645 ry = y + step[1];
646 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
647 rx += step[0];
648 ry += step[1];
649 }
650 if (
651 V.OnBoard(rx, ry) &&
652 this.getPiece(rx, ry) == piece &&
653 this.getColor(rx, ry) == color
654 ) {
8c267d0c
BA
655 // Continue some steps in the same direction (pull)
656 rx += step[0];
657 ry += step[1];
658 while (
659 V.OnBoard(rx, ry) &&
660 this.board[rx][ry] == V.EMPTY &&
661 !oneStep
662 ) {
663 rx += step[0];
664 ry += step[1];
665 }
666 if (!V.OnBoard(rx, ry)) return true;
667 // Step in the other direction (push)
c7550017
BA
668 rx = x - step[0];
669 ry = y - step[1];
2c5d7b20
BA
670 while (
671 V.OnBoard(rx, ry) &&
672 this.board[rx][ry] == V.EMPTY &&
673 !oneStep
674 ) {
c7550017
BA
675 rx -= step[0];
676 ry -= step[1];
677 }
678 if (!V.OnBoard(rx, ry)) return true;
679 }
680 }
681 return false;
682 }
683
684 isAttackedByPawn([x, y], color) {
becbc692 685 // The king can be pushed out by a pawn on last rank or near the edge
c7550017
BA
686 const pawnShift = (color == "w" ? 1 : -1);
687 for (let i of [-1, 1]) {
688 if (
689 y + i >= 0 &&
690 y + i < V.size.y &&
691 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
692 this.getColor(x + pawnShift, y + i) == color
693 ) {
becbc692 694 return !V.OnBoard(x - pawnShift, y - i);
c7550017
BA
695 }
696 }
697 return false;
698 }
61656127 699
156986e6
BA
700 // No consideration of color: all pieces could be played
701 getAllPotentialMoves() {
702 let potentialMoves = [];
703 for (let i = 0; i < V.size.x; i++) {
704 for (let j = 0; j < V.size.y; j++) {
705 if (this.board[i][j] != V.EMPTY) {
706 Array.prototype.push.apply(
707 potentialMoves,
708 this.getPotentialMovesFrom([i, j])
709 );
710 }
711 }
712 }
713 return potentialMoves;
714 }
715
61656127
BA
716 getCurrentScore() {
717 if (this.subTurn == 2)
718 // Move not over
719 return "*";
720 return super.getCurrentScore();
721 }
722
93ce6119 723 doClick(square) {
becbc692
BA
724 // A click to promote a piece on subTurn 2 would trigger this.
725 // For now it would then return [NaN, NaN] because surrounding squares
726 // have no IDs in the promotion modal. TODO: improve this?
727 if (!square[0]) return null;
2e29e0e3 728 // If subTurn == 2 && square is empty && !underCheck && !isOpposite,
b2655276 729 // then return an empty move, allowing to "pass" subTurn2
2e29e0e3
BA
730 const La = this.amoves.length;
731 const Lf = this.firstMove.length;
93ce6119
BA
732 if (
733 this.subTurn == 2 &&
7b53b5a7 734 this.board[square[0]][square[1]] == V.EMPTY &&
2e29e0e3
BA
735 !this.underCheck(this.turn) &&
736 (La == 0 || !this.oppositeMoves(this.amoves[La-1], this.firstMove[Lf-1]))
93ce6119
BA
737 ) {
738 return {
7b53b5a7
BA
739 start: { x: -1, y: -1 },
740 end: { x: -1, y: -1 },
93ce6119
BA
741 appear: [],
742 vanish: []
743 };
744 }
745 return null;
746 }
747
61656127
BA
748 play(move) {
749 move.flags = JSON.stringify(this.aggregateFlags());
750 V.PlayOnBoard(this.board, move);
7ddfec38 751 if (this.subTurn == 2) {
7b53b5a7
BA
752 const L = this.firstMove.length;
753 this.amoves.push(this.getAmove(this.firstMove[L-1], move));
61656127 754 this.turn = V.GetOppCol(this.turn);
7ddfec38 755 this.movesCount++;
61656127 756 }
a443d256 757 else this.firstMove.push(move);
7ddfec38 758 this.subTurn = 3 - this.subTurn;
61656127
BA
759 this.postPlay(move);
760 }
761
7b53b5a7
BA
762 postPlay(move) {
763 if (move.start.x < 0) return;
764 for (let a of move.appear)
765 if (a.p == V.KING) this.kingPos[a.c] = [a.x, a.y];
766 this.updateCastleFlags(move);
767 }
768
769 updateCastleFlags(move) {
770 const firstRank = { 'w': V.size.x - 1, 'b': 0 };
7ddfec38 771 for (let v of move.vanish) {
7b53b5a7
BA
772 if (v.p == V.KING) this.castleFlags[v.c] = [V.size.y, V.size.y];
773 else if (v.x == firstRank[v.c] && this.castleFlags[v.c].includes(v.y)) {
774 const flagIdx = (v.y == this.castleFlags[v.c][0] ? 0 : 1);
775 this.castleFlags[v.c][flagIdx] = V.size.y;
7ddfec38 776 }
61656127
BA
777 }
778 }
779
780 undo(move) {
781 this.disaggregateFlags(JSON.parse(move.flags));
782 V.UndoOnBoard(this.board, move);
7ddfec38 783 if (this.subTurn == 1) {
2e29e0e3 784 this.amoves.pop();
61656127 785 this.turn = V.GetOppCol(this.turn);
7ddfec38 786 this.movesCount--;
61656127 787 }
a443d256 788 else this.firstMove.pop();
7ddfec38 789 this.subTurn = 3 - this.subTurn;
61656127
BA
790 this.postUndo(move);
791 }
7b53b5a7
BA
792
793 postUndo(move) {
794 // (Potentially) Reset king position
795 for (let v of move.vanish)
796 if (v.p == V.KING) this.kingPos[v.c] = [v.x, v.y];
797 }
798
ad1e629e
BA
799 getComputerMove() {
800 let moves = this.getAllValidMoves();
801 if (moves.length == 0) return null;
802 // "Search" at depth 1 for now
803 const maxeval = V.INFINITY;
804 const color = this.turn;
805 const emptyMove = {
806 start: { x: -1, y: -1 },
807 end: { x: -1, y: -1 },
808 appear: [],
809 vanish: []
810 };
811 moves.forEach(m => {
812 this.play(m);
813 m.eval = (color == "w" ? -1 : 1) * maxeval;
814 const moves2 = this.getAllValidMoves().concat([emptyMove]);
815 m.next = moves2[0];
816 moves2.forEach(m2 => {
817 this.play(m2);
818 const score = this.getCurrentScore();
819 let mvEval = 0;
820 if (score != "1/2") {
821 if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
822 else mvEval = this.evalPosition();
823 }
824 if (
825 (color == 'w' && mvEval > m.eval) ||
826 (color == 'b' && mvEval < m.eval)
827 ) {
828 m.eval = mvEval;
829 m.next = m2;
830 }
831 this.undo(m2);
832 });
833 this.undo(m);
834 });
835 moves.sort((a, b) => {
836 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
837 });
838 let candidates = [0];
839 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
840 candidates.push(i);
841 const mIdx = candidates[randInt(candidates.length)];
842 const move2 = moves[mIdx].next;
843 delete moves[mIdx]["next"];
844 return [moves[mIdx], move2];
845 }
846
7b53b5a7
BA
847 getNotation(move) {
848 if (move.start.x < 0)
849 // A second move is always required, but may be empty
850 return "-";
851 const initialSquare = V.CoordsToSquare(move.start);
852 const finalSquare = V.CoordsToSquare(move.end);
853 if (move.appear.length == 0)
854 // Pushed or pulled out of the board
855 return initialSquare + "R";
856 return move.appear[0].p.toUpperCase() + initialSquare + finalSquare;
857 }
0d5335de 858};