Fix Bario, write rules
[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 }
171
172 static IsGoodFlags(flags) {
173 // 4 for castle + 16 for pawns
174 return !!flags.match(/^[a-z]{4,4}[01]{16,16}$/);
175 }
176
177 setFlags(fenflags) {
178 super.setFlags(fenflags); //castleFlags
179 this.pawnFlags = {
180 w: [...Array(8)], //pawns can move 2 squares?
181 b: [...Array(8)]
182 };
183 const flags = fenflags.substr(4); //skip first 4 letters, for castle
184 for (let c of ["w", "b"]) {
185 for (let i = 0; i < 8; i++)
186 this.pawnFlags[c][i] = flags.charAt((c == "w" ? 0 : 8) + i) == "1";
187 }
188 }
189
190 aggregateFlags() {
191 return [this.castleFlags, this.pawnFlags];
192 }
193
194 disaggregateFlags(flags) {
195 this.castleFlags = flags[0];
196 this.pawnFlags = flags[1];
197 }
198
199 static GenRandInitFen(randomness) {
200 // Add 16 pawns flags:
201 return ChessRules.GenRandInitFen(randomness)
202 .slice(0, -2) + "1111111111111111 -";
203 }
204
205 getFlagsFen() {
206 let fen = super.getFlagsFen();
207 // Add pawns flags
208 for (let c of ["w", "b"])
209 for (let i = 0; i < 8; i++) fen += (this.pawnFlags[c][i] ? "1" : "0");
210 return fen;
211 }
212
213 getPiece(i, j) {
214 const p = this.board[i][j].charAt(1);
215 if (ChessRules.PIECES.includes(p)) return p;
216 const c = this.board[i][j].charAt(0);
217 const idx = (['a', 'w'].includes(c) ? 0 : 1);
218 return V.UNIONS[p][idx];
219 }
220
221 getUnionPieces(color, code) {
222 const pieces = V.UNIONS[code];
223 return {
224 w: pieces[ ['b', 'w'].includes(color) ? 0 : 1 ],
225 b: pieces[ ['a', 'v'].includes(color) ? 0 : 1 ]
226 };
227 }
228
229 // p1: white piece, p2: black piece, capturer: (temporary) owner
230 getUnionCode(p1, p2, capturer) {
231 let uIdx = (
232 Object.values(V.UNIONS).findIndex(v => v[0] == p1 && v[1] == p2)
233 );
234 let c = '';
235 if (capturer == 'w') c = (uIdx >= 0 ? 'w' : 'v');
236 else c = (uIdx >= 0 ? 'b' : 'a');
237 if (uIdx == -1) {
238 uIdx = (
239 Object.values(V.UNIONS).findIndex(v => v[0] == p2 && v[1] == p1)
240 );
241 }
242 return { c: c, p: Object.keys(V.UNIONS)[uIdx] };
243 }
244
245 getBasicMove([sx, sy], [ex, ey], tr) {
246 const L = this.lastMoveEnd.length;
247 const lm = this.lastMoveEnd[L-1];
248 const piece = (!!lm ? lm.p : null);
249 const initColor = (!!piece ? this.turn : this.board[sx][sy].charAt(0));
250 const initPiece = (piece || this.board[sx][sy].charAt(1));
251 const c = this.turn;
252 const oppCol = V.GetOppCol(c);
253 if (!!tr && !(ChessRules.PIECES.includes(initPiece))) {
254 // Transformation computed without taking union into account
255 const up = this.getUnionPieces(initColor, initPiece);
256 let args = [tr.p, up[oppCol]];
257 if (['a', 'v'].includes(initColor)) args = args.reverse();
258 const capturer = (['a', 'b'].includes(initColor) ? 'b' : 'w');
259 const cp = this.getUnionCode(args[0], args[1], capturer);
260 tr.c = cp.c;
261 tr.p = cp.p;
262 }
263 // 4 cases : moving
264 // - union to free square (other cases are illegal: return null)
265 // - normal piece to free square,
266 // to enemy normal piece, or
267 // to union (releasing our piece)
268 let mv = new Move({
269 start: { x: sx, y: sy },
270 end: { x: ex, y: ey },
271 vanish: []
272 });
273 if (!piece) {
274 mv.vanish = [
275 new PiPo({
276 x: sx,
277 y: sy,
278 c: initColor,
279 p: initPiece
280 })
281 ];
282 }
283 // Treat free square cases first:
284 if (this.board[ex][ey] == V.EMPTY) {
285 mv.appear = [
286 new PiPo({
287 x: ex,
288 y: ey,
289 c: !!tr ? tr.c : initColor,
290 p: !!tr ? tr.p : initPiece
291 })
292 ];
293 return mv;
294 }
295 // Now the two cases with union / release:
296 const destColor = this.board[ex][ey].charAt(0);
297 const destPiece = this.board[ex][ey].charAt(1);
298 mv.vanish.push(
299 new PiPo({
300 x: ex,
301 y: ey,
302 c: destColor,
303 p: destPiece
304 })
305 );
306 if (ChessRules.PIECES.includes(destPiece)) {
307 // Normal piece: just create union
308 let args = [!!tr ? tr.p : initPiece, destPiece];
309 if (c == 'b') args = args.reverse();
310 const cp = this.getUnionCode(args[0], args[1], c);
311 mv.appear = [
312 new PiPo({
313 x: ex,
314 y: ey,
315 c: cp.c,
316 p: cp.p
317 })
318 ];
319 return mv;
320 }
321 // Releasing a piece in an union: keep track of released piece
322 const up = this.getUnionPieces(destColor, destPiece);
323 let args = [!!tr ? tr.p : initPiece, up[oppCol]];
324 if (c == 'b') args = args.reverse();
325 const cp = this.getUnionCode(args[0], args[1], c);
326 mv.appear = [
327 new PiPo({
328 x: ex,
329 y: ey,
330 c: cp.c,
331 p: cp.p
332 })
333 ];
334 mv.end.released = up[c];
335 return mv;
336 }
337
338 // noCastle arg: when detecting king attacks
339 getPotentialMovesFrom([x, y], noCastle) {
340 const L = this.lastMoveEnd.length;
341 const lm = this.lastMoveEnd[L-1];
342 if (!!lm && (x != lm.x || y != lm.y)) return [];
343 const piece = (!!lm ? lm.p : this.getPiece(x, y));
344 if (!!lm) {
345 var saveSquare = this.board[x][y];
346 this.board[x][y] = this.turn + piece;
347 }
348 let baseMoves = [];
349 const c = this.turn;
350 switch (piece || this.getPiece(x, y)) {
351 case V.PAWN: {
352 const firstRank = (c == 'w' ? 7 : 0);
353 baseMoves = this.getPotentialPawnMoves([x, y]).filter(m => {
354 // Skip forbidden 2-squares jumps (except from first rank)
355 // Also skip unions capturing en-passant (not allowed).
356 return (
357 (
358 m.start.x == firstRank ||
359 Math.abs(m.end.x - m.start.x) == 1 ||
360 this.pawnFlags[c][m.start.y]
361 )
362 &&
363 (
364 this.board[x][y].charAt(1) == V.PAWN ||
365 m.start.y == m.end.y
366 )
367 );
368 });
369 break;
370 }
371 case V.ROOK:
372 baseMoves = this.getPotentialRookMoves([x, y]);
373 break;
374 case V.KNIGHT:
375 baseMoves = this.getPotentialKnightMoves([x, y]);
376 break;
377 case V.BISHOP:
378 baseMoves = this.getPotentialBishopMoves([x, y]);
379 break;
380 case V.QUEEN:
381 baseMoves = this.getPotentialQueenMoves([x, y]);
382 break;
383 case V.KING:
384 baseMoves = this.getSlideNJumpMoves(
385 [x, y],
386 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
387 "oneStep"
388 );
389 if (!noCastle && this.castleFlags[this.turn].some(v => v < V.size.y))
390 baseMoves = baseMoves.concat(this.getCastleMoves([x, y]));
391 break;
392 }
393 // When a pawn in an union reaches final rank with a non-standard
394 // promotion move: apply promotion anyway
395 let moves = [];
396 const oppCol = V.GetOppCol(c);
397 const oppLastRank = (c == 'w' ? 7 : 0);
398 baseMoves.forEach(m => {
399 if (
400 m.end.x == oppLastRank &&
401 ['c', 'd', 'e', 'f', 'g'].includes(m.appear[0].p)
402 ) {
403 // Move to first rank, which is last rank for opponent's pawn.
404 // => Show promotion choices.
405 // Find our piece in union (not a pawn)
406 const up = this.getUnionPieces(m.appear[0].c, m.appear[0].p);
407 // merge with all potential promotion pieces + push (loop)
408 for (let promotionPiece of [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN]) {
409 let args = [up[c], promotionPiece];
410 if (c == 'b') args = args.reverse();
411 const cp = this.getUnionCode(args[0], args[1], c);
412 let cpMove = JSON.parse(JSON.stringify(m));
413 cpMove.appear[0].c = cp.c;
414 cpMove.appear[0].p = cp.p;
415 moves.push(cpMove);
416 }
417 }
418 else {
419 if (
420 m.vanish.length > 0 &&
421 m.vanish[0].p == V.PAWN &&
422 m.start.y != m.end.y &&
423 this.board[m.end.x][m.end.y] == V.EMPTY
424 ) {
425 if (!!lm)
426 // No en-passant inside a chaining
427 return;
428 // Fix en-passant capture: union type, maybe released piece too
429 const cs = [m.end.x + (c == 'w' ? 1 : -1), m.end.y];
430 const code = this.board[cs[0]][cs[1]].charAt(1);
431 if (code == V.PAWN) {
432 // Simple en-passant capture (usual: just form union)
433 m.appear[0].c = c;
434 m.appear[0].p = 'a';
435 }
436 else {
437 // An union pawn + something just moved two squares
438 const color = this.board[cs[0]][cs[1]].charAt(0);
439 const up = this.getUnionPieces(color, code);
440 m.end.released = up[c];
441 let args = [V.PAWN, up[oppCol]];
442 if (c == 'b') args = args.reverse();
443 const cp = this.getUnionCode(args[0], args[1], c);
444 m.appear[0].c = cp.c;
445 m.appear[0].p = cp.p;
446 }
447 }
448 moves.push(m);
449 }
450 });
451 if (!!lm) this.board[x][y] = saveSquare;
452 return moves;
453 }
454
455 getEpSquare(moveOrSquare) {
456 if (typeof moveOrSquare === "string") {
457 const square = moveOrSquare;
458 if (square == "-") return undefined;
459 return V.SquareToCoords(square);
460 }
461 const move = moveOrSquare;
462 const s = move.start,
463 e = move.end;
464 if (
465 s.y == e.y &&
466 Math.abs(s.x - e.x) == 2 &&
467 this.getPiece(s.x, s.y) == V.PAWN
468 ) {
469 return {
470 x: (s.x + e.x) / 2,
471 y: s.y
472 };
473 }
474 return undefined;
475 }
476
477 getCastleMoves([x, y]) {
478 const c = this.turn;
479 const accepted = (c == 'w' ? ['v', 'w'] : ['a', 'b']);
480 const oppCol = V.GetOppCol(c);
481 let moves = [];
482 const finalSquares = [ [2, 3], [6, 5] ];
483 castlingCheck: for (let castleSide = 0; castleSide < 2; castleSide++) {
484 if (this.castleFlags[c][castleSide] >= 8) continue;
485 const rookPos = this.castleFlags[c][castleSide];
486 const castlingColor = this.board[x][rookPos].charAt(0);
487 const castlingPiece = this.board[x][rookPos].charAt(1);
488
489 // Nothing on the path of the king ?
490 const finDist = finalSquares[castleSide][0] - y;
491 let step = finDist / Math.max(1, Math.abs(finDist));
492 let i = y;
493 let kingSquares = [y];
494 do {
495 if (
496 this.board[x][i] != V.EMPTY &&
497 !accepted.includes(this.getColor(x, i))
498 ) {
499 continue castlingCheck;
500 }
501 i += step;
502 kingSquares.push(i);
503 } while (i != finalSquares[castleSide][0]);
504 // No checks on the path of the king ?
505 if (this.isAttacked(kingSquares, oppCol)) continue castlingCheck;
506
507 // Nothing on the path to the rook?
508 step = castleSide == 0 ? -1 : 1;
509 for (i = y + step; i != rookPos; i += step) {
510 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
511 }
512
513 // Nothing on final squares, except maybe king and castling rook?
514 for (i = 0; i < 2; i++) {
515 if (
516 finalSquares[castleSide][i] != rookPos &&
517 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
518 (
519 finalSquares[castleSide][i] != y ||
520 // TODO: next test seems superflu
521 !accepted.includes(this.getColor(x, finalSquares[castleSide][i]))
522 )
523 ) {
524 continue castlingCheck;
525 }
526 }
527
528 moves.push(
529 new Move({
530 appear: [
531 new PiPo({
532 x: x,
533 y: finalSquares[castleSide][0],
534 p: V.KING,
535 c: c
536 }),
537 new PiPo({
538 x: x,
539 y: finalSquares[castleSide][1],
540 p: castlingPiece,
541 c: castlingColor
542 })
543 ],
544 vanish: [
545 // King might be initially disguised (Titan...)
546 new PiPo({ x: x, y: y, p: V.KING, c: c }),
547 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: castlingColor })
548 ],
549 end:
550 Math.abs(y - rookPos) <= 2
551 ? { x: x, y: rookPos }
552 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
553 })
554 );
555 }
556
557 return moves;
558 }
559
560 getEnpassantCaptures(sq, shiftX) {
561 // HACK: when artificially change turn, do not consider en-passant
562 const mcMod2 = this.movesCount % 2;
563 const c = this.turn;
564 if ((c == 'w' && mcMod2 == 1) || (c == 'b' && mcMod2 == 0)) return [];
565 return super.getEnpassantCaptures(sq, shiftX);
566 }
567
568 isAttacked_aux(files, color, positions, fromSquare, released) {
569 // "positions" = array of FENs to detect infinite loops. Example:
570 // r1q1k2r/p1Pb1ppp/5n2/1f1p4/AV5P/P1eDP3/3B1PP1/R3K1NR,
571 // Bxd2 Bxc3 Bxb4 Bxc3 Bxb4 etc.
572 const newPos = { fen: super.getBaseFen(), piece: released };
573 if (positions.some(p => p.piece == newPos.piece && p.fen == newPos.fen))
574 // Start of an infinite loop: exit
575 return false;
576 positions.push(newPos);
577 const rank = (color == 'w' ? 0 : 7);
578 const moves = this.getPotentialMovesFrom(fromSquare);
579 if (moves.some(m => m.end.x == rank && files.includes(m.end.y)))
580 // Found an attack!
581 return true;
582 for (let m of moves) {
583 if (!!m.end.released) {
584 // Turn won't change since !!m.released
585 this.play(m);
586 const res = this.isAttacked_aux(
587 files, color, positions, [m.end.x, m.end.y], m.end.released);
588 this.undo(m);
589 if (res) return true;
590 }
591 }
592 return false;
593 }
594
595 isAttacked(files, color) {
596 const rank = (color == 'w' ? 0 : 7);
597 // Since it's too difficult (impossible?) to search from the square itself,
598 // let's adopt a suboptimal but working strategy: find all attacks.
599 const c = this.turn;
600 // Artificial turn change is required:
601 this.turn = color;
602 let res = false;
603 outerLoop: for (let i=0; i<8; i++) {
604 for (let j=0; j<8; j++) {
605 // Attacks must start from a normal piece, not an union.
606 // Therefore, the following test is correct.
607 if (
608 this.board[i][j] != V.EMPTY &&
609 [V.KING, V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN].includes(
610 this.board[i][j].charAt(1)) &&
611 this.board[i][j].charAt(0) == color
612 ) {
613 // Try from here.
614 const moves = this.getPotentialMovesFrom([i, j], "noCastle");
615 if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) {
616 res = true;
617 break outerLoop;
618 }
619 for (let m of moves) {
620 if (!!m.end.released) {
621 // Turn won't change since !!m.released
622 this.play(m);
623 let positions = [];
624 res = this.isAttacked_aux(
625 files, color, positions, [m.end.x, m.end.y], m.end.released);
626 this.undo(m);
627 if (res) break outerLoop;
628 }
629 }
630 }
631 }
632 }
633 this.turn = c;
634 return res;
635 }
636
637 // Do not consider checks, except to forbid castling
638 getCheckSquares() {
639 return [];
640 }
641 filterValid(moves) {
642 return moves;
643 }
644
645 updateCastleFlags(move, piece) {
646 const c = this.turn;
647 const firstRank = (c == "w" ? 7 : 0);
648 if (piece == V.KING && move.appear.length > 0)
649 this.castleFlags[c] = [V.size.y, V.size.y];
650 else if (
651 move.start.x == firstRank &&
652 this.castleFlags[c].includes(move.start.y)
653 ) {
654 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
655 this.castleFlags[c][flagIdx] = V.size.y;
656 }
657 else if (
658 move.end.x == firstRank &&
659 this.castleFlags[c].includes(move.end.y)
660 ) {
661 // Move to our rook: necessary normal piece, to union, releasing
662 // (or the rook was moved before!)
663 const flagIdx = (move.end.y == this.castleFlags[c][0] ? 0 : 1);
664 this.castleFlags[c][flagIdx] = V.size.y;
665 }
666 }
667
668 prePlay(move) {
669 // Easier before move is played in this case (flags are saved)
670 const c = this.turn;
671 const L = this.lastMoveEnd.length;
672 const lm = this.lastMoveEnd[L-1];
673 const piece =
674 !!lm
675 ? lm.p :
676 this.getPiece(move.vanish[0].x, move.vanish[0].y);
677 if (piece == V.KING)
678 this.kingPos[c] = [move.appear[0].x, move.appear[0].y];
679 this.updateCastleFlags(move, piece);
680 const pawnFirstRank = (c == 'w' ? 6 : 1);
681 if (
682 move.start.x == pawnFirstRank &&
683 piece == V.PAWN &&
684 Math.abs(move.end.x - move.start.x) == 2
685 ) {
686 // This move turns off a 2-squares pawn flag
687 this.pawnFlags[c][move.start.y] = false;
688 }
689 }
690
691 play(move) {
692 move.flags = JSON.stringify(this.aggregateFlags());
693 this.prePlay(move);
694 this.epSquares.push(this.getEpSquare(move));
695 // Check if the move is the last of the turn: all cases except releases
696 if (!move.end.released) {
697 // No more union releases available
698 this.turn = V.GetOppCol(this.turn);
699 this.movesCount++;
700 this.lastMoveEnd.push(null);
701 }
702 else
703 this.lastMoveEnd.push(Object.assign({ p: move.end.released }, move.end));
704 V.PlayOnBoard(this.board, move);
705 }
706
707 undo(move) {
708 this.epSquares.pop();
709 this.disaggregateFlags(JSON.parse(move.flags));
710 V.UndoOnBoard(this.board, move);
711 this.lastMoveEnd.pop();
712 if (!move.end.released) {
713 this.turn = V.GetOppCol(this.turn);
714 this.movesCount--;
715 }
716 this.postUndo(move);
717 }
718
719 postUndo(move) {
720 if (this.getPiece(move.start.x, move.start.y) == V.KING)
721 this.kingPos[this.turn] = [move.start.x, move.start.y];
722 }
723
724 getCurrentScore() {
725 // Check kings: if one is captured, the side lost
726 for (let c of ['w', 'b']) {
727 const kp = this.kingPos[c];
728 const cell = this.board[kp[0]][kp[1]];
729 if (
730 cell[1] != V.KING &&
731 (
732 (c == 'w' && ['a', 'b'].includes(cell[0])) ||
733 (c == 'b' && ['v', 'w'].includes(cell[0]))
734 )
735 ) {
736 // King is captured
737 return (c == 'w' ? "0-1" : "1-0");
738 }
739 }
740 return "*";
741 }
742
743 getComputerMove() {
744 let initMoves = this.getAllValidMoves();
745 if (initMoves.length == 0) return null;
746 // Loop until valid move is found (no blocked pawn released...)
747 while (true) {
748 let moves = JSON.parse(JSON.stringify(initMoves));
749 let mvArray = [];
750 let mv = null;
751 // Just play random moves (for now at least. TODO?)
752 while (moves.length > 0) {
753 mv = moves[randInt(moves.length)];
754 mvArray.push(mv);
755 this.play(mv);
756 if (!!mv.end.released)
757 // A piece was just released from an union
758 moves = this.getPotentialMovesFrom([mv.end.x, mv.end.y]);
759 else break;
760 }
761 for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]);
762 if (!mv.end.released) return (mvArray.length > 1 ? mvArray : mvArray[0]);
763 }
764 return null; //never reached
765 }
766
767 // NOTE: evalPosition() is wrong, but unused since bot plays at random
768
769 getNotation(move) {
770 if (move.appear.length == 2 && move.appear[0].p == V.KING)
771 return (move.end.y < move.start.y ? "0-0-0" : "0-0");
772
773 const c = this.turn;
774 const L = this.lastMoveEnd.length;
775 const lm = this.lastMoveEnd[L-1];
776 let piece = null;
777 if (!lm && move.vanish.length == 0)
778 // When importing a game, the info move.released is lost
779 piece = move.appear[0].p;
780 else piece = (!!lm ? lm.p : move.vanish[0].p);
781 if (!(ChessRules.PIECES.includes(piece))) {
782 // Decode (moving) union
783 const up = this.getUnionPieces(
784 move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c, piece);
785 piece = up[c]
786 }
787
788 // Basic move notation:
789 let notation = piece.toUpperCase();
790 if (
791 this.board[move.end.x][move.end.y] != V.EMPTY ||
792 (piece == V.PAWN && move.start.y != move.end.y)
793 ) {
794 notation += "x";
795 }
796 const finalSquare = V.CoordsToSquare(move.end);
797 notation += finalSquare;
798
799 // Add potential promotion indications:
800 const firstLastRank = (c == 'w' ? [7, 0] : [0, 7]);
801 if (move.end.x == firstLastRank[1] && piece == V.PAWN) {
802 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
803 notation += "=" + up[c].toUpperCase();
804 }
805 else if (
806 move.end.x == firstLastRank[0] &&
807 move.vanish.length > 0 &&
808 ['c', 'd', 'e', 'f', 'g'].includes(move.vanish[0].p)
809 ) {
810 // We promoted an opponent's pawn
811 const oppCol = V.GetOppCol(c);
812 const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p);
813 notation += "=" + up[oppCol].toUpperCase();
814 }
815
816 return notation;
817 }
818
819 };