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