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