Commit | Line | Data |
---|---|---|
92342261 BA |
1 | // (Orthodox) Chess rules are defined in ChessRules class. |
2 | // Variants generally inherit from it, and modify some parts. | |
3 | ||
1d184b4c BA |
4 | class PiPo //Piece+Position |
5 | { | |
6 | // o: {piece[p], color[c], posX[x], posY[y]} | |
7 | constructor(o) | |
8 | { | |
9 | this.p = o.p; | |
10 | this.c = o.c; | |
11 | this.x = o.x; | |
12 | this.y = o.y; | |
13 | } | |
14 | } | |
15 | ||
098e8468 | 16 | // TODO: for animation, moves should contains "moving" and "fading" maybe... |
1d184b4c BA |
17 | class Move |
18 | { | |
19 | // o: {appear, vanish, [start,] [end,]} | |
20 | // appear,vanish = arrays of PiPo | |
21 | // start,end = coordinates to apply to trigger move visually (think castle) | |
22 | constructor(o) | |
23 | { | |
24 | this.appear = o.appear; | |
25 | this.vanish = o.vanish; | |
26 | this.start = !!o.start ? o.start : {x:o.vanish[0].x, y:o.vanish[0].y}; | |
27 | this.end = !!o.end ? o.end : {x:o.appear[0].x, y:o.appear[0].y}; | |
28 | } | |
29 | } | |
30 | ||
31 | // NOTE: x coords = top to bottom; y = left to right (from white player perspective) | |
32 | class ChessRules | |
33 | { | |
34 | // Path to pieces | |
35 | static getPpath(b) | |
36 | { | |
37 | return b; //usual pieces in pieces/ folder | |
38 | } | |
39 | // Turn "wb" into "B" (for FEN) | |
40 | static board2fen(b) | |
41 | { | |
42 | return b[0]=='w' ? b[1].toUpperCase() : b[1]; | |
43 | } | |
44 | // Turn "p" into "bp" (for board) | |
45 | static fen2board(f) | |
46 | { | |
47 | return f.charCodeAt()<=90 ? "w"+f.toLowerCase() : "b"+f; | |
48 | } | |
49 | ||
50 | ///////////////// | |
51 | // INITIALIZATION | |
52 | ||
d3334c3a | 53 | // fen == "position flags" |
dfb4afc1 | 54 | constructor(fen, moves) |
1d184b4c | 55 | { |
dfb4afc1 | 56 | this.moves = moves; |
7931e479 BA |
57 | // Use fen string to initialize variables, flags, turn and board |
58 | const fenParts = fen.split(" "); | |
59 | this.board = V.GetBoard(fenParts[0]); | |
60 | this.setFlags(fenParts[1]); //NOTE: fenParts[1] might be undefined | |
61 | this.setTurn(fenParts[2]); //Same note | |
ffbae57a | 62 | this.initVariables(fen); |
1d184b4c BA |
63 | } |
64 | ||
7931e479 | 65 | // Some additional variables from FEN (variant dependant) |
1d184b4c BA |
66 | initVariables(fen) |
67 | { | |
68 | this.INIT_COL_KING = {'w':-1, 'b':-1}; | |
69 | this.INIT_COL_ROOK = {'w':[-1,-1], 'b':[-1,-1]}; | |
92342261 | 70 | this.kingPos = {'w':[-1,-1], 'b':[-1,-1]}; //squares of white and black king |
1d184b4c BA |
71 | const fenParts = fen.split(" "); |
72 | const position = fenParts[0].split("/"); | |
73 | for (let i=0; i<position.length; i++) | |
74 | { | |
6037f1d8 BA |
75 | let k = 0; //column index on board |
76 | for (let j=0; j<position[i].length; j++) | |
1d184b4c BA |
77 | { |
78 | switch (position[i].charAt(j)) | |
79 | { | |
80 | case 'k': | |
6037f1d8 BA |
81 | this.kingPos['b'] = [i,k]; |
82 | this.INIT_COL_KING['b'] = k; | |
1d184b4c BA |
83 | break; |
84 | case 'K': | |
6037f1d8 BA |
85 | this.kingPos['w'] = [i,k]; |
86 | this.INIT_COL_KING['w'] = k; | |
1d184b4c BA |
87 | break; |
88 | case 'r': | |
89 | if (this.INIT_COL_ROOK['b'][0] < 0) | |
6037f1d8 | 90 | this.INIT_COL_ROOK['b'][0] = k; |
1d184b4c | 91 | else |
6037f1d8 | 92 | this.INIT_COL_ROOK['b'][1] = k; |
1d184b4c BA |
93 | break; |
94 | case 'R': | |
95 | if (this.INIT_COL_ROOK['w'][0] < 0) | |
6037f1d8 | 96 | this.INIT_COL_ROOK['w'][0] = k; |
1d184b4c | 97 | else |
6037f1d8 | 98 | this.INIT_COL_ROOK['w'][1] = k; |
1d184b4c BA |
99 | break; |
100 | default: | |
7931e479 | 101 | const num = parseInt(position[i].charAt(j)); |
1d184b4c | 102 | if (!isNaN(num)) |
6037f1d8 | 103 | k += (num-1); |
1d184b4c | 104 | } |
6037f1d8 | 105 | k++; |
1d184b4c BA |
106 | } |
107 | } | |
0b7d99ec | 108 | const epSq = (this.moves.length > 0 ? this.getEpSquare(this.lastMove) : undefined); |
1d184b4c | 109 | this.epSquares = [ epSq ]; |
1d184b4c BA |
110 | } |
111 | ||
7931e479 BA |
112 | // Check if FEN describe a position |
113 | static IsGoodFen(fen) | |
114 | { | |
115 | const fenParts = fen.split(" "); | |
116 | if (fenParts.length== 0 || fenParts.length > 3) | |
117 | return false; | |
118 | // 1) Check position | |
119 | const position = fenParts[0]; | |
120 | const rows = position.split("/"); | |
121 | if (rows.length != V.size.x) | |
122 | return false; | |
123 | for (let row of rows) | |
124 | { | |
125 | let sumElts = 0; | |
126 | for (let i=0; i<row.length; i++) | |
127 | { | |
128 | if (V.PIECES.includes(row[i].toLowerCase())) | |
129 | sumElts++; | |
130 | else | |
131 | { | |
132 | const num = parseInt(row[i]); | |
133 | if (isNaN(num)) | |
134 | return false; | |
135 | sumElts += num; | |
136 | } | |
137 | } | |
138 | if (sumElts != V.size.y) | |
139 | return false; | |
140 | } | |
141 | // 2) Check flags (if present) | |
142 | if (fenParts.length >= 2) | |
143 | { | |
144 | if (!V.IsGoodFlags(fenParts[1])) | |
145 | return false; | |
146 | } | |
147 | // 3) Check turn (if present) | |
148 | if (fenParts.length == 3) | |
149 | { | |
150 | if (!["w","b"].includes(fenParts[2])) | |
151 | return false; | |
152 | } | |
153 | return true; | |
154 | } | |
155 | ||
156 | // For FEN checking | |
157 | static IsGoodFlags(flags) | |
158 | { | |
159 | return !!flags.match(/^[01]{4,4}$/); | |
160 | } | |
161 | ||
1d184b4c BA |
162 | // Turn diagram fen into double array ["wb","wp","bk",...] |
163 | static GetBoard(fen) | |
164 | { | |
7931e479 | 165 | const rows = fen.split(" ")[0].split("/"); |
0b7d99ec | 166 | let board = doubleArray(V.size.x, V.size.y, ""); |
1d184b4c BA |
167 | for (let i=0; i<rows.length; i++) |
168 | { | |
169 | let j = 0; | |
170 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) | |
171 | { | |
7931e479 BA |
172 | const character = rows[i][indexInRow]; |
173 | const num = parseInt(character); | |
1d184b4c BA |
174 | if (!isNaN(num)) |
175 | j += num; //just shift j | |
176 | else //something at position i,j | |
0b7d99ec | 177 | board[i][j++] = V.fen2board(character); |
1d184b4c BA |
178 | } |
179 | } | |
180 | return board; | |
181 | } | |
182 | ||
dda21a71 | 183 | // Extract (relevant) flags from fen |
7931e479 | 184 | setFlags(fenflags) |
1d184b4c BA |
185 | { |
186 | // white a-castle, h-castle, black a-castle, h-castle | |
7931e479 BA |
187 | this.castleFlags = {'w': [true,true], 'b': [true,true]}; |
188 | if (!fenflags) | |
189 | return; | |
1d184b4c | 190 | for (let i=0; i<4; i++) |
7931e479 BA |
191 | this.castleFlags[i < 2 ? 'w' : 'b'][i%2] = (fenflags.charAt(i) == '1'); |
192 | } | |
193 | ||
194 | // Initialize turn (white or black) | |
195 | setTurn(turnflag) | |
196 | { | |
197 | this.turn = turnflag || "w"; | |
1d184b4c BA |
198 | } |
199 | ||
200 | /////////////////// | |
201 | // GETTERS, SETTERS | |
202 | ||
0b7d99ec BA |
203 | static get size() { return {x:8, y:8}; } |
204 | ||
1d184b4c BA |
205 | // Two next functions return 'undefined' if called on empty square |
206 | getColor(i,j) { return this.board[i][j].charAt(0); } | |
207 | getPiece(i,j) { return this.board[i][j].charAt(1); } | |
208 | ||
209 | // Color | |
0b7d99ec | 210 | getOppCol(color) { return (color=="w" ? "b" : "w"); } |
1d184b4c BA |
211 | |
212 | get lastMove() { | |
213 | const L = this.moves.length; | |
0b7d99ec | 214 | return (L>0 ? this.moves[L-1] : null); |
1d184b4c | 215 | } |
0b7d99ec | 216 | |
1d184b4c BA |
217 | // Pieces codes |
218 | static get PAWN() { return 'p'; } | |
219 | static get ROOK() { return 'r'; } | |
220 | static get KNIGHT() { return 'n'; } | |
221 | static get BISHOP() { return 'b'; } | |
222 | static get QUEEN() { return 'q'; } | |
223 | static get KING() { return 'k'; } | |
224 | ||
7931e479 BA |
225 | // For FEN checking: |
226 | static get PIECES() { | |
227 | return [V.PAWN,V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN,V.KING]; | |
228 | } | |
229 | ||
1d184b4c BA |
230 | // Empty square |
231 | static get EMPTY() { return ''; } | |
232 | ||
233 | // Some pieces movements | |
234 | static get steps() { | |
235 | return { | |
236 | 'r': [ [-1,0],[1,0],[0,-1],[0,1] ], | |
237 | 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ], | |
238 | 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ], | |
1d184b4c BA |
239 | }; |
240 | } | |
241 | ||
2526c041 BA |
242 | // Aggregates flags into one object |
243 | get flags() { | |
244 | return this.castleFlags; | |
245 | } | |
246 | ||
247 | // Reverse operation | |
248 | parseFlags(flags) | |
249 | { | |
250 | this.castleFlags = flags; | |
251 | } | |
252 | ||
1d184b4c BA |
253 | // En-passant square, if any |
254 | getEpSquare(move) | |
255 | { | |
256 | const [sx,sy,ex] = [move.start.x,move.start.y,move.end.x]; | |
0b7d99ec | 257 | if (this.getPiece(sx,sy) == V.PAWN && Math.abs(sx - ex) == 2) |
1d184b4c BA |
258 | { |
259 | return { | |
260 | x: (sx + ex)/2, | |
261 | y: sy | |
262 | }; | |
263 | } | |
264 | return undefined; //default | |
265 | } | |
266 | ||
dda21a71 | 267 | // Can thing on square1 take thing on square2 |
46302e64 | 268 | canTake([x1,y1], [x2,y2]) |
1d184b4c | 269 | { |
0b7d99ec | 270 | return this.getColor(x1,y1) !== this.getColor(x2,y2); |
1d184b4c BA |
271 | } |
272 | ||
273 | /////////////////// | |
274 | // MOVES GENERATION | |
275 | ||
276 | // All possible moves from selected square (assumption: color is OK) | |
277 | getPotentialMovesFrom([x,y]) | |
278 | { | |
1d184b4c BA |
279 | switch (this.getPiece(x,y)) |
280 | { | |
0b7d99ec | 281 | case V.PAWN: |
46302e64 | 282 | return this.getPotentialPawnMoves([x,y]); |
0b7d99ec | 283 | case V.ROOK: |
46302e64 | 284 | return this.getPotentialRookMoves([x,y]); |
0b7d99ec | 285 | case V.KNIGHT: |
46302e64 | 286 | return this.getPotentialKnightMoves([x,y]); |
0b7d99ec | 287 | case V.BISHOP: |
46302e64 | 288 | return this.getPotentialBishopMoves([x,y]); |
0b7d99ec | 289 | case V.QUEEN: |
46302e64 | 290 | return this.getPotentialQueenMoves([x,y]); |
0b7d99ec | 291 | case V.KING: |
46302e64 | 292 | return this.getPotentialKingMoves([x,y]); |
1d184b4c BA |
293 | } |
294 | } | |
295 | ||
296 | // Build a regular move from its initial and destination squares; tr: transformation | |
46302e64 | 297 | getBasicMove([sx,sy], [ex,ey], tr) |
1d184b4c | 298 | { |
2526c041 | 299 | let mv = new Move({ |
1d184b4c BA |
300 | appear: [ |
301 | new PiPo({ | |
302 | x: ex, | |
303 | y: ey, | |
46302e64 BA |
304 | c: !!tr ? tr.c : this.getColor(sx,sy), |
305 | p: !!tr ? tr.p : this.getPiece(sx,sy) | |
1d184b4c BA |
306 | }) |
307 | ], | |
308 | vanish: [ | |
309 | new PiPo({ | |
310 | x: sx, | |
311 | y: sy, | |
312 | c: this.getColor(sx,sy), | |
313 | p: this.getPiece(sx,sy) | |
314 | }) | |
315 | ] | |
316 | }); | |
317 | ||
318 | // The opponent piece disappears if we take it | |
0b7d99ec | 319 | if (this.board[ex][ey] != V.EMPTY) |
1d184b4c BA |
320 | { |
321 | mv.vanish.push( | |
322 | new PiPo({ | |
323 | x: ex, | |
324 | y: ey, | |
325 | c: this.getColor(ex,ey), | |
326 | p: this.getPiece(ex,ey) | |
327 | }) | |
328 | ); | |
329 | } | |
330 | return mv; | |
331 | } | |
332 | ||
0b7d99ec BA |
333 | // Is (x,y) on the chessboard? |
334 | static OnBoard(x,y) | |
335 | { | |
336 | return (x>=0 && x<V.size.x && y>=0 && y<V.size.y); | |
337 | } | |
338 | ||
1d184b4c | 339 | // Generic method to find possible moves of non-pawn pieces ("sliding or jumping") |
46302e64 | 340 | getSlideNJumpMoves([x,y], steps, oneStep) |
1d184b4c | 341 | { |
46302e64 | 342 | const color = this.getColor(x,y); |
2526c041 | 343 | let moves = []; |
1d184b4c BA |
344 | outerLoop: |
345 | for (let step of steps) | |
346 | { | |
46302e64 BA |
347 | let i = x + step[0]; |
348 | let j = y + step[1]; | |
0b7d99ec | 349 | while (V.OnBoard(i,j) && this.board[i][j] == V.EMPTY) |
1d184b4c | 350 | { |
46302e64 | 351 | moves.push(this.getBasicMove([x,y], [i,j])); |
1d184b4c BA |
352 | if (oneStep !== undefined) |
353 | continue outerLoop; | |
354 | i += step[0]; | |
355 | j += step[1]; | |
356 | } | |
0b7d99ec | 357 | if (V.OnBoard(i,j) && this.canTake([x,y], [i,j])) |
46302e64 | 358 | moves.push(this.getBasicMove([x,y], [i,j])); |
1d184b4c BA |
359 | } |
360 | return moves; | |
361 | } | |
362 | ||
dda21a71 | 363 | // What are the pawn moves from square x,y ? |
46302e64 | 364 | getPotentialPawnMoves([x,y]) |
1d184b4c | 365 | { |
2526c041 BA |
366 | const color = this.turn; |
367 | let moves = []; | |
0b7d99ec | 368 | const [sizeX,sizeY] = [V.size.x,V.size.y]; |
2526c041 | 369 | const shift = (color == "w" ? -1 : 1); |
cf130369 BA |
370 | const firstRank = (color == 'w' ? sizeX-1 : 0); |
371 | const startRank = (color == "w" ? sizeX-2 : 1); | |
372 | const lastRank = (color == "w" ? 0 : sizeX-1); | |
1d184b4c BA |
373 | |
374 | if (x+shift >= 0 && x+shift < sizeX && x+shift != lastRank) | |
375 | { | |
376 | // Normal moves | |
377 | if (this.board[x+shift][y] == V.EMPTY) | |
378 | { | |
46302e64 | 379 | moves.push(this.getBasicMove([x,y], [x+shift,y])); |
1221ac47 | 380 | // Next condition because variants with pawns on 1st rank allow them to jump |
2526c041 | 381 | if ([startRank,firstRank].includes(x) && this.board[x+2*shift][y] == V.EMPTY) |
1d184b4c BA |
382 | { |
383 | // Two squares jump | |
46302e64 | 384 | moves.push(this.getBasicMove([x,y], [x+2*shift,y])); |
1d184b4c BA |
385 | } |
386 | } | |
387 | // Captures | |
0b7d99ec BA |
388 | if (y>0 && this.board[x+shift][y-1] != V.EMPTY |
389 | && this.canTake([x,y], [x+shift,y-1])) | |
1221ac47 | 390 | { |
46302e64 | 391 | moves.push(this.getBasicMove([x,y], [x+shift,y-1])); |
1221ac47 | 392 | } |
0b7d99ec BA |
393 | if (y<sizeY-1 && this.board[x+shift][y+1] != V.EMPTY |
394 | && this.canTake([x,y], [x+shift,y+1])) | |
1221ac47 | 395 | { |
46302e64 | 396 | moves.push(this.getBasicMove([x,y], [x+shift,y+1])); |
1221ac47 | 397 | } |
1d184b4c BA |
398 | } |
399 | ||
400 | if (x+shift == lastRank) | |
401 | { | |
402 | // Promotion | |
68f5ccc8 | 403 | const pawnColor = this.getColor(x,y); //can be different for checkered |
1d184b4c BA |
404 | let promotionPieces = [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN]; |
405 | promotionPieces.forEach(p => { | |
406 | // Normal move | |
407 | if (this.board[x+shift][y] == V.EMPTY) | |
68f5ccc8 | 408 | moves.push(this.getBasicMove([x,y], [x+shift,y], {c:pawnColor,p:p})); |
1d184b4c | 409 | // Captures |
0b7d99ec BA |
410 | if (y>0 && this.board[x+shift][y-1] != V.EMPTY |
411 | && this.canTake([x,y], [x+shift,y-1])) | |
1221ac47 | 412 | { |
68f5ccc8 | 413 | moves.push(this.getBasicMove([x,y], [x+shift,y-1], {c:pawnColor,p:p})); |
1221ac47 | 414 | } |
0b7d99ec BA |
415 | if (y<sizeY-1 && this.board[x+shift][y+1] != V.EMPTY |
416 | && this.canTake([x,y], [x+shift,y+1])) | |
1221ac47 | 417 | { |
68f5ccc8 | 418 | moves.push(this.getBasicMove([x,y], [x+shift,y+1], {c:pawnColor,p:p})); |
1221ac47 | 419 | } |
1d184b4c BA |
420 | }); |
421 | } | |
422 | ||
423 | // En passant | |
424 | const Lep = this.epSquares.length; | |
0b7d99ec | 425 | const epSquare = (Lep>0 ? this.epSquares[Lep-1] : undefined); |
1d184b4c BA |
426 | if (!!epSquare && epSquare.x == x+shift && Math.abs(epSquare.y - y) == 1) |
427 | { | |
0b7d99ec BA |
428 | const epStep = epSquare.y - y; |
429 | let enpassantMove = this.getBasicMove([x,y], [x+shift,y+epStep]); | |
1d184b4c BA |
430 | enpassantMove.vanish.push({ |
431 | x: x, | |
432 | y: y+epStep, | |
433 | p: 'p', | |
434 | c: this.getColor(x,y+epStep) | |
435 | }); | |
436 | moves.push(enpassantMove); | |
437 | } | |
438 | ||
439 | return moves; | |
440 | } | |
441 | ||
442 | // What are the rook moves from square x,y ? | |
46302e64 | 443 | getPotentialRookMoves(sq) |
1d184b4c | 444 | { |
0b7d99ec | 445 | return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]); |
1d184b4c BA |
446 | } |
447 | ||
448 | // What are the knight moves from square x,y ? | |
46302e64 | 449 | getPotentialKnightMoves(sq) |
1d184b4c | 450 | { |
0b7d99ec | 451 | return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"); |
1d184b4c BA |
452 | } |
453 | ||
454 | // What are the bishop moves from square x,y ? | |
46302e64 | 455 | getPotentialBishopMoves(sq) |
1d184b4c | 456 | { |
0b7d99ec | 457 | return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]); |
1d184b4c BA |
458 | } |
459 | ||
460 | // What are the queen moves from square x,y ? | |
46302e64 | 461 | getPotentialQueenMoves(sq) |
1d184b4c | 462 | { |
a37076f1 | 463 | return this.getSlideNJumpMoves(sq, V.steps[V.ROOK].concat(V.steps[V.BISHOP])); |
1d184b4c BA |
464 | } |
465 | ||
466 | // What are the king moves from square x,y ? | |
46302e64 | 467 | getPotentialKingMoves(sq) |
1d184b4c BA |
468 | { |
469 | // Initialize with normal moves | |
a37076f1 BA |
470 | let moves = this.getSlideNJumpMoves(sq, |
471 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep"); | |
46302e64 | 472 | return moves.concat(this.getCastleMoves(sq)); |
1d184b4c BA |
473 | } |
474 | ||
46302e64 | 475 | getCastleMoves([x,y]) |
1d184b4c | 476 | { |
46302e64 | 477 | const c = this.getColor(x,y); |
0b7d99ec | 478 | if (x != (c=="w" ? V.size.x-1 : 0) || y != this.INIT_COL_KING[c]) |
1d184b4c BA |
479 | return []; //x isn't first rank, or king has moved (shortcut) |
480 | ||
1d184b4c BA |
481 | // Castling ? |
482 | const oppCol = this.getOppCol(c); | |
483 | let moves = []; | |
484 | let i = 0; | |
0b7d99ec | 485 | const finalSquares = [ [2,3], [V.size.y-2,V.size.y-3] ]; //king, then rook |
1d184b4c BA |
486 | castlingCheck: |
487 | for (let castleSide=0; castleSide < 2; castleSide++) //large, then small | |
488 | { | |
2526c041 | 489 | if (!this.castleFlags[c][castleSide]) |
1d184b4c BA |
490 | continue; |
491 | // If this code is reached, rooks and king are on initial position | |
492 | ||
493 | // Nothing on the path of the king (and no checks; OK also if y==finalSquare)? | |
494 | let step = finalSquares[castleSide][0] < y ? -1 : 1; | |
495 | for (i=y; i!=finalSquares[castleSide][0]; i+=step) | |
496 | { | |
cf130369 | 497 | if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY && |
1d184b4c BA |
498 | // NOTE: next check is enough, because of chessboard constraints |
499 | (this.getColor(x,i) != c || ![V.KING,V.ROOK].includes(this.getPiece(x,i))))) | |
500 | { | |
501 | continue castlingCheck; | |
502 | } | |
503 | } | |
504 | ||
505 | // Nothing on the path to the rook? | |
506 | step = castleSide == 0 ? -1 : 1; | |
507 | for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) | |
508 | { | |
509 | if (this.board[x][i] != V.EMPTY) | |
510 | continue castlingCheck; | |
511 | } | |
512 | const rookPos = this.INIT_COL_ROOK[c][castleSide]; | |
513 | ||
514 | // Nothing on final squares, except maybe king and castling rook? | |
515 | for (i=0; i<2; i++) | |
516 | { | |
517 | if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY && | |
518 | this.getPiece(x,finalSquares[castleSide][i]) != V.KING && | |
519 | finalSquares[castleSide][i] != rookPos) | |
520 | { | |
521 | continue castlingCheck; | |
522 | } | |
523 | } | |
524 | ||
525 | // If this code is reached, castle is valid | |
526 | moves.push( new Move({ | |
527 | appear: [ | |
528 | new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}), | |
529 | new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})], | |
530 | vanish: [ | |
531 | new PiPo({x:x,y:y,p:V.KING,c:c}), | |
532 | new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})], | |
533 | end: Math.abs(y - rookPos) <= 2 | |
534 | ? {x:x, y:rookPos} | |
535 | : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)} | |
536 | }) ); | |
537 | } | |
538 | ||
539 | return moves; | |
540 | } | |
541 | ||
542 | /////////////////// | |
543 | // MOVES VALIDATION | |
544 | ||
46302e64 | 545 | canIplay(side, [x,y]) |
1d184b4c | 546 | { |
7931e479 | 547 | return (this.turn == side && this.getColor(x,y) == side); |
1d184b4c BA |
548 | } |
549 | ||
550 | getPossibleMovesFrom(sq) | |
551 | { | |
552 | // Assuming color is right (already checked) | |
553 | return this.filterValid( this.getPotentialMovesFrom(sq) ); | |
554 | } | |
555 | ||
92342261 | 556 | // TODO: promotions (into R,B,N,Q) should be filtered only once |
1d184b4c BA |
557 | filterValid(moves) |
558 | { | |
559 | if (moves.length == 0) | |
560 | return []; | |
b8121223 | 561 | return moves.filter(m => { return !this.underCheck(m); }); |
1d184b4c BA |
562 | } |
563 | ||
564 | // Search for all valid moves considering current turn (for engine and game end) | |
46302e64 | 565 | getAllValidMoves() |
1d184b4c | 566 | { |
46302e64 | 567 | const color = this.turn; |
1d184b4c | 568 | const oppCol = this.getOppCol(color); |
c6052161 | 569 | let potentialMoves = []; |
0b7d99ec | 570 | for (let i=0; i<V.size.x; i++) |
1d184b4c | 571 | { |
0b7d99ec | 572 | for (let j=0; j<V.size.y; j++) |
1d184b4c | 573 | { |
92342261 | 574 | // Next condition "!= oppCol" = harmless hack to work with checkered variant |
0b7d99ec | 575 | if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol) |
1d184b4c BA |
576 | Array.prototype.push.apply(potentialMoves, this.getPotentialMovesFrom([i,j])); |
577 | } | |
578 | } | |
579 | // NOTE: prefer lazy undercheck tests, letting the king being taken? | |
580 | // No: if happen on last 1/2 move, could lead to forbidden moves, wrong evals | |
581 | return this.filterValid(potentialMoves); | |
582 | } | |
9de73b71 | 583 | |
e64a4eff | 584 | // Stop at the first move found |
46302e64 | 585 | atLeastOneMove() |
e64a4eff | 586 | { |
46302e64 | 587 | const color = this.turn; |
e64a4eff | 588 | const oppCol = this.getOppCol(color); |
0b7d99ec | 589 | for (let i=0; i<V.size.x; i++) |
e64a4eff | 590 | { |
0b7d99ec | 591 | for (let j=0; j<V.size.y; j++) |
e64a4eff | 592 | { |
0b7d99ec | 593 | if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol) |
e64a4eff BA |
594 | { |
595 | const moves = this.getPotentialMovesFrom([i,j]); | |
596 | if (moves.length > 0) | |
597 | { | |
9de73b71 | 598 | for (let k=0; k<moves.length; k++) |
e64a4eff | 599 | { |
9de73b71 | 600 | if (this.filterValid([moves[k]]).length > 0) |
e64a4eff BA |
601 | return true; |
602 | } | |
603 | } | |
604 | } | |
605 | } | |
606 | } | |
607 | return false; | |
608 | } | |
1d184b4c | 609 | |
dda21a71 | 610 | // Check if pieces of color in array 'colors' are attacking square x,y |
46302e64 | 611 | isAttacked(sq, colors) |
1d184b4c | 612 | { |
46302e64 BA |
613 | return (this.isAttackedByPawn(sq, colors) |
614 | || this.isAttackedByRook(sq, colors) | |
615 | || this.isAttackedByKnight(sq, colors) | |
616 | || this.isAttackedByBishop(sq, colors) | |
617 | || this.isAttackedByQueen(sq, colors) | |
618 | || this.isAttackedByKing(sq, colors)); | |
1d184b4c BA |
619 | } |
620 | ||
dda21a71 | 621 | // Is square x,y attacked by 'colors' pawns ? |
46302e64 | 622 | isAttackedByPawn([x,y], colors) |
1d184b4c | 623 | { |
46302e64 | 624 | for (let c of colors) |
1d184b4c | 625 | { |
46302e64 | 626 | let pawnShift = (c=="w" ? 1 : -1); |
0b7d99ec | 627 | if (x+pawnShift>=0 && x+pawnShift<V.size.x) |
1d184b4c | 628 | { |
46302e64 | 629 | for (let i of [-1,1]) |
1d184b4c | 630 | { |
0b7d99ec | 631 | if (y+i>=0 && y+i<V.size.y && this.getPiece(x+pawnShift,y+i)==V.PAWN |
46302e64 BA |
632 | && this.getColor(x+pawnShift,y+i)==c) |
633 | { | |
634 | return true; | |
635 | } | |
1d184b4c BA |
636 | } |
637 | } | |
638 | } | |
639 | return false; | |
640 | } | |
641 | ||
dda21a71 | 642 | // Is square x,y attacked by 'colors' rooks ? |
46302e64 | 643 | isAttackedByRook(sq, colors) |
1d184b4c | 644 | { |
0b7d99ec | 645 | return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]); |
1d184b4c BA |
646 | } |
647 | ||
dda21a71 | 648 | // Is square x,y attacked by 'colors' knights ? |
46302e64 | 649 | isAttackedByKnight(sq, colors) |
1d184b4c | 650 | { |
46302e64 | 651 | return this.isAttackedBySlideNJump(sq, colors, |
0b7d99ec | 652 | V.KNIGHT, V.steps[V.KNIGHT], "oneStep"); |
1d184b4c BA |
653 | } |
654 | ||
dda21a71 | 655 | // Is square x,y attacked by 'colors' bishops ? |
46302e64 | 656 | isAttackedByBishop(sq, colors) |
1d184b4c | 657 | { |
0b7d99ec | 658 | return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]); |
1d184b4c BA |
659 | } |
660 | ||
dda21a71 | 661 | // Is square x,y attacked by 'colors' queens ? |
46302e64 | 662 | isAttackedByQueen(sq, colors) |
1d184b4c | 663 | { |
a37076f1 BA |
664 | return this.isAttackedBySlideNJump(sq, colors, V.QUEEN, |
665 | V.steps[V.ROOK].concat(V.steps[V.BISHOP])); | |
1d184b4c BA |
666 | } |
667 | ||
dda21a71 | 668 | // Is square x,y attacked by 'colors' king(s) ? |
46302e64 | 669 | isAttackedByKing(sq, colors) |
1d184b4c | 670 | { |
a37076f1 BA |
671 | return this.isAttackedBySlideNJump(sq, colors, V.KING, |
672 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep"); | |
1d184b4c BA |
673 | } |
674 | ||
1221ac47 | 675 | // Generic method for non-pawn pieces ("sliding or jumping"): |
dda21a71 | 676 | // is x,y attacked by a piece of color in array 'colors' ? |
46302e64 | 677 | isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep) |
1d184b4c BA |
678 | { |
679 | for (let step of steps) | |
680 | { | |
681 | let rx = x+step[0], ry = y+step[1]; | |
0b7d99ec | 682 | while (V.OnBoard(rx,ry) && this.board[rx][ry] == V.EMPTY && !oneStep) |
1d184b4c BA |
683 | { |
684 | rx += step[0]; | |
685 | ry += step[1]; | |
686 | } | |
0b7d99ec BA |
687 | if (V.OnBoard(rx,ry) && this.getPiece(rx,ry) === piece |
688 | && colors.includes(this.getColor(rx,ry))) | |
1d184b4c BA |
689 | { |
690 | return true; | |
691 | } | |
692 | } | |
693 | return false; | |
694 | } | |
695 | ||
dda21a71 | 696 | // Is current player under check after his move ? |
46302e64 | 697 | underCheck(move) |
1d184b4c | 698 | { |
46302e64 | 699 | const color = this.turn; |
1d184b4c | 700 | this.play(move); |
cf130369 | 701 | let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]); |
1d184b4c BA |
702 | this.undo(move); |
703 | return res; | |
704 | } | |
705 | ||
dda21a71 | 706 | // On which squares is opponent under check after our move ? |
46302e64 | 707 | getCheckSquares(move) |
4b5fe306 BA |
708 | { |
709 | this.play(move); | |
204e289b | 710 | const color = this.turn; //opponent |
cf130369 | 711 | let res = this.isAttacked(this.kingPos[color], [this.getOppCol(color)]) |
46302e64 | 712 | ? [ JSON.parse(JSON.stringify(this.kingPos[color])) ] //need to duplicate! |
4b5fe306 BA |
713 | : [ ]; |
714 | this.undo(move); | |
715 | return res; | |
716 | } | |
717 | ||
1d184b4c BA |
718 | // Apply a move on board |
719 | static PlayOnBoard(board, move) | |
720 | { | |
721 | for (let psq of move.vanish) | |
0b7d99ec | 722 | board[psq.x][psq.y] = V.EMPTY; |
1d184b4c BA |
723 | for (let psq of move.appear) |
724 | board[psq.x][psq.y] = psq.c + psq.p; | |
725 | } | |
726 | // Un-apply the played move | |
727 | static UndoOnBoard(board, move) | |
728 | { | |
729 | for (let psq of move.appear) | |
0b7d99ec | 730 | board[psq.x][psq.y] = V.EMPTY; |
1d184b4c BA |
731 | for (let psq of move.vanish) |
732 | board[psq.x][psq.y] = psq.c + psq.p; | |
733 | } | |
734 | ||
d3334c3a | 735 | // Before move is played, update variables + flags |
1d184b4c BA |
736 | updateVariables(move) |
737 | { | |
738 | const piece = this.getPiece(move.start.x,move.start.y); | |
0b7d99ec BA |
739 | const c = this.turn; |
740 | const firstRank = (c == "w" ? V.size.x-1 : 0); | |
1d184b4c BA |
741 | |
742 | // Update king position + flags | |
0b7d99ec | 743 | if (piece == V.KING && move.appear.length > 0) |
1d184b4c BA |
744 | { |
745 | this.kingPos[c][0] = move.appear[0].x; | |
746 | this.kingPos[c][1] = move.appear[0].y; | |
2526c041 | 747 | this.castleFlags[c] = [false,false]; |
1d184b4c BA |
748 | return; |
749 | } | |
750 | const oppCol = this.getOppCol(c); | |
0b7d99ec | 751 | const oppFirstRank = (V.size.x-1) - firstRank; |
1d184b4c BA |
752 | if (move.start.x == firstRank //our rook moves? |
753 | && this.INIT_COL_ROOK[c].includes(move.start.y)) | |
754 | { | |
2526c041 BA |
755 | const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1); |
756 | this.castleFlags[c][flagIdx] = false; | |
1d184b4c BA |
757 | } |
758 | else if (move.end.x == oppFirstRank //we took opponent rook? | |
aea1443e | 759 | && this.INIT_COL_ROOK[oppCol].includes(move.end.y)) |
1d184b4c | 760 | { |
2526c041 BA |
761 | const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1); |
762 | this.castleFlags[oppCol][flagIdx] = false; | |
1d184b4c BA |
763 | } |
764 | } | |
765 | ||
dda21a71 BA |
766 | // After move is undo-ed, un-update variables (flags are reset) |
767 | // TODO: more symmetry, by storing flags increment in move... | |
d3334c3a | 768 | unupdateVariables(move) |
1d184b4c | 769 | { |
d3334c3a BA |
770 | // (Potentially) Reset king position |
771 | const c = this.getColor(move.start.x,move.start.y); | |
0b7d99ec | 772 | if (this.getPiece(move.start.x,move.start.y) == V.KING) |
d3334c3a BA |
773 | this.kingPos[c] = [move.start.x, move.start.y]; |
774 | } | |
1d184b4c | 775 | |
15c1295a BA |
776 | // Hash of position+flags+turn after a move is played (to detect repetitions) |
777 | getHashState() | |
331fc58c | 778 | { |
7931e479 | 779 | return hex_md5(this.getFen()); |
331fc58c BA |
780 | } |
781 | ||
d3334c3a BA |
782 | play(move, ingame) |
783 | { | |
a3c86ec9 BA |
784 | // DEBUG: |
785 | // if (!this.states) this.states = []; | |
786 | // if (!ingame) this.states.push(JSON.stringify(this.board)); | |
787 | ||
dfb4afc1 | 788 | if (!!ingame) |
6752407b | 789 | move.notation = [this.getNotation(move), this.getLongNotation(move)]; |
dfb4afc1 | 790 | |
2526c041 | 791 | move.flags = JSON.stringify(this.flags); //save flags (for undo) |
d3334c3a BA |
792 | this.updateVariables(move); |
793 | this.moves.push(move); | |
1d184b4c | 794 | this.epSquares.push( this.getEpSquare(move) ); |
0b7d99ec | 795 | V.PlayOnBoard(this.board, move); |
331fc58c BA |
796 | |
797 | if (!!ingame) | |
15c1295a | 798 | move.hash = this.getHashState(); |
1d184b4c BA |
799 | } |
800 | ||
cd4cad04 | 801 | undo(move) |
1d184b4c | 802 | { |
0b7d99ec | 803 | V.UndoOnBoard(this.board, move); |
1d184b4c | 804 | this.epSquares.pop(); |
d3334c3a BA |
805 | this.moves.pop(); |
806 | this.unupdateVariables(move); | |
2526c041 | 807 | this.parseFlags(JSON.parse(move.flags)); |
a3c86ec9 BA |
808 | |
809 | // DEBUG: | |
810 | // if (JSON.stringify(this.board) != this.states[this.states.length-1]) | |
811 | // debugger; | |
812 | // this.states.pop(); | |
1d184b4c BA |
813 | } |
814 | ||
815 | ////////////// | |
816 | // END OF GAME | |
817 | ||
331fc58c | 818 | // Check for 3 repetitions (position + flags + turn) |
1af36beb | 819 | checkRepetition() |
1d184b4c | 820 | { |
15c1295a BA |
821 | if (!this.hashStates) |
822 | this.hashStates = {}; | |
823 | const startIndex = | |
824 | Object.values(this.hashStates).reduce((a,b) => { return a+b; }, 0) | |
825 | // Update this.hashStates with last move (or all moves if continuation) | |
826 | // NOTE: redundant storage, but faster and moderate size | |
827 | for (let i=startIndex; i<this.moves.length; i++) | |
828 | { | |
829 | const move = this.moves[i]; | |
830 | if (!this.hashStates[move.hash]) | |
831 | this.hashStates[move.hash] = 1; | |
832 | else | |
833 | this.hashStates[move.hash]++; | |
834 | } | |
331fc58c | 835 | return Object.values(this.hashStates).some(elt => { return (elt >= 3); }); |
1af36beb | 836 | } |
1d184b4c | 837 | |
dda21a71 | 838 | // Is game over ? And if yes, what is the score ? |
1af36beb BA |
839 | checkGameOver() |
840 | { | |
841 | if (this.checkRepetition()) | |
842 | return "1/2"; | |
843 | ||
844 | if (this.atLeastOneMove()) // game not over | |
1d184b4c | 845 | return "*"; |
1d184b4c BA |
846 | |
847 | // Game over | |
46302e64 | 848 | return this.checkGameEnd(); |
1d184b4c BA |
849 | } |
850 | ||
46302e64 BA |
851 | // No moves are possible: compute score |
852 | checkGameEnd() | |
1d184b4c | 853 | { |
46302e64 | 854 | const color = this.turn; |
1d184b4c | 855 | // No valid move: stalemate or checkmate? |
cf130369 | 856 | if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)])) |
1d184b4c BA |
857 | return "1/2"; |
858 | // OK, checkmate | |
859 | return color == "w" ? "0-1" : "1-0"; | |
860 | } | |
861 | ||
862 | //////// | |
863 | //ENGINE | |
864 | ||
865 | // Pieces values | |
866 | static get VALUES() { | |
867 | return { | |
868 | 'p': 1, | |
869 | 'r': 5, | |
870 | 'n': 3, | |
871 | 'b': 3, | |
872 | 'q': 9, | |
873 | 'k': 1000 | |
874 | }; | |
875 | } | |
876 | ||
9e42b4dd BA |
877 | static get INFINITY() { |
878 | return 9999; //"checkmate" (unreachable eval) | |
879 | } | |
880 | ||
881 | static get THRESHOLD_MATE() { | |
882 | // At this value or above, the game is over | |
0b7d99ec | 883 | return V.INFINITY; |
9e42b4dd BA |
884 | } |
885 | ||
3c09dc49 BA |
886 | static get SEARCH_DEPTH() { |
887 | return 3; //2 for high branching factor, 4 for small (Loser chess) | |
888 | } | |
889 | ||
1d184b4c | 890 | // Assumption: at least one legal move |
a6abf094 BA |
891 | // NOTE: works also for extinction chess because depth is 3... |
892 | getComputerMove() | |
1d184b4c | 893 | { |
0b7d99ec | 894 | const maxeval = V.INFINITY; |
46302e64 | 895 | const color = this.turn; |
15952ada BA |
896 | // Some variants may show a bigger moves list to the human (Switching), |
897 | // thus the argument "computer" below (which is generally ignored) | |
898 | let moves1 = this.getAllValidMoves("computer"); | |
a6abf094 BA |
899 | |
900 | // Can I mate in 1 ? (for Magnetic & Extinction) | |
901 | for (let i of _.shuffle(_.range(moves1.length))) | |
902 | { | |
903 | this.play(moves1[i]); | |
0b7d99ec BA |
904 | let finish = (Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE); |
905 | if (!finish && !this.atLeastOneMove()) | |
906 | { | |
907 | // Try mate (for other variants) | |
908 | const score = this.checkGameEnd(); | |
909 | if (score != "1/2") | |
910 | finish = true; | |
911 | } | |
a6abf094 BA |
912 | this.undo(moves1[i]); |
913 | if (finish) | |
914 | return moves1[i]; | |
915 | } | |
1d184b4c | 916 | |
06ddfe34 | 917 | // Rank moves using a min-max at depth 2 |
1d184b4c BA |
918 | for (let i=0; i<moves1.length; i++) |
919 | { | |
9e42b4dd | 920 | moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; //very low, I'm checkmated |
1d184b4c | 921 | this.play(moves1[i]); |
68f5ccc8 BA |
922 | let eval2 = undefined; |
923 | if (this.atLeastOneMove()) | |
1d184b4c | 924 | { |
68f5ccc8 BA |
925 | eval2 = (color=="w" ? 1 : -1) * maxeval; //initialized with checkmate value |
926 | // Second half-move: | |
15952ada | 927 | let moves2 = this.getAllValidMoves("computer"); |
68f5ccc8 BA |
928 | for (let j=0; j<moves2.length; j++) |
929 | { | |
930 | this.play(moves2[j]); | |
931 | let evalPos = undefined; | |
932 | if (this.atLeastOneMove()) | |
933 | evalPos = this.evalPosition() | |
934 | else | |
935 | { | |
936 | // Work with scores for Loser variant | |
937 | const score = this.checkGameEnd(); | |
938 | evalPos = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval); | |
939 | } | |
940 | if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2)) | |
941 | eval2 = evalPos; | |
942 | this.undo(moves2[j]); | |
943 | } | |
944 | } | |
945 | else | |
946 | { | |
947 | const score = this.checkGameEnd(); | |
948 | eval2 = (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval); | |
1d184b4c | 949 | } |
92342261 BA |
950 | if ((color=="w" && eval2 > moves1[i].eval) |
951 | || (color=="b" && eval2 < moves1[i].eval)) | |
952 | { | |
1d184b4c | 953 | moves1[i].eval = eval2; |
92342261 | 954 | } |
1d184b4c BA |
955 | this.undo(moves1[i]); |
956 | } | |
957 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
11a31682 | 958 | //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); |
1d184b4c | 959 | |
3c09dc49 BA |
960 | let candidates = [0]; //indices of candidates moves |
961 | for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++) | |
962 | candidates.push(j); | |
963 | let currentBest = moves1[_.sample(candidates, 1)]; | |
964 | ||
e82cd979 BA |
965 | // From here, depth >= 3: may take a while, so we control time |
966 | const timeStart = Date.now(); | |
967 | ||
a6abf094 | 968 | // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...) |
0b7d99ec | 969 | if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) |
e64a4eff | 970 | { |
9e42b4dd BA |
971 | for (let i=0; i<moves1.length; i++) |
972 | { | |
e82cd979 BA |
973 | if (Date.now()-timeStart >= 5000) //more than 5 seconds |
974 | return currentBest; //depth 2 at least | |
9e42b4dd BA |
975 | this.play(moves1[i]); |
976 | // 0.1 * oldEval : heuristic to avoid some bad moves (not all...) | |
3c09dc49 | 977 | moves1[i].eval = 0.1*moves1[i].eval + |
0b7d99ec | 978 | this.alphabeta(V.SEARCH_DEPTH-1, -maxeval, maxeval); |
9e42b4dd BA |
979 | this.undo(moves1[i]); |
980 | } | |
981 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
e64a4eff | 982 | } |
3c09dc49 BA |
983 | else |
984 | return currentBest; | |
68f5ccc8 | 985 | //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); |
1d184b4c | 986 | |
3c09dc49 | 987 | candidates = [0]; |
1d184b4c BA |
988 | for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++) |
989 | candidates.push(j); | |
1d184b4c BA |
990 | return moves1[_.sample(candidates, 1)]; |
991 | } | |
992 | ||
46302e64 | 993 | alphabeta(depth, alpha, beta) |
1d184b4c | 994 | { |
0b7d99ec | 995 | const maxeval = V.INFINITY; |
46302e64 BA |
996 | const color = this.turn; |
997 | if (!this.atLeastOneMove()) | |
1d184b4c | 998 | { |
46302e64 | 999 | switch (this.checkGameEnd()) |
1d184b4c | 1000 | { |
68f5ccc8 BA |
1001 | case "1/2": |
1002 | return 0; | |
1003 | default: | |
1004 | const score = this.checkGameEnd(); | |
1005 | return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval); | |
1d184b4c BA |
1006 | } |
1007 | } | |
1008 | if (depth == 0) | |
1009 | return this.evalPosition(); | |
15952ada | 1010 | const moves = this.getAllValidMoves("computer"); |
9e42b4dd | 1011 | let v = color=="w" ? -maxeval : maxeval; |
1d184b4c BA |
1012 | if (color == "w") |
1013 | { | |
1014 | for (let i=0; i<moves.length; i++) | |
1015 | { | |
1016 | this.play(moves[i]); | |
46302e64 | 1017 | v = Math.max(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
1018 | this.undo(moves[i]); |
1019 | alpha = Math.max(alpha, v); | |
1020 | if (alpha >= beta) | |
1021 | break; //beta cutoff | |
1022 | } | |
1023 | } | |
1024 | else //color=="b" | |
1025 | { | |
1026 | for (let i=0; i<moves.length; i++) | |
1027 | { | |
1028 | this.play(moves[i]); | |
46302e64 | 1029 | v = Math.min(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
1030 | this.undo(moves[i]); |
1031 | beta = Math.min(beta, v); | |
1032 | if (alpha >= beta) | |
1033 | break; //alpha cutoff | |
1034 | } | |
1035 | } | |
1036 | return v; | |
1037 | } | |
1038 | ||
1039 | evalPosition() | |
1040 | { | |
1d184b4c | 1041 | let evaluation = 0; |
a6abf094 | 1042 | // Just count material for now |
0b7d99ec | 1043 | for (let i=0; i<V.size.x; i++) |
1d184b4c | 1044 | { |
0b7d99ec | 1045 | for (let j=0; j<V.size.y; j++) |
1d184b4c | 1046 | { |
0b7d99ec | 1047 | if (this.board[i][j] != V.EMPTY) |
1d184b4c BA |
1048 | { |
1049 | const sign = this.getColor(i,j) == "w" ? 1 : -1; | |
0b7d99ec | 1050 | evaluation += sign * V.VALUES[this.getPiece(i,j)]; |
1d184b4c BA |
1051 | } |
1052 | } | |
1053 | } | |
1054 | return evaluation; | |
1055 | } | |
1056 | ||
1057 | //////////// | |
1058 | // FEN utils | |
1059 | ||
dda21a71 | 1060 | // Setup the initial random (assymetric) position |
1d184b4c BA |
1061 | static GenRandInitFen() |
1062 | { | |
32cfcea4 | 1063 | let pieces = { "w": new Array(8), "b": new Array(8) }; |
1d184b4c | 1064 | // Shuffle pieces on first and last rank |
32cfcea4 | 1065 | for (let c of ["w","b"]) |
1d184b4c BA |
1066 | { |
1067 | let positions = _.range(8); | |
1068 | ||
1069 | // Get random squares for bishops | |
1070 | let randIndex = 2 * _.random(3); | |
1071 | let bishop1Pos = positions[randIndex]; | |
1072 | // The second bishop must be on a square of different color | |
1073 | let randIndex_tmp = 2 * _.random(3) + 1; | |
1074 | let bishop2Pos = positions[randIndex_tmp]; | |
1075 | // Remove chosen squares | |
1076 | positions.splice(Math.max(randIndex,randIndex_tmp), 1); | |
1077 | positions.splice(Math.min(randIndex,randIndex_tmp), 1); | |
1078 | ||
1079 | // Get random squares for knights | |
1080 | randIndex = _.random(5); | |
1081 | let knight1Pos = positions[randIndex]; | |
1082 | positions.splice(randIndex, 1); | |
1083 | randIndex = _.random(4); | |
1084 | let knight2Pos = positions[randIndex]; | |
1085 | positions.splice(randIndex, 1); | |
1086 | ||
1087 | // Get random square for queen | |
1088 | randIndex = _.random(3); | |
1089 | let queenPos = positions[randIndex]; | |
1090 | positions.splice(randIndex, 1); | |
1091 | ||
1092 | // Rooks and king positions are now fixed, because of the ordering rook-king-rook | |
1093 | let rook1Pos = positions[0]; | |
1094 | let kingPos = positions[1]; | |
1095 | let rook2Pos = positions[2]; | |
1096 | ||
1097 | // Finally put the shuffled pieces in the board array | |
1098 | pieces[c][rook1Pos] = 'r'; | |
1099 | pieces[c][knight1Pos] = 'n'; | |
1100 | pieces[c][bishop1Pos] = 'b'; | |
1101 | pieces[c][queenPos] = 'q'; | |
1102 | pieces[c][kingPos] = 'k'; | |
1103 | pieces[c][bishop2Pos] = 'b'; | |
1104 | pieces[c][knight2Pos] = 'n'; | |
1105 | pieces[c][rook2Pos] = 'r'; | |
1106 | } | |
2eef6db6 | 1107 | return pieces["b"].join("") + |
1d184b4c | 1108 | "/pppppppp/8/8/8/8/PPPPPPPP/" + |
32cfcea4 | 1109 | pieces["w"].join("").toUpperCase() + |
f3802fcd | 1110 | " 1111"; //add flags |
1d184b4c BA |
1111 | } |
1112 | ||
1113 | // Return current fen according to pieces+colors state | |
1114 | getFen() | |
1115 | { | |
7931e479 | 1116 | return this.getBaseFen() + " " + this.getFlagsFen() + " " + this.turn; |
1d184b4c BA |
1117 | } |
1118 | ||
dda21a71 | 1119 | // Position part of the FEN string |
1d184b4c BA |
1120 | getBaseFen() |
1121 | { | |
1122 | let fen = ""; | |
0b7d99ec | 1123 | for (let i=0; i<V.size.x; i++) |
1d184b4c BA |
1124 | { |
1125 | let emptyCount = 0; | |
0b7d99ec | 1126 | for (let j=0; j<V.size.y; j++) |
1d184b4c | 1127 | { |
0b7d99ec | 1128 | if (this.board[i][j] == V.EMPTY) |
1d184b4c BA |
1129 | emptyCount++; |
1130 | else | |
1131 | { | |
1132 | if (emptyCount > 0) | |
1133 | { | |
1134 | // Add empty squares in-between | |
1135 | fen += emptyCount; | |
1136 | emptyCount = 0; | |
1137 | } | |
0b7d99ec | 1138 | fen += V.board2fen(this.board[i][j]); |
1d184b4c BA |
1139 | } |
1140 | } | |
1141 | if (emptyCount > 0) | |
1142 | { | |
1143 | // "Flush remainder" | |
1144 | fen += emptyCount; | |
1145 | } | |
0b7d99ec | 1146 | if (i < V.size.x - 1) |
1d184b4c BA |
1147 | fen += "/"; //separate rows |
1148 | } | |
1149 | return fen; | |
1150 | } | |
1151 | ||
dda21a71 | 1152 | // Flags part of the FEN string |
1d184b4c BA |
1153 | getFlagsFen() |
1154 | { | |
1155 | let fen = ""; | |
1156 | // Add castling flags | |
1157 | for (let i of ['w','b']) | |
1158 | { | |
1159 | for (let j=0; j<2; j++) | |
77e1ec78 | 1160 | fen += (this.castleFlags[i][j] ? '1' : '0'); |
1d184b4c BA |
1161 | } |
1162 | return fen; | |
1163 | } | |
1164 | ||
1165 | // Context: just before move is played, turn hasn't changed | |
1166 | getNotation(move) | |
1167 | { | |
0b7d99ec | 1168 | if (move.appear.length == 2 && move.appear[0].p == V.KING) //castle |
15952ada | 1169 | return (move.end.y < move.start.y ? "0-0-0" : "0-0"); |
1d184b4c BA |
1170 | |
1171 | // Translate final square | |
0b7d99ec | 1172 | const finalSquare = String.fromCharCode(97 + move.end.y) + (V.size.x-move.end.x); |
1d184b4c | 1173 | |
270968d6 | 1174 | const piece = this.getPiece(move.start.x, move.start.y); |
0b7d99ec | 1175 | if (piece == V.PAWN) |
1d184b4c BA |
1176 | { |
1177 | // Pawn move | |
1178 | let notation = ""; | |
5bfb0956 | 1179 | if (move.vanish.length > move.appear.length) |
1d184b4c BA |
1180 | { |
1181 | // Capture | |
270968d6 | 1182 | const startColumn = String.fromCharCode(97 + move.start.y); |
1d184b4c BA |
1183 | notation = startColumn + "x" + finalSquare; |
1184 | } | |
1185 | else //no capture | |
1186 | notation = finalSquare; | |
1187 | if (move.appear.length > 0 && piece != move.appear[0].p) //promotion | |
1188 | notation += "=" + move.appear[0].p.toUpperCase(); | |
1189 | return notation; | |
1190 | } | |
1191 | ||
1192 | else | |
1193 | { | |
1194 | // Piece movement | |
f3c10e18 BA |
1195 | return piece.toUpperCase() + |
1196 | (move.vanish.length > move.appear.length ? "x" : "") + finalSquare; | |
1d184b4c BA |
1197 | } |
1198 | } | |
dfb4afc1 | 1199 | |
6752407b BA |
1200 | // Complete the usual notation, may be required for de-ambiguification |
1201 | getLongNotation(move) | |
1202 | { | |
1203 | const startSquare = | |
0b7d99ec BA |
1204 | String.fromCharCode(97 + move.start.y) + (V.size.x-move.start.x); |
1205 | const finalSquare = String.fromCharCode(97 + move.end.y) + (V.size.x-move.end.x); | |
6752407b BA |
1206 | return startSquare + finalSquare; //not encoding move. But short+long is enough |
1207 | } | |
1208 | ||
dfb4afc1 | 1209 | // The score is already computed when calling this function |
01a135e2 | 1210 | getPGN(mycolor, score, fenStart, mode) |
dfb4afc1 | 1211 | { |
16984853 | 1212 | const zeroPad = x => { return (x<10 ? "0" : "") + x; }; |
dfb4afc1 BA |
1213 | let pgn = ""; |
1214 | pgn += '[Site "vchess.club"]<br>'; | |
1215 | const d = new Date(); | |
5e622704 | 1216 | const opponent = mode=="human" ? "Anonymous" : "Computer"; |
0f51ef98 | 1217 | pgn += '[Variant "' + variant + '"]<br>'; |
92342261 BA |
1218 | pgn += '[Date "' + d.getFullYear() + '-' + (d.getMonth()+1) + |
1219 | '-' + zeroPad(d.getDate()) + '"]<br>'; | |
01a135e2 BA |
1220 | pgn += '[White "' + (mycolor=='w'?'Myself':opponent) + '"]<br>'; |
1221 | pgn += '[Black "' + (mycolor=='b'?'Myself':opponent) + '"]<br>'; | |
04449c97 BA |
1222 | pgn += '[FenStart "' + fenStart + '"]<br>'; |
1223 | pgn += '[Fen "' + this.getFen() + '"]<br>'; | |
762b7c9c | 1224 | pgn += '[Result "' + score + '"]<br><br>'; |
dfb4afc1 | 1225 | |
6752407b | 1226 | // Standard PGN |
dfb4afc1 BA |
1227 | for (let i=0; i<this.moves.length; i++) |
1228 | { | |
1229 | if (i % 2 == 0) | |
1230 | pgn += ((i/2)+1) + "."; | |
6752407b | 1231 | pgn += this.moves[i].notation[0] + " "; |
dfb4afc1 | 1232 | } |
97fc8bf7 | 1233 | pgn += "<br><br>"; |
dfb4afc1 | 1234 | |
6752407b BA |
1235 | // "Complete moves" PGN (helping in ambiguous cases) |
1236 | for (let i=0; i<this.moves.length; i++) | |
1237 | { | |
1238 | if (i % 2 == 0) | |
1239 | pgn += ((i/2)+1) + "."; | |
1240 | pgn += this.moves[i].notation[1] + " "; | |
1241 | } | |
6752407b | 1242 | |
dfb4afc1 BA |
1243 | return pgn; |
1244 | } | |
1d184b4c | 1245 | } |