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