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