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