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