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