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