Implement Wildebeest castling rule (well... almost correct)
[vchess.git] / client / src / variants / Wildebeest.js
1 import { ChessRules, Move, PiPo } from "@/base_rules";
2 import { ArrayFun } from "@/utils/array";
3 import { sample, randInt } from "@/utils/alea";
4
5 export class WildebeestRules extends ChessRules {
6
7 static get size() {
8 return { x: 10, y: 11 };
9 }
10
11 static get CAMEL() {
12 return "c";
13 }
14 static get WILDEBEEST() {
15 return "w";
16 }
17
18 static get PIECES() {
19 return ChessRules.PIECES.concat([V.CAMEL, V.WILDEBEEST]);
20 }
21
22 static get steps() {
23 return Object.assign(
24 {},
25 ChessRules.steps,
26 // Add camel moves:
27 {
28 c: [
29 [-3, -1],
30 [-3, 1],
31 [-1, -3],
32 [-1, 3],
33 [1, -3],
34 [1, 3],
35 [3, -1],
36 [3, 1]
37 ]
38 }
39 );
40 }
41
42 static IsGoodEnpassant(enpassant) {
43 if (enpassant != "-") return !!enpassant.match(/^([a-j][0-9]{1,2},?)+$/);
44 return true;
45 }
46
47 getPpath(b) {
48 return ([V.CAMEL, V.WILDEBEEST].includes(b[1]) ? "Wildebeest/" : "") + b;
49 }
50
51 // There may be 2 enPassant squares (if pawn jump 3 squares)
52 getEnpassantFen() {
53 const L = this.epSquares.length;
54 if (!this.epSquares[L - 1]) return "-"; //no en-passant
55 let res = "";
56 this.epSquares[L - 1].forEach(sq => {
57 res += V.CoordsToSquare(sq) + ",";
58 });
59 return res.slice(0, -1); //remove last comma
60 }
61
62 // En-passant after 2-sq or 3-sq jumps
63 getEpSquare(moveOrSquare) {
64 if (!moveOrSquare) return undefined;
65 if (typeof moveOrSquare === "string") {
66 const square = moveOrSquare;
67 if (square == "-") return undefined;
68 let res = [];
69 square.split(",").forEach(sq => {
70 res.push(V.SquareToCoords(sq));
71 });
72 return res;
73 }
74 // Argument is a move:
75 const move = moveOrSquare;
76 const [sx, sy, ex] = [move.start.x, move.start.y, move.end.x];
77 if (this.getPiece(sx, sy) == V.PAWN && Math.abs(sx - ex) >= 2) {
78 const step = (ex - sx) / Math.abs(ex - sx);
79 let res = [
80 {
81 x: sx + step,
82 y: sy
83 }
84 ];
85 if (sx + 2 * step != ex) {
86 //3-squares move
87 res.push({
88 x: sx + 2 * step,
89 y: sy
90 });
91 }
92 return res;
93 }
94 return undefined; //default
95 }
96
97 getPotentialMovesFrom([x, y]) {
98 switch (this.getPiece(x, y)) {
99 case V.CAMEL:
100 return this.getPotentialCamelMoves([x, y]);
101 case V.WILDEBEEST:
102 return this.getPotentialWildebeestMoves([x, y]);
103 default:
104 return super.getPotentialMovesFrom([x, y]);
105 }
106 }
107
108 // Pawns jump 2 or 3 squares, and promote to queen or wildebeest
109 getPotentialPawnMoves([x, y]) {
110 const color = this.turn;
111 let moves = [];
112 const [sizeX, sizeY] = [V.size.x, V.size.y];
113 const shiftX = color == "w" ? -1 : 1;
114 const startRanks = color == "w" ? [sizeX - 2, sizeX - 3] : [1, 2];
115 const lastRank = color == "w" ? 0 : sizeX - 1;
116 const finalPieces = x + shiftX == lastRank
117 ? [V.WILDEBEEST, V.QUEEN]
118 : [V.PAWN];
119
120 if (this.board[x + shiftX][y] == V.EMPTY) {
121 // One square forward
122 for (let piece of finalPieces)
123 moves.push(
124 this.getBasicMove([x, y], [x + shiftX, y], { c: color, p: piece })
125 );
126 if (startRanks.includes(x)) {
127 if (this.board[x + 2 * shiftX][y] == V.EMPTY) {
128 // Two squares jump
129 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
130 if (x == startRanks[0] && this.board[x + 3 * shiftX][y] == V.EMPTY) {
131 // Three squares jump
132 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
133 }
134 }
135 }
136 }
137 // Captures
138 for (let shiftY of [-1, 1]) {
139 if (
140 y + shiftY >= 0 &&
141 y + shiftY < sizeY &&
142 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
143 this.canTake([x, y], [x + shiftX, y + shiftY])
144 ) {
145 for (let piece of finalPieces) {
146 moves.push(
147 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
148 c: color,
149 p: piece
150 })
151 );
152 }
153 }
154 }
155
156 // En passant
157 const Lep = this.epSquares.length;
158 const epSquare = this.epSquares[Lep - 1];
159 if (!!epSquare) {
160 for (let epsq of epSquare) {
161 // TODO: some redundant checks
162 if (epsq.x == x + shiftX && Math.abs(epsq.y - y) == 1) {
163 let enpassantMove = this.getBasicMove([x, y], [epsq.x, epsq.y]);
164 // WARNING: the captured pawn may be diagonally behind us,
165 // if it's a 3-squares jump and we take on 1st passing square
166 const px = this.board[x][epsq.y] != V.EMPTY ? x : x - shiftX;
167 enpassantMove.vanish.push({
168 x: px,
169 y: epsq.y,
170 p: "p",
171 c: this.getColor(px, epsq.y)
172 });
173 moves.push(enpassantMove);
174 }
175 }
176 }
177
178 return moves;
179 }
180
181 getPotentialCamelMoves(sq) {
182 return this.getSlideNJumpMoves(sq, V.steps[V.CAMEL], "oneStep");
183 }
184
185 getPotentialWildebeestMoves(sq) {
186 return this.getSlideNJumpMoves(
187 sq,
188 V.steps[V.KNIGHT].concat(V.steps[V.CAMEL]),
189 "oneStep"
190 );
191 }
192
193 getPPpath(m) {
194 if (
195 m.appear.length == 2 && m.vanish.length == 2 &&
196 Math.abs(m.end.y - m.start.y) == 1 &&
197 this.board[m.end.x][m.end.y] == V.EMPTY
198 ) {
199 // Castle, king moved by one square only, not directly onto rook
200 return "Wildebeest/castle";
201 }
202 return super.getPPpath(m);
203 }
204
205 // Special Wildebeest castling rules:
206 getCastleMoves([x, y]) {
207 const c = this.getColor(x, y);
208 const oppCol = V.GetOppCol(c);
209 let moves = [];
210 let i = 0;
211 const castlingKing = this.board[x][y].charAt(1);
212 castlingCheck: for (
213 let castleSide = 0;
214 castleSide < 2;
215 castleSide++ //"large", then "small"
216 ) {
217 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
218 // Rook and king are on initial position
219 const rookPos = this.castleFlags[c][castleSide];
220 const range = (castleSide == 0 ? [rookPos, y] : [y, rookPos]);
221
222 // King and rook must be connected:
223 for (let i = range[0] + 1; i <= range[1] - 1; i++) {
224 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
225 }
226 const step = 2 * castleSide - 1;
227 // No attacks on the path of the king ?
228 for (let i = range[0]; i <= range[1]; i++) {
229 if (i != rookPos && this.isAttacked([x, i], oppCol))
230 continue castlingCheck;
231 if (i != y) {
232 // Found a possible castle move:
233 moves.push(
234 new Move({
235 appear: [
236 new PiPo({
237 x: x,
238 y: i,
239 p: V.KING,
240 c: c
241 }),
242 new PiPo({
243 x: x,
244 y: i - step,
245 p: V.ROOK,
246 c: c
247 })
248 ],
249 vanish: [
250 new PiPo({ x: x, y: y, p: V.KING, c: c }),
251 new PiPo({ x: x, y: rookPos, p: V.ROOK, c: c })
252 ]
253 })
254 );
255 }
256 }
257 }
258
259 return moves;
260 }
261
262 isAttacked(sq, color) {
263 return (
264 super.isAttacked(sq, color) ||
265 this.isAttackedByCamel(sq, color) ||
266 this.isAttackedByWildebeest(sq, color)
267 );
268 }
269
270 isAttackedByCamel(sq, color) {
271 return this.isAttackedBySlideNJump(
272 sq,
273 color,
274 V.CAMEL,
275 V.steps[V.CAMEL],
276 "oneStep"
277 );
278 }
279
280 isAttackedByWildebeest(sq, color) {
281 return this.isAttackedBySlideNJump(
282 sq,
283 color,
284 V.WILDEBEEST,
285 V.steps[V.KNIGHT].concat(V.steps[V.CAMEL]),
286 "oneStep"
287 );
288 }
289
290 getCurrentScore() {
291 if (this.atLeastOneMove()) return "*";
292 // No valid move: game is lost (stalemate is a win)
293 return this.turn == "w" ? "0-1" : "1-0";
294 }
295
296 static get VALUES() {
297 return Object.assign(
298 { c: 3, w: 7 }, //experimental
299 ChessRules.VALUES
300 );
301 }
302
303 static get SEARCH_DEPTH() {
304 return 2;
305 }
306
307 static GenRandInitFen(randomness) {
308 if (!randomness) randomness = 2;
309 if (randomness == 0) {
310 return (
311 "rnccwkqbbnr/ppppppppppp/92/92/92/92/92/92/PPPPPPPPPPP/RNBBQKWCCNR " +
312 "w 0 akak -"
313 );
314 }
315
316 let pieces = { w: new Array(11), b: new Array(11) };
317 let flags = "";
318 for (let c of ["w", "b"]) {
319 if (c == 'b' && randomness == 1) {
320 pieces['b'] = pieces['w'];
321 flags += flags;
322 break;
323 }
324
325 let positions = ArrayFun.range(11);
326
327 // Get random squares for bishops + camels (different colors)
328 let randIndexes = sample(ArrayFun.range(6), 2).map(i => {
329 return 2 * i;
330 });
331 let bishop1Pos = positions[randIndexes[0]];
332 let camel1Pos = positions[randIndexes[1]];
333 // The second bishop (camel) must be on a square of different color
334 let randIndexes_tmp = sample(ArrayFun.range(5), 2).map(i => {
335 return 2 * i + 1;
336 });
337 let bishop2Pos = positions[randIndexes_tmp[0]];
338 let camel2Pos = positions[randIndexes_tmp[1]];
339 for (let idx of randIndexes.concat(randIndexes_tmp).sort((a, b) => {
340 return b - a;
341 })) {
342 // Largest indices first
343 positions.splice(idx, 1);
344 }
345
346 let randIndex = randInt(7);
347 let knight1Pos = positions[randIndex];
348 positions.splice(randIndex, 1);
349 randIndex = randInt(6);
350 let knight2Pos = positions[randIndex];
351 positions.splice(randIndex, 1);
352
353 randIndex = randInt(5);
354 let queenPos = positions[randIndex];
355 positions.splice(randIndex, 1);
356
357 // Random square for wildebeest
358 randIndex = randInt(4);
359 let wildebeestPos = positions[randIndex];
360 positions.splice(randIndex, 1);
361
362 let rook1Pos = positions[0];
363 let kingPos = positions[1];
364 let rook2Pos = positions[2];
365
366 pieces[c][rook1Pos] = "r";
367 pieces[c][knight1Pos] = "n";
368 pieces[c][bishop1Pos] = "b";
369 pieces[c][queenPos] = "q";
370 pieces[c][camel1Pos] = "c";
371 pieces[c][camel2Pos] = "c";
372 pieces[c][wildebeestPos] = "w";
373 pieces[c][kingPos] = "k";
374 pieces[c][bishop2Pos] = "b";
375 pieces[c][knight2Pos] = "n";
376 pieces[c][rook2Pos] = "r";
377 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
378 }
379 return (
380 pieces["b"].join("") +
381 "/ppppppppppp/92/92/92/92/92/92/PPPPPPPPPPP/" +
382 pieces["w"].join("").toUpperCase() +
383 " w 0 " + flags + " -"
384 );
385 }
386
387 };