Some fixes, draw lines on board, add 7 variants
[vchess.git] / client / src / variants / Dynamo.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3
4 export class DynamoRules extends ChessRules {
5 // TODO? later, allow to push out pawns on a and h files
6 static get HasEnpassant() {
7 return false;
8 }
9
10 canIplay(side, [x, y]) {
11 // Sometimes opponent's pieces can be moved directly
12 return this.turn == side;
13 }
14
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;
21 if (amove != "-") {
22 const amoveParts = amove.split("/");
23 let move = {
24 // No need for start & end
25 appear: [],
26 vanish: []
27 };
28 [0, 1].map(i => {
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 }
43 });
44 this.amoves.push(move);
45 }
46 // Stack "first moves" (on subTurn 1) to merge and check opposite moves
47 this.firstMove = [];
48 }
49
50 static ParseFen(fen) {
51 return Object.assign(
52 ChessRules.ParseFen(fen),
53 { amove: fen.split(" ")[4] }
54 );
55 }
56
57 static IsGoodFen(fen) {
58 if (!ChessRules.IsGoodFen(fen)) return false;
59 const fenParts = fen.split(" ");
60 if (fenParts.length != 5) return false;
61 if (fenParts[4] != "-") {
62 // TODO: a single regexp instead.
63 // Format is [bpa2[.wpd3]] || '-'/[bbc3[.wrd5]] || '-'
64 const amoveParts = fenParts[4].split("/");
65 if (amoveParts.length != 2) return false;
66 for (let part of amoveParts) {
67 if (part != "-") {
68 for (let psq of part.split("."))
69 if (!psq.match(/^[a-r]{3}[1-8]$/)) return false;
70 }
71 }
72 }
73 return true;
74 }
75
76 getFen() {
77 return super.getFen() + " " + this.getAmoveFen();
78 }
79
80 getFenForRepeat() {
81 return super.getFenForRepeat() + "_" + this.getAmoveFen();
82 }
83
84 getAmoveFen() {
85 const L = this.amoves.length;
86 if (L == 0) return "-";
87 return (
88 ["appear","vanish"].map(
89 mpart => {
90 if (this.amoves[L-1][mpart].length == 0) return "-";
91 return (
92 this.amoves[L-1][mpart].map(
93 av => {
94 const square = V.CoordsToSquare({ x: av.x, y: av.y });
95 return av.c + av.p + square;
96 }
97 ).join(".")
98 );
99 }
100 ).join("/")
101 );
102 }
103
104 canTake() {
105 // Captures don't occur (only pulls & pushes)
106 return false;
107 }
108
109 // Step is right, just add (push/pull) moves in this direction
110 // Direction is assumed normalized.
111 getMovesInDirection([x, y], [dx, dy], nbSteps) {
112 nbSteps = nbSteps || 8; //max 8 steps anyway
113 let [i, j] = [x + dx, y + dy];
114 let moves = [];
115 const color = this.getColor(x, y);
116 const piece = this.getPiece(x, y);
117 const lastRank = (color == 'w' ? 0 : 7);
118 let counter = 1;
119 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
120 if (i == lastRank && piece == V.PAWN) {
121 // Promotion by push or pull
122 V.PawnSpecs.promotions.forEach(p => {
123 let move = super.getBasicMove([x, y], [i, j], { c: color, p: p });
124 moves.push(move);
125 });
126 }
127 else moves.push(super.getBasicMove([x, y], [i, j]));
128 if (++counter > nbSteps) break;
129 i += dx;
130 j += dy;
131 }
132 if (!V.OnBoard(i, j) && piece != V.KING) {
133 // Add special "exit" move, by "taking king"
134 moves.push(
135 new Move({
136 start: { x: x, y: y },
137 end: { x: this.kingPos[color][0], y: this.kingPos[color][1] },
138 appear: [],
139 vanish: [{ x: x, y: y, c: color, p: piece }]
140 })
141 );
142 }
143 return moves;
144 }
145
146 // Normalize direction to know the step
147 getNormalizedDirection([dx, dy]) {
148 const absDir = [Math.abs(dx), Math.abs(dy)];
149 let divisor = 0;
150 if (absDir[0] != 0 && absDir[1] != 0 && absDir[0] != absDir[1])
151 // Knight
152 divisor = Math.min(absDir[0], absDir[1]);
153 else
154 // Standard slider (or maybe a pawn or king: same)
155 divisor = Math.max(absDir[0], absDir[1]);
156 return [dx / divisor, dy / divisor];
157 }
158
159 // There was something on x2,y2, maybe our color, pushed or (self)pulled
160 isAprioriValidExit([x1, y1], [x2, y2], color2, piece2) {
161 const color1 = this.getColor(x1, y1);
162 const pawnShift = (color1 == 'w' ? -1 : 1);
163 const lastRank = (color1 == 'w' ? 0 : 7);
164 const deltaX = Math.abs(x1 - x2);
165 const deltaY = Math.abs(y1 - y2);
166 const checkSlider = () => {
167 const dir = this.getNormalizedDirection([x2 - x1, y2 - y1]);
168 let [i, j] = [x1 + dir[0], y1 + dir[1]];
169 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
170 i += dir[0];
171 j += dir[1];
172 }
173 return !V.OnBoard(i, j);
174 };
175 switch (piece2 || this.getPiece(x1, y1)) {
176 case V.PAWN:
177 return (
178 x1 + pawnShift == x2 &&
179 (
180 (color1 == color2 && x2 == lastRank && y1 == y2) ||
181 (
182 color1 != color2 &&
183 deltaY == 1 &&
184 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
185 )
186 )
187 );
188 case V.ROOK:
189 if (x1 != x2 && y1 != y2) return false;
190 return checkSlider();
191 case V.KNIGHT:
192 return (
193 deltaX + deltaY == 3 &&
194 (deltaX == 1 || deltaY == 1) &&
195 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
196 );
197 case V.BISHOP:
198 if (deltaX != deltaY) return false;
199 return checkSlider();
200 case V.QUEEN:
201 if (deltaX != 0 && deltaY != 0 && deltaX != deltaY) return false;
202 return checkSlider();
203 case V.KING:
204 return (
205 deltaX <= 1 &&
206 deltaY <= 1 &&
207 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
208 );
209 }
210 return false;
211 }
212
213 isAprioriValidVertical([x1, y1], x2) {
214 const piece = this.getPiece(x1, y1);
215 const deltaX = Math.abs(x1 - x2);
216 const startRank = (this.getColor(x1, y1) == 'w' ? 6 : 1);
217 return (
218 [V.QUEEN, V.ROOK].includes(piece) ||
219 (
220 [V.KING, V.PAWN].includes(piece) &&
221 (
222 deltaX == 1 ||
223 (deltaX == 2 && piece == V.PAWN && x1 == startRank)
224 )
225 )
226 );
227 }
228
229 // NOTE: for pushes, play the pushed piece first.
230 // for pulls: play the piece doing the action first
231 // NOTE: to push a piece out of the board, make it slide until its king
232 getPotentialMovesFrom([x, y]) {
233 const color = this.turn;
234 const sqCol = this.getColor(x, y);
235 const pawnShift = (color == 'w' ? -1 : 1);
236 const pawnStartRank = (color == 'w' ? 6 : 1);
237 const getMoveHash = (m) => {
238 return V.CoordsToSquare(m.start) + V.CoordsToSquare(m.end);
239 };
240 if (this.subTurn == 1) {
241 const addMoves = (dir, nbSteps) => {
242 const newMoves =
243 this.getMovesInDirection([x, y], [-dir[0], -dir[1]], nbSteps)
244 .filter(m => !movesHash[getMoveHash(m)]);
245 newMoves.forEach(m => { movesHash[getMoveHash(m)] = true; });
246 Array.prototype.push.apply(moves, newMoves);
247 };
248 // Free to play any move (if piece of my color):
249 let moves =
250 sqCol == color
251 ? super.getPotentialMovesFrom([x, y])
252 : [];
253 // There may be several suicide moves: keep only one
254 let hasExit = false;
255 moves = moves.filter(m => {
256 const suicide = (m.appear.length == 0);
257 if (suicide) {
258 if (hasExit) return false;
259 hasExit = true;
260 }
261 return true;
262 });
263 // Structure to avoid adding moves twice (can be action & move)
264 let movesHash = {};
265 moves.forEach(m => { movesHash[getMoveHash(m)] = true; });
266 // [x, y] is pushed by 'color'
267 for (let step of V.steps[V.KNIGHT]) {
268 const [i, j] = [x + step[0], y + step[1]];
269 if (
270 V.OnBoard(i, j) &&
271 this.board[i][j] != V.EMPTY &&
272 this.getColor(i, j) == color &&
273 this.getPiece(i, j) == V.KNIGHT
274 ) {
275 addMoves(step, 1);
276 }
277 }
278 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
279 let [i, j] = [x + step[0], y + step[1]];
280 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
281 i += step[0];
282 j += step[1];
283 }
284 if (
285 V.OnBoard(i, j) &&
286 this.board[i][j] != V.EMPTY &&
287 this.getColor(i, j) == color
288 ) {
289 const deltaX = Math.abs(i - x);
290 const deltaY = Math.abs(j - y);
291 switch (this.getPiece(i, j)) {
292 case V.PAWN:
293 if (
294 (x - i) / deltaX == pawnShift &&
295 deltaX <= 2 &&
296 deltaY <= 1
297 ) {
298 if (sqCol == color && deltaY == 0) {
299 // Pushed forward
300 const maxSteps = (i == pawnStartRank && deltaX == 1 ? 2 : 1);
301 addMoves(step, maxSteps);
302 }
303 else if (sqCol != color && deltaY == 1 && deltaX == 1)
304 // Pushed diagonally
305 addMoves(step, 1);
306 }
307 break;
308 case V.ROOK:
309 if (deltaX == 0 || deltaY == 0) addMoves(step);
310 break;
311 case V.BISHOP:
312 if (deltaX == deltaY) addMoves(step);
313 break;
314 case V.QUEEN:
315 // All steps are valid for a queen:
316 addMoves(step);
317 break;
318 case V.KING:
319 if (deltaX <= 1 && deltaY <= 1) addMoves(step, 1);
320 break;
321 }
322 }
323 }
324 return moves;
325 }
326 // If subTurn == 2 then we should have a first move,
327 // which restrict what we can play now: only in the first move direction
328 const L = this.firstMove.length;
329 const fm = this.firstMove[L-1];
330 if (
331 (fm.appear.length == 2 && fm.vanish.length == 2) ||
332 (fm.vanish[0].c == sqCol && sqCol != color)
333 ) {
334 // Castle or again opponent color: no move playable then.
335 return [];
336 }
337 const piece = this.getPiece(x, y);
338 const getPushExit = () => {
339 // Piece at subTurn 1 exited: can I have caused the exit?
340 if (
341 this.isAprioriValidExit(
342 [x, y],
343 [fm.start.x, fm.start.y],
344 fm.vanish[0].c
345 )
346 ) {
347 // Seems so:
348 const dir = this.getNormalizedDirection(
349 [fm.start.x - x, fm.start.y - y]);
350 const nbSteps =
351 [V.PAWN, V.KING, V.KNIGHT].includes(piece)
352 ? 1
353 : null;
354 return this.getMovesInDirection([x, y], dir, nbSteps);
355 }
356 return [];
357 }
358 const getPushMoves = () => {
359 // Piece from subTurn 1 is still on board:
360 const dirM = this.getNormalizedDirection(
361 [fm.end.x - fm.start.x, fm.end.y - fm.start.y]);
362 const dir = this.getNormalizedDirection(
363 [fm.start.x - x, fm.start.y - y]);
364 // Normalized directions should match
365 if (dir[0] == dirM[0] && dir[1] == dirM[1]) {
366 // We don't know if first move is a pushed piece or normal move,
367 // so still must check if the push is valid.
368 const deltaX = Math.abs(fm.start.x - x);
369 const deltaY = Math.abs(fm.start.y - y);
370 switch (piece) {
371 case V.PAWN:
372 if (x == pawnStartRank) {
373 if (
374 (fm.start.x - x) * pawnShift < 0 ||
375 deltaX >= 3 ||
376 deltaY >= 2 ||
377 (fm.vanish[0].c == color && deltaY > 0) ||
378 (fm.vanish[0].c != color && deltaY == 0) ||
379 Math.abs(fm.end.x - fm.start.x) > deltaX ||
380 fm.end.y - fm.start.y != fm.start.y - y
381 ) {
382 return [];
383 }
384 }
385 else {
386 if (
387 fm.start.x - x != pawnShift ||
388 deltaY >= 2 ||
389 (fm.vanish[0].c == color && deltaY == 1) ||
390 (fm.vanish[0].c != color && deltaY == 0) ||
391 fm.end.x - fm.start.x != pawnShift ||
392 fm.end.y - fm.start.y != fm.start.y - y
393 ) {
394 return [];
395 }
396 }
397 break;
398 case V.KNIGHT:
399 if (
400 (deltaX + deltaY != 3 || (deltaX == 0 && deltaY == 0)) ||
401 (fm.end.x - fm.start.x != fm.start.x - x) ||
402 (fm.end.y - fm.start.y != fm.start.y - y)
403 ) {
404 return [];
405 }
406 break;
407 case V.KING:
408 if (
409 (deltaX >= 2 || deltaY >= 2) ||
410 (fm.end.x - fm.start.x != fm.start.x - x) ||
411 (fm.end.y - fm.start.y != fm.start.y - y)
412 ) {
413 return [];
414 }
415 break;
416 case V.BISHOP:
417 if (deltaX != deltaY) return [];
418 break;
419 case V.ROOK:
420 if (deltaX != 0 && deltaY != 0) return [];
421 break;
422 case V.QUEEN:
423 if (deltaX != deltaY && deltaX != 0 && deltaY != 0) return [];
424 break;
425 }
426 // Nothing should stand between [x, y] and the square fm.start
427 let [i, j] = [x + dir[0], y + dir[1]];
428 while (
429 (i != fm.start.x || j != fm.start.y) &&
430 this.board[i][j] == V.EMPTY
431 ) {
432 i += dir[0];
433 j += dir[1];
434 }
435 if (i == fm.start.x && j == fm.start.y)
436 return this.getMovesInDirection([x, y], dir);
437 }
438 return [];
439 }
440 const getPullExit = () => {
441 // Piece at subTurn 1 exited: can I be pulled?
442 // Note: kings cannot suicide, so fm.vanish[0].p is not KING.
443 // Could be PAWN though, if a pawn was pushed out of board.
444 if (
445 fm.vanish[0].p != V.PAWN && //pawns cannot pull
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);
474 if (
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))
478 ) {
479 return [];
480 }
481 // Nothing should stand between [x, y] and the square fm.start
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 }
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 );
521 }
522 return [];
523 }
524
525 getSlideNJumpMoves([x, y], steps, oneStep) {
526 let moves = [];
527 const c = this.getColor(x, y);
528 const piece = this.getPiece(x, y);
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
544 if (piece != V.KING) {
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
564 // Does m2 un-do m1 ? (to disallow undoing actions)
565 oppositeMoves(m1, m2) {
566 const isEqual = (av1, av2) => {
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 };
580 // All appear and vanish arrays must have the same length
581 const mL = m1.appear.length;
582 return (
583 m2.appear.length == mL &&
584 m1.vanish.length == mL &&
585 m2.vanish.length == mL &&
586 isEqual(m1.appear, m2.vanish) &&
587 isEqual(m1.vanish, m2.appear)
588 );
589 }
590
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
599 filterValid(moves) {
600 const color = this.turn;
601 const La = this.amoves.length;
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);
609 let isOpposite = La > 0 && this.oppositeMoves(this.amoves[La-1], m);
610 if (res || isOpposite) {
611 const moves2 = this.getAllPotentialMoves();
612 for (let m2 of moves2) {
613 this.play(m2);
614 const res2 = this.underCheck(color);
615 const amove = this.getAmove(m, m2);
616 isOpposite =
617 La > 0 && this.oppositeMoves(this.amoves[La-1], amove);
618 this.undo(m2);
619 if (!res2 && !isOpposite) {
620 res = false;
621 break;
622 }
623 }
624 }
625 this.undo(m);
626 return !res;
627 });
628 }
629 if (La == 0) return super.filterValid(moves);
630 const Lf = this.firstMove.length;
631 return (
632 super.filterValid(
633 moves.filter(m => {
634 // Move shouldn't undo another:
635 const amove = this.getAmove(this.firstMove[Lf-1], m);
636 return !this.oppositeMoves(this.amoves[La-1], amove);
637 })
638 )
639 );
640 }
641
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 ) {
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)
668 rx = x - step[0];
669 ry = y - step[1];
670 while (
671 V.OnBoard(rx, ry) &&
672 this.board[rx][ry] == V.EMPTY &&
673 !oneStep
674 ) {
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) {
685 // The king can be pushed out by a pawn on last rank or near the edge
686 const pawnShift = (color == "w" ? 1 : -1);
687 for (let i of [-1, 1]) {
688 if (
689 V.OnBoard(x + pawnShift, y + i) &&
690 this.board[x + pawnShift][y + i] != V.EMPTY &&
691 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
692 this.getColor(x + pawnShift, y + i) == color
693 ) {
694 if (!V.OnBoard(x - pawnShift, y - i)) return true;
695 }
696 }
697 return false;
698 }
699
700 static OnTheEdge(x, y) {
701 return (x == 0 || x == 7 || y == 0 || y == 7);
702 }
703
704 isAttackedByKing([x, y], color) {
705 // Attacked if I'm on the edge and the opponent king just next,
706 // but not on the edge.
707 if (V.OnTheEdge(x, y)) {
708 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
709 const [i, j] = [x + step[0], y + step[1]];
710 if (
711 V.OnBoard(i, j) &&
712 !V.OnTheEdge(i, j) &&
713 this.board[i][j] != V.EMPTY &&
714 this.getPiece(i, j) == V.KING
715 // NOTE: since only one king of each color, and (x, y) is occupied
716 // by our king, no need to check other king's color.
717 ) {
718 return true;
719 }
720 }
721 }
722 return false;
723 }
724
725 // No consideration of color: all pieces could be played
726 getAllPotentialMoves() {
727 let potentialMoves = [];
728 for (let i = 0; i < V.size.x; i++) {
729 for (let j = 0; j < V.size.y; j++) {
730 if (this.board[i][j] != V.EMPTY) {
731 Array.prototype.push.apply(
732 potentialMoves,
733 this.getPotentialMovesFrom([i, j])
734 );
735 }
736 }
737 }
738 return potentialMoves;
739 }
740
741 getCurrentScore() {
742 if (this.subTurn == 2)
743 // Move not over
744 return "*";
745 return super.getCurrentScore();
746 }
747
748 doClick(square) {
749 // A click to promote a piece on subTurn 2 would trigger this.
750 // For now it would then return [NaN, NaN] because surrounding squares
751 // have no IDs in the promotion modal. TODO: improve this?
752 if (isNaN(square[0])) return null;
753 // If subTurn == 2 && square is empty && !underCheck && !isOpposite,
754 // then return an empty move, allowing to "pass" subTurn2
755 const La = this.amoves.length;
756 const Lf = this.firstMove.length;
757 if (
758 this.subTurn == 2 &&
759 this.board[square[0]][square[1]] == V.EMPTY &&
760 !this.underCheck(this.turn) &&
761 (La == 0 || !this.oppositeMoves(this.amoves[La-1], this.firstMove[Lf-1]))
762 ) {
763 return {
764 start: { x: -1, y: -1 },
765 end: { x: -1, y: -1 },
766 appear: [],
767 vanish: []
768 };
769 }
770 return null;
771 }
772
773 play(move) {
774 move.flags = JSON.stringify(this.aggregateFlags());
775 V.PlayOnBoard(this.board, move);
776 if (this.subTurn == 2) {
777 const L = this.firstMove.length;
778 this.amoves.push(this.getAmove(this.firstMove[L-1], move));
779 this.turn = V.GetOppCol(this.turn);
780 this.movesCount++;
781 }
782 else this.firstMove.push(move);
783 this.subTurn = 3 - this.subTurn;
784 this.postPlay(move);
785 }
786
787 postPlay(move) {
788 if (move.start.x < 0) return;
789 for (let a of move.appear)
790 if (a.p == V.KING) this.kingPos[a.c] = [a.x, a.y];
791 this.updateCastleFlags(move);
792 }
793
794 updateCastleFlags(move) {
795 const firstRank = { 'w': V.size.x - 1, 'b': 0 };
796 for (let v of move.vanish) {
797 if (v.p == V.KING) this.castleFlags[v.c] = [V.size.y, V.size.y];
798 else if (v.x == firstRank[v.c] && this.castleFlags[v.c].includes(v.y)) {
799 const flagIdx = (v.y == this.castleFlags[v.c][0] ? 0 : 1);
800 this.castleFlags[v.c][flagIdx] = V.size.y;
801 }
802 }
803 }
804
805 undo(move) {
806 this.disaggregateFlags(JSON.parse(move.flags));
807 V.UndoOnBoard(this.board, move);
808 if (this.subTurn == 1) {
809 this.amoves.pop();
810 this.turn = V.GetOppCol(this.turn);
811 this.movesCount--;
812 }
813 else this.firstMove.pop();
814 this.subTurn = 3 - this.subTurn;
815 this.postUndo(move);
816 }
817
818 postUndo(move) {
819 // (Potentially) Reset king position
820 for (let v of move.vanish)
821 if (v.p == V.KING) this.kingPos[v.c] = [v.x, v.y];
822 }
823
824 getComputerMove() {
825 let moves = this.getAllValidMoves();
826 if (moves.length == 0) return null;
827 // "Search" at depth 1 for now
828 const maxeval = V.INFINITY;
829 const color = this.turn;
830 const emptyMove = {
831 start: { x: -1, y: -1 },
832 end: { x: -1, y: -1 },
833 appear: [],
834 vanish: []
835 };
836 moves.forEach(m => {
837 this.play(m);
838 m.eval = (color == "w" ? -1 : 1) * maxeval;
839 const moves2 = this.getAllValidMoves().concat([emptyMove]);
840 m.next = moves2[0];
841 moves2.forEach(m2 => {
842 this.play(m2);
843 const score = this.getCurrentScore();
844 let mvEval = 0;
845 if (score != "1/2") {
846 if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
847 else mvEval = this.evalPosition();
848 }
849 if (
850 (color == 'w' && mvEval > m.eval) ||
851 (color == 'b' && mvEval < m.eval)
852 ) {
853 m.eval = mvEval;
854 m.next = m2;
855 }
856 this.undo(m2);
857 });
858 this.undo(m);
859 });
860 moves.sort((a, b) => {
861 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
862 });
863 let candidates = [0];
864 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
865 candidates.push(i);
866 const mIdx = candidates[randInt(candidates.length)];
867 const move2 = moves[mIdx].next;
868 delete moves[mIdx]["next"];
869 return [moves[mIdx], move2];
870 }
871
872 getNotation(move) {
873 if (move.start.x < 0)
874 // A second move is always required, but may be empty
875 return "-";
876 const initialSquare = V.CoordsToSquare(move.start);
877 const finalSquare = V.CoordsToSquare(move.end);
878 if (move.appear.length == 0)
879 // Pushed or pulled out of the board
880 return initialSquare + "R";
881 return move.appear[0].p.toUpperCase() + initialSquare + finalSquare;
882 }
883 };