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