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