Fix typo
[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
6cc34165
BA
37 static fen2board(f) {
38 // Underscore is character 95, in file w_
39 return f.charCodeAt() <= 95 ? "w" + f.toLowerCase() : "b" + f;
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;
059f0aa2 46 let kingSymb = ['k', 'g', 'm', 'u', 'x', '_'];
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++) {
059f0aa2 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 };
059f0aa2 107 const kingSymb = ['k', 'g', 'm', 'u', 'x', '_'];
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);
059f0aa2
BA
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 }
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 }
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
059f0aa2
BA
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
4a209313
BA
180 getUmove(move) {
181 if (
182 move.vanish.length == 1 &&
9d15c433
BA
183 !(ChessRules.PIECES.includes(move.appear[0].p)) &&
184 move.appear[0].p == move.vanish[0].p //not a promotion
4a209313
BA
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) {
059f0aa2
BA
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;
4a209313
BA
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();
173f11dc
BA
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);
4a209313 235 return this.turn; //union: I can use it, so it's "my" color...
173f11dc
BA
236 }
237
238 getPiece(i, j, color) {
239 const p = this.board[i][j].charAt(1);
173f11dc
BA
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
4a209313 255 // p1: white piece, p2: black piece
173f11dc
BA
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) {
4a209313
BA
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 }
173f11dc
BA
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({
4a209313
BA
292 start: { x: sx, y: sy },
293 end: { x: ex, y: ey },
294 vanish: []
295 });
296 if (!piece) {
297 mv.vanish = [
173f11dc
BA
298 new PiPo({
299 x: sx,
300 y: sy,
301 c: initColor,
302 p: initPiece
303 })
4a209313
BA
304 ];
305 }
173f11dc
BA
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,
4a209313 312 c: !!tr ? tr.c : initColor,
173f11dc
BA
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
4a209313
BA
331 let args = [!!tr ? tr.p : initPiece, destPiece];
332 if (c == 'b') args = args.reverse();
333 const cp = this.getUnionCode(args[0], args[1]);
173f11dc
BA
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);
4a209313
BA
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]);
173f11dc
BA
349 mv.appear = [
350 new PiPo({
351 x: ex,
352 y: ey,
353 c: cp.c,
354 p: cp.p
355 })
356 ];
9d15c433
BA
357 // In move.end, to be sent to the server
358 mv.end.released = up[c];
173f11dc
BA
359 return mv;
360 }
361
4a209313 362 getPotentialMovesFrom([x, y]) {
173f11dc
BA
363 const L = this.lastMoveEnd.length;
364 const lm = this.lastMoveEnd[L-1];
4a209313
BA
365 if (!!lm && (x != lm.x || y != lm.y)) return [];
366 const piece = (!!lm ? lm.p : this.getPiece(x, y));
173f11dc 367 if (!!lm) {
4a209313 368 var saveSquare = this.board[x][y];
173f11dc
BA
369 this.board[x][y] = this.turn + piece;
370 }
371 let baseMoves = [];
059f0aa2 372 const c = this.turn;
173f11dc 373 switch (piece || this.getPiece(x, y)) {
059f0aa2
BA
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 });
173f11dc 392 break;
059f0aa2 393 }
173f11dc
BA
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 = [];
4a209313
BA
413 const oppCol = V.GetOppCol(c);
414 const oppLastRank = (c == 'w' ? 7 : 0);
173f11dc 415 baseMoves.forEach(m => {
4a209313
BA
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];
4a209313
BA
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 {
9d15c433
BA
454 // An union pawn + something just moved two squares
455 const color = this.board[cs[0]][cs[1]].charAt(0);
4a209313 456 const up = this.getUnionPieces(color, code);
9d15c433 457 m.end.released = up[c];
4a209313
BA
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 }
173f11dc 467 });
4a209313 468 if (!!lm) this.board[x][y] = saveSquare;
173f11dc
BA
469 return moves;
470 }
471
4a209313
BA
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;
4a209313
BA
481 if (
482 s.y == e.y &&
483 Math.abs(s.x - e.x) == 2 &&
9d15c433 484 this.getPiece(s.x, s.y, this.turn) == V.PAWN
4a209313
BA
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 &&
9d15c433 500 !m2.end.released &&
4a209313
BA
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
059f0aa2
BA
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];
0b4bca84
BA
516 const castlingColor = this.board[x][rookPos].charAt(0);
517 const castlingPiece = this.board[x][rookPos].charAt(1);
059f0aa2
BA
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],
0b4bca84
BA
571 p: castlingPiece,
572 c: castlingColor
059f0aa2
BA
573 })
574 ],
575 vanish: [
576 // King might be initially disguised (Titan...)
577 new PiPo({ x: x, y: y, p: V.KING, c: c }),
0b4bca84 578 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: castlingColor })
059f0aa2
BA
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
0b4bca84
BA
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
059f0aa2
BA
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 = { fen: super.getBaseFen(), piece: released };
604 if (positions.some(p => p.piece == newPos.piece && p.fen == newPos.fen))
605 // Start of an infinite loop: exit
606 return false;
607 positions.push(newPos);
608 const rank = (color == 'w' ? 0 : 7);
609 const moves = this.getPotentialMovesFrom(fromSquare);
610 if (moves.some(m => m.end.x == rank && files.includes(m.end.y)))
611 // Found an attack!
612 return true;
613 for (let m of moves) {
9d15c433 614 if (!!m.end.released) {
059f0aa2
BA
615 // Turn won't change since !!m.released
616 this.play(m);
617 const res = this.isAttacked_aux(
9d15c433 618 files, color, positions, [m.end.x, m.end.y], m.end.released);
059f0aa2
BA
619 this.undo(m);
620 if (res) return true;
621 }
622 }
4a209313
BA
623 return false;
624 }
059f0aa2
BA
625
626 isAttacked(files, color) {
627 const rank = (color == 'w' ? 0 : 7);
628 // Since it's too difficult (impossible?) to search from the square itself,
629 // let's adopt a suboptimal but working strategy: find all attacks.
630 const c = this.turn;
631 // Artificial turn change is required:
632 this.turn = color;
633 let res = false;
634 outerLoop: for (let i=0; i<8; i++) {
635 for (let j=0; j<8; j++) {
636 // Attacks must start from a normal piece, not an union.
637 // Therefore, the following test is correct.
638 if (
639 this.board[i][j] != V.EMPTY &&
640 // Do not start with king (irrelevant, and lead to infinite calls)
641 [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN].includes(
642 this.board[i][j].charAt(1)) &&
643 this.board[i][j].charAt(0) == color
644 ) {
645 // Try from here.
646 const moves = this.getPotentialMovesFrom([i, j]);
647 if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) {
648 res = true;
649 break outerLoop;
650 }
651 for (let m of moves) {
9d15c433 652 if (!!m.end.released) {
059f0aa2
BA
653 // Turn won't change since !!m.released
654 this.play(m);
655 let positions = [];
656 res = this.isAttacked_aux(
9d15c433 657 files, color, positions, [m.end.x, m.end.y], m.end.released);
059f0aa2
BA
658 this.undo(m);
659 if (res) break outerLoop;
660 }
661 }
662 }
663 }
664 }
665 this.turn = c;
666 return res;
667 }
668
669 // Do not consider checks, except to forbid castling
4a209313
BA
670 getCheckSquares() {
671 return [];
672 }
673 filterValid(moves) {
674 if (moves.length == 0) return [];
675 const L = this.umoves.length; //at least 1: init from FEN
676 return moves.filter(m => !this.oppositeMoves(this.umoves[L - 1], m));
677 }
678
0b4bca84 679 updateCastleFlags(move, piece) {
4258b58c 680 const c = this.turn;
0b4bca84 681 const firstRank = (c == "w" ? 7 : 0);
0b4bca84
BA
682 if (piece == V.KING && move.appear.length > 0)
683 this.castleFlags[c] = [V.size.y, V.size.y];
684 else if (
685 move.start.x == firstRank &&
686 this.castleFlags[c].includes(move.start.y)
687 ) {
688 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
689 this.castleFlags[c][flagIdx] = V.size.y;
690 }
4258b58c
BA
691 else if (
692 move.end.x == firstRank &&
693 this.castleFlags[c].includes(move.end.y)
694 ) {
695 // Move to our rook: necessary normal piece, to union, releasing
696 // (or the rook was moved before!)
697 const flagIdx = (move.end.y == this.castleFlags[c][0] ? 0 : 1);
698 this.castleFlags[c][flagIdx] = V.size.y;
699 }
0b4bca84
BA
700 }
701
4258b58c
BA
702 prePlay(move) {
703 // Easier before move is played in this case (flags are saved)
704 const c = this.turn;
705 const L = this.lastMoveEnd.length;
706 const lm = this.lastMoveEnd[L-1];
707 const piece = (!!lm ? lm.p : move.vanish[0].p);
4a209313
BA
708 if (piece == V.KING)
709 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
710 this.updateCastleFlags(move, piece);
4258b58c
BA
711 const pawnFirstRank = (c == 'w' ? 6 : 1);
712 if (move.start.x == pawnFirstRank)
713 // This move (potentially) turns off a 2-squares pawn flag
714 this.pawnFlags[c][move.start.y] = false;
715 }
716
717 play(move) {
718 move.flags = JSON.stringify(this.aggregateFlags());
719 this.prePlay(move);
720 this.epSquares.push(this.getEpSquare(move));
721 // Check if the move is the last of the turn: all cases except releases
9d15c433 722 if (!move.end.released) {
4258b58c
BA
723 // No more union releases available
724 this.turn = V.GetOppCol(this.turn);
725 this.movesCount++;
726 this.lastMoveEnd.push(null);
059f0aa2 727 }
9d15c433
BA
728 else {
729 this.lastMoveEnd.push({
730 p: move.end.released,
731 x: move.end.x,
732 y: move.end.y
733 });
734 }
4258b58c
BA
735 V.PlayOnBoard(this.board, move);
736 this.umoves.push(this.getUmove(move));
4a209313
BA
737 }
738
173f11dc
BA
739 undo(move) {
740 this.epSquares.pop();
c27fcf89 741 this.disaggregateFlags(JSON.parse(move.flags));
173f11dc
BA
742 V.UndoOnBoard(this.board, move);
743 this.lastMoveEnd.pop();
9d15c433 744 if (!move.end.released) {
173f11dc
BA
745 this.turn = V.GetOppCol(this.turn);
746 this.movesCount--;
747 }
4a209313 748 this.umoves.pop();
3cf54395 749 this.postUndo(move);
173f11dc
BA
750 }
751
4a209313
BA
752 postUndo(move) {
753 if (this.getPiece(move.start.x, move.start.y) == V.KING)
754 this.kingPos[this.turn] = [move.start.x, move.start.y];
755 }
756
173f11dc
BA
757 getCurrentScore() {
758 // Check kings: if one is dancing, the side lost
4a209313 759 // But, if both dancing, let's say it's a draw :-)
173f11dc 760 const [kpW, kpB] = [this.kingPos['w'], this.kingPos['b']];
4a209313
BA
761 const atKingPlace = [
762 this.board[kpW[0]][kpW[1]].charAt(1),
763 this.board[kpB[0]][kpB[1]].charAt(1)
764 ];
765 if (!atKingPlace.includes('k')) return "1/2";
766 if (atKingPlace[0] != 'k') return "0-1";
767 if (atKingPlace[1] != 'k') return "1-0";
173f11dc
BA
768 return "*";
769 }
770
771 getComputerMove() {
4a209313
BA
772 let initMoves = this.getAllValidMoves();
773 if (initMoves.length == 0) return null;
774 // Loop until valid move is found (no blocked pawn released...)
775 while (true) {
776 let moves = JSON.parse(JSON.stringify(initMoves));
777 let mvArray = [];
778 let mv = null;
779 // Just play random moves (for now at least. TODO?)
780 while (moves.length > 0) {
781 mv = moves[randInt(moves.length)];
782 mvArray.push(mv);
783 this.play(mv);
9d15c433 784 if (!!mv.end.released)
4a209313
BA
785 // A piece was just released from an union
786 moves = this.getPotentialMovesFrom([mv.end.x, mv.end.y]);
787 else break;
788 }
789 for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]);
9d15c433 790 if (!mv.end.released) return (mvArray.length > 1 ? mvArray : mvArray[0]);
173f11dc 791 }
173f11dc
BA
792 }
793
794 // NOTE: evalPosition() is wrong, but unused since bot plays at random
795
796 getNotation(move) {
4a209313
BA
797 if (move.appear.length == 2 && move.appear[0].p == V.KING)
798 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
799
800 const c = this.turn;
801 const L = this.lastMoveEnd.length;
802 const lm = this.lastMoveEnd[L-1];
803 let piece = null;
804 if (!lm && move.vanish.length == 0)
805 // When importing a game, the info move.released is lost
806 piece = move.appear[0].p;
807 else piece = (!!lm ? lm.p : move.vanish[0].p);
808 if (!(ChessRules.PIECES.includes(piece))) {
809 // Decode (moving) union
810 const up = this.getUnionPieces(
811 move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c, piece);
812 piece = up[c]
813 }
814
815 // Basic move notation:
816 let notation = piece.toUpperCase();
817 if (
818 this.board[move.end.x][move.end.y] != V.EMPTY ||
819 (piece == V.PAWN && move.start.y != move.end.y)
820 ) {
821 notation += "x";
822 }
823 const finalSquare = V.CoordsToSquare(move.end);
824 notation += finalSquare;
825
826 // Add potential promotion indications:
827 const firstLastRank = (c == 'w' ? [7, 0] : [0, 7]);
828 if (move.end.x == firstLastRank[1] && piece == V.PAWN) {
829 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
830 notation += "=" + up[c].toUpperCase();
831 }
832 else if (
833 move.end.x == firstLastRank[0] &&
834 move.vanish.length > 0 &&
835 ['c', 'd', 'e', 'f', 'g'].includes(move.vanish[0].p)
836 ) {
837 // We promoted an opponent's pawn
838 const oppCol = V.GetOppCol(c);
839 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
840 notation += "=" + up[oppCol].toUpperCase();
841 }
842
843 return notation;
173f11dc
BA
844 }
845
846};