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