Update TODO + 'simplify' download_objects script
[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];
0b4bca84
BA
511 const castlingColor = this.board[x][rookPos].charAt(0);
512 const castlingPiece = this.board[x][rookPos].charAt(1);
059f0aa2
BA
513
514 // Nothing on the path of the king ?
515 const finDist = finalSquares[castleSide][0] - y;
516 let step = finDist / Math.max(1, Math.abs(finDist));
517 let i = y;
518 let kingSquares = [y];
519 do {
520 if (
521 (
522 this.board[x][i] != V.EMPTY &&
523 (this.getColor(x, i) != c || ![y, rookPos].includes(i))
524 )
525 ) {
526 continue castlingCheck;
527 }
528 i += step;
529 kingSquares.push(i);
530 } while (i != finalSquares[castleSide][0]);
531 // No checks on the path of the king ?
532 if (this.isAttacked(kingSquares, oppCol)) continue castlingCheck;
533
534 // Nothing on the path to the rook?
535 step = castleSide == 0 ? -1 : 1;
536 for (i = y + step; i != rookPos; i += step) {
537 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
538 }
539
540 // Nothing on final squares, except maybe king and castling rook?
541 for (i = 0; i < 2; i++) {
542 if (
543 finalSquares[castleSide][i] != rookPos &&
544 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
545 (
546 finalSquares[castleSide][i] != y ||
547 this.getColor(x, finalSquares[castleSide][i]) != c
548 )
549 ) {
550 continue castlingCheck;
551 }
552 }
553
554 moves.push(
555 new Move({
556 appear: [
557 new PiPo({
558 x: x,
559 y: finalSquares[castleSide][0],
560 p: V.KING,
561 c: c
562 }),
563 new PiPo({
564 x: x,
565 y: finalSquares[castleSide][1],
0b4bca84
BA
566 p: castlingPiece,
567 c: castlingColor
059f0aa2
BA
568 })
569 ],
570 vanish: [
571 // King might be initially disguised (Titan...)
572 new PiPo({ x: x, y: y, p: V.KING, c: c }),
0b4bca84 573 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: castlingColor })
059f0aa2
BA
574 ],
575 end:
576 Math.abs(y - rookPos) <= 2
577 ? { x: x, y: rookPos }
578 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
579 })
580 );
581 }
582
583 return moves;
584 }
585
0b4bca84
BA
586 getEnpassantCaptures(sq, shiftX) {
587 // HACK: when artificially change turn, do not consider en-passant
588 const mcMod2 = this.movesCount % 2;
589 const c = this.turn;
590 if ((c == 'w' && mcMod2 == 1) || (c == 'b' && mcMod2 == 0)) return [];
591 return super.getEnpassantCaptures(sq, shiftX);
592 }
593
059f0aa2
BA
594 isAttacked_aux(files, color, positions, fromSquare, released) {
595 // "positions" = array of FENs to detect infinite loops. Example:
596 // r1q1k2r/p1Pb1ppp/5n2/1f1p4/AV5P/P1eDP3/3B1PP1/R3K1NR,
597 // Bxd2 Bxc3 Bxb4 Bxc3 Bxb4 etc.
598 const newPos = { fen: super.getBaseFen(), piece: released };
599 if (positions.some(p => p.piece == newPos.piece && p.fen == newPos.fen))
600 // Start of an infinite loop: exit
601 return false;
602 positions.push(newPos);
603 const rank = (color == 'w' ? 0 : 7);
604 const moves = this.getPotentialMovesFrom(fromSquare);
605 if (moves.some(m => m.end.x == rank && files.includes(m.end.y)))
606 // Found an attack!
607 return true;
608 for (let m of moves) {
609 if (!!m.released) {
610 // Turn won't change since !!m.released
611 this.play(m);
612 const res = this.isAttacked_aux(
613 files, color, positions, [m.end.x, m.end.y], m.released);
614 this.undo(m);
615 if (res) return true;
616 }
617 }
4a209313
BA
618 return false;
619 }
059f0aa2
BA
620
621 isAttacked(files, color) {
622 const rank = (color == 'w' ? 0 : 7);
623 // Since it's too difficult (impossible?) to search from the square itself,
624 // let's adopt a suboptimal but working strategy: find all attacks.
625 const c = this.turn;
626 // Artificial turn change is required:
627 this.turn = color;
628 let res = false;
629 outerLoop: for (let i=0; i<8; i++) {
630 for (let j=0; j<8; j++) {
631 // Attacks must start from a normal piece, not an union.
632 // Therefore, the following test is correct.
633 if (
634 this.board[i][j] != V.EMPTY &&
635 // Do not start with king (irrelevant, and lead to infinite calls)
636 [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN].includes(
637 this.board[i][j].charAt(1)) &&
638 this.board[i][j].charAt(0) == color
639 ) {
640 // Try from here.
641 const moves = this.getPotentialMovesFrom([i, j]);
642 if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) {
643 res = true;
644 break outerLoop;
645 }
646 for (let m of moves) {
647 if (!!m.released) {
648 // Turn won't change since !!m.released
649 this.play(m);
650 let positions = [];
651 res = this.isAttacked_aux(
652 files, color, positions, [m.end.x, m.end.y], m.released);
653 this.undo(m);
654 if (res) break outerLoop;
655 }
656 }
657 }
658 }
659 }
660 this.turn = c;
661 return res;
662 }
663
664 // Do not consider checks, except to forbid castling
4a209313
BA
665 getCheckSquares() {
666 return [];
667 }
668 filterValid(moves) {
669 if (moves.length == 0) return [];
670 const L = this.umoves.length; //at least 1: init from FEN
671 return moves.filter(m => !this.oppositeMoves(this.umoves[L - 1], m));
672 }
673
0b4bca84 674 updateCastleFlags(move, piece) {
4258b58c 675 const c = this.turn;
0b4bca84 676 const firstRank = (c == "w" ? 7 : 0);
0b4bca84
BA
677 if (piece == V.KING && move.appear.length > 0)
678 this.castleFlags[c] = [V.size.y, V.size.y];
679 else if (
680 move.start.x == firstRank &&
681 this.castleFlags[c].includes(move.start.y)
682 ) {
683 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
684 this.castleFlags[c][flagIdx] = V.size.y;
685 }
4258b58c
BA
686 else if (
687 move.end.x == firstRank &&
688 this.castleFlags[c].includes(move.end.y)
689 ) {
690 // Move to our rook: necessary normal piece, to union, releasing
691 // (or the rook was moved before!)
692 const flagIdx = (move.end.y == this.castleFlags[c][0] ? 0 : 1);
693 this.castleFlags[c][flagIdx] = V.size.y;
694 }
0b4bca84
BA
695 }
696
4258b58c
BA
697 prePlay(move) {
698 // Easier before move is played in this case (flags are saved)
699 const c = this.turn;
700 const L = this.lastMoveEnd.length;
701 const lm = this.lastMoveEnd[L-1];
702 const piece = (!!lm ? lm.p : move.vanish[0].p);
4a209313
BA
703 if (piece == V.KING)
704 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
705 this.updateCastleFlags(move, piece);
4258b58c
BA
706 const pawnFirstRank = (c == 'w' ? 6 : 1);
707 if (move.start.x == pawnFirstRank)
708 // This move (potentially) turns off a 2-squares pawn flag
709 this.pawnFlags[c][move.start.y] = false;
710 }
711
712 play(move) {
713 move.flags = JSON.stringify(this.aggregateFlags());
714 this.prePlay(move);
715 this.epSquares.push(this.getEpSquare(move));
716 // Check if the move is the last of the turn: all cases except releases
717 if (!move.released) {
718 // No more union releases available
719 this.turn = V.GetOppCol(this.turn);
720 this.movesCount++;
721 this.lastMoveEnd.push(null);
059f0aa2 722 }
4258b58c
BA
723 else this.lastMoveEnd.push(Object.assign({ p: move.released }, move.end));
724 V.PlayOnBoard(this.board, move);
725 this.umoves.push(this.getUmove(move));
4a209313
BA
726 }
727
173f11dc
BA
728 undo(move) {
729 this.epSquares.pop();
c27fcf89 730 this.disaggregateFlags(JSON.parse(move.flags));
173f11dc
BA
731 V.UndoOnBoard(this.board, move);
732 this.lastMoveEnd.pop();
4a209313 733 if (!move.released) {
173f11dc
BA
734 this.turn = V.GetOppCol(this.turn);
735 this.movesCount--;
736 }
4a209313 737 this.umoves.pop();
3cf54395 738 this.postUndo(move);
173f11dc
BA
739 }
740
4a209313
BA
741 postUndo(move) {
742 if (this.getPiece(move.start.x, move.start.y) == V.KING)
743 this.kingPos[this.turn] = [move.start.x, move.start.y];
744 }
745
173f11dc
BA
746 getCurrentScore() {
747 // Check kings: if one is dancing, the side lost
4a209313 748 // But, if both dancing, let's say it's a draw :-)
173f11dc 749 const [kpW, kpB] = [this.kingPos['w'], this.kingPos['b']];
4a209313
BA
750 const atKingPlace = [
751 this.board[kpW[0]][kpW[1]].charAt(1),
752 this.board[kpB[0]][kpB[1]].charAt(1)
753 ];
754 if (!atKingPlace.includes('k')) return "1/2";
755 if (atKingPlace[0] != 'k') return "0-1";
756 if (atKingPlace[1] != 'k') return "1-0";
173f11dc
BA
757 return "*";
758 }
759
760 getComputerMove() {
4a209313
BA
761 let initMoves = this.getAllValidMoves();
762 if (initMoves.length == 0) return null;
763 // Loop until valid move is found (no blocked pawn released...)
764 while (true) {
765 let moves = JSON.parse(JSON.stringify(initMoves));
766 let mvArray = [];
767 let mv = null;
768 // Just play random moves (for now at least. TODO?)
769 while (moves.length > 0) {
770 mv = moves[randInt(moves.length)];
771 mvArray.push(mv);
772 this.play(mv);
773 if (!!mv.released)
774 // A piece was just released from an union
775 moves = this.getPotentialMovesFrom([mv.end.x, mv.end.y]);
776 else break;
777 }
778 for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]);
779 if (!mv.released) return (mvArray.length > 1 ? mvArray : mvArray[0]);
173f11dc 780 }
173f11dc
BA
781 }
782
783 // NOTE: evalPosition() is wrong, but unused since bot plays at random
784
785 getNotation(move) {
4a209313
BA
786 if (move.appear.length == 2 && move.appear[0].p == V.KING)
787 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
788
789 const c = this.turn;
790 const L = this.lastMoveEnd.length;
791 const lm = this.lastMoveEnd[L-1];
792 let piece = null;
793 if (!lm && move.vanish.length == 0)
794 // When importing a game, the info move.released is lost
795 piece = move.appear[0].p;
796 else piece = (!!lm ? lm.p : move.vanish[0].p);
797 if (!(ChessRules.PIECES.includes(piece))) {
798 // Decode (moving) union
799 const up = this.getUnionPieces(
800 move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c, piece);
801 piece = up[c]
802 }
803
804 // Basic move notation:
805 let notation = piece.toUpperCase();
806 if (
807 this.board[move.end.x][move.end.y] != V.EMPTY ||
808 (piece == V.PAWN && move.start.y != move.end.y)
809 ) {
810 notation += "x";
811 }
812 const finalSquare = V.CoordsToSquare(move.end);
813 notation += finalSquare;
814
815 // Add potential promotion indications:
816 const firstLastRank = (c == 'w' ? [7, 0] : [0, 7]);
817 if (move.end.x == firstLastRank[1] && piece == V.PAWN) {
818 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
819 notation += "=" + up[c].toUpperCase();
820 }
821 else if (
822 move.end.x == firstLastRank[0] &&
823 move.vanish.length > 0 &&
824 ['c', 'd', 'e', 'f', 'g'].includes(move.vanish[0].p)
825 ) {
826 // We promoted an opponent's pawn
827 const oppCol = V.GetOppCol(c);
828 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
829 notation += "=" + up[oppCol].toUpperCase();
830 }
831
832 return notation;
173f11dc
BA
833 }
834
835};