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 | } | |
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 | } | |
e64a4eff BA |
520 | |
521 | // Stop at the first move found | |
522 | atLeastOneMove(color) | |
523 | { | |
524 | const oppCol = this.getOppCol(color); | |
525 | let [sizeX,sizeY] = VariantRules.size; | |
526 | for (var i=0; i<sizeX; i++) | |
527 | { | |
528 | for (var j=0; j<sizeY; j++) | |
529 | { | |
530 | if (this.board[i][j] != VariantRules.EMPTY && this.getColor(i,j) != oppCol) | |
531 | { | |
532 | const moves = this.getPotentialMovesFrom([i,j]); | |
533 | if (moves.length > 0) | |
534 | { | |
535 | for (let i=0; i<moves.length; i++) | |
536 | { | |
537 | if (this.filterValid([moves[i]]).length > 0) | |
538 | return true; | |
539 | } | |
540 | } | |
541 | } | |
542 | } | |
543 | } | |
544 | return false; | |
545 | } | |
1d184b4c BA |
546 | |
547 | // Check if pieces of color 'color' are attacking square x,y | |
548 | isAttacked(sq, color) | |
549 | { | |
550 | return (this.isAttackedByPawn(sq, color) | |
551 | || this.isAttackedByRook(sq, color) | |
552 | || this.isAttackedByKnight(sq, color) | |
553 | || this.isAttackedByBishop(sq, color) | |
554 | || this.isAttackedByQueen(sq, color) | |
555 | || this.isAttackedByKing(sq, color)); | |
556 | } | |
557 | ||
558 | // Is square x,y attacked by pawns of color c ? | |
559 | isAttackedByPawn([x,y], c) | |
560 | { | |
561 | let pawnShift = (c=="w" ? 1 : -1); | |
562 | if (x+pawnShift>=0 && x+pawnShift<8) | |
563 | { | |
564 | for (let i of [-1,1]) | |
565 | { | |
566 | if (y+i>=0 && y+i<8 && this.getPiece(x+pawnShift,y+i)==VariantRules.PAWN | |
567 | && this.getColor(x+pawnShift,y+i)==c) | |
568 | { | |
569 | return true; | |
570 | } | |
571 | } | |
572 | } | |
573 | return false; | |
574 | } | |
575 | ||
576 | // Is square x,y attacked by rooks of color c ? | |
577 | isAttackedByRook(sq, color) | |
578 | { | |
579 | return this.isAttackedBySlideNJump(sq, color, | |
580 | VariantRules.ROOK, VariantRules.steps[VariantRules.ROOK]); | |
581 | } | |
582 | ||
583 | // Is square x,y attacked by knights of color c ? | |
584 | isAttackedByKnight(sq, color) | |
585 | { | |
586 | return this.isAttackedBySlideNJump(sq, color, | |
587 | VariantRules.KNIGHT, VariantRules.steps[VariantRules.KNIGHT], "oneStep"); | |
588 | } | |
589 | ||
590 | // Is square x,y attacked by bishops of color c ? | |
591 | isAttackedByBishop(sq, color) | |
592 | { | |
593 | return this.isAttackedBySlideNJump(sq, color, | |
594 | VariantRules.BISHOP, VariantRules.steps[VariantRules.BISHOP]); | |
595 | } | |
596 | ||
597 | // Is square x,y attacked by queens of color c ? | |
598 | isAttackedByQueen(sq, color) | |
599 | { | |
600 | return this.isAttackedBySlideNJump(sq, color, | |
601 | VariantRules.QUEEN, VariantRules.steps[VariantRules.QUEEN]); | |
602 | } | |
603 | ||
604 | // Is square x,y attacked by king of color c ? | |
605 | isAttackedByKing(sq, color) | |
606 | { | |
607 | return this.isAttackedBySlideNJump(sq, color, | |
608 | VariantRules.KING, VariantRules.steps[VariantRules.QUEEN], "oneStep"); | |
609 | } | |
610 | ||
611 | // Generic method for non-pawn pieces ("sliding or jumping"): is x,y attacked by piece != color ? | |
612 | isAttackedBySlideNJump([x,y], c,piece,steps,oneStep) | |
613 | { | |
614 | for (let step of steps) | |
615 | { | |
616 | let rx = x+step[0], ry = y+step[1]; | |
617 | while (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] == VariantRules.EMPTY | |
618 | && !oneStep) | |
619 | { | |
620 | rx += step[0]; | |
621 | ry += step[1]; | |
622 | } | |
623 | if (rx>=0 && rx<8 && ry>=0 && ry<8 && this.board[rx][ry] != VariantRules.EMPTY | |
624 | && this.getPiece(rx,ry) == piece && this.getColor(rx,ry) == c) | |
625 | { | |
626 | return true; | |
627 | } | |
628 | } | |
629 | return false; | |
630 | } | |
631 | ||
4b5fe306 | 632 | // Is color c under check after move ? |
1d184b4c BA |
633 | underCheck(move, c) |
634 | { | |
635 | this.play(move); | |
636 | let res = this.isAttacked(this.kingPos[c], this.getOppCol(c)); | |
637 | this.undo(move); | |
638 | return res; | |
639 | } | |
640 | ||
4b5fe306 BA |
641 | // On which squares is color c under check (after move) ? |
642 | getCheckSquares(move, c) | |
643 | { | |
644 | this.play(move); | |
645 | let res = this.isAttacked(this.kingPos[c], this.getOppCol(c)) | |
646 | ? [ JSON.parse(JSON.stringify(this.kingPos[c])) ] //need to duplicate! | |
647 | : [ ]; | |
648 | this.undo(move); | |
649 | return res; | |
650 | } | |
651 | ||
1d184b4c BA |
652 | // Apply a move on board |
653 | static PlayOnBoard(board, move) | |
654 | { | |
655 | for (let psq of move.vanish) | |
656 | board[psq.x][psq.y] = VariantRules.EMPTY; | |
657 | for (let psq of move.appear) | |
658 | board[psq.x][psq.y] = psq.c + psq.p; | |
659 | } | |
660 | // Un-apply the played move | |
661 | static UndoOnBoard(board, move) | |
662 | { | |
663 | for (let psq of move.appear) | |
664 | board[psq.x][psq.y] = VariantRules.EMPTY; | |
665 | for (let psq of move.vanish) | |
666 | board[psq.x][psq.y] = psq.c + psq.p; | |
667 | } | |
668 | ||
669 | // Before move is played: | |
670 | updateVariables(move) | |
671 | { | |
672 | const piece = this.getPiece(move.start.x,move.start.y); | |
673 | const c = this.getColor(move.start.x,move.start.y); | |
674 | const firstRank = (c == "w" ? 7 : 0); | |
675 | ||
676 | // Update king position + flags | |
677 | if (piece == VariantRules.KING && move.appear.length > 0) | |
678 | { | |
679 | this.kingPos[c][0] = move.appear[0].x; | |
680 | this.kingPos[c][1] = move.appear[0].y; | |
681 | this.flags[c] = [false,false]; | |
682 | return; | |
683 | } | |
684 | const oppCol = this.getOppCol(c); | |
685 | const oppFirstRank = 7 - firstRank; | |
686 | if (move.start.x == firstRank //our rook moves? | |
687 | && this.INIT_COL_ROOK[c].includes(move.start.y)) | |
688 | { | |
689 | const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1; | |
690 | this.flags[c][flagIdx] = false; | |
691 | } | |
692 | else if (move.end.x == oppFirstRank //we took opponent rook? | |
693 | && this.INIT_COL_ROOK[c].includes(move.end.y)) | |
694 | { | |
695 | const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1; | |
696 | this.flags[oppCol][flagIdx] = false; | |
697 | } | |
698 | } | |
699 | ||
700 | play(move, ingame) | |
701 | { | |
702 | // Save flags (for undo) | |
703 | move.flags = JSON.stringify(this.flags); //TODO: less costly | |
704 | this.updateVariables(move); | |
705 | ||
dfb4afc1 BA |
706 | if (!!ingame) |
707 | { | |
708 | move.notation = this.getNotation(move); | |
709 | this.moves.push(move); | |
710 | } | |
711 | ||
1d184b4c BA |
712 | this.epSquares.push( this.getEpSquare(move) ); |
713 | VariantRules.PlayOnBoard(this.board, move); | |
714 | this.movesCount++; | |
1d184b4c BA |
715 | } |
716 | ||
e64a4eff | 717 | undo(move, ingame) |
1d184b4c BA |
718 | { |
719 | VariantRules.UndoOnBoard(this.board, move); | |
720 | this.epSquares.pop(); | |
721 | this.movesCount--; | |
722 | ||
e64a4eff BA |
723 | if (!!ingame) |
724 | this.moves.pop(); | |
725 | ||
1d184b4c BA |
726 | // Update king position, and reset stored/computed flags |
727 | const c = this.getColor(move.start.x,move.start.y); | |
728 | if (this.getPiece(move.start.x,move.start.y) == VariantRules.KING) | |
729 | this.kingPos[c] = [move.start.x, move.start.y]; | |
730 | ||
731 | this.flags = JSON.parse(move.flags); | |
732 | } | |
733 | ||
734 | ////////////// | |
735 | // END OF GAME | |
736 | ||
737 | checkGameOver(color) | |
738 | { | |
739 | // Check for 3 repetitions | |
740 | if (this.moves.length >= 8) | |
741 | { | |
742 | // NOTE: crude detection, only moves repetition | |
743 | const L = this.moves.length; | |
744 | if (_.isEqual(this.moves[L-1], this.moves[L-5]) && | |
745 | _.isEqual(this.moves[L-2], this.moves[L-6]) && | |
746 | _.isEqual(this.moves[L-3], this.moves[L-7]) && | |
747 | _.isEqual(this.moves[L-4], this.moves[L-8])) | |
748 | { | |
749 | return "1/2 (repetition)"; | |
750 | } | |
751 | } | |
752 | ||
e64a4eff | 753 | if (this.atLeastOneMove(color)) |
1d184b4c BA |
754 | { |
755 | // game not over | |
756 | return "*"; | |
757 | } | |
758 | ||
759 | // Game over | |
760 | return this.checkGameEnd(color); | |
761 | } | |
762 | ||
763 | // Useful stand-alone for engine | |
764 | checkGameEnd(color) | |
765 | { | |
766 | // No valid move: stalemate or checkmate? | |
767 | if (!this.isAttacked(this.kingPos[color], this.getOppCol(color))) | |
768 | return "1/2"; | |
769 | // OK, checkmate | |
770 | return color == "w" ? "0-1" : "1-0"; | |
771 | } | |
772 | ||
773 | //////// | |
774 | //ENGINE | |
775 | ||
776 | // Pieces values | |
777 | static get VALUES() { | |
778 | return { | |
779 | 'p': 1, | |
780 | 'r': 5, | |
781 | 'n': 3, | |
782 | 'b': 3, | |
783 | 'q': 9, | |
784 | 'k': 1000 | |
785 | }; | |
786 | } | |
787 | ||
788 | // Assumption: at least one legal move | |
789 | getComputerMove(color) | |
790 | { | |
791 | const oppCol = this.getOppCol(color); | |
792 | ||
793 | // Rank moves using a min-max at depth 2 | |
794 | let moves1 = this.getAllValidMoves(color); | |
795 | ||
796 | for (let i=0; i<moves1.length; i++) | |
797 | { | |
798 | moves1[i].eval = (color=="w" ? -1 : 1) * 1000; //very low, I'm checkmated | |
799 | let eval2 = (color=="w" ? 1 : -1) * 1000; //initialized with very high (checkmate) value | |
800 | this.play(moves1[i]); | |
801 | // Second half-move: | |
802 | let moves2 = this.getAllValidMoves(oppCol); | |
803 | // If no possible moves AND underCheck, eval2 is correct. | |
804 | // If !underCheck, eval2 is 0 (stalemate). | |
805 | if (moves2.length == 0 && this.checkGameEnd(oppCol) == "1/2") | |
806 | eval2 = 0; | |
807 | for (let j=0; j<moves2.length; j++) | |
808 | { | |
809 | this.play(moves2[j]); | |
810 | let evalPos = this.evalPosition(); | |
811 | if ((color == "w" && evalPos < eval2) || (color=="b" && evalPos > eval2)) | |
812 | eval2 = evalPos; | |
813 | this.undo(moves2[j]); | |
814 | } | |
815 | if ((color=="w" && eval2 > moves1[i].eval) || (color=="b" && eval2 < moves1[i].eval)) | |
816 | moves1[i].eval = eval2; | |
817 | this.undo(moves1[i]); | |
818 | } | |
819 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
820 | ||
821 | // TODO: show current analyzed move for depth 3, allow stopping eval (return moves1[0]) | |
e64a4eff BA |
822 | for (let i=0; i<moves1.length; i++) |
823 | { | |
824 | this.play(moves1[i]); | |
825 | // 0.1 * oldEval : heuristic to avoid some bad moves (not all...) | |
826 | moves1[i].eval = 0.1*moves1[i].eval + this.alphabeta(oppCol, color, 2, -1000, 1000); | |
827 | this.undo(moves1[i]); | |
828 | } | |
829 | moves1.sort( (a,b) => { return (color=="w" ? 1 : -1) * (b.eval - a.eval); }); | |
1d184b4c BA |
830 | |
831 | let candidates = [0]; //indices of candidates moves | |
832 | for (let j=1; j<moves1.length && moves1[j].eval == moves1[0].eval; j++) | |
833 | candidates.push(j); | |
834 | ||
835 | //console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; })); | |
836 | return moves1[_.sample(candidates, 1)]; | |
837 | } | |
838 | ||
839 | alphabeta(color, oppCol, depth, alpha, beta) | |
840 | { | |
e64a4eff | 841 | const moves = this.getAllValidMoves(color); |
1d184b4c BA |
842 | if (moves.length == 0) |
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(); | |
852 | let v = color=="w" ? -1000 : 1000; | |
853 | if (color == "w") | |
854 | { | |
855 | for (let i=0; i<moves.length; i++) | |
856 | { | |
857 | this.play(moves[i]); | |
858 | v = Math.max(v, this.alphabeta(oppCol, color, depth-1, alpha, beta)); | |
859 | this.undo(moves[i]); | |
860 | alpha = Math.max(alpha, v); | |
861 | if (alpha >= beta) | |
862 | break; //beta cutoff | |
863 | } | |
864 | } | |
865 | else //color=="b" | |
866 | { | |
867 | for (let i=0; i<moves.length; i++) | |
868 | { | |
869 | this.play(moves[i]); | |
870 | v = Math.min(v, this.alphabeta(oppCol, color, depth-1, alpha, beta)); | |
871 | this.undo(moves[i]); | |
872 | beta = Math.min(beta, v); | |
873 | if (alpha >= beta) | |
874 | break; //alpha cutoff | |
875 | } | |
876 | } | |
877 | return v; | |
878 | } | |
879 | ||
880 | evalPosition() | |
881 | { | |
882 | const [sizeX,sizeY] = VariantRules.size; | |
883 | let evaluation = 0; | |
884 | //Just count material for now | |
885 | for (let i=0; i<sizeX; i++) | |
886 | { | |
887 | for (let j=0; j<sizeY; j++) | |
888 | { | |
889 | if (this.board[i][j] != VariantRules.EMPTY) | |
890 | { | |
891 | const sign = this.getColor(i,j) == "w" ? 1 : -1; | |
892 | evaluation += sign * VariantRules.VALUES[this.getPiece(i,j)]; | |
893 | } | |
894 | } | |
895 | } | |
896 | return evaluation; | |
897 | } | |
898 | ||
899 | //////////// | |
900 | // FEN utils | |
901 | ||
902 | // Overridable.. | |
903 | static GenRandInitFen() | |
904 | { | |
905 | let pieces = [new Array(8), new Array(8)]; | |
906 | // Shuffle pieces on first and last rank | |
907 | for (let c = 0; c <= 1; c++) | |
908 | { | |
909 | let positions = _.range(8); | |
910 | ||
911 | // Get random squares for bishops | |
912 | let randIndex = 2 * _.random(3); | |
913 | let bishop1Pos = positions[randIndex]; | |
914 | // The second bishop must be on a square of different color | |
915 | let randIndex_tmp = 2 * _.random(3) + 1; | |
916 | let bishop2Pos = positions[randIndex_tmp]; | |
917 | // Remove chosen squares | |
918 | positions.splice(Math.max(randIndex,randIndex_tmp), 1); | |
919 | positions.splice(Math.min(randIndex,randIndex_tmp), 1); | |
920 | ||
921 | // Get random squares for knights | |
922 | randIndex = _.random(5); | |
923 | let knight1Pos = positions[randIndex]; | |
924 | positions.splice(randIndex, 1); | |
925 | randIndex = _.random(4); | |
926 | let knight2Pos = positions[randIndex]; | |
927 | positions.splice(randIndex, 1); | |
928 | ||
929 | // Get random square for queen | |
930 | randIndex = _.random(3); | |
931 | let queenPos = positions[randIndex]; | |
932 | positions.splice(randIndex, 1); | |
933 | ||
934 | // Rooks and king positions are now fixed, because of the ordering rook-king-rook | |
935 | let rook1Pos = positions[0]; | |
936 | let kingPos = positions[1]; | |
937 | let rook2Pos = positions[2]; | |
938 | ||
939 | // Finally put the shuffled pieces in the board array | |
940 | pieces[c][rook1Pos] = 'r'; | |
941 | pieces[c][knight1Pos] = 'n'; | |
942 | pieces[c][bishop1Pos] = 'b'; | |
943 | pieces[c][queenPos] = 'q'; | |
944 | pieces[c][kingPos] = 'k'; | |
945 | pieces[c][bishop2Pos] = 'b'; | |
946 | pieces[c][knight2Pos] = 'n'; | |
947 | pieces[c][rook2Pos] = 'r'; | |
948 | } | |
949 | let fen = pieces[0].join("") + | |
950 | "/pppppppp/8/8/8/8/PPPPPPPP/" + | |
951 | pieces[1].join("").toUpperCase() + | |
952 | " 1111 - 0"; //flags + enPassant + movesCount | |
953 | return fen; | |
954 | } | |
955 | ||
956 | // Return current fen according to pieces+colors state | |
957 | getFen() | |
958 | { | |
959 | const L = this.epSquares.length; | |
960 | const epSq = this.epSquares[L-1]===undefined | |
961 | ? "-" | |
962 | : this.epSquares[L-1].x+","+this.epSquares[L-1].y; | |
963 | return this.getBaseFen() + " " + this.getFlagsFen() | |
964 | + " " + epSq + " " + this.movesCount; | |
965 | } | |
966 | ||
967 | getBaseFen() | |
968 | { | |
969 | let fen = ""; | |
970 | let [sizeX,sizeY] = VariantRules.size; | |
971 | for (let i=0; i<sizeX; i++) | |
972 | { | |
973 | let emptyCount = 0; | |
974 | for (let j=0; j<sizeY; j++) | |
975 | { | |
976 | if (this.board[i][j] == VariantRules.EMPTY) | |
977 | emptyCount++; | |
978 | else | |
979 | { | |
980 | if (emptyCount > 0) | |
981 | { | |
982 | // Add empty squares in-between | |
983 | fen += emptyCount; | |
984 | emptyCount = 0; | |
985 | } | |
986 | fen += VariantRules.board2fen(this.board[i][j]); | |
987 | } | |
988 | } | |
989 | if (emptyCount > 0) | |
990 | { | |
991 | // "Flush remainder" | |
992 | fen += emptyCount; | |
993 | } | |
994 | if (i < sizeX - 1) | |
995 | fen += "/"; //separate rows | |
996 | } | |
997 | return fen; | |
998 | } | |
999 | ||
1000 | // Overridable.. | |
1001 | getFlagsFen() | |
1002 | { | |
1003 | let fen = ""; | |
1004 | // Add castling flags | |
1005 | for (let i of ['w','b']) | |
1006 | { | |
1007 | for (let j=0; j<2; j++) | |
1008 | fen += this.flags[i][j] ? '1' : '0'; | |
1009 | } | |
1010 | return fen; | |
1011 | } | |
1012 | ||
1013 | // Context: just before move is played, turn hasn't changed | |
1014 | getNotation(move) | |
1015 | { | |
1016 | if (move.appear.length == 2) | |
1017 | { | |
1018 | // Castle | |
1019 | if (move.end.y < move.start.y) | |
1020 | return "0-0-0"; | |
1021 | else | |
1022 | return "0-0"; | |
1023 | } | |
1024 | ||
1025 | // Translate final square | |
1026 | let finalSquare = | |
1027 | String.fromCharCode(97 + move.end.y) + (VariantRules.size[0]-move.end.x); | |
1028 | ||
1029 | let piece = this.getPiece(move.start.x, move.start.y); | |
1030 | if (piece == VariantRules.PAWN) | |
1031 | { | |
1032 | // Pawn move | |
1033 | let notation = ""; | |
1034 | if (move.vanish.length > 1) | |
1035 | { | |
1036 | // Capture | |
1037 | let startColumn = String.fromCharCode(97 + move.start.y); | |
1038 | notation = startColumn + "x" + finalSquare; | |
1039 | } | |
1040 | else //no capture | |
1041 | notation = finalSquare; | |
1042 | if (move.appear.length > 0 && piece != move.appear[0].p) //promotion | |
1043 | notation += "=" + move.appear[0].p.toUpperCase(); | |
1044 | return notation; | |
1045 | } | |
1046 | ||
1047 | else | |
1048 | { | |
1049 | // Piece movement | |
1050 | return piece.toUpperCase() + (move.vanish.length > 1 ? "x" : "") + finalSquare; | |
1051 | } | |
1052 | } | |
dfb4afc1 BA |
1053 | |
1054 | // The score is already computed when calling this function | |
762b7c9c | 1055 | getPGN(mycolor, score, fenStart) |
dfb4afc1 BA |
1056 | { |
1057 | let pgn = ""; | |
1058 | pgn += '[Site "vchess.club"]<br>'; | |
1059 | const d = new Date(); | |
1060 | pgn += '[Date "' + d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + '"]<br>'; | |
1061 | pgn += '[White "' + (mycolor=='w'?'Myself':'Anonymous') + '"]<br>'; | |
1062 | pgn += '[Black "' + (mycolor=='b'?'Myself':'Anonymous') + '"]<br>'; | |
762b7c9c BA |
1063 | pgn += '[Fen "' + fenStart + '"]<br>'; |
1064 | pgn += '[Result "' + score + '"]<br><br>'; | |
dfb4afc1 BA |
1065 | |
1066 | for (let i=0; i<this.moves.length; i++) | |
1067 | { | |
1068 | if (i % 2 == 0) | |
1069 | pgn += ((i/2)+1) + "."; | |
1070 | pgn += this.moves[i].notation + " "; | |
1071 | } | |
1072 | ||
1073 | pgn += score; | |
1074 | return pgn; | |
1075 | } | |
1d184b4c | 1076 | } |