Some fixes + draft newmove pingback logic (unfinished, not working)
[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 getFenForRepeat() {
43 return (
44 this.getBaseFen() + "_" +
45 this.getTurnFen() + "_" +
46 this.getFlagsFen() + "_" +
47 this.getEnpassantFen() + "_" +
48 this.getCapturedFen()
49 );
50 }
51
52 getCapturedFen() {
53 let counts = [...Array(14).fill(0)];
54 let i = 0;
55 for (let j = 0; j < V.PIECES.length; j++) {
56 if (V.PIECES[j] == V.KING)
57 //no king captured
58 continue;
59 counts[i] = this.captured["w"][V.PIECES[i]];
60 counts[7 + i] = this.captured["b"][V.PIECES[i]];
61 i++;
62 }
63 return counts.join("");
64 }
65
66 setOtherVariables(fen) {
67 super.setOtherVariables(fen);
68 const fenParsed = V.ParseFen(fen);
69 // Initialize captured pieces' counts from FEN
70 this.captured = {
71 w: {
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]),
78 [V.CARDINAL]: parseInt(fenParsed.captured[6])
79 },
80 b: {
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]),
87 [V.CARDINAL]: parseInt(fenParsed.captured[13])
88 }
89 };
90 }
91
92 static get size() {
93 return { x: 10, y: 10 };
94 }
95
96 static get MARSHALL() {
97 return "m";
98 } //rook+knight
99 static get CARDINAL() {
100 return "c";
101 } //bishop+knight
102
103 static get PIECES() {
104 return ChessRules.PIECES.concat([V.MARSHALL, V.CARDINAL]);
105 }
106
107 // There may be 2 enPassant squares (if pawn jump 3 squares)
108 getEnpassantFen() {
109 const L = this.epSquares.length;
110 if (!this.epSquares[L - 1]) return "-"; //no en-passant
111 let res = "";
112 this.epSquares[L - 1].forEach(sq => {
113 res += V.CoordsToSquare(sq) + ",";
114 });
115 return res.slice(0, -1); //remove last comma
116 }
117
118 // En-passant after 2-sq or 3-sq jumps
119 getEpSquare(moveOrSquare) {
120 if (!moveOrSquare) return undefined;
121 if (typeof moveOrSquare === "string") {
122 const square = moveOrSquare;
123 if (square == "-") return undefined;
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;
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
143 res.push({
144 x: sx + 2 * step,
145 y: sy
146 });
147 }
148 return res;
149 }
150 return undefined; //default
151 }
152
153 getPotentialMovesFrom([x, y]) {
154 switch (this.getPiece(x, y)) {
155 case V.MARSHALL:
156 return this.getPotentialMarshallMoves([x, y]);
157 case V.CARDINAL:
158 return this.getPotentialCardinalMoves([x, y]);
159 default:
160 return super.getPotentialMovesFrom([x, y]);
161 }
162 }
163
164 // Special pawn rules: promotions to captured friendly pieces,
165 // optional on ranks 8-9 and mandatory on rank 10.
166 getPotentialPawnMoves([x, y]) {
167 const color = this.turn;
168 let moves = [];
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 ];
182
183 // Always x+shiftX >= 0 && x+shiftX < sizeX, because no pawns on last rank
184 let finalPieces = undefined;
185 if (lastRanks.includes(x + shiftX)) {
186 finalPieces = promotionPieces.filter(p => this.captured[color][p] > 0);
187 if (x + shiftX != lastRanks[0]) finalPieces.push(V.PAWN);
188 } else finalPieces = [V.PAWN];
189 if (this.board[x + shiftX][y] == V.EMPTY) {
190 // One square forward
191 for (let piece of finalPieces)
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) {
197 // Two squares jump
198 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
199 if (x == startRanks[0] && this.board[x + 3 * shiftX][y] == V.EMPTY) {
200 // Three squares jump
201 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
202 }
203 }
204 }
205 }
206 // Captures
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 );
221 }
222 }
223 }
224
225 // En passant
226 const Lep = this.epSquares.length;
227 const epSquare = this.epSquares[Lep - 1];
228 if (epSquare) {
229 for (let epsq of epSquare) {
230 // TODO: some redundant checks
231 if (epsq.x == x + shiftX && Math.abs(epsq.y - y) == 1) {
232 var enpassantMove = this.getBasicMove([x, y], [epsq.x, epsq.y]);
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
235 const px = this.board[x][epsq.y] != V.EMPTY ? x : x - shiftX;
236 enpassantMove.vanish.push({
237 x: px,
238 y: epsq.y,
239 p: "p",
240 c: this.getColor(px, epsq.y)
241 });
242 moves.push(enpassantMove);
243 }
244 }
245 }
246
247 return moves;
248 }
249
250 // TODO: different castle?
251
252 getPotentialMarshallMoves(sq) {
253 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]).concat(
254 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep")
255 );
256 }
257
258 getPotentialCardinalMoves(sq) {
259 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]).concat(
260 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep")
261 );
262 }
263
264 isAttacked(sq, colors) {
265 return (
266 super.isAttacked(sq, colors) ||
267 this.isAttackedByMarshall(sq, colors) ||
268 this.isAttackedByCardinal(sq, colors)
269 );
270 }
271
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 );
283 }
284
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 );
296 }
297
298 updateVariables(move) {
299 super.updateVariables(move);
300 if (move.vanish.length == 2 && move.appear.length == 1) {
301 // Capture: update this.captured
302 this.captured[move.vanish[1].c][move.vanish[1].p]++;
303 }
304 if (move.vanish[0].p != move.appear[0].p) {
305 // Promotion: update this.captured
306 this.captured[move.vanish[0].c][move.appear[0].p]--;
307 }
308 }
309
310 unupdateVariables(move) {
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
318 static get VALUES() {
319 return Object.assign(
320 { c: 5, m: 7 }, //experimental
321 ChessRules.VALUES
322 );
323 }
324
325 static get SEARCH_DEPTH() {
326 return 2;
327 }
328
329 static GenRandInitFen(randomness) {
330 if (randomness == 0) {
331 return "rnbqkmcbnr/pppppppppp/10/10/10/10/10/10/PPPPPPPPPP/RNBQKMCBNR " +
332 "w 0 1111 - 00000000000000";
333 }
334
335 let pieces = { w: new Array(10), b: new Array(10) };
336 // Shuffle pieces on first and last rank
337 for (let c of ["w", "b"]) {
338 if (c == 'b' && randomness == 1) {
339 pieces['b'] = pieces['w'];
340 break;
341 }
342
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
352 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
353 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
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
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";
394 }
395 return (
396 pieces["b"].join("") +
397 "/pppppppppp/10/10/10/10/10/10/PPPPPPPPPP/" +
398 pieces["w"].join("").toUpperCase() +
399 " w 0 1111 - 00000000000000"
400 );
401 }
402 };