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