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