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