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