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