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