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