A few fixes. Draft Synchrone2 (not working at all right now)
[vchess.git] / client / src / variants / Otage.js
1 import { ChessRules, PiPo, Move } from "@/base_rules";
2 import { randInt } from "@/utils/alea";
3 import { ArrayFun } from "@/utils/array";
4
5 export class OtageRules extends ChessRules {
6
7 static get IMAGE_EXTENSION() {
8 return ".png";
9 }
10
11 // Hostage / Capturer combinations
12 // + letter among a, b, v, w to indicate colors + config:
13 // a: black first, black controls
14 // b: white first, black controls
15 // v: black first, white controls
16 // w: white first, white controls
17 static get UNIONS() {
18 return {
19 a: ['p', 'p'],
20 c: ['p', 'r'],
21 d: ['p', 'n'],
22 e: ['p', 'b'],
23 f: ['p', 'q'],
24 g: ['p', 'k'],
25 h: ['r', 'r'],
26 i: ['r', 'n'],
27 j: ['r', 'b'],
28 l: ['r', 'q'],
29 m: ['r', 'k'],
30 o: ['n', 'n'],
31 s: ['n', 'b'],
32 t: ['n', 'q'],
33 u: ['n', 'k'],
34 v: ['b', 'b'],
35 w: ['b', 'q'],
36 x: ['b', 'k'],
37 y: ['q', 'q'],
38 z: ['q', 'k'],
39 '_': ['k', 'k']
40 };
41 }
42
43 static board2fen(b) {
44 if (ChessRules.PIECES.includes(b[1])) return ChessRules.board2fen(b);
45 // Show symbol first (no collisions)
46 return b[1] + b[0];
47 }
48
49 static fen2board(f) {
50 if (f.length == 1) return ChessRules.fen2board(f);
51 return f[1] + f[0]; //"color" first
52 }
53
54 static IsGoodPosition(position) {
55 if (position.length == 0) return false;
56 const rows = position.split("/");
57 if (rows.length != V.size.x) return false;
58 let kingSymb = ['k', 'g', 'm', 'u', 'x', '_'];
59 let kings = { 'k': 0, 'K': 0 };
60 for (let row of rows) {
61 let sumElts = 0;
62 for (let i = 0; i < row.length; i++) {
63 const lowR = row[i].toLowerCase
64 const readNext = !(ChessRules.PIECES.includes(lowR));
65 if (!!(lowR.match(/[a-z_]/))) {
66 sumElts++;
67 if (kingSymb.includes(row[i])) kings['k']++;
68 // Not "else if", if two kings dancing together
69 if (kingSymb.some(s => row[i] == s.toUpperCase())) kings['K']++;
70 if (readNext) i++;
71 }
72 else {
73 const num = parseInt(row[i], 10);
74 if (isNaN(num) || num <= 0) return false;
75 sumElts += num;
76 }
77 }
78 if (sumElts != V.size.y) return false;
79 }
80 // Both kings should be on board. Exactly one per color.
81 if (Object.values(kings).some(v => v != 1)) return false;
82 return true;
83 }
84
85 static GetBoard(position) {
86 const rows = position.split("/");
87 let board = ArrayFun.init(V.size.x, V.size.y, "");
88 for (let i = 0; i < rows.length; i++) {
89 let j = 0;
90 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
91 const character = rows[i][indexInRow];
92 const num = parseInt(character, 10);
93 // If num is a number, just shift j:
94 if (!isNaN(num)) j += num;
95 else {
96 // Something at position i,j
97 const lowC = character.toLowerCase();
98 if (ChessRules.PIECES.includes(lowC))
99 board[i][j++] = V.fen2board(character);
100 else
101 board[i][j++] = V.fen2board(lowC + rows[i][++indexInRow]);
102 }
103 }
104 }
105 return board;
106 }
107
108 getPpath(b) {
109 return "Otage/" + b;
110 }
111
112 getPPpath(m) {
113 if (ChessRules.PIECES.includes(m.appear[0].p)) return super.getPPpath(m);
114 // For an "union", show only relevant piece:
115 // The color must be deduced from the move: reaching final rank of who?
116 const color = (m.appear[0].x == 0 ? 'w' : 'b');
117 const up = this.getUnionPieces(m.appear[0].c, m.appear[0].p);
118 return "Pacosako/" + color + up[color];
119 }
120
121 canTake([x1, y1], [x2, y2]) {
122 const p1 = this.board[x1][y1].charAt(1);
123 if (!(ChessRules.PIECES.includes(p1))) return false;
124 const p2 = this.board[x2][y2].charAt(1);
125 if (!(ChessRules.PIECES.includes(p2))) return true;
126 const c1 = this.board[x1][y1].charAt(0);
127 const c2 = this.board[x2][y2].charAt(0);
128 return (c1 != c2);
129 }
130
131 canIplay(side, [x, y]) {
132 const c = this.board[x][y].charAt(0);
133 const compSide = (side == 'w' ? 'v' : 'a');
134 return (this.turn == side && [side, compSide].includes(c));
135 }
136
137 scanKings(fen) {
138 this.kingPos = { w: [-1, -1], b: [-1, -1] };
139 const fenRows = V.ParseFen(fen).position.split("/");
140 const startRow = { 'w': V.size.x - 1, 'b': 0 };
141 const kingSymb = ['k', 'g', 'm', 'u', 'x', '_'];
142 for (let i = 0; i < fenRows.length; i++) {
143 let k = 0;
144 for (let j = 0; j < fenRows[i].length; j++) {
145 const c = fenRows[i].charAt(j);
146 const lowR = c.toLowerCase();
147 const readNext = !(ChessRules.PIECES.includes(lowR));
148 if (!!(lowR.match(/[a-z_]/))) {
149 if (kingSymb.includes(c))
150 this.kingPos["b"] = [i, k];
151 // Not "else if", in case of two kings dancing together
152 if (kingSymb.some(s => c == s.toUpperCase()))
153 this.kingPos["w"] = [i, k];
154 if (readNext) j++;
155 }
156 else {
157 const num = parseInt(fenRows[i].charAt(j), 10);
158 if (!isNaN(num)) k += num - 1;
159 }
160 k++;
161 }
162 }
163 }
164
165 setOtherVariables(fen) {
166 super.setOtherVariables(fen);
167 // Stack of "last move" only for intermediate chaining
168 this.lastMoveEnd = [null];
169 }
170
171 static IsGoodFlags(flags) {
172 // 4 for castle + 16 for pawns
173 return !!flags.match(/^[a-z]{4,4}[01]{16,16}$/);
174 }
175
176 setFlags(fenflags) {
177 super.setFlags(fenflags); //castleFlags
178 this.pawnFlags = {
179 w: [...Array(8)], //pawns can move 2 squares?
180 b: [...Array(8)]
181 };
182 const flags = fenflags.substr(4); //skip first 4 letters, for castle
183 for (let c of ["w", "b"]) {
184 for (let i = 0; i < 8; i++)
185 this.pawnFlags[c][i] = flags.charAt((c == "w" ? 0 : 8) + i) == "1";
186 }
187 }
188
189 aggregateFlags() {
190 return [this.castleFlags, this.pawnFlags];
191 }
192
193 disaggregateFlags(flags) {
194 this.castleFlags = flags[0];
195 this.pawnFlags = flags[1];
196 }
197
198 static GenRandInitFen(randomness) {
199 // Add 16 pawns flags:
200 return ChessRules.GenRandInitFen(randomness)
201 .slice(0, -2) + "1111111111111111 -";
202 }
203
204 getFlagsFen() {
205 let fen = super.getFlagsFen();
206 // Add pawns flags
207 for (let c of ["w", "b"])
208 for (let i = 0; i < 8; i++) fen += (this.pawnFlags[c][i] ? "1" : "0");
209 return fen;
210 }
211
212 getPiece(i, j) {
213 const p = this.board[i][j].charAt(1);
214 if (ChessRules.PIECES.includes(p)) return p;
215 const c = this.board[i][j].charAt(0);
216 const idx = (['a', 'w'].includes(c) ? 0 : 1);
217 return V.UNIONS[p][idx];
218 }
219
220 getUnionPieces(color, code) {
221 const pieces = V.UNIONS[code];
222 return {
223 w: pieces[ ['b', 'w'].includes(color) ? 0 : 1 ],
224 b: pieces[ ['a', 'v'].includes(color) ? 0 : 1 ]
225 };
226 }
227
228 // p1: white piece, p2: black piece, capturer: (temporary) owner
229 getUnionCode(p1, p2, capturer) {
230 let uIdx = (
231 Object.values(V.UNIONS).findIndex(v => v[0] == p1 && v[1] == p2)
232 );
233 let c = '';
234 if (capturer == 'w') c = (uIdx >= 0 ? 'w' : 'v');
235 else c = (uIdx >= 0 ? 'b' : 'a');
236 if (uIdx == -1) {
237 uIdx = (
238 Object.values(V.UNIONS).findIndex(v => v[0] == p2 && v[1] == p1)
239 );
240 }
241 return { c: c, p: Object.keys(V.UNIONS)[uIdx] };
242 }
243
244 getBasicMove([sx, sy], [ex, ey], tr) {
245 const L = this.lastMoveEnd.length;
246 const lm = this.lastMoveEnd[L-1];
247 const piece = (!!lm ? lm.p : null);
248 const initColor = (!!piece ? this.turn : this.board[sx][sy].charAt(0));
249 const initPiece = (piece || this.board[sx][sy].charAt(1));
250 const c = this.turn;
251 const oppCol = V.GetOppCol(c);
252 if (!!tr && !(ChessRules.PIECES.includes(initPiece))) {
253 // Transformation computed without taking union into account
254 const up = this.getUnionPieces(initColor, initPiece);
255 let args = [tr.p, up[oppCol]];
256 if (['a', 'v'].includes(initColor)) args = args.reverse();
257 const capturer = (['a', 'b'].includes(initColor) ? 'b' : 'w');
258 const cp = this.getUnionCode(args[0], args[1], capturer);
259 tr.c = cp.c;
260 tr.p = cp.p;
261 }
262 // 4 cases : moving
263 // - union to free square (other cases are illegal: return null)
264 // - normal piece to free square,
265 // to enemy normal piece, or
266 // to union (releasing our piece)
267 let mv = new Move({
268 start: { x: sx, y: sy },
269 end: { x: ex, y: ey },
270 vanish: []
271 });
272 if (!piece) {
273 mv.vanish = [
274 new PiPo({
275 x: sx,
276 y: sy,
277 c: initColor,
278 p: initPiece
279 })
280 ];
281 }
282 // Treat free square cases first:
283 if (this.board[ex][ey] == V.EMPTY) {
284 mv.appear = [
285 new PiPo({
286 x: ex,
287 y: ey,
288 c: !!tr ? tr.c : initColor,
289 p: !!tr ? tr.p : initPiece
290 })
291 ];
292 return mv;
293 }
294 // Now the two cases with union / release:
295 const destColor = this.board[ex][ey].charAt(0);
296 const destPiece = this.board[ex][ey].charAt(1);
297 mv.vanish.push(
298 new PiPo({
299 x: ex,
300 y: ey,
301 c: destColor,
302 p: destPiece
303 })
304 );
305 if (ChessRules.PIECES.includes(destPiece)) {
306 // Normal piece: just create union
307 let args = [!!tr ? tr.p : initPiece, destPiece];
308 if (c == 'b') args = args.reverse();
309 const cp = this.getUnionCode(args[0], args[1], c);
310 mv.appear = [
311 new PiPo({
312 x: ex,
313 y: ey,
314 c: cp.c,
315 p: cp.p
316 })
317 ];
318 return mv;
319 }
320 // Releasing a piece in an union: keep track of released piece
321 const up = this.getUnionPieces(destColor, destPiece);
322 let args = [!!tr ? tr.p : initPiece, up[oppCol]];
323 if (c == 'b') args = args.reverse();
324 const cp = this.getUnionCode(args[0], args[1], c);
325 mv.appear = [
326 new PiPo({
327 x: ex,
328 y: ey,
329 c: cp.c,
330 p: cp.p
331 })
332 ];
333 mv.end.released = up[c];
334 return mv;
335 }
336
337 // noCastle arg: when detecting king attacks
338 getPotentialMovesFrom([x, y], noCastle) {
339 const L = this.lastMoveEnd.length;
340 const lm = this.lastMoveEnd[L-1];
341 if (!!lm && (x != lm.x || y != lm.y)) return [];
342 const piece = (!!lm ? lm.p : this.getPiece(x, y));
343 if (!!lm) {
344 var saveSquare = this.board[x][y];
345 this.board[x][y] = this.turn + piece;
346 }
347 let baseMoves = [];
348 const c = this.turn;
349 switch (piece || this.getPiece(x, y)) {
350 case V.PAWN: {
351 const firstRank = (c == 'w' ? 7 : 0);
352 baseMoves = this.getPotentialPawnMoves([x, y]).filter(m => {
353 // Skip forbidden 2-squares jumps (except from first rank)
354 // Also skip unions capturing en-passant (not allowed).
355 return (
356 (
357 m.start.x == firstRank ||
358 Math.abs(m.end.x - m.start.x) == 1 ||
359 this.pawnFlags[c][m.start.y]
360 )
361 &&
362 (
363 this.board[x][y].charAt(1) == V.PAWN ||
364 m.start.y == m.end.y
365 )
366 );
367 });
368 break;
369 }
370 case V.ROOK:
371 baseMoves = this.getPotentialRookMoves([x, y]);
372 break;
373 case V.KNIGHT:
374 baseMoves = this.getPotentialKnightMoves([x, y]);
375 break;
376 case V.BISHOP:
377 baseMoves = this.getPotentialBishopMoves([x, y]);
378 break;
379 case V.QUEEN:
380 baseMoves = this.getPotentialQueenMoves([x, y]);
381 break;
382 case V.KING:
383 baseMoves = this.getSlideNJumpMoves(
384 sq,
385 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
386 "oneStep"
387 );
388 if (!noCastle && this.castleFlags[this.turn].some(v => v < V.size.y))
389 baseMoves = baseMoves.concat(this.getCastleMoves(sq));
390 break;
391 }
392 // When a pawn in an union reaches final rank with a non-standard
393 // promotion move: apply promotion anyway
394 let moves = [];
395 const oppCol = V.GetOppCol(c);
396 const oppLastRank = (c == 'w' ? 7 : 0);
397 baseMoves.forEach(m => {
398 if (
399 m.end.x == oppLastRank &&
400 ['c', 'd', 'e', 'f', 'g'].includes(m.appear[0].p)
401 ) {
402 // Move to first rank, which is last rank for opponent's pawn.
403 // => Show promotion choices.
404 // Find our piece in union (not a pawn)
405 const up = this.getUnionPieces(m.appear[0].c, m.appear[0].p);
406 // merge with all potential promotion pieces + push (loop)
407 for (let promotionPiece of [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN]) {
408 let args = [up[c], promotionPiece];
409 if (c == 'b') args = args.reverse();
410 const cp = this.getUnionCode(args[0], args[1], c);
411 let cpMove = JSON.parse(JSON.stringify(m));
412 cpMove.appear[0].c = cp.c;
413 cpMove.appear[0].p = cp.p;
414 moves.push(cpMove);
415 }
416 }
417 else {
418 if (
419 m.vanish.length > 0 &&
420 m.vanish[0].p == V.PAWN &&
421 m.start.y != m.end.y &&
422 this.board[m.end.x][m.end.y] == V.EMPTY
423 ) {
424 if (!!lm)
425 // No en-passant inside a chaining
426 return;
427 // Fix en-passant capture: union type, maybe released piece too
428 const cs = [m.end.x + (c == 'w' ? 1 : -1), m.end.y];
429 const code = this.board[cs[0]][cs[1]].charAt(1);
430 if (code == V.PAWN) {
431 // Simple en-passant capture (usual: just form union)
432 m.appear[0].c = c;
433 m.appear[0].p = 'a';
434 }
435 else {
436 // An union pawn + something just moved two squares
437 const color = this.board[cs[0]][cs[1]].charAt(0);
438 const up = this.getUnionPieces(color, code);
439 m.end.released = up[c];
440 let args = [V.PAWN, up[oppCol]];
441 if (c == 'b') args = args.reverse();
442 const cp = this.getUnionCode(args[0], args[1], c);
443 m.appear[0].c = cp.c;
444 m.appear[0].p = cp.p;
445 }
446 }
447 moves.push(m);
448 }
449 });
450 if (!!lm) this.board[x][y] = saveSquare;
451 return moves;
452 }
453
454 getEpSquare(moveOrSquare) {
455 if (typeof moveOrSquare === "string") {
456 const square = moveOrSquare;
457 if (square == "-") return undefined;
458 return V.SquareToCoords(square);
459 }
460 const move = moveOrSquare;
461 const s = move.start,
462 e = move.end;
463 if (
464 s.y == e.y &&
465 Math.abs(s.x - e.x) == 2 &&
466 this.getPiece(s.x, s.y) == V.PAWN
467 ) {
468 return {
469 x: (s.x + e.x) / 2,
470 y: s.y
471 };
472 }
473 return undefined;
474 }
475
476 getCastleMoves([x, y]) {
477 const c = this.turn;
478 const accepted = (c == 'w' ? ['v', 'w'] : ['a', 'b']);
479 const oppCol = V.GetOppCol(c);
480 let moves = [];
481 const finalSquares = [ [2, 3], [6, 5] ];
482 castlingCheck: for (let castleSide = 0; castleSide < 2; castleSide++) {
483 if (this.castleFlags[c][castleSide] >= 8) continue;
484 const rookPos = this.castleFlags[c][castleSide];
485 const castlingColor = this.board[x][rookPos].charAt(0);
486 const castlingPiece = this.board[x][rookPos].charAt(1);
487
488 // Nothing on the path of the king ?
489 const finDist = finalSquares[castleSide][0] - y;
490 let step = finDist / Math.max(1, Math.abs(finDist));
491 let i = y;
492 let kingSquares = [y];
493 do {
494 if (
495 this.board[x][i] != V.EMPTY &&
496 !accepted.includes(this.getColor(x, i))
497 ) {
498 continue castlingCheck;
499 }
500 i += step;
501 kingSquares.push(i);
502 } while (i != finalSquares[castleSide][0]);
503 // No checks on the path of the king ?
504 if (this.isAttacked(kingSquares, oppCol)) continue castlingCheck;
505
506 // Nothing on the path to the rook?
507 step = castleSide == 0 ? -1 : 1;
508 for (i = y + step; i != rookPos; i += step) {
509 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
510 }
511
512 // Nothing on final squares, except maybe king and castling rook?
513 for (i = 0; i < 2; i++) {
514 if (
515 finalSquares[castleSide][i] != rookPos &&
516 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
517 (
518 finalSquares[castleSide][i] != y ||
519 // TODO: next test seems superflu
520 !accepted.includes(this.getColor(x, finalSquares[castleSide][i]))
521 )
522 ) {
523 continue castlingCheck;
524 }
525 }
526
527 moves.push(
528 new Move({
529 appear: [
530 new PiPo({
531 x: x,
532 y: finalSquares[castleSide][0],
533 p: V.KING,
534 c: c
535 }),
536 new PiPo({
537 x: x,
538 y: finalSquares[castleSide][1],
539 p: castlingPiece,
540 c: castlingColor
541 })
542 ],
543 vanish: [
544 // King might be initially disguised (Titan...)
545 new PiPo({ x: x, y: y, p: V.KING, c: c }),
546 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: castlingColor })
547 ],
548 end:
549 Math.abs(y - rookPos) <= 2
550 ? { x: x, y: rookPos }
551 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
552 })
553 );
554 }
555
556 return moves;
557 }
558
559 getEnpassantCaptures(sq, shiftX) {
560 // HACK: when artificially change turn, do not consider en-passant
561 const mcMod2 = this.movesCount % 2;
562 const c = this.turn;
563 if ((c == 'w' && mcMod2 == 1) || (c == 'b' && mcMod2 == 0)) return [];
564 return super.getEnpassantCaptures(sq, shiftX);
565 }
566
567 isAttacked_aux(files, color, positions, fromSquare, released) {
568 // "positions" = array of FENs to detect infinite loops. Example:
569 // r1q1k2r/p1Pb1ppp/5n2/1f1p4/AV5P/P1eDP3/3B1PP1/R3K1NR,
570 // Bxd2 Bxc3 Bxb4 Bxc3 Bxb4 etc.
571 const newPos = { fen: super.getBaseFen(), piece: released };
572 if (positions.some(p => p.piece == newPos.piece && p.fen == newPos.fen))
573 // Start of an infinite loop: exit
574 return false;
575 positions.push(newPos);
576 const rank = (color == 'w' ? 0 : 7);
577 const moves = this.getPotentialMovesFrom(fromSquare);
578 if (moves.some(m => m.end.x == rank && files.includes(m.end.y)))
579 // Found an attack!
580 return true;
581 for (let m of moves) {
582 if (!!m.end.released) {
583 // Turn won't change since !!m.released
584 this.play(m);
585 const res = this.isAttacked_aux(
586 files, color, positions, [m.end.x, m.end.y], m.end.released);
587 this.undo(m);
588 if (res) return true;
589 }
590 }
591 return false;
592 }
593
594 isAttacked(files, color) {
595 const rank = (color == 'w' ? 0 : 7);
596 // Since it's too difficult (impossible?) to search from the square itself,
597 // let's adopt a suboptimal but working strategy: find all attacks.
598 const c = this.turn;
599 // Artificial turn change is required:
600 this.turn = color;
601 let res = false;
602 outerLoop: for (let i=0; i<8; i++) {
603 for (let j=0; j<8; j++) {
604 // Attacks must start from a normal piece, not an union.
605 // Therefore, the following test is correct.
606 if (
607 this.board[i][j] != V.EMPTY &&
608 [V.KING, V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN].includes(
609 this.board[i][j].charAt(1)) &&
610 this.board[i][j].charAt(0) == color
611 ) {
612 // Try from here.
613 const moves = this.getPotentialMovesFrom([i, j], "noCastle");
614 if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) {
615 res = true;
616 break outerLoop;
617 }
618 for (let m of moves) {
619 if (!!m.end.released) {
620 // Turn won't change since !!m.released
621 this.play(m);
622 let positions = [];
623 res = this.isAttacked_aux(
624 files, color, positions, [m.end.x, m.end.y], m.end.released);
625 this.undo(m);
626 if (res) break outerLoop;
627 }
628 }
629 }
630 }
631 }
632 this.turn = c;
633 return res;
634 }
635
636 // Do not consider checks, except to forbid castling
637 getCheckSquares() {
638 return [];
639 }
640 filterValid(moves) {
641 return moves;
642 }
643
644 updateCastleFlags(move, piece) {
645 const c = this.turn;
646 const firstRank = (c == "w" ? 7 : 0);
647 if (piece == V.KING && move.appear.length > 0)
648 this.castleFlags[c] = [V.size.y, V.size.y];
649 else if (
650 move.start.x == firstRank &&
651 this.castleFlags[c].includes(move.start.y)
652 ) {
653 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
654 this.castleFlags[c][flagIdx] = V.size.y;
655 }
656 else if (
657 move.end.x == firstRank &&
658 this.castleFlags[c].includes(move.end.y)
659 ) {
660 // Move to our rook: necessary normal piece, to union, releasing
661 // (or the rook was moved before!)
662 const flagIdx = (move.end.y == this.castleFlags[c][0] ? 0 : 1);
663 this.castleFlags[c][flagIdx] = V.size.y;
664 }
665 }
666
667 prePlay(move) {
668 // Easier before move is played in this case (flags are saved)
669 const c = this.turn;
670 const L = this.lastMoveEnd.length;
671 const lm = this.lastMoveEnd[L-1];
672 const piece = (!!lm ? lm.p : move.vanish[0].p);
673 if (piece == V.KING)
674 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
675 this.updateCastleFlags(move, piece);
676 const pawnFirstRank = (c == 'w' ? 6 : 1);
677 if (move.start.x == pawnFirstRank)
678 // This move (potentially) turns off a 2-squares pawn flag
679 this.pawnFlags[c][move.start.y] = false;
680 }
681
682 play(move) {
683 move.flags = JSON.stringify(this.aggregateFlags());
684 this.prePlay(move);
685 this.epSquares.push(this.getEpSquare(move));
686 // Check if the move is the last of the turn: all cases except releases
687 if (!move.end.released) {
688 // No more union releases available
689 this.turn = V.GetOppCol(this.turn);
690 this.movesCount++;
691 this.lastMoveEnd.push(null);
692 }
693 else
694 this.lastMoveEnd.push(Object.assign({ p: move.end.released }, move.end));
695 V.PlayOnBoard(this.board, move);
696 }
697
698 undo(move) {
699 this.epSquares.pop();
700 this.disaggregateFlags(JSON.parse(move.flags));
701 V.UndoOnBoard(this.board, move);
702 this.lastMoveEnd.pop();
703 if (!move.end.released) {
704 this.turn = V.GetOppCol(this.turn);
705 this.movesCount--;
706 }
707 this.postUndo(move);
708 }
709
710 postUndo(move) {
711 if (this.getPiece(move.start.x, move.start.y) == V.KING)
712 this.kingPos[this.turn] = [move.start.x, move.start.y];
713 }
714
715 getCurrentScore() {
716 // Check kings: if one is captured, the side lost
717 for (let c of ['w', 'b']) {
718 const kp = this.kingPos[c];
719 const cell = this.board[kp[0]][kp[1]];
720 if (
721 cell[1] != V.KING &&
722 (
723 (c == 'w' && ['a', 'b'].includes(cell[0])) ||
724 (c == 'b' && ['v', 'w'].includes(cell[0]))
725 )
726 ) {
727 // King is captured
728 return (c == 'w' ? "0-1" : "1-0");
729 }
730 }
731 return "*";
732 }
733
734 getComputerMove() {
735 let initMoves = this.getAllValidMoves();
736 if (initMoves.length == 0) return null;
737 // Loop until valid move is found (no blocked pawn released...)
738 while (true) {
739 let moves = JSON.parse(JSON.stringify(initMoves));
740 let mvArray = [];
741 let mv = null;
742 // Just play random moves (for now at least. TODO?)
743 while (moves.length > 0) {
744 mv = moves[randInt(moves.length)];
745 mvArray.push(mv);
746 this.play(mv);
747 if (!!mv.end.released)
748 // A piece was just released from an union
749 moves = this.getPotentialMovesFrom([mv.end.x, mv.end.y]);
750 else break;
751 }
752 for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]);
753 if (!mv.end.released) return (mvArray.length > 1 ? mvArray : mvArray[0]);
754 }
755 }
756
757 // NOTE: evalPosition() is wrong, but unused since bot plays at random
758
759 getNotation(move) {
760 if (move.appear.length == 2 && move.appear[0].p == V.KING)
761 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
762
763 const c = this.turn;
764 const L = this.lastMoveEnd.length;
765 const lm = this.lastMoveEnd[L-1];
766 let piece = null;
767 if (!lm && move.vanish.length == 0)
768 // When importing a game, the info move.released is lost
769 piece = move.appear[0].p;
770 else piece = (!!lm ? lm.p : move.vanish[0].p);
771 if (!(ChessRules.PIECES.includes(piece))) {
772 // Decode (moving) union
773 const up = this.getUnionPieces(
774 move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c, piece);
775 piece = up[c]
776 }
777
778 // Basic move notation:
779 let notation = piece.toUpperCase();
780 if (
781 this.board[move.end.x][move.end.y] != V.EMPTY ||
782 (piece == V.PAWN && move.start.y != move.end.y)
783 ) {
784 notation += "x";
785 }
786 const finalSquare = V.CoordsToSquare(move.end);
787 notation += finalSquare;
788
789 // Add potential promotion indications:
790 const firstLastRank = (c == 'w' ? [7, 0] : [0, 7]);
791 if (move.end.x == firstLastRank[1] && piece == V.PAWN) {
792 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
793 notation += "=" + up[c].toUpperCase();
794 }
795 else if (
796 move.end.x == firstLastRank[0] &&
797 move.vanish.length > 0 &&
798 ['c', 'd', 'e', 'f', 'g'].includes(move.vanish[0].p)
799 ) {
800 // We promoted an opponent's pawn
801 const oppCol = V.GetOppCol(c);
802 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
803 notation += "=" + up[oppCol].toUpperCase();
804 }
805
806 return notation;
807 }
808
809 };