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