A few fixes + remove debug traces (Eightpieces variant)
[vchess.git] / client / src / variants / Eightpieces.js
CommitLineData
2a8a94c9 1import { ArrayFun } from "@/utils/array";
afbf3ca7 2import { randInt } from "@/utils/alea";
2a8a94c9
BA
3import { ChessRules, PiPo, Move } from "@/base_rules";
4
5export const VariantRules = class EightpiecesRules extends ChessRules {
6 static get JAILER() {
7 return "j";
8 }
9 static get SENTRY() {
10 return "s";
11 }
12 static get LANCER() {
13 return "l";
14 }
15
ee307044 16 // Lancer directions *from white perspective*
28b32b4f
BA
17 static get LANCER_DIRS() {
18 return {
19 'c': [-1, 0], //north
20 'd': [-1, 1], //N-E
21 'e': [0, 1], //east
22 'f': [1, 1], //S-E
23 'g': [1, 0], //south
24 'h': [1, -1], //S-W
25 'm': [0, -1], //west
26 'o': [-1, -1] //N-W
27 };
28 }
29
3a2a7b5f
BA
30 static get PIECES() {
31 return ChessRules.PIECES
32 .concat([V.JAILER, V.SENTRY])
33 .concat(Object.keys(V.LANCER_DIRS));
34 }
35
28b32b4f
BA
36 getPiece(i, j) {
37 const piece = this.board[i][j].charAt(1);
38 // Special lancer case: 8 possible orientations
39 if (Object.keys(V.LANCER_DIRS).includes(piece)) return V.LANCER;
40 return piece;
41 }
42
3a2a7b5f
BA
43 getPpath(b, color, score, orientation) {
44 if ([V.JAILER, V.SENTRY].includes(b[1])) return "Eightpieces/" + b;
45 if (Object.keys(V.LANCER_DIRS).includes(b[1])) {
46 if (orientation == 'w') return "Eightpieces/" + b;
47 // Find opposite direction for adequate display:
48 let oppDir = '';
49 switch (b[1]) {
50 case 'c':
51 oppDir = 'g';
52 break;
53 case 'g':
54 oppDir = 'c';
55 break;
56 case 'd':
57 oppDir = 'h';
58 break;
59 case 'h':
60 oppDir = 'd';
61 break;
62 case 'e':
63 oppDir = 'm';
64 break;
65 case 'm':
66 oppDir = 'e';
67 break;
68 case 'f':
69 oppDir = 'o';
70 break;
71 case 'o':
72 oppDir = 'f';
73 break;
74 }
75 return "Eightpieces/" + b[0] + oppDir;
76 }
90e814b6
BA
77 return b;
78 }
79
3a2a7b5f
BA
80 getPPpath(b, orientation) {
81 return this.getPpath(b, null, null, orientation);
82 }
83
90e814b6
BA
84 static ParseFen(fen) {
85 const fenParts = fen.split(" ");
3a2a7b5f
BA
86 return Object.assign(
87 ChessRules.ParseFen(fen),
88 { sentrypush: fenParts[5] }
89 );
90 }
91
92 static IsGoodFen(fen) {
93 if (!ChessRules.IsGoodFen(fen)) return false;
94 const fenParsed = V.ParseFen(fen);
95 // 5) Check sentry push (if any)
96 if (
97 fenParsed.sentrypush != "-" &&
98 !fenParsed.sentrypush.match(/^([a-h][1-8],?)+$/)
99 ) {
100 return false;
101 }
102 return true;
90e814b6
BA
103 }
104
105 getFen() {
6b7b2cf7 106 return super.getFen() + " " + this.getSentrypushFen();
90e814b6
BA
107 }
108
109 getFenForRepeat() {
6b7b2cf7 110 return super.getFenForRepeat() + "_" + this.getSentrypushFen();
90e814b6
BA
111 }
112
6b7b2cf7
BA
113 getSentrypushFen() {
114 const L = this.sentryPush.length;
115 if (!this.sentryPush[L-1]) return "-";
90e814b6 116 let res = "";
6b7b2cf7 117 this.sentryPush[L-1].forEach(coords =>
90e814b6
BA
118 res += V.CoordsToSquare(coords) + ",");
119 return res.slice(0, -1);
2a8a94c9
BA
120 }
121
28b32b4f
BA
122 setOtherVariables(fen) {
123 super.setOtherVariables(fen);
124 // subTurn == 2 only when a sentry moved, and is about to push something
125 this.subTurn = 1;
afbf3ca7
BA
126 // Sentry position just after a "capture" (subTurn from 1 to 2)
127 this.sentryPos = null;
28b32b4f 128 // Stack pieces' forbidden squares after a sentry move at each turn
90e814b6 129 const parsedFen = V.ParseFen(fen);
6b7b2cf7 130 if (parsedFen.sentrypush == "-") this.sentryPush = [null];
90e814b6 131 else {
6b7b2cf7
BA
132 this.sentryPush = [
133 parsedFen.sentrypush.split(",").map(sq => {
90e814b6
BA
134 return V.SquareToCoords(sq);
135 })
136 ];
137 }
2a8a94c9
BA
138 }
139
2a8a94c9 140 static GenRandInitFen(randomness) {
9842aca2
BA
141 if (randomness == 0)
142 // Deterministic:
3a2a7b5f 143 return "jsfqkbnr/pppppppp/8/8/8/8/PPPPPPPP/JSDQKBNR w 0 ahah - -";
9842aca2
BA
144
145 let pieces = { w: new Array(8), b: new Array(8) };
3a2a7b5f 146 let flags = "";
9842aca2
BA
147 // Shuffle pieces on first (and last rank if randomness == 2)
148 for (let c of ["w", "b"]) {
149 if (c == 'b' && randomness == 1) {
ee307044
BA
150 const lancerIdx = pieces['w'].findIndex(p => {
151 return Object.keys(V.LANCER_DIRS).includes(p);
152 });
153 pieces['b'] =
154 pieces['w'].slice(0, lancerIdx)
155 .concat(['g'])
156 .concat(pieces['w'].slice(lancerIdx + 1));
3a2a7b5f 157 flags += flags;
9842aca2
BA
158 break;
159 }
160
161 let positions = ArrayFun.range(8);
162
163 // Get random squares for bishop and sentry
164 let randIndex = 2 * randInt(4);
165 let bishopPos = positions[randIndex];
166 // The sentry must be on a square of different color
167 let randIndex_tmp = 2 * randInt(4) + 1;
168 let sentryPos = positions[randIndex_tmp];
169 if (c == 'b') {
170 // Check if white sentry is on the same color as ours.
171 // If yes: swap bishop and sentry positions.
172 if ((pieces['w'].indexOf('s') - sentryPos) % 2 == 0)
173 [bishopPos, sentryPos] = [sentryPos, bishopPos];
174 }
175 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
176 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
177
178 // Get random squares for knight and lancer
179 randIndex = randInt(6);
180 const knightPos = positions[randIndex];
181 positions.splice(randIndex, 1);
182 randIndex = randInt(5);
183 const lancerPos = positions[randIndex];
184 positions.splice(randIndex, 1);
185
186 // Get random square for queen
187 randIndex = randInt(4);
188 const queenPos = positions[randIndex];
189 positions.splice(randIndex, 1);
190
191 // Rook, jailer and king positions are now almost fixed,
192 // only the ordering rook-> jailer or jailer->rook must be decided.
193 let rookPos = positions[0];
194 let jailerPos = positions[2];
195 const kingPos = positions[1];
3a2a7b5f 196 flags += V.CoordToColumn(rookPos) + V.CoordToColumn(jailerPos);
9842aca2
BA
197 if (Math.random() < 0.5) [rookPos, jailerPos] = [jailerPos, rookPos];
198
199 pieces[c][rookPos] = "r";
200 pieces[c][knightPos] = "n";
201 pieces[c][bishopPos] = "b";
202 pieces[c][queenPos] = "q";
203 pieces[c][kingPos] = "k";
204 pieces[c][sentryPos] = "s";
205 // Lancer faces north for white, and south for black:
206 pieces[c][lancerPos] = c == 'w' ? 'c' : 'g';
207 pieces[c][jailerPos] = "j";
208 }
209 return (
210 pieces["b"].join("") +
211 "/pppppppp/8/8/8/8/PPPPPPPP/" +
212 pieces["w"].join("").toUpperCase() +
3a2a7b5f 213 " w 0 " + flags + " - -"
9842aca2 214 );
2a8a94c9
BA
215 }
216
b0a0468a
BA
217 canTake([x1, y1], [x2, y2]) {
218 if (this.subTurn == 2)
219 // Only self captures on this subturn:
220 return this.getColor(x1, y1) == this.getColor(x2, y2);
221 return super.canTake([x1, y1], [x2, y2]);
222 }
223
6b7b2cf7
BA
224 // Is piece on square (x,y) immobilized?
225 isImmobilized([x, y]) {
226 const color = this.getColor(x, y);
227 const oppCol = V.GetOppCol(color);
228 for (let step of V.steps[V.ROOK]) {
229 const [i, j] = [x + step[0], y + step[1]];
230 if (
231 V.OnBoard(i, j) &&
232 this.board[i][j] != V.EMPTY &&
233 this.getColor(i, j) == oppCol
234 ) {
bfed878d 235 if (this.getPiece(i, j) == V.JAILER) return [i, j];
6b7b2cf7
BA
236 }
237 }
238 return null;
239 }
240
ee307044
BA
241 // Because of the lancers, getPiece() could be wrong:
242 // use board[x][y][1] instead (always valid).
243 getBasicMove([sx, sy], [ex, ey], tr) {
244 let mv = new Move({
245 appear: [
246 new PiPo({
247 x: ex,
248 y: ey,
249 c: tr ? tr.c : this.getColor(sx, sy),
afbf3ca7 250 p: tr ? tr.p : this.board[sx][sy].charAt(1)
ee307044
BA
251 })
252 ],
253 vanish: [
254 new PiPo({
255 x: sx,
256 y: sy,
257 c: this.getColor(sx, sy),
afbf3ca7 258 p: this.board[sx][sy].charAt(1)
ee307044
BA
259 })
260 ]
261 });
262
263 // The opponent piece disappears if we take it
264 if (this.board[ex][ey] != V.EMPTY) {
265 mv.vanish.push(
266 new PiPo({
267 x: ex,
268 y: ey,
269 c: this.getColor(ex, ey),
afbf3ca7 270 p: this.board[ex][ey].charAt(1)
ee307044
BA
271 })
272 );
273 }
274
275 return mv;
276 }
277
bfed878d
BA
278 canIplay(side, [x, y]) {
279 return (
280 (this.subTurn == 1 && this.turn == side && this.getColor(x, y) == side) ||
281 (this.subTurn == 2 && x == this.sentryPos.x && y == this.sentryPos.y)
282 );
283 }
284
3a2a7b5f 285 getPotentialMovesFrom([x, y]) {
bfed878d 286 // At subTurn == 2, jailers aren't effective (Jeff K)
3a2a7b5f
BA
287 if (this.subTurn == 1) {
288 const jsq = this.isImmobilized([x, y]);
289 if (!!jsq) {
290 let moves = [];
291 // Special pass move if king:
292 if (this.getPiece(x, y) == V.KING) {
293 moves.push(
294 new Move({
295 appear: [],
296 vanish: [],
297 start: { x: x, y: y },
298 end: { x: jsq[0], y: jsq[1] }
299 })
300 );
301 }
302 return moves;
303 }
304 }
bfed878d 305 let moves = [];
6b7b2cf7
BA
306 switch (this.getPiece(x, y)) {
307 case V.JAILER:
bfed878d
BA
308 moves = this.getPotentialJailerMoves([x, y]);
309 break;
6b7b2cf7 310 case V.SENTRY:
bfed878d
BA
311 moves = this.getPotentialSentryMoves([x, y]);
312 break;
13102cab 313 case V.LANCER:
bfed878d
BA
314 moves = this.getPotentialLancerMoves([x, y]);
315 break;
6b7b2cf7 316 default:
bfed878d
BA
317 moves = super.getPotentialMovesFrom([x, y]);
318 break;
6b7b2cf7 319 }
bfed878d
BA
320 const L = this.sentryPush.length;
321 if (!!this.sentryPush[L-1]) {
322 // Delete moves walking back on sentry push path
323 moves = moves.filter(m => {
324 if (
325 m.vanish[0].p != V.PAWN &&
326 this.sentryPush[L-1].some(sq => sq.x == m.end.x && sq.y == m.end.y)
327 ) {
328 return false;
329 }
330 return true;
331 });
b0a0468a
BA
332 } else if (this.subTurn == 2) {
333 // Put back the sentinel on board:
334 const color = this.turn;
bfed878d 335 moves.forEach(m => {
b0a0468a 336 m.appear.push({x: x, y: y, p: V.SENTRY, c: color});
bfed878d
BA
337 });
338 }
339 return moves;
6b7b2cf7
BA
340 }
341
ee307044 342 getPotentialPawnMoves([x, y]) {
bfed878d 343 const color = this.getColor(x, y);
ee307044
BA
344 let moves = [];
345 const [sizeX, sizeY] = [V.size.x, V.size.y];
89781a55 346 let shiftX = (color == "w" ? -1 : 1);
b0a0468a 347 if (this.subTurn == 2) shiftX *= -1;
89781a55 348 const firstRank = color == "w" ? sizeX - 1 : 0;
ee307044
BA
349 const startRank = color == "w" ? sizeX - 2 : 1;
350 const lastRank = color == "w" ? 0 : sizeX - 1;
351
b0a0468a
BA
352 // Pawns might be pushed on 1st rank and attempt to move again:
353 if (!V.OnBoard(x + shiftX, y)) return [];
354
ee307044 355 const finalPieces =
89781a55
BA
356 // A push cannot put a pawn on last rank (it goes backward)
357 x + shiftX == lastRank
358 ? Object.keys(V.LANCER_DIRS).concat(
bfed878d 359 [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.SENTRY, V.JAILER])
ee307044
BA
360 : [V.PAWN];
361 if (this.board[x + shiftX][y] == V.EMPTY) {
362 // One square forward
363 for (let piece of finalPieces) {
364 moves.push(
365 this.getBasicMove([x, y], [x + shiftX, y], {
366 c: color,
367 p: piece
368 })
369 );
370 }
371 if (
89781a55
BA
372 // 2-squares jumps forbidden if pawn push
373 this.subTurn == 1 &&
374 [startRank, firstRank].includes(x) &&
ee307044
BA
375 this.board[x + 2 * shiftX][y] == V.EMPTY
376 ) {
377 // Two squares jump
378 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
379 }
380 }
381 // Captures
382 for (let shiftY of [-1, 1]) {
383 if (
384 y + shiftY >= 0 &&
385 y + shiftY < sizeY &&
386 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
387 this.canTake([x, y], [x + shiftX, y + shiftY])
388 ) {
389 for (let piece of finalPieces) {
390 moves.push(
391 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
392 c: color,
393 p: piece
394 })
395 );
6b7b2cf7 396 }
ee307044
BA
397 }
398 }
399
89781a55 400 // En passant: only on subTurn == 1
ee307044 401 const Lep = this.epSquares.length;
3a2a7b5f 402 const epSquare = this.epSquares[Lep - 1];
ee307044 403 if (
89781a55 404 this.subTurn == 1 &&
ee307044
BA
405 !!epSquare &&
406 epSquare.x == x + shiftX &&
407 Math.abs(epSquare.y - y) == 1
408 ) {
409 let enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
410 enpassantMove.vanish.push({
411 x: x,
412 y: epSquare.y,
413 p: "p",
414 c: this.getColor(x, epSquare.y)
6b7b2cf7 415 });
ee307044 416 moves.push(enpassantMove);
6b7b2cf7 417 }
6b7b2cf7 418
ee307044 419 return moves;
9842aca2
BA
420 }
421
3a2a7b5f 422 // Obtain all lancer moves in "step" direction
afbf3ca7 423 getPotentialLancerMoves_aux([x, y], step, tr) {
9842aca2
BA
424 let moves = [];
425 // Add all moves to vacant squares until opponent is met:
b0a0468a
BA
426 const color = this.getColor(x, y);
427 const oppCol =
428 this.subTurn == 1
429 ? V.GetOppCol(color)
430 // at subTurn == 2, consider own pieces as opponent
431 : color;
9842aca2
BA
432 let sq = [x + step[0], y + step[1]];
433 while (V.OnBoard(sq[0], sq[1]) && this.getColor(sq[0], sq[1]) != oppCol) {
434 if (this.board[sq[0]][sq[1]] == V.EMPTY)
afbf3ca7 435 moves.push(this.getBasicMove([x, y], sq, tr));
9842aca2
BA
436 sq[0] += step[0];
437 sq[1] += step[1];
438 }
439 if (V.OnBoard(sq[0], sq[1]))
440 // Add capturing move
afbf3ca7 441 moves.push(this.getBasicMove([x, y], sq, tr));
9842aca2 442 return moves;
6b7b2cf7
BA
443 }
444
445 getPotentialLancerMoves([x, y]) {
9842aca2
BA
446 let moves = [];
447 // Add all lancer possible orientations, similar to pawn promotions.
448 // Except if just after a push: allow all movements from init square then
ee307044 449 const L = this.sentryPush.length;
89781a55 450 const color = this.getColor(x, y);
ee307044 451 if (!!this.sentryPush[L-1]) {
9842aca2 452 // Maybe I was pushed
ee307044 453 const pl = this.sentryPush[L-1].length;
9842aca2 454 if (
ee307044
BA
455 this.sentryPush[L-1][pl-1].x == x &&
456 this.sentryPush[L-1][pl-1].y == y
9842aca2
BA
457 ) {
458 // I was pushed: allow all directions (for this move only), but
3a2a7b5f
BA
459 // do not change direction after moving, *except* if I keep the
460 // same orientation in which I was pushed.
b0a0468a 461 const curDir = V.LANCER_DIRS[this.board[x][y].charAt(1)];
9842aca2 462 Object.values(V.LANCER_DIRS).forEach(step => {
afbf3ca7 463 const dirCode = Object.keys(V.LANCER_DIRS).find(k => {
3a2a7b5f
BA
464 return (
465 V.LANCER_DIRS[k][0] == step[0] &&
466 V.LANCER_DIRS[k][1] == step[1]
467 );
afbf3ca7 468 });
3a2a7b5f
BA
469 const dirMoves =
470 this.getPotentialLancerMoves_aux(
471 [x, y],
472 step,
473 { p: dirCode, c: color }
474 );
475 if (curDir[0] == step[0] && curDir[1] == step[1]) {
476 // Keeping same orientation: can choose after
477 let chooseMoves = [];
478 dirMoves.forEach(m => {
479 Object.keys(V.LANCER_DIRS).forEach(k => {
480 let mk = JSON.parse(JSON.stringify(m));
481 mk.appear[0].p = k;
482 moves.push(mk);
483 });
484 });
485 Array.prototype.push.apply(moves, chooseMoves);
486 } else Array.prototype.push.apply(moves, dirMoves);
9842aca2
BA
487 });
488 return moves;
489 }
490 }
491 // I wasn't pushed: standard lancer move
492 const dirCode = this.board[x][y][1];
493 const monodirMoves =
494 this.getPotentialLancerMoves_aux([x, y], V.LANCER_DIRS[dirCode]);
bfed878d
BA
495 // Add all possible orientations aftermove except if I'm being pushed
496 if (this.subTurn == 1) {
497 monodirMoves.forEach(m => {
498 Object.keys(V.LANCER_DIRS).forEach(k => {
499 let mk = JSON.parse(JSON.stringify(m));
500 mk.appear[0].p = k;
501 moves.push(mk);
502 });
9842aca2 503 });
bfed878d 504 return moves;
3a2a7b5f
BA
505 } else {
506 // I'm pushed: add potential nudges
507 let potentialNudges = [];
508 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
509 if (
510 V.OnBoard(x + step[0], y + step[1]) &&
511 this.board[x + step[0]][y + step[1]] == V.EMPTY
512 ) {
89781a55
BA
513 const newDirCode = Object.keys(V.LANCER_DIRS).find(k => {
514 const codeStep = V.LANCER_DIRS[k];
515 return (codeStep[0] == step[0] && codeStep[1] == step[1]);
516 });
3a2a7b5f
BA
517 potentialNudges.push(
518 this.getBasicMove(
519 [x, y],
89781a55
BA
520 [x + step[0], y + step[1]],
521 { c: color, p: newDirCode }
3a2a7b5f
BA
522 )
523 );
524 }
525 }
526 return monodirMoves.concat(potentialNudges);
527 }
6b7b2cf7
BA
528 }
529
530 getPotentialSentryMoves([x, y]) {
531 // The sentry moves a priori like a bishop:
532 let moves = super.getPotentialBishopMoves([x, y]);
ee307044
BA
533 // ...but captures are replaced by special move, if and only if
534 // "captured" piece can move now, considered as the capturer unit.
afbf3ca7
BA
535 // --> except is subTurn == 2, in this case I don't push anything.
536 if (this.subTurn == 2) return moves.filter(m => m.vanish.length == 1);
9842aca2
BA
537 moves.forEach(m => {
538 if (m.vanish.length == 2) {
539 // Temporarily cancel the sentry capture:
540 m.appear.pop();
541 m.vanish.pop();
542 }
543 });
bfed878d 544 const color = this.getColor(x, y);
ee307044 545 const fMoves = moves.filter(m => {
b0a0468a 546 // Can the pushed unit make any move? ...resulting in a non-self-check?
bfed878d
BA
547 if (m.appear.length == 0) {
548 let res = false;
549 this.play(m);
b0a0468a 550 let moves2 = this.getPotentialMovesFrom([m.end.x, m.end.y]);
bfed878d
BA
551 for (let m2 of moves2) {
552 this.play(m2);
553 res = !this.underCheck(color);
554 this.undo(m2);
555 if (res) break;
556 }
557 this.undo(m);
558 return res;
559 }
560 return true;
ee307044 561 });
ee307044 562 return fMoves;
6b7b2cf7
BA
563 }
564
565 getPotentialJailerMoves([x, y]) {
ee307044
BA
566 return super.getPotentialRookMoves([x, y]).filter(m => {
567 // Remove jailer captures
568 return m.vanish[0].p != V.JAILER || m.vanish.length == 1;
569 });
6b7b2cf7
BA
570 }
571
b0a0468a
BA
572 getPotentialKingMoves(sq) {
573 const moves = this.getSlideNJumpMoves(
574 sq,
575 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
576 "oneStep"
577 );
578 return (
579 this.subTurn == 1
580 ? moves.concat(this.getCastleMoves(sq))
581 : moves
582 );
583 }
584
90e814b6
BA
585 // Adapted: castle with jailer possible
586 getCastleMoves([x, y]) {
587 const c = this.getColor(x, y);
588 const firstRank = (c == "w" ? V.size.x - 1 : 0);
589 if (x != firstRank || y != this.INIT_COL_KING[c])
590 return [];
591
592 const oppCol = V.GetOppCol(c);
593 let moves = [];
594 let i = 0;
595 // King, then rook or jailer:
596 const finalSquares = [
597 [2, 3],
598 [V.size.y - 2, V.size.y - 3]
599 ];
600 castlingCheck: for (
601 let castleSide = 0;
602 castleSide < 2;
603 castleSide++
604 ) {
3a2a7b5f 605 if (this.castleFlags[c][castleSide] >= 8) continue;
90e814b6 606 // Rook (or jailer) and king are on initial position
90e814b6
BA
607 const finDist = finalSquares[castleSide][0] - y;
608 let step = finDist / Math.max(1, Math.abs(finDist));
609 i = y;
610 do {
611 if (
612 this.isAttacked([x, i], [oppCol]) ||
613 (this.board[x][i] != V.EMPTY &&
614 (this.getColor(x, i) != c ||
3a2a7b5f 615 ![V.KING, V.ROOK, V.JAILER].includes(this.getPiece(x, i))))
90e814b6
BA
616 ) {
617 continue castlingCheck;
618 }
619 i += step;
620 } while (i != finalSquares[castleSide][0]);
90e814b6 621 step = castleSide == 0 ? -1 : 1;
3a2a7b5f 622 const rookOrJailerPos = this.castleFlags[c][castleSide];
90e814b6
BA
623 for (i = y + step; i != rookOrJailerPos; i += step)
624 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
625
626 // Nothing on final squares, except maybe king and castling rook or jailer?
627 for (i = 0; i < 2; i++) {
628 if (
629 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
630 this.getPiece(x, finalSquares[castleSide][i]) != V.KING &&
631 finalSquares[castleSide][i] != rookOrJailerPos
632 ) {
633 continue castlingCheck;
634 }
635 }
636
637 // If this code is reached, castle is valid
638 const castlingPiece = this.getPiece(firstRank, rookOrJailerPos);
639 moves.push(
640 new Move({
641 appear: [
642 new PiPo({ x: x, y: finalSquares[castleSide][0], p: V.KING, c: c }),
643 new PiPo({ x: x, y: finalSquares[castleSide][1], p: castlingPiece, c: c })
644 ],
645 vanish: [
646 new PiPo({ x: x, y: y, p: V.KING, c: c }),
647 new PiPo({ x: x, y: rookOrJailerPos, p: castlingPiece, c: c })
648 ],
649 end:
650 Math.abs(y - rookOrJailerPos) <= 2
651 ? { x: x, y: rookOrJailerPos }
652 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
653 })
654 );
655 }
656
657 return moves;
2a8a94c9
BA
658 }
659
3a2a7b5f
BA
660 atLeastOneMove() {
661 // If in second-half of a move, we already know that a move is possible
662 if (this.subTurn == 2) return true;
663 return super.atLeastOneMove();
664 }
665
ee307044 666 filterValid(moves) {
b0a0468a
BA
667 if (moves.length == 0) return [];
668 const basicFilter = (m, c) => {
669 this.play(m);
670 const res = !this.underCheck(c);
671 this.undo(m);
672 return res;
673 };
bfed878d
BA
674 // Disable check tests for sentry pushes,
675 // because in this case the move isn't finished
676 let movesWithoutSentryPushes = [];
677 let movesWithSentryPushes = [];
678 moves.forEach(m => {
b0a0468a
BA
679 // Second condition below for special king "pass" moves
680 if (m.appear.length > 0 || m.vanish.length == 0)
681 movesWithoutSentryPushes.push(m);
bfed878d
BA
682 else movesWithSentryPushes.push(m);
683 });
b0a0468a
BA
684 const color = this.turn;
685 const oppCol = V.GetOppCol(color);
686 const filteredMoves =
687 movesWithoutSentryPushes.filter(m => basicFilter(m, color));
688 // If at least one full move made, everything is allowed.
689 // Else: forbid checks and captures.
690 return (
691 this.movesCount >= 2
692 ? filteredMoves
693 : filteredMoves.filter(m => {
d958cc68 694 return (m.vanish.length <= 1 && basicFilter(m, oppCol));
b0a0468a
BA
695 })
696 ).concat(movesWithSentryPushes);
bfed878d
BA
697 }
698
699 getAllValidMoves() {
700 if (this.subTurn == 1) return super.getAllValidMoves();
701 // Sentry push:
afbf3ca7 702 const sentrySq = [this.sentryPos.x, this.sentryPos.y];
bfed878d 703 return this.filterValid(this.getPotentialMovesFrom(sentrySq));
ee307044
BA
704 }
705
3a2a7b5f 706 prePlay(move) {
b0a0468a 707 if (move.appear.length == 0 && move.vanish.length == 1)
afbf3ca7 708 // The sentry is about to push a piece: subTurn goes from 1 to 2
93e8684c 709 this.sentryPos = { x: move.end.x, y: move.end.y };
b0a0468a 710 if (this.subTurn == 2 && move.vanish[0].p != V.PAWN) {
9842aca2
BA
711 // A piece is pushed: forbid array of squares between start and end
712 // of move, included (except if it's a pawn)
713 let squares = [];
3a2a7b5f
BA
714 if ([V.KNIGHT,V.KING].includes(move.vanish[0].p))
715 // short-range pieces: just forbid initial square
716 squares.push({ x: move.start.x, y: move.start.y });
717 else {
718 const deltaX = move.end.x - move.start.x;
719 const deltaY = move.end.y - move.start.y;
720 const step = [
721 deltaX / Math.abs(deltaX) || 0,
722 deltaY / Math.abs(deltaY) || 0
723 ];
724 for (
725 let sq = {x: move.start.x, y: move.start.y};
b0a0468a 726 sq.x != move.end.x || sq.y != move.end.y;
3a2a7b5f
BA
727 sq.x += step[0], sq.y += step[1]
728 ) {
729 squares.push({ x: sq.x, y: sq.y });
9842aca2 730 }
90e814b6 731 }
3a2a7b5f
BA
732 // Add end square as well, to know if I was pushed (useful for lancers)
733 squares.push({ x: move.end.x, y: move.end.y });
9842aca2
BA
734 this.sentryPush.push(squares);
735 } else this.sentryPush.push(null);
2a8a94c9
BA
736 }
737
90e814b6 738 play(move) {
89781a55
BA
739// if (!this.states) this.states = [];
740// const stateFen = this.getFen();
741// this.states.push(stateFen);
3a2a7b5f
BA
742
743 this.prePlay(move);
90e814b6
BA
744 move.flags = JSON.stringify(this.aggregateFlags());
745 this.epSquares.push(this.getEpSquare(move));
746 V.PlayOnBoard(this.board, move);
afbf3ca7
BA
747 // Is it a sentry push? (useful for undo)
748 move.sentryPush = (this.subTurn == 2);
9842aca2 749 if (this.subTurn == 1) this.movesCount++;
afbf3ca7 750 if (move.appear.length == 0 && move.vanish.length == 1) this.subTurn = 2;
93e8684c 751 else {
ee307044 752 // Turn changes only if not a sentry "pre-push"
9842aca2 753 this.turn = V.GetOppCol(this.turn);
ee307044 754 this.subTurn = 1;
ee307044 755 }
3a2a7b5f
BA
756 this.postPlay(move);
757 }
758
759 postPlay(move) {
b0a0468a
BA
760 if (move.vanish.length == 0 || this.subTurn == 2)
761 // Special pass move of the king, or sentry pre-push: nothing to update
3a2a7b5f 762 return;
b0a0468a
BA
763 const c = move.vanish[0].c;
764 const piece = move.vanish[0].p;
765 const firstRank = c == "w" ? V.size.x - 1 : 0;
766
767 if (piece == V.KING) {
768 this.kingPos[c][0] = move.appear[0].x;
769 this.kingPos[c][1] = move.appear[0].y;
770 this.castleFlags[c] = [V.size.y, V.size.y];
771 return;
772 }
773 // Update castling flags if rooks are moved
774 const oppCol = V.GetOppCol(c);
775 const oppFirstRank = V.size.x - 1 - firstRank;
776 if (
777 move.start.x == firstRank && //our rook moves?
778 this.castleFlags[c].includes(move.start.y)
779 ) {
780 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
781 this.castleFlags[c][flagIdx] = V.size.y;
782 } else if (
783 move.end.x == oppFirstRank && //we took opponent rook?
784 this.castleFlags[oppCol].includes(move.end.y)
785 ) {
786 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
787 this.castleFlags[oppCol][flagIdx] = V.size.y;
788 }
90e814b6 789 }
2a8a94c9 790
90e814b6
BA
791 undo(move) {
792 this.epSquares.pop();
793 this.disaggregateFlags(JSON.parse(move.flags));
794 V.UndoOnBoard(this.board, move);
ee307044
BA
795 // Decrement movesCount except if the move is a sentry push
796 if (!move.sentryPush) this.movesCount--;
3a2a7b5f
BA
797 if (this.subTurn == 2) this.subTurn = 1;
798 else {
9842aca2 799 this.turn = V.GetOppCol(this.turn);
3a2a7b5f
BA
800 if (move.sentryPush) this.subTurn = 2;
801 }
802 this.postUndo(move);
803
89781a55
BA
804// const stateFen = this.getFen();
805// if (stateFen != this.states[this.states.length-1]) debugger;
806// this.states.pop();
3a2a7b5f
BA
807 }
808
809 postUndo(move) {
810 super.postUndo(move);
811 this.sentryPush.pop();
90e814b6 812 }
2a8a94c9 813
afbf3ca7
BA
814 isAttacked(sq, colors) {
815 return (
816 super.isAttacked(sq, colors) ||
817 this.isAttackedByLancer(sq, colors) ||
818 this.isAttackedBySentry(sq, colors)
819 );
820 }
821
b0a0468a
BA
822 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
823 for (let step of steps) {
824 let rx = x + step[0],
825 ry = y + step[1];
826 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
827 rx += step[0];
828 ry += step[1];
829 }
830 if (
831 V.OnBoard(rx, ry) &&
832 this.getPiece(rx, ry) === piece &&
833 colors.includes(this.getColor(rx, ry)) &&
834 !this.isImmobilized([rx, ry])
835 ) {
836 return true;
837 }
838 }
839 return false;
840 }
841
842 isAttackedByPawn([x, y], colors) {
843 for (let c of colors) {
844 const pawnShift = c == "w" ? 1 : -1;
845 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
846 for (let i of [-1, 1]) {
847 if (
848 y + i >= 0 &&
849 y + i < V.size.y &&
850 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
851 this.getColor(x + pawnShift, y + i) == c &&
852 !this.isImmobilized([x + pawnShift, y + i])
853 ) {
854 return true;
855 }
856 }
857 }
858 }
859 return false;
860 }
861
afbf3ca7
BA
862 isAttackedByLancer([x, y], colors) {
863 for (let step of V.steps[V.ROOK].concat(V.steps[V.BISHOP])) {
864 // If in this direction there are only enemy pieces and empty squares,
865 // and we meet a lancer: can he reach us?
866 // NOTE: do not stop at first lancer, there might be several!
867 let coord = { x: x + step[0], y: y + step[1] };
868 let lancerPos = [];
869 while (
870 V.OnBoard(coord.x, coord.y) &&
871 (
872 this.board[coord.x][coord.y] == V.EMPTY ||
873 colors.includes(this.getColor(coord.x, coord.y))
874 )
875 ) {
b0a0468a
BA
876 if (
877 this.getPiece(coord.x, coord.y) == V.LANCER &&
878 !this.isImmobilized([coord.x, coord.y])
879 ) {
3a2a7b5f 880 lancerPos.push({x: coord.x, y: coord.y});
b0a0468a 881 }
3a2a7b5f
BA
882 coord.x += step[0];
883 coord.y += step[1];
afbf3ca7
BA
884 }
885 for (let xy of lancerPos) {
886 const dir = V.LANCER_DIRS[this.board[xy.x][xy.y].charAt(1)];
887 if (dir[0] == -step[0] && dir[1] == -step[1]) return true;
888 }
889 }
890 return false;
891 }
892
893 // Helper to check sentries attacks:
894 selfAttack([x1, y1], [x2, y2]) {
895 const color = this.getColor(x1, y1);
896 const sliderAttack = (allowedSteps, lancer) => {
89781a55
BA
897 const deltaX = x2 - x1,
898 absDeltaX = Math.abs(deltaX);
899 const deltaY = y2 - y1,
900 absDeltaY = Math.abs(deltaY);
901 const step = [ deltaX / absDeltaX, deltaY / absDeltaY ];
902 if (
903 // Check that the step is a priori valid:
904 (absDeltaX != absDeltaY && deltaX != 0 && deltaY != 0) ||
905 allowedSteps.every(st => st[0] != step[0] || st[1] != step[1])
906 ) {
afbf3ca7 907 return false;
89781a55 908 }
3a2a7b5f 909 let sq = [ x1 + step[0], y1 + step[1] ];
afbf3ca7
BA
910 while (sq[0] != x2 && sq[1] != y2) {
911 if (
3a2a7b5f 912 // NOTE: no need to check OnBoard in this special case
afbf3ca7
BA
913 (!lancer && this.board[sq[0]][sq[1]] != V.EMPTY) ||
914 (!!lancer && this.getColor(sq[0], sq[1]) != color)
915 ) {
916 return false;
917 }
3a2a7b5f
BA
918 sq[0] += step[0];
919 sq[1] += step[1];
afbf3ca7
BA
920 }
921 return true;
922 };
923 switch (this.getPiece(x1, y1)) {
924 case V.PAWN: {
925 // Pushed pawns move as enemy pawns
926 const shift = (color == 'w' ? 1 : -1);
927 return (x1 + shift == x2 && Math.abs(y1 - y2) == 1);
928 }
929 case V.KNIGHT: {
930 const deltaX = Math.abs(x1 - x2);
931 const deltaY = Math.abs(y1 - y2);
932 return (
933 deltaX + deltaY == 3 &&
934 [1, 2].includes(deltaX) &&
935 [1, 2].includes(deltaY)
936 );
937 }
938 case V.ROOK:
939 return sliderAttack(V.steps[V.ROOK]);
940 case V.BISHOP:
941 return sliderAttack(V.steps[V.BISHOP]);
942 case V.QUEEN:
943 return sliderAttack(V.steps[V.ROOK].concat(V.steps[V.BISHOP]));
944 case V.LANCER: {
945 // Special case: as long as no enemy units stands in-between, it attacks
946 // (if it points toward the king).
947 const allowedStep = V.LANCER_DIRS[this.board[x1][y1].charAt(1)];
948 return sliderAttack([allowedStep], "lancer");
949 }
950 // No sentries or jailer tests: they cannot self-capture
951 }
952 return false;
953 }
954
955 isAttackedBySentry([x, y], colors) {
956 // Attacked by sentry means it can self-take our king.
957 // Just check diagonals of enemy sentry(ies), and if it reaches
958 // one of our pieces: can I self-take?
959 const color = V.GetOppCol(colors[0]);
960 let candidates = [];
961 for (let i=0; i<V.size.x; i++) {
962 for (let j=0; j<V.size.y; j++) {
963 if (
964 this.getPiece(i,j) == V.SENTRY &&
b0a0468a
BA
965 colors.includes(this.getColor(i,j)) &&
966 !this.isImmobilized([i, j])
afbf3ca7
BA
967 ) {
968 for (let step of V.steps[V.BISHOP]) {
969 let sq = [ i + step[0], j + step[1] ];
970 while (
971 V.OnBoard(sq[0], sq[1]) &&
972 this.board[sq[0]][sq[1]] == V.EMPTY
973 ) {
974 sq[0] += step[0];
975 sq[1] += step[1];
976 }
977 if (
978 V.OnBoard(sq[0], sq[1]) &&
979 this.getColor(sq[0], sq[1]) == color
980 ) {
3a2a7b5f 981 candidates.push([ sq[0], sq[1] ]);
afbf3ca7
BA
982 }
983 }
984 }
985 }
986 }
987 for (let c of candidates)
988 if (this.selfAttack(c, [x, y])) return true;
989 return false;
990 }
991
992 // Jailer doesn't capture or give check
993
2a8a94c9
BA
994 static get VALUES() {
995 return Object.assign(
28b32b4f 996 { l: 4.8, s: 2.8, j: 3.8 }, //Jeff K. estimations
2a8a94c9
BA
997 ChessRules.VALUES
998 );
999 }
6b7b2cf7 1000
afbf3ca7
BA
1001 getComputerMove() {
1002 const maxeval = V.INFINITY;
1003 const color = this.turn;
1004 let moves1 = this.getAllValidMoves();
1005
1006 if (moves1.length == 0)
1007 // TODO: this situation should not happen
1008 return null;
1009
3a2a7b5f 1010 const setEval = (move, next) => {
afbf3ca7 1011 const score = this.getCurrentScore();
3a2a7b5f 1012 const curEval = move.eval;
afbf3ca7
BA
1013 if (score != "*") {
1014 move.eval =
1015 score == "1/2"
1016 ? 0
1017 : (score == "1-0" ? 1 : -1) * maxeval;
3a2a7b5f
BA
1018 } else move.eval = this.evalPosition();
1019 if (
1020 // "next" is defined after sentry pushes
1021 !!next && (
1022 !curEval ||
1023 color == 'w' && move.eval > curEval ||
1024 color == 'b' && move.eval < curEval
1025 )
1026 ) {
1027 move.second = next;
1028 }
afbf3ca7
BA
1029 };
1030
1031 // Just search_depth == 1 (because of sentries. TODO: can do better...)
1032 moves1.forEach(m1 => {
1033 this.play(m1);
1034 if (this.subTurn == 1) setEval(m1);
1035 else {
1036 // Need to play every pushes and count:
1037 const moves2 = this.getAllValidMoves();
1038 moves2.forEach(m2 => {
1039 this.play(m2);
3a2a7b5f 1040 setEval(m1, m2);
afbf3ca7
BA
1041 this.undo(m2);
1042 });
1043 }
1044 this.undo(m1);
1045 });
1046
1047 moves1.sort((a, b) => {
1048 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1049 });
1050 let candidates = [0];
1051 for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++)
1052 candidates.push(j);
3a2a7b5f
BA
1053 const choice = moves1[candidates[randInt(candidates.length)]];
1054 return (!choice.second ? choice : [choice, choice.second]);
afbf3ca7
BA
1055 }
1056
6b7b2cf7
BA
1057 getNotation(move) {
1058 // Special case "king takes jailer" is a pass move
1059 if (move.appear.length == 0 && move.vanish.length == 0) return "pass";
b0a0468a
BA
1060 if (this.subTurn == 2) {
1061 // Do not consider appear[1] (sentry) for sentry pushes
1062 const simpleMove = {
1063 appear: [move.appear[0]],
1064 vanish: move.vanish,
1065 start: move.start,
1066 end: move.end
1067 };
1068 return super.getNotation(simpleMove);
1069 }
6b7b2cf7
BA
1070 return super.getNotation(move);
1071 }
2a8a94c9 1072};