Prepare some more variants (unfinished)
[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-1; i++) //-1: no king captured
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 var enpassantMove = this.getBasicMove([x,y], [x+shift,epsq.y]);
222 enpassantMove.vanish.push({
223 x: x,
224 y: epsq.y,
225 p: 'p',
226 c: this.getColor(x,epsq.y)
227 });
228 moves.push(enpassantMove);
229 }
230 }
231 }
232
233 return moves;
234 }
235
236 // TODO: different castle?
237
238 getPotentialMarshallMoves(sq)
239 {
240 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]).concat(
241 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"));
242 }
243
244 getPotentialCardinalMoves(sq)
245 {
246 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]).concat(
247 this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"));
248 }
249
250 isAttacked(sq, colors)
251 {
252 return super.isAttacked(sq, colors)
253 || this.isAttackedByMarshall(sq, colors)
254 || this.isAttackedByCardinal(sq, colors);
255 }
256
257 isAttackedByMarshall(sq, colors)
258 {
259 return this.isAttackedBySlideNJump(sq, colors, V.MARSHALL, V.steps[V.ROOK])
260 || this.isAttackedBySlideNJump(
261 sq, colors, V.MARSHALL, V.steps[V.KNIGHT], "oneStep");
262 }
263
264 isAttackedByCardinal(sq, colors)
265 {
266 return this.isAttackedBySlideNJump(sq, colors, V.CARDINAL, V.steps[V.BISHOP])
267 || this.isAttackedBySlideNJump(
268 sq, colors, V.CARDINAL, V.steps[V.KNIGHT], "oneStep");
269 }
270
271 updateVariables(move)
272 {
273 super.updateVariables(move);
274 if (move.vanish.length==2 && move.appear.length==1 && move.vanish[1].p != V.PAWN)
275 {
276 // Capture: update this.captured
277 this.captured[move.vanish[1].c][move.vanish[1].p]++;
278 }
279 }
280
281 unupdateVariables(move)
282 {
283 super.unupdateVariables(move);
284 if (move.vanish.length==2 && move.appear.length==1 && move.vanish[1].p != V.PAWN)
285 this.captured[move.vanish[1].c][move.vanish[1].p]--;
286 }
287
288 static get VALUES()
289 {
290 return Object.assign(
291 ChessRules.VALUES,
292 {'c': 5, 'm': 7} //experimental
293 );
294 }
295
296 static get SEARCH_DEPTH() { return 2; }
297
298 // TODO: this function could be generalized and shared better (how ?!...)
299 static GenRandInitFen()
300 {
301 let pieces = { "w": new Array(10), "b": new Array(10) };
302 // Shuffle pieces on first and last rank
303 for (let c of ["w","b"])
304 {
305 let positions = _.range(10);
306
307 // Get random squares for bishops
308 let randIndex = 2 * _.random(4);
309 let bishop1Pos = positions[randIndex];
310 // The second bishop must be on a square of different color
311 let randIndex_tmp = 2 * _.random(4) + 1;
312 let bishop2Pos = positions[randIndex_tmp];
313 // Remove chosen squares
314 positions.splice(Math.max(randIndex,randIndex_tmp), 1);
315 positions.splice(Math.min(randIndex,randIndex_tmp), 1);
316
317 // Get random squares for knights
318 randIndex = _.random(7);
319 let knight1Pos = positions[randIndex];
320 positions.splice(randIndex, 1);
321 randIndex = _.random(6);
322 let knight2Pos = positions[randIndex];
323 positions.splice(randIndex, 1);
324
325 // Get random square for queen
326 randIndex = _.random(5);
327 let queenPos = positions[randIndex];
328 positions.splice(randIndex, 1);
329
330 // ...random square for marshall
331 randIndex = _.random(4);
332 let marshallPos = positions[randIndex];
333 positions.splice(randIndex, 1);
334
335 // ...random square for cardinal
336 randIndex = _.random(3);
337 let cardinalPos = positions[randIndex];
338 positions.splice(randIndex, 1);
339
340 // Rooks and king positions are now fixed, because of the ordering rook-king-rook
341 let rook1Pos = positions[0];
342 let kingPos = positions[1];
343 let rook2Pos = positions[2];
344
345 // Finally put the shuffled pieces in the board array
346 pieces[c][rook1Pos] = 'r';
347 pieces[c][knight1Pos] = 'n';
348 pieces[c][bishop1Pos] = 'b';
349 pieces[c][queenPos] = 'q';
350 pieces[c][marshallPos] = 'm';
351 pieces[c][cardinalPos] = 'c';
352 pieces[c][kingPos] = 'k';
353 pieces[c][bishop2Pos] = 'b';
354 pieces[c][knight2Pos] = 'n';
355 pieces[c][rook2Pos] = 'r';
356 }
357 return pieces["b"].join("") +
358 "/pppppppppp/10/10/10/10/10/10/PPPPPPPPPP/" +
359 pieces["w"].join("").toUpperCase() +
360 " w 1111 - 0000000000";
361 }
362 }
363
364 const VariantRules = GrandRules;