Fix Chakart (promotions + queen visibility)
[vchess.git] / client / src / variants / Grand.js
CommitLineData
0c3fe8a6
BA
1import { ChessRules } from "@/base_rules";
2import { ArrayFun } from "@/utils/array";
3import { randInt } from "@/utils/alea";
4
92342261
BA
5// NOTE: initial setup differs from the original; see
6// https://www.chessvariants.com/large.dir/freeling.html
32f6285e 7export class GrandRules extends ChessRules {
6808d7a1
BA
8 static IsGoodFen(fen) {
9 if (!ChessRules.IsGoodFen(fen)) return false;
dac39588
BA
10 const fenParsed = V.ParseFen(fen);
11 // 5) Check captures
472c0c4f 12 if (!fenParsed.captured || !fenParsed.captured.match(/^[0-9]{12,12}$/))
dac39588
BA
13 return false;
14 return true;
15 }
16
6808d7a1 17 static IsGoodEnpassant(enpassant) {
472c0c4f 18 if (enpassant != "-") return !!enpassant.match(/^([a-j][0-9]{1,2},?)+$/);
dac39588
BA
19 return true;
20 }
21
6808d7a1 22 static ParseFen(fen) {
dac39588 23 const fenParts = fen.split(" ");
6f2f9437
BA
24 return Object.assign(
25 ChessRules.ParseFen(fen),
26 { captured: fenParts[5] }
27 );
dac39588
BA
28 }
29
241bf8f2
BA
30 getPpath(b) {
31 return ([V.MARSHALL, V.CARDINAL].includes(b[1]) ? "Grand/" : "") + b;
32 }
33
6808d7a1 34 getFen() {
dac39588
BA
35 return super.getFen() + " " + this.getCapturedFen();
36 }
37
f9c36b2d 38 getFenForRepeat() {
90e814b6 39 return super.getFenForRepeat() + "_" + this.getCapturedFen();
f9c36b2d
BA
40 }
41
6808d7a1 42 getCapturedFen() {
6e47d367 43 let counts = [...Array(12).fill(0)];
dac39588 44 let i = 0;
6808d7a1 45 for (let j = 0; j < V.PIECES.length; j++) {
6e47d367
BA
46 if ([V.KING, V.PAWN].includes(V.PIECES[j]))
47 // No king captured, and pawns don't promote in pawns
dac39588 48 continue;
6e47d367
BA
49 counts[i] = this.captured["w"][V.PIECES[j]];
50 counts[6 + i] = this.captured["b"][V.PIECES[j]];
dac39588
BA
51 i++;
52 }
53 return counts.join("");
54 }
55
6808d7a1 56 setOtherVariables(fen) {
dac39588
BA
57 super.setOtherVariables(fen);
58 const fenParsed = V.ParseFen(fen);
59 // Initialize captured pieces' counts from FEN
6808d7a1
BA
60 this.captured = {
61 w: {
6e47d367
BA
62 [V.ROOK]: parseInt(fenParsed.captured[0]),
63 [V.KNIGHT]: parseInt(fenParsed.captured[1]),
64 [V.BISHOP]: parseInt(fenParsed.captured[2]),
65 [V.QUEEN]: parseInt(fenParsed.captured[3]),
66 [V.MARSHALL]: parseInt(fenParsed.captured[4]),
67 [V.CARDINAL]: parseInt(fenParsed.captured[5])
dac39588 68 },
6808d7a1 69 b: {
6e47d367
BA
70 [V.ROOK]: parseInt(fenParsed.captured[6]),
71 [V.KNIGHT]: parseInt(fenParsed.captured[7]),
72 [V.BISHOP]: parseInt(fenParsed.captured[8]),
73 [V.QUEEN]: parseInt(fenParsed.captured[9]),
74 [V.MARSHALL]: parseInt(fenParsed.captured[10]),
75 [V.CARDINAL]: parseInt(fenParsed.captured[11])
dac39588
BA
76 }
77 };
78 }
79
6808d7a1
BA
80 static get size() {
81 return { x: 10, y: 10 };
82 }
dac39588 83
a6836242 84 // Rook + knight:
6808d7a1
BA
85 static get MARSHALL() {
86 return "m";
a6836242
BA
87 }
88
89 // Bishop + knight
6808d7a1
BA
90 static get CARDINAL() {
91 return "c";
a6836242 92 }
dac39588 93
6808d7a1
BA
94 static get PIECES() {
95 return ChessRules.PIECES.concat([V.MARSHALL, V.CARDINAL]);
dac39588
BA
96 }
97
98 // There may be 2 enPassant squares (if pawn jump 3 squares)
6808d7a1 99 getEnpassantFen() {
dac39588 100 const L = this.epSquares.length;
6808d7a1 101 if (!this.epSquares[L - 1]) return "-"; //no en-passant
dac39588 102 let res = "";
6808d7a1 103 this.epSquares[L - 1].forEach(sq => {
dac39588
BA
104 res += V.CoordsToSquare(sq) + ",";
105 });
6808d7a1 106 return res.slice(0, -1); //remove last comma
dac39588
BA
107 }
108
109 // En-passant after 2-sq or 3-sq jumps
6808d7a1
BA
110 getEpSquare(moveOrSquare) {
111 if (!moveOrSquare) return undefined;
112 if (typeof moveOrSquare === "string") {
dac39588 113 const square = moveOrSquare;
6808d7a1 114 if (square == "-") return undefined;
dac39588
BA
115 let res = [];
116 square.split(",").forEach(sq => {
117 res.push(V.SquareToCoords(sq));
118 });
119 return res;
120 }
121 // Argument is a move:
122 const move = moveOrSquare;
6808d7a1
BA
123 const [sx, sy, ex] = [move.start.x, move.start.y, move.end.x];
124 if (this.getPiece(sx, sy) == V.PAWN && Math.abs(sx - ex) >= 2) {
125 const step = (ex - sx) / Math.abs(ex - sx);
126 let res = [
127 {
128 x: sx + step,
129 y: sy
130 }
131 ];
132 if (sx + 2 * step != ex) {
472c0c4f 133 // 3-squares jump
dac39588 134 res.push({
6808d7a1 135 x: sx + 2 * step,
dac39588
BA
136 y: sy
137 });
138 }
139 return res;
140 }
141 return undefined; //default
142 }
143
6808d7a1
BA
144 getPotentialMovesFrom([x, y]) {
145 switch (this.getPiece(x, y)) {
dac39588 146 case V.MARSHALL:
6808d7a1 147 return this.getPotentialMarshallMoves([x, y]);
dac39588 148 case V.CARDINAL:
6808d7a1 149 return this.getPotentialCardinalMoves([x, y]);
dac39588 150 default:
6808d7a1 151 return super.getPotentialMovesFrom([x, y]);
dac39588
BA
152 }
153 }
154
155 // Special pawn rules: promotions to captured friendly pieces,
156 // optional on ranks 8-9 and mandatory on rank 10.
6808d7a1 157 getPotentialPawnMoves([x, y]) {
dac39588
BA
158 const color = this.turn;
159 let moves = [];
6808d7a1
BA
160 const [sizeX, sizeY] = [V.size.x, V.size.y];
161 const shiftX = color == "w" ? -1 : 1;
162 const startRanks = color == "w" ? [sizeX - 2, sizeX - 3] : [1, 2];
163 const lastRanks =
164 color == "w" ? [0, 1, 2] : [sizeX - 1, sizeX - 2, sizeX - 3];
165 const promotionPieces = [
166 V.ROOK,
167 V.KNIGHT,
168 V.BISHOP,
169 V.QUEEN,
170 V.MARSHALL,
171 V.CARDINAL
172 ];
dac39588
BA
173
174 // Always x+shiftX >= 0 && x+shiftX < sizeX, because no pawns on last rank
175 let finalPieces = undefined;
6808d7a1 176 if (lastRanks.includes(x + shiftX)) {
dac39588 177 finalPieces = promotionPieces.filter(p => this.captured[color][p] > 0);
6808d7a1
BA
178 if (x + shiftX != lastRanks[0]) finalPieces.push(V.PAWN);
179 } else finalPieces = [V.PAWN];
180 if (this.board[x + shiftX][y] == V.EMPTY) {
dac39588
BA
181 // One square forward
182 for (let piece of finalPieces)
6808d7a1
BA
183 moves.push(
184 this.getBasicMove([x, y], [x + shiftX, y], { c: color, p: piece })
185 );
186 if (startRanks.includes(x)) {
187 if (this.board[x + 2 * shiftX][y] == V.EMPTY) {
dac39588 188 // Two squares jump
6808d7a1
BA
189 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
190 if (x == startRanks[0] && this.board[x + 3 * shiftX][y] == V.EMPTY) {
dac39588 191 // Three squares jump
6808d7a1 192 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
dac39588
BA
193 }
194 }
195 }
196 }
197 // Captures
6808d7a1
BA
198 for (let shiftY of [-1, 1]) {
199 if (
200 y + shiftY >= 0 &&
201 y + shiftY < sizeY &&
202 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
203 this.canTake([x, y], [x + shiftX, y + shiftY])
204 ) {
205 for (let piece of finalPieces) {
206 moves.push(
207 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
208 c: color,
209 p: piece
210 })
211 );
dac39588
BA
212 }
213 }
214 }
215
216 // En passant
217 const Lep = this.epSquares.length;
6808d7a1 218 const epSquare = this.epSquares[Lep - 1];
472c0c4f 219 if (!!epSquare) {
6808d7a1 220 for (let epsq of epSquare) {
dac39588 221 // TODO: some redundant checks
6808d7a1 222 if (epsq.x == x + shiftX && Math.abs(epsq.y - y) == 1) {
32f6285e 223 let enpassantMove = this.getBasicMove([x, y], [epsq.x, epsq.y]);
dac39588
BA
224 // WARNING: the captured pawn may be diagonally behind us,
225 // if it's a 3-squares jump and we take on 1st passing square
6808d7a1 226 const px = this.board[x][epsq.y] != V.EMPTY ? x : x - shiftX;
dac39588
BA
227 enpassantMove.vanish.push({
228 x: px,
229 y: epsq.y,
6808d7a1
BA
230 p: "p",
231 c: this.getColor(px, epsq.y)
dac39588
BA
232 });
233 moves.push(enpassantMove);
234 }
235 }
236 }
237
238 return moves;
239 }
240
241 // TODO: different castle?
242
6808d7a1 243 getPotentialMarshallMoves(sq) {
dac39588 244 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]).concat(
6808d7a1
BA
245 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep")
246 );
dac39588
BA
247 }
248
6808d7a1 249 getPotentialCardinalMoves(sq) {
dac39588 250 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]).concat(
6808d7a1
BA
251 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep")
252 );
dac39588
BA
253 }
254
68e19a44 255 isAttacked(sq, color) {
6808d7a1 256 return (
68e19a44
BA
257 super.isAttacked(sq, color) ||
258 this.isAttackedByMarshall(sq, color) ||
259 this.isAttackedByCardinal(sq, color)
6808d7a1 260 );
dac39588
BA
261 }
262
68e19a44 263 isAttackedByMarshall(sq, color) {
6808d7a1 264 return (
68e19a44 265 this.isAttackedBySlideNJump(sq, color, V.MARSHALL, V.steps[V.ROOK]) ||
6808d7a1
BA
266 this.isAttackedBySlideNJump(
267 sq,
68e19a44 268 color,
6808d7a1
BA
269 V.MARSHALL,
270 V.steps[V.KNIGHT],
271 "oneStep"
272 )
273 );
dac39588
BA
274 }
275
68e19a44 276 isAttackedByCardinal(sq, color) {
6808d7a1 277 return (
68e19a44 278 this.isAttackedBySlideNJump(sq, color, V.CARDINAL, V.steps[V.BISHOP]) ||
6808d7a1
BA
279 this.isAttackedBySlideNJump(
280 sq,
68e19a44 281 color,
6808d7a1
BA
282 V.CARDINAL,
283 V.steps[V.KNIGHT],
284 "oneStep"
285 )
286 );
dac39588
BA
287 }
288
3a2a7b5f
BA
289 postPlay(move) {
290 super.postPlay(move);
6e47d367 291 if (move.vanish.length == 2 && move.appear.length == 1)
dac39588
BA
292 // Capture: update this.captured
293 this.captured[move.vanish[1].c][move.vanish[1].p]++;
dac39588
BA
294 }
295
3a2a7b5f
BA
296 postUndo(move) {
297 super.postUndo(move);
dac39588
BA
298 if (move.vanish.length == 2 && move.appear.length == 1)
299 this.captured[move.vanish[1].c][move.vanish[1].p]--;
dac39588
BA
300 }
301
6808d7a1 302 static get VALUES() {
dac39588 303 return Object.assign(
a97bdbda
BA
304 { c: 5, m: 7 }, //experimental
305 ChessRules.VALUES
dac39588
BA
306 );
307 }
308
6808d7a1
BA
309 static get SEARCH_DEPTH() {
310 return 2;
311 }
dac39588 312
7ba4a5bc 313 static GenRandInitFen(randomness) {
7ba4a5bc 314 if (randomness == 0) {
2c5d7b20
BA
315 return (
316 "r8r/1nbqkmcbn1/pppppppppp/91/91/91/91/PPPPPPPPPP/1NBQKMCBN1/R8R " +
317 // No castling in the official initial setup
318 "w 0 zzzz - 00000000000000"
319 );
7ba4a5bc
BA
320 }
321
6808d7a1 322 let pieces = { w: new Array(10), b: new Array(10) };
6f2f9437 323 let flags = "";
dac39588 324 // Shuffle pieces on first and last rank
6808d7a1 325 for (let c of ["w", "b"]) {
7ba4a5bc
BA
326 if (c == 'b' && randomness == 1) {
327 pieces['b'] = pieces['w'];
6f2f9437 328 flags += flags;
7ba4a5bc
BA
329 break;
330 }
331
dac39588
BA
332 let positions = ArrayFun.range(10);
333
334 // Get random squares for bishops
335 let randIndex = 2 * randInt(5);
336 let bishop1Pos = positions[randIndex];
337 // The second bishop must be on a square of different color
338 let randIndex_tmp = 2 * randInt(5) + 1;
339 let bishop2Pos = positions[randIndex_tmp];
340 // Remove chosen squares
6808d7a1
BA
341 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
342 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
dac39588
BA
343
344 // Get random squares for knights
345 randIndex = randInt(8);
346 let knight1Pos = positions[randIndex];
347 positions.splice(randIndex, 1);
348 randIndex = randInt(7);
349 let knight2Pos = positions[randIndex];
350 positions.splice(randIndex, 1);
351
352 // Get random square for queen
353 randIndex = randInt(6);
354 let queenPos = positions[randIndex];
355 positions.splice(randIndex, 1);
356
357 // ...random square for marshall
358 randIndex = randInt(5);
359 let marshallPos = positions[randIndex];
360 positions.splice(randIndex, 1);
361
362 // ...random square for cardinal
363 randIndex = randInt(4);
364 let cardinalPos = positions[randIndex];
365 positions.splice(randIndex, 1);
366
2c5d7b20
BA
367 // Rooks and king positions are now fixed,
368 // because of the ordering rook-king-rook
dac39588
BA
369 let rook1Pos = positions[0];
370 let kingPos = positions[1];
371 let rook2Pos = positions[2];
372
373 // Finally put the shuffled pieces in the board array
6808d7a1
BA
374 pieces[c][rook1Pos] = "r";
375 pieces[c][knight1Pos] = "n";
376 pieces[c][bishop1Pos] = "b";
377 pieces[c][queenPos] = "q";
378 pieces[c][marshallPos] = "m";
379 pieces[c][cardinalPos] = "c";
380 pieces[c][kingPos] = "k";
381 pieces[c][bishop2Pos] = "b";
382 pieces[c][knight2Pos] = "n";
383 pieces[c][rook2Pos] = "r";
6f2f9437 384 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
dac39588 385 }
6808d7a1
BA
386 return (
387 pieces["b"].join("") +
6f2f9437 388 "/pppppppppp/91/91/91/91/91/91/PPPPPPPPPP/" +
dac39588 389 pieces["w"].join("").toUpperCase() +
6f2f9437 390 " w 0 " + flags + " - 00000000000000"
6808d7a1 391 );
dac39588 392 }
6808d7a1 393};