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