Commit | Line | Data |
---|---|---|
1d184b4c BA |
1 | class PiPo //Piece+Position |
2 | { | |
3 | // o: {piece[p], color[c], posX[x], posY[y]} | |
4 | constructor(o) | |
5 | { | |
6 | this.p = o.p; | |
7 | this.c = o.c; | |
8 | this.x = o.x; | |
9 | this.y = o.y; | |
10 | } | |
11 | } | |
12 | ||
13 | class Move | |
14 | { | |
15 | // o: {appear, vanish, [start,] [end,]} | |
16 | // appear,vanish = arrays of PiPo | |
17 | // start,end = coordinates to apply to trigger move visually (think castle) | |
18 | constructor(o) | |
19 | { | |
20 | this.appear = o.appear; | |
21 | this.vanish = o.vanish; | |
22 | this.start = !!o.start ? o.start : {x:o.vanish[0].x, y:o.vanish[0].y}; | |
23 | this.end = !!o.end ? o.end : {x:o.appear[0].x, y:o.appear[0].y}; | |
24 | } | |
25 | } | |
26 | ||
27 | // NOTE: x coords = top to bottom; y = left to right (from white player perspective) | |
28 | class ChessRules | |
29 | { | |
30 | // Path to pieces | |
31 | static getPpath(b) | |
32 | { | |
33 | return b; //usual pieces in pieces/ folder | |
34 | } | |
35 | // Turn "wb" into "B" (for FEN) | |
36 | static board2fen(b) | |
37 | { | |
38 | return b[0]=='w' ? b[1].toUpperCase() : b[1]; | |
39 | } | |
40 | // Turn "p" into "bp" (for board) | |
41 | static fen2board(f) | |
42 | { | |
43 | return f.charCodeAt()<=90 ? "w"+f.toLowerCase() : "b"+f; | |
44 | } | |
45 | ||
46 | ///////////////// | |
47 | // INITIALIZATION | |
48 | ||
d3334c3a | 49 | // fen == "position flags" |
dfb4afc1 | 50 | constructor(fen, moves) |
1d184b4c | 51 | { |
dfb4afc1 | 52 | this.moves = moves; |
1d184b4c | 53 | // Use fen string to initialize variables, flags and board |
1d184b4c | 54 | this.board = VariantRules.GetBoard(fen); |
f3802fcd | 55 | this.flags = VariantRules.GetFlags(fen); |
ffbae57a | 56 | this.initVariables(fen); |
1d184b4c BA |
57 | } |
58 | ||
59 | initVariables(fen) | |
60 | { | |
61 | this.INIT_COL_KING = {'w':-1, 'b':-1}; | |
62 | this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]}; | |
63 | this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //respective squares of white and black king | |
64 | const fenParts = fen.split(" "); | |
65 | const position = fenParts[0].split("/"); | |
66 | for (let i=0; i<position.length; i++) | |
67 | { | |
68 | let j = 0; | |
69 | while (j < position[i].length) | |
70 | { | |
71 | switch (position[i].charAt(j)) | |
72 | { | |
73 | case 'k': | |
74 | this.kingPos['b'] = [i,j]; | |
75 | this.INIT_COL_KING['b'] = j; | |
76 | break; | |
77 | case 'K': | |
78 | this.kingPos['w'] = [i,j]; | |
79 | this.INIT_COL_KING['w'] = j; | |
80 | break; | |
81 | case 'r': | |
82 | if (this.INIT_COL_ROOK['b'][0] < 0) | |
83 | this.INIT_COL_ROOK['b'][0] = j; | |
84 | else | |
85 | this.INIT_COL_ROOK['b'][1] = j; | |
86 | break; | |
87 | case 'R': | |
88 | if (this.INIT_COL_ROOK['w'][0] < 0) | |
89 | this.INIT_COL_ROOK['w'][0] = j; | |
90 | else | |
91 | this.INIT_COL_ROOK['w'][1] = j; | |
92 | break; | |
93 | default: | |
94 | let num = parseInt(position[i].charAt(j)); | |
95 | if (!isNaN(num)) | |
96 | j += (num-1); | |
97 | } | |
98 | j++; | |
99 | } | |
100 | } | |
f3802fcd | 101 | const epSq = this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined; |
1d184b4c | 102 | this.epSquares = [ epSq ]; |
1d184b4c BA |
103 | } |
104 | ||
105 | // Turn diagram fen into double array ["wb","wp","bk",...] | |
106 | static GetBoard(fen) | |
107 | { | |
108 | let rows = fen.split(" ")[0].split("/"); | |
46302e64 | 109 | const [sizeX,sizeY] = VariantRules.size; |
1d184b4c BA |
110 | let board = doubleArray(sizeX, sizeY, ""); |
111 | for (let i=0; i<rows.length; i++) | |
112 | { | |
113 | let j = 0; | |
114 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) | |
115 | { | |
116 | let character = rows[i][indexInRow]; | |
117 | let num = parseInt(character); | |
118 | if (!isNaN(num)) | |
119 | j += num; //just shift j | |
120 | else //something at position i,j | |
121 | board[i][j++] = VariantRules.fen2board(character); | |
122 | } | |
123 | } | |
124 | return board; | |
125 | } | |
126 | ||
127 | // Overridable: flags can change a lot | |
128 | static GetFlags(fen) | |
129 | { | |
130 | // white a-castle, h-castle, black a-castle, h-castle | |
131 | let flags = {'w': new Array(2), 'b': new Array(2)}; | |
132 | let fenFlags = fen.split(" ")[1]; //flags right after position | |
133 | for (let i=0; i<4; i++) | |
134 | flags[i < 2 ? 'w' : 'b'][i%2] = (fenFlags.charAt(i) == '1'); | |
135 | return flags; | |
136 | } | |
137 | ||
138 | /////////////////// | |
139 | // GETTERS, SETTERS | |
140 | ||
141 | // Simple useful getters | |
142 | static get size() { return [8,8]; } | |
143 | // Two next functions return 'undefined' if called on empty square | |
144 | getColor(i,j) { return this.board[i][j].charAt(0); } | |
145 | getPiece(i,j) { return this.board[i][j].charAt(1); } | |
146 | ||
147 | // Color | |
148 | getOppCol(color) { return color=="w" ? "b" : "w"; } | |
149 | ||
150 | get lastMove() { | |
151 | const L = this.moves.length; | |
152 | return L>0 ? this.moves[L-1] : null; | |
153 | } | |
154 | get turn() { | |
d3334c3a | 155 | return this.moves.length%2==0 ? 'w' : 'b'; |
1d184b4c BA |
156 | } |
157 | ||
158 | // Pieces codes | |
159 | static get PAWN() { return 'p'; } | |
160 | static get ROOK() { return 'r'; } | |
161 | static get KNIGHT() { return 'n'; } | |
162 | static get BISHOP() { return 'b'; } | |
163 | static get QUEEN() { return 'q'; } | |
164 | static get KING() { return 'k'; } | |
165 | ||
166 | // Empty square | |
167 | static get EMPTY() { return ''; } | |
168 | ||
169 | // Some pieces movements | |
170 | static get steps() { | |
171 | return { | |
172 | 'r': [ [-1,0],[1,0],[0,-1],[0,1] ], | |
173 | 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ], | |
174 | 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ], | |
175 | 'q': [ [-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1] ] | |
176 | }; | |
177 | } | |
178 | ||
179 | // En-passant square, if any | |
180 | getEpSquare(move) | |
181 | { | |
182 | const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x]; | |
183 | if (this.getPiece(sx,sy) == VariantRules.PAWN && Math.abs(sx - ex) == 2) | |
184 | { | |
185 | return { | |
186 | x: (sx + ex)/2, | |
187 | y: sy | |
188 | }; | |
189 | } | |
190 | return undefined; //default | |
191 | } | |
192 | ||
46302e64 BA |
193 | // can thing on square1 take thing on square2 |
194 | canTake([x1,y1], [x2,y2]) | |
1d184b4c | 195 | { |
46302e64 | 196 | return this.getColor(x1,y1) != this.getColor(x2,y2); |
1d184b4c BA |
197 | } |
198 | ||
199 | /////////////////// | |
200 | // MOVES GENERATION | |
201 | ||
202 | // All possible moves from selected square (assumption: color is OK) | |
203 | getPotentialMovesFrom([x,y]) | |
204 | { | |
1d184b4c BA |
205 | switch (this.getPiece(x,y)) |
206 | { | |
207 | case VariantRules.PAWN: | |
46302e64 | 208 | return this.getPotentialPawnMoves([x,y]); |
1d184b4c | 209 | case VariantRules.ROOK: |
46302e64 | 210 | return this.getPotentialRookMoves([x,y]); |
1d184b4c | 211 | case VariantRules.KNIGHT: |
46302e64 | 212 | return this.getPotentialKnightMoves([x,y]); |
1d184b4c | 213 | case VariantRules.BISHOP: |
46302e64 | 214 | return this.getPotentialBishopMoves([x,y]); |
1d184b4c | 215 | case VariantRules.QUEEN: |
46302e64 | 216 | return this.getPotentialQueenMoves([x,y]); |
1d184b4c | 217 | case VariantRules.KING: |
46302e64 | 218 | return this.getPotentialKingMoves([x,y]); |
1d184b4c BA |
219 | } |
220 | } | |
221 | ||
222 | // Build a regular move from its initial and destination squares; tr: transformation | |
46302e64 | 223 | getBasicMove([sx,sy], [ex,ey], tr) |
1d184b4c BA |
224 | { |
225 | var mv = new Move({ | |
226 | appear: [ | |
227 | new PiPo({ | |
228 | x: ex, | |
229 | y: ey, | |
46302e64 BA |
230 | c: !!tr ? tr.c : this.getColor(sx,sy), |
231 | p: !!tr ? tr.p : this.getPiece(sx,sy) | |
1d184b4c BA |
232 | }) |
233 | ], | |
234 | vanish: [ | |
235 | new PiPo({ | |
236 | x: sx, | |
237 | y: sy, | |
238 | c: this.getColor(sx,sy), | |
239 | p: this.getPiece(sx,sy) | |
240 | }) | |
241 | ] | |
242 | }); | |
243 | ||
244 | // The opponent piece disappears if we take it | |
245 | if (this.board[ex][ey] != VariantRules.EMPTY) | |
246 | { | |
247 | mv.vanish.push( | |
248 | new PiPo({ | |
249 | x: ex, | |
250 | y: ey, | |
251 | c: this.getColor(ex,ey), | |
252 | p: this.getPiece(ex,ey) | |
253 | }) | |
254 | ); | |
255 | } | |
256 | return mv; | |
257 | } | |
258 | ||
259 | // Generic method to find possible moves of non-pawn pieces ("sliding or jumping") | |
46302e64 | 260 | getSlideNJumpMoves([x,y], steps, oneStep) |
1d184b4c | 261 | { |
46302e64 | 262 | const color = this.getColor(x,y); |
1d184b4c | 263 | var moves = []; |
46302e64 | 264 | const [sizeX,sizeY] = VariantRules.size; |
1d184b4c BA |
265 | outerLoop: |
266 | for (let step of steps) | |
267 | { | |
46302e64 BA |
268 | let i = x + step[0]; |
269 | let j = y + step[1]; | |
818ede16 | 270 | while (i>=0 && i<sizeX && j>=0 && j<sizeY && this.board[i][j] == VariantRules.EMPTY) |
1d184b4c | 271 | { |
46302e64 | 272 | moves.push(this.getBasicMove([x,y], [i,j])); |
1d184b4c BA |
273 | if (oneStep !== undefined) |
274 | continue outerLoop; | |
275 | i += step[0]; | |
276 | j += step[1]; | |
277 | } | |
46302e64 BA |
278 | if (i>=0 && i<8 && j>=0 && j<8 && this.canTake([x,y], [i,j])) |
279 | moves.push(this.getBasicMove([x,y], [i,j])); | |
1d184b4c BA |
280 | } |
281 | return moves; | |
282 | } | |
283 | ||
284 | // What are the pawn moves from square x,y considering color "color" ? | |
46302e64 | 285 | getPotentialPawnMoves([x,y]) |
1d184b4c | 286 | { |
46302e64 | 287 | const color = this.getColor(x,y); |
1d184b4c BA |
288 | var moves = []; |
289 | var V = VariantRules; | |
46302e64 | 290 | const [sizeX,sizeY] = VariantRules.size; |
1d184b4c BA |
291 | let shift = (color == "w" ? -1 : 1); |
292 | let startRank = (color == "w" ? sizeY-2 : 1); | |
293 | let lastRank = (color == "w" ? 0 : sizeY-1); | |
294 | ||
295 | if (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank) | |
296 | { | |
297 | // Normal moves | |
298 | if (this.board[x+shift][y] == V.EMPTY) | |
299 | { | |
46302e64 | 300 | moves.push(this.getBasicMove([x,y], [x+shift,y])); |
1d184b4c BA |
301 | if (x==startRank && this.board[x+2*shift][y] == V.EMPTY) |
302 | { | |
303 | // Two squares jump | |
46302e64 | 304 | moves.push(this.getBasicMove([x,y], [x+2*shift,y])); |
1d184b4c BA |
305 | } |
306 | } | |
307 | // Captures | |
46302e64 BA |
308 | if (y>0 && this.canTake([x,y], [x+shift,y-1]) && this.board[x+shift][y-1] != V.EMPTY) |
309 | moves.push(this.getBasicMove([x,y], [x+shift,y-1])); | |
310 | if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1]) && this.board[x+shift][y+1] != V.EMPTY) | |
311 | moves.push(this.getBasicMove([x,y], [x+shift,y+1])); | |
1d184b4c BA |
312 | } |
313 | ||
314 | if (x+shift == lastRank) | |
315 | { | |
316 | // Promotion | |
317 | let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN]; | |
318 | promotionPieces.forEach(p => { | |
319 | // Normal move | |
320 | if (this.board[x+shift][y] == V.EMPTY) | |
46302e64 | 321 | moves.push(this.getBasicMove([x,y], [x+shift,y], {c:color,p:p})); |
1d184b4c | 322 | // Captures |
46302e64 BA |
323 | if (y>0 && this.canTake([x,y], [x+shift,y-1]) && this.board[x+shift][y-1] != V.EMPTY) |
324 | moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:color,p:p})); | |
325 | if (y<sizeY-1 && this.canTake([x,y], [x+shift,y+1]) && this.board[x+shift][y+1] != V.EMPTY) | |
326 | moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:color,p:p})); | |
1d184b4c BA |
327 | }); |
328 | } | |
329 | ||
330 | // En passant | |
331 | const Lep = this.epSquares.length; | |
332 | const epSquare = Lep>0 ? this.epSquares[Lep-1] : undefined; | |
333 | if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1) | |
334 | { | |
335 | let epStep = epSquare.y - y; | |
46302e64 | 336 | var enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]); |
1d184b4c BA |
337 | enpassantMove.vanish.push({ |
338 | x: x, | |
339 | y: y+epStep, | |
340 | p: 'p', | |
341 | c: this.getColor(x,y+epStep) | |
342 | }); | |
343 | moves.push(enpassantMove); | |
344 | } | |
345 | ||
346 | return moves; | |
347 | } | |
348 | ||
349 | // What are the rook moves from square x,y ? | |
46302e64 | 350 | getPotentialRookMoves(sq) |
1d184b4c | 351 | { |
46302e64 | 352 | return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.ROOK]); |
1d184b4c BA |
353 | } |
354 | ||
355 | // What are the knight moves from square x,y ? | |
46302e64 | 356 | getPotentialKnightMoves(sq) |
1d184b4c | 357 | { |
46302e64 | 358 | return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.KNIGHT], "oneStep"); |
1d184b4c BA |
359 | } |
360 | ||
361 | // What are the bishop moves from square x,y ? | |
46302e64 | 362 | getPotentialBishopMoves(sq) |
1d184b4c | 363 | { |
46302e64 | 364 | return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.BISHOP]); |
1d184b4c BA |
365 | } |
366 | ||
367 | // What are the queen moves from square x,y ? | |
46302e64 | 368 | getPotentialQueenMoves(sq) |
1d184b4c | 369 | { |
46302e64 | 370 | return this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.QUEEN]); |
1d184b4c BA |
371 | } |
372 | ||
373 | // What are the king moves from square x,y ? | |
46302e64 | 374 | getPotentialKingMoves(sq) |
1d184b4c BA |
375 | { |
376 | // Initialize with normal moves | |
46302e64 BA |
377 | let moves = this.getSlideNJumpMoves(sq, VariantRules.steps[VariantRules.QUEEN], "oneStep"); |
378 | return moves.concat(this.getCastleMoves(sq)); | |
1d184b4c BA |
379 | } |
380 | ||
46302e64 | 381 | getCastleMoves([x,y]) |
1d184b4c | 382 | { |
46302e64 | 383 | const c = this.getColor(x,y); |
1d184b4c BA |
384 | if (x != (c=="w" ? 7 : 0) || y != this.INIT_COL_KING[c]) |
385 | return []; //x isn't first rank, or king has moved (shortcut) | |
386 | ||
387 | const V = VariantRules; | |
388 | ||
389 | // Castling ? | |
390 | const oppCol = this.getOppCol(c); | |
391 | let moves = []; | |
392 | let i = 0; | |
393 | const finalSquares = [ [2,3], [6,5] ]; //king, then rook | |
394 | castlingCheck: | |
395 | for (let castleSide=0; castleSide < 2; castleSide++) //large, then small | |
396 | { | |
397 | if (!this.flags[c][castleSide]) | |
398 | continue; | |
399 | // If this code is reached, rooks and king are on initial position | |
400 | ||
401 | // Nothing on the path of the king (and no checks; OK also if y==finalSquare)? | |
402 | let step = finalSquares[castleSide][0] < y ? -1 : 1; | |
403 | for (i=y; i!=finalSquares[castleSide][0]; i+=step) | |
404 | { | |
405 | if (this.isAttacked([x,i], oppCol) || (this.board[x][i] != V.EMPTY && | |
406 | // NOTE: next check is enough, because of chessboard constraints | |
407 | (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i))))) | |
408 | { | |
409 | continue castlingCheck; | |
410 | } | |
411 | } | |
412 | ||
413 | // Nothing on the path to the rook? | |
414 | step = castleSide == 0 ? -1 : 1; | |
415 | for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) | |
416 | { | |
417 | if (this.board[x][i] != V.EMPTY) | |
418 | continue castlingCheck; | |
419 | } | |
420 | const rookPos = this.INIT_COL_ROOK[c][castleSide]; | |
421 | ||
422 | // Nothing on final squares, except maybe king and castling rook? | |
423 | for (i=0; i<2; i++) | |
424 | { | |
425 | if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY && | |
426 | this.getPiece(x,finalSquares[castleSide][i]) != V.KING && | |
427 | finalSquares[castleSide][i] != rookPos) | |
428 | { | |
429 | continue castlingCheck; | |
430 | } | |
431 | } | |
432 | ||
433 | // If this code is reached, castle is valid | |
434 | moves.push( new Move({ | |
435 | appear: [ | |
436 | new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}), | |
437 | new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})], | |
438 | vanish: [ | |
439 | new PiPo({x:x,y:y,p:V.KING,c:c}), | |
440 | new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})], | |
441 | end: Math.abs(y - rookPos) <= 2 | |
442 | ? {x:x, y:rookPos} | |
443 | : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)} | |
444 | }) ); | |
445 | } | |
446 | ||
447 | return moves; | |
448 | } | |
449 | ||
450 | /////////////////// | |
451 | // MOVES VALIDATION | |
452 | ||
46302e64 | 453 | canIplay(side, [x,y]) |
1d184b4c | 454 | { |
46302e64 BA |
455 | return ((side=='w' && this.moves.length%2==0) || (side=='b' && this.moves.length%2==1)) |
456 | && this.getColor(x,y) == side; | |
1d184b4c BA |
457 | } |
458 | ||
459 | getPossibleMovesFrom(sq) | |
460 | { | |
461 | // Assuming color is right (already checked) | |
462 | return this.filterValid( this.getPotentialMovesFrom(sq) ); | |
463 | } | |
464 | ||
465 | // TODO: once a promotion is filtered, the others results are same: useless computations | |
466 | filterValid(moves) | |
467 | { | |
468 | if (moves.length == 0) | |
469 | return []; | |
46302e64 BA |
470 | let color = this.turn; |
471 | return moves.filter(m => { return !this.underCheck(m, color); }); | |
1d184b4c BA |
472 | } |
473 | ||
474 | // Search for all valid moves considering current turn (for engine and game end) | |
46302e64 | 475 | getAllValidMoves() |
1d184b4c | 476 | { |
46302e64 | 477 | const color = this.turn; |
1d184b4c BA |
478 | const oppCol = this.getOppCol(color); |
479 | var potentialMoves = []; | |
480 | let [sizeX,sizeY] = VariantRules.size; | |
481 | for (var i=0; i<sizeX; i++) | |
482 | { | |
483 | for (var j=0; j<sizeY; j++) | |
484 | { | |
485 | // Next condition ... != oppCol is a little HACK to work with checkered variant | |
486 | if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol) | |
487 | Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j])); | |
488 | } | |
489 | } | |
490 | // NOTE: prefer lazy undercheck tests, letting the king being taken? | |
491 | // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals | |
492 | return this.filterValid(potentialMoves); | |
493 | } | |
e64a4eff BA |
494 | |
495 | // Stop at the first move found | |
46302e64 | 496 | atLeastOneMove() |
e64a4eff | 497 | { |
46302e64 | 498 | const color = this.turn; |
e64a4eff BA |
499 | const oppCol = this.getOppCol(color); |
500 | let [sizeX,sizeY] = VariantRules.size; | |
501 | for (var i=0; i<sizeX; i++) | |
502 | { | |
503 | for (var j=0; j<sizeY; j++) | |
504 | { | |
505 | if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol) | |
506 | { | |
507 | const moves = this.getPotentialMovesFrom([i,j]); | |
508 | if (moves.length > 0) | |
509 | { | |
510 | for (let i=0; i<moves.length; i++) | |
511 | { | |
512 | if (this.filterValid([moves[i]]).length > 0) | |
513 | return true; | |
514 | } | |
515 | } | |
516 | } | |
517 | } | |
518 | } | |
519 | return false; | |
520 | } | |
1d184b4c | 521 | |
46302e64 BA |
522 | // Check if pieces of color 'colors' are attacking square x,y |
523 | isAttacked(sq, colors) | |
1d184b4c | 524 | { |
46302e64 BA |
525 | return (this.isAttackedByPawn(sq, colors) |
526 | || this.isAttackedByRook(sq, colors) | |
527 | || this.isAttackedByKnight(sq, colors) | |
528 | || this.isAttackedByBishop(sq, colors) | |
529 | || this.isAttackedByQueen(sq, colors) | |
530 | || this.isAttackedByKing(sq, colors)); | |
1d184b4c BA |
531 | } |
532 | ||
533 | // Is square x,y attacked by pawns of color c ? | |
46302e64 | 534 | isAttackedByPawn([x,y], colors) |
1d184b4c | 535 | { |
46302e64 | 536 | for (let c of colors) |
1d184b4c | 537 | { |
46302e64 BA |
538 | let pawnShift = (c=="w" ? 1 : -1); |
539 | if (x+pawnShift>=0 && x+pawnShift<8) | |
1d184b4c | 540 | { |
46302e64 | 541 | for (let i of [-1,1]) |
1d184b4c | 542 | { |
46302e64 BA |
543 | if (y+i>=0 && y+i<8 && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN |
544 | && this.getColor(x+pawnShift,y+i)==c) | |
545 | { | |
546 | return true; | |
547 | } | |
1d184b4c BA |
548 | } |
549 | } | |
550 | } | |
551 | return false; | |
552 | } | |
553 | ||
554 | // Is square x,y attacked by rooks of color c ? | |
46302e64 | 555 | isAttackedByRook(sq, colors) |
1d184b4c | 556 | { |
46302e64 | 557 | return this.isAttackedBySlideNJump(sq, colors, |
1d184b4c BA |
558 | VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]); |
559 | } | |
560 | ||
561 | // Is square x,y attacked by knights of color c ? | |
46302e64 | 562 | isAttackedByKnight(sq, colors) |
1d184b4c | 563 | { |
46302e64 | 564 | return this.isAttackedBySlideNJump(sq, colors, |
1d184b4c BA |
565 | VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep"); |
566 | } | |
567 | ||
568 | // Is square x,y attacked by bishops of color c ? | |
46302e64 | 569 | isAttackedByBishop(sq, colors) |
1d184b4c | 570 | { |
46302e64 | 571 | return this.isAttackedBySlideNJump(sq, colors, |
1d184b4c BA |
572 | VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]); |
573 | } | |
574 | ||
575 | // Is square x,y attacked by queens of color c ? | |
46302e64 | 576 | isAttackedByQueen(sq, colors) |
1d184b4c | 577 | { |
46302e64 | 578 | return this.isAttackedBySlideNJump(sq, colors, |
1d184b4c BA |
579 | VariantRules.QUEEN, VariantRules.steps[VariantRules.QUEEN]); |
580 | } | |
581 | ||
582 | // Is square x,y attacked by king of color c ? | |
46302e64 | 583 | isAttackedByKing(sq, colors) |
1d184b4c | 584 | { |
46302e64 | 585 | return this.isAttackedBySlideNJump(sq, colors, |
1d184b4c BA |
586 | VariantRules.KING, VariantRules.steps[VariantRules.QUEEN], "oneStep"); |
587 | } | |
588 | ||
589 | // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ? | |
46302e64 | 590 | isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep) |
1d184b4c BA |
591 | { |
592 | for (let step of steps) | |
593 | { | |
594 | let rx = x+step[0], ry = y+step[1]; | |
595 | while (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] == VariantRules.EMPTY | |
596 | && !oneStep) | |
597 | { | |
598 | rx += step[0]; | |
599 | ry += step[1]; | |
600 | } | |
601 | if (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] != VariantRules.EMPTY | |
46302e64 | 602 | && this.getPiece(rx,ry) == piece && colors.includes(this.getColor(rx,ry))) |
1d184b4c BA |
603 | { |
604 | return true; | |
605 | } | |
606 | } | |
607 | return false; | |
608 | } | |
609 | ||
4b5fe306 | 610 | // Is color c under check after move ? |
46302e64 | 611 | underCheck(move) |
1d184b4c | 612 | { |
46302e64 | 613 | const color = this.turn; |
1d184b4c | 614 | this.play(move); |
46302e64 | 615 | let res = this.isAttacked(this.kingPos[color], this.getOppCol(color)); |
1d184b4c BA |
616 | this.undo(move); |
617 | return res; | |
618 | } | |
619 | ||
4b5fe306 | 620 | // On which squares is color c under check (after move) ? |
46302e64 | 621 | getCheckSquares(move) |
4b5fe306 BA |
622 | { |
623 | this.play(move); | |
46302e64 BA |
624 | const color = this.turn; |
625 | let res = this.isAttacked(this.kingPos[color], this.getOppCol(color)) | |
626 | ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate! | |
4b5fe306 BA |
627 | : [ ]; |
628 | this.undo(move); | |
629 | return res; | |
630 | } | |
631 | ||
1d184b4c BA |
632 | // Apply a move on board |
633 | static PlayOnBoard(board, move) | |
634 | { | |
635 | for (let psq of move.vanish) | |
636 | board[psq.x][psq.y] = VariantRules.EMPTY; | |
637 | for (let psq of move.appear) | |
638 | board[psq.x][psq.y] = psq.c + psq.p; | |
639 | } | |
640 | // Un-apply the played move | |
641 | static UndoOnBoard(board, move) | |
642 | { | |
643 | for (let psq of move.appear) | |
644 | board[psq.x][psq.y] = VariantRules.EMPTY; | |
645 | for (let psq of move.vanish) | |
646 | board[psq.x][psq.y] = psq.c + psq.p; | |
647 | } | |
648 | ||
d3334c3a | 649 | // Before move is played, update variables + flags |
1d184b4c BA |
650 | updateVariables(move) |
651 | { | |
652 | const piece = this.getPiece(move.start.x,move.start.y); | |
653 | const c = this.getColor(move.start.x,move.start.y); | |
654 | const firstRank = (c == "w" ? 7 : 0); | |
655 | ||
656 | // Update king position + flags | |
657 | if (piece == VariantRules.KING && move.appear.length > 0) | |
658 | { | |
659 | this.kingPos[c][0] = move.appear[0].x; | |
660 | this.kingPos[c][1] = move.appear[0].y; | |
661 | this.flags[c] = [false,false]; | |
662 | return; | |
663 | } | |
664 | const oppCol = this.getOppCol(c); | |
665 | const oppFirstRank = 7 - firstRank; | |
666 | if (move.start.x == firstRank //our rook moves? | |
667 | && this.INIT_COL_ROOK[c].includes(move.start.y)) | |
668 | { | |
669 | const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1; | |
670 | this.flags[c][flagIdx] = false; | |
671 | } | |
672 | else if (move.end.x == oppFirstRank //we took opponent rook? | |
673 | && this.INIT_COL_ROOK[c].includes(move.end.y)) | |
674 | { | |
675 | const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1; | |
676 | this.flags[oppCol][flagIdx] = false; | |
677 | } | |
678 | } | |
679 | ||
d3334c3a | 680 | unupdateVariables(move) |
1d184b4c | 681 | { |
d3334c3a BA |
682 | // (Potentially) Reset king position |
683 | const c = this.getColor(move.start.x,move.start.y); | |
684 | if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING) | |
685 | this.kingPos[c] = [move.start.x, move.start.y]; | |
686 | } | |
1d184b4c | 687 | |
d3334c3a BA |
688 | play(move, ingame) |
689 | { | |
dfb4afc1 | 690 | if (!!ingame) |
dfb4afc1 | 691 | move.notation = this.getNotation(move); |
dfb4afc1 | 692 | |
d3334c3a BA |
693 | // Save flags (for undo) |
694 | move.flags = JSON.stringify(this.flags); //TODO: less costly? | |
695 | this.updateVariables(move); | |
696 | this.moves.push(move); | |
1d184b4c BA |
697 | this.epSquares.push( this.getEpSquare(move) ); |
698 | VariantRules.PlayOnBoard(this.board, move); | |
1d184b4c BA |
699 | } |
700 | ||
cd4cad04 | 701 | undo(move) |
1d184b4c BA |
702 | { |
703 | VariantRules.UndoOnBoard(this.board, move); | |
704 | this.epSquares.pop(); | |
d3334c3a BA |
705 | this.moves.pop(); |
706 | this.unupdateVariables(move); | |
1d184b4c BA |
707 | this.flags = JSON.parse(move.flags); |
708 | } | |
709 | ||
710 | ////////////// | |
711 | // END OF GAME | |
712 | ||
46302e64 | 713 | checkGameOver() |
1d184b4c BA |
714 | { |
715 | // Check for 3 repetitions | |
716 | if (this.moves.length >= 8) | |
717 | { | |
718 | // NOTE: crude detection, only moves repetition | |
719 | const L = this.moves.length; | |
720 | if (_.isEqual(this.moves[L-1], this.moves[L-5]) && | |
721 | _.isEqual(this.moves[L-2], this.moves[L-6]) && | |
722 | _.isEqual(this.moves[L-3], this.moves[L-7]) && | |
723 | _.isEqual(this.moves[L-4], this.moves[L-8])) | |
724 | { | |
725 | return "1/2 (repetition)"; | |
726 | } | |
727 | } | |
728 | ||
46302e64 | 729 | if (this.atLeastOneMove()) |
1d184b4c BA |
730 | { |
731 | // game not over | |
732 | return "*"; | |
733 | } | |
734 | ||
735 | // Game over | |
46302e64 | 736 | return this.checkGameEnd(); |
1d184b4c BA |
737 | } |
738 | ||
46302e64 BA |
739 | // No moves are possible: compute score |
740 | checkGameEnd() | |
1d184b4c | 741 | { |
46302e64 | 742 | const color = this.turn; |
1d184b4c BA |
743 | // No valid move: stalemate or checkmate? |
744 | if (!this.isAttacked(this.kingPos[color], this.getOppCol(color))) | |
745 | return "1/2"; | |
746 | // OK, checkmate | |
747 | return color == "w" ? "0-1" : "1-0"; | |
748 | } | |
749 | ||
750 | //////// | |
751 | //ENGINE | |
752 | ||
753 | // Pieces values | |
754 | static get VALUES() { | |
755 | return { | |
756 | 'p': 1, | |
757 | 'r': 5, | |
758 | 'n': 3, | |
759 | 'b': 3, | |
760 | 'q': 9, | |
761 | 'k': 1000 | |
762 | }; | |
763 | } | |
764 | ||
765 | // Assumption: at least one legal move | |
46302e64 | 766 | getComputerMove() |
1d184b4c | 767 | { |
46302e64 | 768 | const color = this.turn; |
1d184b4c BA |
769 | |
770 | // Rank moves using a min-max at depth 2 | |
46302e64 | 771 | let moves1 = this.getAllValidMoves(); |
1d184b4c BA |
772 | |
773 | for (let i=0; i<moves1.length; i++) | |
774 | { | |
775 | moves1[i].eval = (color=="w" ? -1 : 1) * 1000; //very low, I'm checkmated | |
776 | let eval2 = (color=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value | |
777 | this.play(moves1[i]); | |
778 | // Second half-move: | |
46302e64 | 779 | let moves2 = this.getAllValidMoves(); |
1d184b4c BA |
780 | // If no possible moves AND underCheck, eval2 is correct. |
781 | // If !underCheck, eval2 is 0 (stalemate). | |
46302e64 | 782 | if (moves2.length == 0 && this.checkGameEnd() == "1/2") |
1d184b4c BA |
783 | eval2 = 0; |
784 | for (let j=0; j<moves2.length; j++) | |
785 | { | |
786 | this.play(moves2[j]); | |
787 | let evalPos = this.evalPosition(); | |
788 | if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2)) | |
789 | eval2 = evalPos; | |
790 | this.undo(moves2[j]); | |
791 | } | |
792 | if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval)) | |
793 | moves1[i].eval = eval2; | |
794 | this.undo(moves1[i]); | |
795 | } | |
796 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
797 | ||
798 | // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0]) | |
e64a4eff BA |
799 | for (let i=0; i<moves1.length; i++) |
800 | { | |
801 | this.play(moves1[i]); | |
802 | // 0.1 * oldEval : heuristic to avoid some bad moves (not all...) | |
46302e64 | 803 | moves1[i].eval = 0.1*moves1[i].eval + this.alphabeta(2, -1000, 1000); |
e64a4eff BA |
804 | this.undo(moves1[i]); |
805 | } | |
806 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
1d184b4c BA |
807 | |
808 | let candidates = [0]; //indices of candidates moves | |
809 | for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++) | |
810 | candidates.push(j); | |
811 | ||
812 | //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); | |
813 | return moves1[_.sample(candidates, 1)]; | |
814 | } | |
815 | ||
46302e64 | 816 | alphabeta(depth, alpha, beta) |
1d184b4c | 817 | { |
46302e64 BA |
818 | const color = this.turn; |
819 | if (!this.atLeastOneMove()) | |
1d184b4c | 820 | { |
46302e64 | 821 | switch (this.checkGameEnd()) |
1d184b4c BA |
822 | { |
823 | case "1/2": return 0; | |
824 | default: return color=="w" ? -1000 : 1000; | |
825 | } | |
826 | } | |
827 | if (depth == 0) | |
828 | return this.evalPosition(); | |
46302e64 | 829 | const moves = this.getAllValidMoves(); |
1d184b4c BA |
830 | let v = color=="w" ? -1000 : 1000; |
831 | if (color == "w") | |
832 | { | |
833 | for (let i=0; i<moves.length; i++) | |
834 | { | |
835 | this.play(moves[i]); | |
46302e64 | 836 | v = Math.max(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
837 | this.undo(moves[i]); |
838 | alpha = Math.max(alpha, v); | |
839 | if (alpha >= beta) | |
840 | break; //beta cutoff | |
841 | } | |
842 | } | |
843 | else //color=="b" | |
844 | { | |
845 | for (let i=0; i<moves.length; i++) | |
846 | { | |
847 | this.play(moves[i]); | |
46302e64 | 848 | v = Math.min(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
849 | this.undo(moves[i]); |
850 | beta = Math.min(beta, v); | |
851 | if (alpha >= beta) | |
852 | break; //alpha cutoff | |
853 | } | |
854 | } | |
855 | return v; | |
856 | } | |
857 | ||
858 | evalPosition() | |
859 | { | |
860 | const [sizeX,sizeY] = VariantRules.size; | |
861 | let evaluation = 0; | |
862 | //Just count material for now | |
863 | for (let i=0; i<sizeX; i++) | |
864 | { | |
865 | for (let j=0; j<sizeY; j++) | |
866 | { | |
867 | if (this.board[i][j] != VariantRules.EMPTY) | |
868 | { | |
869 | const sign = this.getColor(i,j) == "w" ? 1 : -1; | |
870 | evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)]; | |
871 | } | |
872 | } | |
873 | } | |
874 | return evaluation; | |
875 | } | |
876 | ||
877 | //////////// | |
878 | // FEN utils | |
879 | ||
880 | // Overridable.. | |
881 | static GenRandInitFen() | |
882 | { | |
883 | let pieces = [new Array(8), new Array(8)]; | |
884 | // Shuffle pieces on first and last rank | |
885 | for (let c = 0; c <= 1; c++) | |
886 | { | |
887 | let positions = _.range(8); | |
888 | ||
889 | // Get random squares for bishops | |
890 | let randIndex = 2 * _.random(3); | |
891 | let bishop1Pos = positions[randIndex]; | |
892 | // The second bishop must be on a square of different color | |
893 | let randIndex_tmp = 2 * _.random(3) + 1; | |
894 | let bishop2Pos = positions[randIndex_tmp]; | |
895 | // Remove chosen squares | |
896 | positions.splice(Math.max(randIndex,randIndex_tmp), 1); | |
897 | positions.splice(Math.min(randIndex,randIndex_tmp), 1); | |
898 | ||
899 | // Get random squares for knights | |
900 | randIndex = _.random(5); | |
901 | let knight1Pos = positions[randIndex]; | |
902 | positions.splice(randIndex, 1); | |
903 | randIndex = _.random(4); | |
904 | let knight2Pos = positions[randIndex]; | |
905 | positions.splice(randIndex, 1); | |
906 | ||
907 | // Get random square for queen | |
908 | randIndex = _.random(3); | |
909 | let queenPos = positions[randIndex]; | |
910 | positions.splice(randIndex, 1); | |
911 | ||
912 | // Rooks and king positions are now fixed, because of the ordering rook-king-rook | |
913 | let rook1Pos = positions[0]; | |
914 | let kingPos = positions[1]; | |
915 | let rook2Pos = positions[2]; | |
916 | ||
917 | // Finally put the shuffled pieces in the board array | |
918 | pieces[c][rook1Pos] = 'r'; | |
919 | pieces[c][knight1Pos] = 'n'; | |
920 | pieces[c][bishop1Pos] = 'b'; | |
921 | pieces[c][queenPos] = 'q'; | |
922 | pieces[c][kingPos] = 'k'; | |
923 | pieces[c][bishop2Pos] = 'b'; | |
924 | pieces[c][knight2Pos] = 'n'; | |
925 | pieces[c][rook2Pos] = 'r'; | |
926 | } | |
927 | let fen = pieces[0].join("") + | |
928 | "/pppppppp/8/8/8/8/PPPPPPPP/" + | |
929 | pieces[1].join("").toUpperCase() + | |
f3802fcd | 930 | " 1111"; //add flags |
1d184b4c BA |
931 | return fen; |
932 | } | |
933 | ||
934 | // Return current fen according to pieces+colors state | |
935 | getFen() | |
936 | { | |
f3802fcd | 937 | return this.getBaseFen() + " " + this.getFlagsFen(); |
1d184b4c BA |
938 | } |
939 | ||
940 | getBaseFen() | |
941 | { | |
942 | let fen = ""; | |
943 | let [sizeX,sizeY] = VariantRules.size; | |
944 | for (let i=0; i<sizeX; i++) | |
945 | { | |
946 | let emptyCount = 0; | |
947 | for (let j=0; j<sizeY; j++) | |
948 | { | |
949 | if (this.board[i][j] == VariantRules.EMPTY) | |
950 | emptyCount++; | |
951 | else | |
952 | { | |
953 | if (emptyCount > 0) | |
954 | { | |
955 | // Add empty squares in-between | |
956 | fen += emptyCount; | |
957 | emptyCount = 0; | |
958 | } | |
959 | fen += VariantRules.board2fen(this.board[i][j]); | |
960 | } | |
961 | } | |
962 | if (emptyCount > 0) | |
963 | { | |
964 | // "Flush remainder" | |
965 | fen += emptyCount; | |
966 | } | |
967 | if (i < sizeX - 1) | |
968 | fen += "/"; //separate rows | |
969 | } | |
970 | return fen; | |
971 | } | |
972 | ||
973 | // Overridable.. | |
974 | getFlagsFen() | |
975 | { | |
976 | let fen = ""; | |
977 | // Add castling flags | |
978 | for (let i of ['w','b']) | |
979 | { | |
980 | for (let j=0; j<2; j++) | |
981 | fen += this.flags[i][j] ? '1' : '0'; | |
982 | } | |
983 | return fen; | |
984 | } | |
985 | ||
986 | // Context: just before move is played, turn hasn't changed | |
987 | getNotation(move) | |
988 | { | |
989 | if (move.appear.length == 2) | |
990 | { | |
991 | // Castle | |
992 | if (move.end.y < move.start.y) | |
993 | return "0-0-0"; | |
994 | else | |
995 | return "0-0"; | |
996 | } | |
997 | ||
998 | // Translate final square | |
999 | let finalSquare = | |
1000 | String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x); | |
1001 | ||
1002 | let piece = this.getPiece(move.start.x, move.start.y); | |
1003 | if (piece == VariantRules.PAWN) | |
1004 | { | |
1005 | // Pawn move | |
1006 | let notation = ""; | |
1007 | if (move.vanish.length > 1) | |
1008 | { | |
1009 | // Capture | |
1010 | let startColumn = String.fromCharCode(97 + move.start.y); | |
1011 | notation = startColumn + "x" + finalSquare; | |
1012 | } | |
1013 | else //no capture | |
1014 | notation = finalSquare; | |
1015 | if (move.appear.length > 0 && piece != move.appear[0].p) //promotion | |
1016 | notation += "=" + move.appear[0].p.toUpperCase(); | |
1017 | return notation; | |
1018 | } | |
1019 | ||
1020 | else | |
1021 | { | |
1022 | // Piece movement | |
1023 | return piece.toUpperCase() + (move.vanish.length > 1 ? "x" : "") + finalSquare; | |
1024 | } | |
1025 | } | |
dfb4afc1 BA |
1026 | |
1027 | // The score is already computed when calling this function | |
01a135e2 | 1028 | getPGN(mycolor, score, fenStart, mode) |
dfb4afc1 BA |
1029 | { |
1030 | let pgn = ""; | |
1031 | pgn += '[Site "vchess.club"]<br>'; | |
1032 | const d = new Date(); | |
01a135e2 | 1033 | const opponent = this.mode=="human" ? "Anonymous" : "Computer"; |
f61349e6 | 1034 | pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + '-' + d.getDate() + '"]<br>'; |
01a135e2 BA |
1035 | pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>'; |
1036 | pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>'; | |
762b7c9c BA |
1037 | pgn += '[Fen "' + fenStart + '"]<br>'; |
1038 | pgn += '[Result "' + score + '"]<br><br>'; | |
dfb4afc1 BA |
1039 | |
1040 | for (let i=0; i<this.moves.length; i++) | |
1041 | { | |
1042 | if (i % 2 == 0) | |
1043 | pgn += ((i/2)+1) + "."; | |
1044 | pgn += this.moves[i].notation + " "; | |
1045 | } | |
1046 | ||
1047 | pgn += score; | |
1048 | return pgn; | |
1049 | } | |
1d184b4c | 1050 | } |