Fix games download/upload + Dynamo variant
[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 {
7ddfec38 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
ad1e629e 160 // There was something on x2,y2, maybe our color, pushed/pulled.
ad1e629e 161 isAprioriValidExit([x1, y1], [x2, y2], color2) {
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 };
b2655276
BA
176 switch (this.getPiece(x1, y1)) {
177 case V.PAWN:
178 return (
ad1e629e 179 x1 + pawnShift == x2 &&
b2655276 180 (
ad1e629e
BA
181 (color1 == color2 && x2 == lastRank && y1 == y2) ||
182 (color1 != color2 && deltaY == 1 && !V.OnBoard(x2, 2 * y2 - y1))
b2655276
BA
183 )
184 );
185 case V.ROOK:
ad1e629e
BA
186 if (x1 != x2 && y1 != y2) return false;
187 return checkSlider();
188 case V.KNIGHT:
189 return (
190 deltaX + deltaY == 3 &&
191 (deltaX == 1 || deltaY == 1) &&
192 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
193 );
b2655276 194 case V.BISHOP:
ad1e629e
BA
195 if (deltaX != deltaY) return false;
196 return checkSlider();
b2655276 197 case V.QUEEN:
ad1e629e
BA
198 if (deltaX != 0 && deltaY != 0 && deltaX != deltaY) return false;
199 return checkSlider();
200 case V.KING:
b2655276 201 return (
ad1e629e
BA
202 deltaX <= 1 &&
203 deltaY <= 1 &&
204 !V.OnBoard(2 * x2 - x1, 2 * y2 - y1)
b2655276 205 );
93ce6119 206 }
b2655276 207 return false;
b866a62a
BA
208 }
209
05d37cc7
BA
210 isAprioriValidVertical([x1, y1], x2) {
211 const piece = this.getPiece(x1, y1);
212 const deltaX = Math.abs(x1 - x2);
213 const startRank = (this.getColor(x1, y1) == 'w' ? 6 : 1);
214 return (
215 [V.QUEEN, V.ROOK].includes(piece) ||
216 (
217 [V.KING, V.PAWN].includes(piece) &&
218 (
219 deltaX == 1 ||
220 (deltaX == 2 && piece == V.PAWN && x1 == startRank)
221 )
222 )
223 );
224 }
225
93ce6119 226 // NOTE: for pushes, play the pushed piece first.
61656127 227 // for pulls: play the piece doing the action first
b2655276 228 // NOTE: to push a piece out of the board, make it slide until its king
b866a62a
BA
229 getPotentialMovesFrom([x, y]) {
230 const color = this.turn;
81e74ee5 231 const sqCol = this.getColor(x, y);
93ce6119 232 if (this.subTurn == 1) {
b2655276
BA
233 const getMoveHash = (m) => {
234 return V.CoordsToSquare(m.start) + V.CoordsToSquare(m.end);
235 };
236 const addMoves = (dir, nbSteps) => {
237 const newMoves =
238 this.getMovesInDirection([x, y], [-dir[0], -dir[1]], nbSteps)
239 .filter(m => !movesHash[getMoveHash(m)]);
7b53b5a7 240 newMoves.forEach(m => { movesHash[getMoveHash(m)] = true; });
b2655276
BA
241 Array.prototype.push.apply(moves, newMoves);
242 };
8c267d0c 243 // Free to play any move (if piece of my color):
cfceecba 244 let moves =
81e74ee5 245 sqCol == color
8c267d0c
BA
246 ? super.getPotentialMovesFrom([x, y])
247 : [];
cfceecba
BA
248 // There may be several suicide moves: keep only one
249 let hasExit = false;
250 moves = moves.filter(m => {
251 const suicide = (m.appear.length == 0);
252 if (suicide) {
253 if (hasExit) return false;
254 hasExit = true;
255 }
256 return true;
257 });
b2655276
BA
258 const pawnShift = (color == 'w' ? -1 : 1);
259 const pawnStartRank = (color == 'w' ? 6 : 1);
7b53b5a7
BA
260 // Structure to avoid adding moves twice (can be action & move)
261 let movesHash = {};
262 moves.forEach(m => { movesHash[getMoveHash(m)] = true; });
b2655276
BA
263 // [x, y] is pushed by 'color'
264 for (let step of V.steps[V.KNIGHT]) {
265 const [i, j] = [x + step[0], y + step[1]];
7b53b5a7
BA
266 if (
267 V.OnBoard(i, j) &&
268 this.board[i][j] != V.EMPTY &&
269 this.getColor(i, j) == color &&
270 this.getPiece(i, j) == V.KNIGHT
271 ) {
272 addMoves(step, 1);
b2655276
BA
273 }
274 }
7b53b5a7 275 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
b2655276
BA
276 let [i, j] = [x + step[0], y + step[1]];
277 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
278 i += step[0];
279 j += step[1];
280 }
281 if (
282 V.OnBoard(i, j) &&
283 this.board[i][j] != V.EMPTY &&
284 this.getColor(i, j) == color
285 ) {
286 const deltaX = Math.abs(i - x);
287 const deltaY = Math.abs(j - y);
b2655276
BA
288 switch (this.getPiece(i, j)) {
289 case V.PAWN:
ad1e629e
BA
290 if (
291 (x - i) / deltaX == pawnShift &&
292 deltaX <= 2 &&
293 deltaY <= 1
294 ) {
81e74ee5 295 if (sqCol == color && deltaY == 0) {
b2655276
BA
296 // Pushed forward
297 const maxSteps = (i == pawnStartRank && deltaX == 1 ? 2 : 1);
298 addMoves(step, maxSteps);
299 }
81e74ee5 300 else if (sqCol != color && deltaY == 1 && deltaX == 1)
b2655276
BA
301 // Pushed diagonally
302 addMoves(step, 1);
303 }
304 break;
305 case V.ROOK:
306 if (deltaX == 0 || deltaY == 0) addMoves(step);
307 break;
b2655276
BA
308 case V.BISHOP:
309 if (deltaX == deltaY) addMoves(step);
310 break;
311 case V.QUEEN:
cfceecba
BA
312 // All steps are valid for a queen:
313 addMoves(step);
b2655276
BA
314 break;
315 case V.KING:
316 if (deltaX <= 1 && deltaY <= 1) addMoves(step, 1);
317 break;
318 }
319 }
320 }
321 return moves;
b866a62a 322 }
93ce6119 323 // If subTurn == 2 then we should have a first move,
b2655276
BA
324 // which restrict what we can play now: only in the first move direction
325 // NOTE: no need for knight or pawn checks, because the move will be
326 // naturally limited in those cases.
93ce6119
BA
327 const L = this.firstMove.length;
328 const fm = this.firstMove[L-1];
81e74ee5
BA
329 if (
330 (fm.appear.length == 2 && fm.vanish.length == 2) ||
331 (fm.vanish[0].c == sqCol && sqCol != color)
332 ) {
333 // Castle or again opponent color: no move playable then.
b2655276 334 return [];
81e74ee5 335 }
b2655276
BA
336 if (fm.appear.length == 0) {
337 // Piece at subTurn 1 just exited the board.
338 // Can I be a piece which caused the exit?
ad1e629e 339 if (
6e0c0bcb
BA
340 // Only "turn" color can do actions
341 sqCol == color &&
ad1e629e
BA
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
BA
351 const nbSteps =
352 ([V.PAWN,V.KING,V.KNIGHT].includes(this.getPiece(x, y)) ? 1 : null);
353 return this.getMovesInDirection([x, y], dir, nbSteps);
b2655276 354 }
93ce6119
BA
355 }
356 else {
b2655276
BA
357 const dirM = this.getNormalizedDirection(
358 [fm.end.x - fm.start.x, fm.end.y - fm.start.y]);
359 const dir = this.getNormalizedDirection(
360 [fm.start.x - x, fm.start.y - y]);
ad1e629e
BA
361 // Normalized directions should match
362 if (dir[0] == dirM[0] && dir[1] == dirM[1]) {
05d37cc7
BA
363 // If first move is a pawn move, only a queen, rook, or maybe king or
364 // pawn can follow (need vertical movement option).
365 if (
366 fm.vanish[0].p == V.PAWN &&
367 fm.vanish[0].c == color &&
368 !this.isAprioriValidVertical([x, y], fm.start.x)
369 ) {
370 return [];
371 }
ad1e629e
BA
372 // And nothing should stand between [x, y] and the square fm.start
373 let [i, j] = [x + dir[0], y + dir[1]];
374 while (
375 (i != fm.start.x || j != fm.start.y) &&
376 this.board[i][j] == V.EMPTY
377 ) {
378 i += dir[0];
379 j += dir[1];
380 }
381 if (i == fm.start.x && j == fm.start.y)
382 return this.getMovesInDirection([x, y], dir);
383 }
93ce6119 384 }
b2655276 385 return [];
61656127
BA
386 }
387
cfceecba
BA
388 getSlideNJumpMoves([x, y], steps, oneStep) {
389 let moves = [];
81e74ee5
BA
390 const c = this.getColor(x, y);
391 const piece = this.getPiece(x, y);
cfceecba
BA
392 outerLoop: for (let step of steps) {
393 let i = x + step[0];
394 let j = y + step[1];
395 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
396 moves.push(this.getBasicMove([x, y], [i, j]));
397 if (oneStep) continue outerLoop;
398 i += step[0];
399 j += step[1];
400 }
401 if (V.OnBoard(i, j)) {
402 if (this.canTake([x, y], [i, j]))
403 moves.push(this.getBasicMove([x, y], [i, j]));
404 }
405 else {
406 // Add potential board exit (suicide), except for the king
cfceecba 407 if (piece != V.KING) {
cfceecba
BA
408 moves.push({
409 start: { x: x, y: y},
410 end: { x: this.kingPos[c][0], y: this.kingPos[c][1] },
411 appear: [],
412 vanish: [
413 new PiPo({
414 x: x,
415 y: y,
416 c: c,
417 p: piece
418 })
419 ]
420 });
421 }
422 }
423 }
424 return moves;
425 }
426
61656127
BA
427 // Does m2 un-do m1 ? (to disallow undoing actions)
428 oppositeMoves(m1, m2) {
429 const isEqual = (av1, av2) => {
430 // Precondition: av1 and av2 length = 2
431 for (let av of av1) {
432 const avInAv2 = av2.find(elt => {
433 return (
434 elt.x == av.x &&
435 elt.y == av.y &&
436 elt.c == av.c &&
437 elt.p == av.p
438 );
439 });
440 if (!avInAv2) return false;
441 }
442 return true;
443 };
444 return (
61656127
BA
445 m1.appear.length == 2 &&
446 m2.appear.length == 2 &&
447 m1.vanish.length == 2 &&
448 m2.vanish.length == 2 &&
449 isEqual(m1.appear, m2.vanish) &&
450 isEqual(m1.vanish, m2.appear)
451 );
452 }
453
93ce6119
BA
454 getAmove(move1, move2) {
455 // Just merge (one is action one is move, one may be empty)
456 return {
457 appear: move1.appear.concat(move2.appear),
458 vanish: move1.vanish.concat(move2.vanish)
459 }
460 }
461
61656127 462 filterValid(moves) {
93ce6119
BA
463 const color = this.turn;
464 if (this.subTurn == 1) {
465 return moves.filter(m => {
466 // A move is valid either if it doesn't result in a check,
467 // or if a second move is possible to counter the check
468 // (not undoing a potential move + action of the opponent)
469 this.play(m);
470 let res = this.underCheck(color);
471 if (res) {
472 const moves2 = this.getAllPotentialMoves();
ad1e629e 473 for (let m2 of moves2) {
93ce6119
BA
474 this.play(m2);
475 const res2 = this.underCheck(color);
476 this.undo(m2);
477 if (!res2) {
478 res = false;
479 break;
480 }
481 }
482 }
483 this.undo(m);
484 return !res;
485 });
486 }
487 const Lf = this.firstMove.length;
488 const La = this.amoves.length;
489 if (La == 0) return super.filterValid(moves);
a443d256 490 return (
93ce6119 491 super.filterValid(
a443d256
BA
492 moves.filter(m => {
493 // Move shouldn't undo another:
93ce6119
BA
494 const amove = this.getAmove(this.firstMove[Lf-1], m);
495 return !this.oppositeMoves(this.amoves[La-1], amove);
a443d256
BA
496 })
497 )
498 );
b866a62a
BA
499 }
500
c7550017
BA
501 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
502 for (let step of steps) {
503 let rx = x + step[0],
504 ry = y + step[1];
505 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
506 rx += step[0];
507 ry += step[1];
508 }
509 if (
510 V.OnBoard(rx, ry) &&
511 this.getPiece(rx, ry) == piece &&
512 this.getColor(rx, ry) == color
513 ) {
8c267d0c
BA
514 // Continue some steps in the same direction (pull)
515 rx += step[0];
516 ry += step[1];
517 while (
518 V.OnBoard(rx, ry) &&
519 this.board[rx][ry] == V.EMPTY &&
520 !oneStep
521 ) {
522 rx += step[0];
523 ry += step[1];
524 }
525 if (!V.OnBoard(rx, ry)) return true;
526 // Step in the other direction (push)
c7550017
BA
527 rx = x - step[0];
528 ry = y - step[1];
2c5d7b20
BA
529 while (
530 V.OnBoard(rx, ry) &&
531 this.board[rx][ry] == V.EMPTY &&
532 !oneStep
533 ) {
c7550017
BA
534 rx -= step[0];
535 ry -= step[1];
536 }
537 if (!V.OnBoard(rx, ry)) return true;
538 }
539 }
540 return false;
541 }
542
543 isAttackedByPawn([x, y], color) {
544 const lastRank = (color == 'w' ? 0 : 7);
ad1e629e 545 if (x != lastRank)
c7550017
BA
546 // The king can be pushed out by a pawn only on last rank
547 return false;
548 const pawnShift = (color == "w" ? 1 : -1);
549 for (let i of [-1, 1]) {
550 if (
551 y + i >= 0 &&
552 y + i < V.size.y &&
553 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
554 this.getColor(x + pawnShift, y + i) == color
555 ) {
556 return true;
557 }
558 }
559 return false;
560 }
61656127 561
156986e6
BA
562 // No consideration of color: all pieces could be played
563 getAllPotentialMoves() {
564 let potentialMoves = [];
565 for (let i = 0; i < V.size.x; i++) {
566 for (let j = 0; j < V.size.y; j++) {
567 if (this.board[i][j] != V.EMPTY) {
568 Array.prototype.push.apply(
569 potentialMoves,
570 this.getPotentialMovesFrom([i, j])
571 );
572 }
573 }
574 }
575 return potentialMoves;
576 }
577
61656127
BA
578 getCurrentScore() {
579 if (this.subTurn == 2)
580 // Move not over
581 return "*";
582 return super.getCurrentScore();
583 }
584
93ce6119 585 doClick(square) {
b2655276
BA
586 // If subTurn == 2 && square is empty && !underCheck,
587 // then return an empty move, allowing to "pass" subTurn2
93ce6119
BA
588 if (
589 this.subTurn == 2 &&
7b53b5a7 590 this.board[square[0]][square[1]] == V.EMPTY &&
b2655276 591 !this.underCheck(this.turn)
93ce6119
BA
592 ) {
593 return {
7b53b5a7
BA
594 start: { x: -1, y: -1 },
595 end: { x: -1, y: -1 },
93ce6119
BA
596 appear: [],
597 vanish: []
598 };
599 }
600 return null;
601 }
602
61656127
BA
603 play(move) {
604 move.flags = JSON.stringify(this.aggregateFlags());
605 V.PlayOnBoard(this.board, move);
7ddfec38 606 if (this.subTurn == 2) {
7b53b5a7
BA
607 const L = this.firstMove.length;
608 this.amoves.push(this.getAmove(this.firstMove[L-1], move));
61656127 609 this.turn = V.GetOppCol(this.turn);
7ddfec38 610 this.movesCount++;
61656127 611 }
a443d256 612 else this.firstMove.push(move);
7ddfec38 613 this.subTurn = 3 - this.subTurn;
61656127
BA
614 this.postPlay(move);
615 }
616
7b53b5a7
BA
617 postPlay(move) {
618 if (move.start.x < 0) return;
619 for (let a of move.appear)
620 if (a.p == V.KING) this.kingPos[a.c] = [a.x, a.y];
621 this.updateCastleFlags(move);
622 }
623
624 updateCastleFlags(move) {
625 const firstRank = { 'w': V.size.x - 1, 'b': 0 };
7ddfec38 626 for (let v of move.vanish) {
7b53b5a7
BA
627 if (v.p == V.KING) this.castleFlags[v.c] = [V.size.y, V.size.y];
628 else if (v.x == firstRank[v.c] && this.castleFlags[v.c].includes(v.y)) {
629 const flagIdx = (v.y == this.castleFlags[v.c][0] ? 0 : 1);
630 this.castleFlags[v.c][flagIdx] = V.size.y;
7ddfec38 631 }
61656127
BA
632 }
633 }
634
635 undo(move) {
636 this.disaggregateFlags(JSON.parse(move.flags));
637 V.UndoOnBoard(this.board, move);
7ddfec38 638 if (this.subTurn == 1) {
61656127 639 this.turn = V.GetOppCol(this.turn);
7ddfec38 640 this.movesCount--;
61656127 641 }
a443d256 642 else this.firstMove.pop();
7ddfec38 643 this.subTurn = 3 - this.subTurn;
61656127
BA
644 this.postUndo(move);
645 }
7b53b5a7
BA
646
647 postUndo(move) {
648 // (Potentially) Reset king position
649 for (let v of move.vanish)
650 if (v.p == V.KING) this.kingPos[v.c] = [v.x, v.y];
651 }
652
ad1e629e
BA
653 getComputerMove() {
654 let moves = this.getAllValidMoves();
655 if (moves.length == 0) return null;
656 // "Search" at depth 1 for now
657 const maxeval = V.INFINITY;
658 const color = this.turn;
659 const emptyMove = {
660 start: { x: -1, y: -1 },
661 end: { x: -1, y: -1 },
662 appear: [],
663 vanish: []
664 };
665 moves.forEach(m => {
666 this.play(m);
667 m.eval = (color == "w" ? -1 : 1) * maxeval;
668 const moves2 = this.getAllValidMoves().concat([emptyMove]);
669 m.next = moves2[0];
670 moves2.forEach(m2 => {
671 this.play(m2);
672 const score = this.getCurrentScore();
673 let mvEval = 0;
674 if (score != "1/2") {
675 if (score != "*") mvEval = (score == "1-0" ? 1 : -1) * maxeval;
676 else mvEval = this.evalPosition();
677 }
678 if (
679 (color == 'w' && mvEval > m.eval) ||
680 (color == 'b' && mvEval < m.eval)
681 ) {
682 m.eval = mvEval;
683 m.next = m2;
684 }
685 this.undo(m2);
686 });
687 this.undo(m);
688 });
689 moves.sort((a, b) => {
690 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
691 });
692 let candidates = [0];
693 for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++)
694 candidates.push(i);
695 const mIdx = candidates[randInt(candidates.length)];
696 const move2 = moves[mIdx].next;
697 delete moves[mIdx]["next"];
698 return [moves[mIdx], move2];
699 }
700
7b53b5a7
BA
701 getNotation(move) {
702 if (move.start.x < 0)
703 // A second move is always required, but may be empty
704 return "-";
705 const initialSquare = V.CoordsToSquare(move.start);
706 const finalSquare = V.CoordsToSquare(move.end);
707 if (move.appear.length == 0)
708 // Pushed or pulled out of the board
709 return initialSquare + "R";
710 return move.appear[0].p.toUpperCase() + initialSquare + finalSquare;
711 }
0d5335de 712};