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 | |
067c675b BA |
506 | // Get next color (for compatibility with 3 and 4 players games) |
507 | getNextCol(color) | |
508 | { | |
509 | return this.getOppCol(color); | |
510 | } | |
511 | ||
1a788978 | 512 | // Pieces codes (for a clearer code) |
1d184b4c BA |
513 | static get PAWN() { return 'p'; } |
514 | static get ROOK() { return 'r'; } | |
515 | static get KNIGHT() { return 'n'; } | |
516 | static get BISHOP() { return 'b'; } | |
517 | static get QUEEN() { return 'q'; } | |
518 | static get KING() { return 'k'; } | |
519 | ||
7931e479 | 520 | // For FEN checking: |
1a788978 BA |
521 | static get PIECES() |
522 | { | |
7931e479 BA |
523 | return [V.PAWN,V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN,V.KING]; |
524 | } | |
525 | ||
1d184b4c | 526 | // Empty square |
1a788978 | 527 | static get EMPTY() { return ""; } |
1d184b4c BA |
528 | |
529 | // Some pieces movements | |
1a788978 BA |
530 | static get steps() |
531 | { | |
1d184b4c BA |
532 | return { |
533 | 'r': [ [-1,0],[1,0],[0,-1],[0,1] ], | |
534 | 'n': [ [-1,-2],[-1,2],[1,-2],[1,2],[-2,-1],[-2,1],[2,-1],[2,1] ], | |
535 | 'b': [ [-1,-1],[-1,1],[1,-1],[1,1] ], | |
1d184b4c BA |
536 | }; |
537 | } | |
538 | ||
1a788978 | 539 | //////////////////// |
1d184b4c BA |
540 | // MOVES GENERATION |
541 | ||
542 | // All possible moves from selected square (assumption: color is OK) | |
543 | getPotentialMovesFrom([x,y]) | |
544 | { | |
1d184b4c BA |
545 | switch (this.getPiece(x,y)) |
546 | { | |
0b7d99ec | 547 | case V.PAWN: |
46302e64 | 548 | return this.getPotentialPawnMoves([x,y]); |
0b7d99ec | 549 | case V.ROOK: |
46302e64 | 550 | return this.getPotentialRookMoves([x,y]); |
0b7d99ec | 551 | case V.KNIGHT: |
46302e64 | 552 | return this.getPotentialKnightMoves([x,y]); |
0b7d99ec | 553 | case V.BISHOP: |
46302e64 | 554 | return this.getPotentialBishopMoves([x,y]); |
0b7d99ec | 555 | case V.QUEEN: |
46302e64 | 556 | return this.getPotentialQueenMoves([x,y]); |
0b7d99ec | 557 | case V.KING: |
46302e64 | 558 | return this.getPotentialKingMoves([x,y]); |
1d184b4c BA |
559 | } |
560 | } | |
561 | ||
26c1e3bd BA |
562 | // Build a regular move from its initial and destination squares. |
563 | // tr: transformation | |
46302e64 | 564 | getBasicMove([sx,sy], [ex,ey], tr) |
1d184b4c | 565 | { |
2526c041 | 566 | let mv = new Move({ |
1d184b4c BA |
567 | appear: [ |
568 | new PiPo({ | |
569 | x: ex, | |
570 | y: ey, | |
46302e64 BA |
571 | c: !!tr ? tr.c : this.getColor(sx,sy), |
572 | p: !!tr ? tr.p : this.getPiece(sx,sy) | |
1d184b4c BA |
573 | }) |
574 | ], | |
575 | vanish: [ | |
576 | new PiPo({ | |
577 | x: sx, | |
578 | y: sy, | |
579 | c: this.getColor(sx,sy), | |
580 | p: this.getPiece(sx,sy) | |
581 | }) | |
582 | ] | |
583 | }); | |
584 | ||
585 | // The opponent piece disappears if we take it | |
0b7d99ec | 586 | if (this.board[ex][ey] != V.EMPTY) |
1d184b4c BA |
587 | { |
588 | mv.vanish.push( | |
589 | new PiPo({ | |
590 | x: ex, | |
591 | y: ey, | |
592 | c: this.getColor(ex,ey), | |
593 | p: this.getPiece(ex,ey) | |
594 | }) | |
595 | ); | |
596 | } | |
597 | return mv; | |
598 | } | |
599 | ||
26c1e3bd BA |
600 | // Generic method to find possible moves of non-pawn pieces: |
601 | // "sliding or jumping" | |
46302e64 | 602 | getSlideNJumpMoves([x,y], steps, oneStep) |
1d184b4c | 603 | { |
46302e64 | 604 | const color = this.getColor(x,y); |
2526c041 | 605 | let moves = []; |
1d184b4c BA |
606 | outerLoop: |
607 | for (let step of steps) | |
608 | { | |
46302e64 BA |
609 | let i = x + step[0]; |
610 | let j = y + step[1]; | |
0b7d99ec | 611 | while (V.OnBoard(i,j) && this.board[i][j] == V.EMPTY) |
1d184b4c | 612 | { |
46302e64 | 613 | moves.push(this.getBasicMove([x,y], [i,j])); |
1d184b4c BA |
614 | if (oneStep !== undefined) |
615 | continue outerLoop; | |
616 | i += step[0]; | |
617 | j += step[1]; | |
618 | } | |
0b7d99ec | 619 | if (V.OnBoard(i,j) && this.canTake([x,y], [i,j])) |
46302e64 | 620 | moves.push(this.getBasicMove([x,y], [i,j])); |
1d184b4c BA |
621 | } |
622 | return moves; | |
623 | } | |
624 | ||
dda21a71 | 625 | // What are the pawn moves from square x,y ? |
46302e64 | 626 | getPotentialPawnMoves([x,y]) |
1d184b4c | 627 | { |
2526c041 BA |
628 | const color = this.turn; |
629 | let moves = []; | |
0b7d99ec | 630 | const [sizeX,sizeY] = [V.size.x,V.size.y]; |
375ecdd1 | 631 | const shiftX = (color == "w" ? -1 : 1); |
cf130369 BA |
632 | const firstRank = (color == 'w' ? sizeX-1 : 0); |
633 | const startRank = (color == "w" ? sizeX-2 : 1); | |
634 | const lastRank = (color == "w" ? 0 : sizeX-1); | |
375ecdd1 | 635 | const pawnColor = this.getColor(x,y); //can be different for checkered |
1d184b4c | 636 | |
69f3d801 BA |
637 | // NOTE: next condition is generally true (no pawn on last rank) |
638 | if (x+shiftX >= 0 && x+shiftX < sizeX) | |
1d184b4c | 639 | { |
375ecdd1 BA |
640 | const finalPieces = x + shiftX == lastRank |
641 | ? [V.ROOK,V.KNIGHT,V.BISHOP,V.QUEEN] | |
642 | : [V.PAWN] | |
643 | // One square forward | |
644 | if (this.board[x+shiftX][y] == V.EMPTY) | |
1d184b4c | 645 | { |
375ecdd1 BA |
646 | for (let piece of finalPieces) |
647 | { | |
648 | moves.push(this.getBasicMove([x,y], [x+shiftX,y], | |
649 | {c:pawnColor,p:piece})); | |
650 | } | |
651 | // Next condition because pawns on 1st rank can generally jump | |
652 | if ([startRank,firstRank].includes(x) | |
653 | && this.board[x+2*shiftX][y] == V.EMPTY) | |
1d184b4c BA |
654 | { |
655 | // Two squares jump | |
375ecdd1 | 656 | moves.push(this.getBasicMove([x,y], [x+2*shiftX,y])); |
1d184b4c BA |
657 | } |
658 | } | |
659 | // Captures | |
375ecdd1 | 660 | for (let shiftY of [-1,1]) |
1221ac47 | 661 | { |
375ecdd1 BA |
662 | if (y + shiftY >= 0 && y + shiftY < sizeY |
663 | && this.board[x+shiftX][y+shiftY] != V.EMPTY | |
664 | && this.canTake([x,y], [x+shiftX,y+shiftY])) | |
1221ac47 | 665 | { |
375ecdd1 BA |
666 | for (let piece of finalPieces) |
667 | { | |
668 | moves.push(this.getBasicMove([x,y], [x+shiftX,y+shiftY], | |
669 | {c:pawnColor,p:piece})); | |
670 | } | |
1221ac47 | 671 | } |
375ecdd1 | 672 | } |
1d184b4c BA |
673 | } |
674 | ||
375ecdd1 | 675 | if (V.HasEnpassant) |
1d184b4c | 676 | { |
375ecdd1 BA |
677 | // En passant |
678 | const Lep = this.epSquares.length; | |
679 | const epSquare = this.epSquares[Lep-1]; //always at least one element | |
680 | if (!!epSquare && epSquare.x == x+shiftX && Math.abs(epSquare.y - y) == 1) | |
681 | { | |
682 | let enpassantMove = this.getBasicMove([x,y], [epSquare.x,epSquare.y]); | |
683 | enpassantMove.vanish.push({ | |
684 | x: x, | |
685 | y: epSquare.y, | |
686 | p: 'p', | |
687 | c: this.getColor(x,epSquare.y) | |
688 | }); | |
689 | moves.push(enpassantMove); | |
690 | } | |
1d184b4c BA |
691 | } |
692 | ||
693 | return moves; | |
694 | } | |
695 | ||
696 | // What are the rook moves from square x,y ? | |
46302e64 | 697 | getPotentialRookMoves(sq) |
1d184b4c | 698 | { |
0b7d99ec | 699 | return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]); |
1d184b4c BA |
700 | } |
701 | ||
702 | // What are the knight moves from square x,y ? | |
46302e64 | 703 | getPotentialKnightMoves(sq) |
1d184b4c | 704 | { |
0b7d99ec | 705 | return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep"); |
1d184b4c BA |
706 | } |
707 | ||
708 | // What are the bishop moves from square x,y ? | |
46302e64 | 709 | getPotentialBishopMoves(sq) |
1d184b4c | 710 | { |
0b7d99ec | 711 | return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]); |
1d184b4c BA |
712 | } |
713 | ||
714 | // What are the queen moves from square x,y ? | |
46302e64 | 715 | getPotentialQueenMoves(sq) |
1d184b4c | 716 | { |
26c1e3bd BA |
717 | return this.getSlideNJumpMoves(sq, |
718 | V.steps[V.ROOK].concat(V.steps[V.BISHOP])); | |
1d184b4c BA |
719 | } |
720 | ||
721 | // What are the king moves from square x,y ? | |
46302e64 | 722 | getPotentialKingMoves(sq) |
1d184b4c BA |
723 | { |
724 | // Initialize with normal moves | |
a37076f1 BA |
725 | let moves = this.getSlideNJumpMoves(sq, |
726 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep"); | |
46302e64 | 727 | return moves.concat(this.getCastleMoves(sq)); |
1d184b4c BA |
728 | } |
729 | ||
46302e64 | 730 | getCastleMoves([x,y]) |
1d184b4c | 731 | { |
46302e64 | 732 | const c = this.getColor(x,y); |
0b7d99ec | 733 | if (x != (c=="w" ? V.size.x-1 : 0) || y != this.INIT_COL_KING[c]) |
1d184b4c BA |
734 | return []; //x isn't first rank, or king has moved (shortcut) |
735 | ||
1d184b4c BA |
736 | // Castling ? |
737 | const oppCol = this.getOppCol(c); | |
738 | let moves = []; | |
739 | let i = 0; | |
0b7d99ec | 740 | const finalSquares = [ [2,3], [V.size.y-2,V.size.y-3] ]; //king, then rook |
1d184b4c BA |
741 | castlingCheck: |
742 | for (let castleSide=0; castleSide < 2; castleSide++) //large, then small | |
743 | { | |
2526c041 | 744 | if (!this.castleFlags[c][castleSide]) |
1d184b4c BA |
745 | continue; |
746 | // If this code is reached, rooks and king are on initial position | |
747 | ||
26c1e3bd BA |
748 | // Nothing on the path of the king ? |
749 | // (And no checks; OK also if y==finalSquare) | |
1d184b4c BA |
750 | let step = finalSquares[castleSide][0] < y ? -1 : 1; |
751 | for (i=y; i!=finalSquares[castleSide][0]; i+=step) | |
752 | { | |
cf130369 | 753 | if (this.isAttacked([x,i], [oppCol]) || (this.board[x][i] != V.EMPTY && |
1d184b4c | 754 | // NOTE: next check is enough, because of chessboard constraints |
26c1e3bd BA |
755 | (this.getColor(x,i) != c |
756 | || ![V.KING,V.ROOK].includes(this.getPiece(x,i))))) | |
1d184b4c BA |
757 | { |
758 | continue castlingCheck; | |
759 | } | |
760 | } | |
761 | ||
762 | // Nothing on the path to the rook? | |
763 | step = castleSide == 0 ? -1 : 1; | |
764 | for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) | |
765 | { | |
766 | if (this.board[x][i] != V.EMPTY) | |
767 | continue castlingCheck; | |
768 | } | |
769 | const rookPos = this.INIT_COL_ROOK[c][castleSide]; | |
770 | ||
771 | // Nothing on final squares, except maybe king and castling rook? | |
772 | for (i=0; i<2; i++) | |
773 | { | |
774 | if (this.board[x][finalSquares[castleSide][i]] != V.EMPTY && | |
775 | this.getPiece(x,finalSquares[castleSide][i]) != V.KING && | |
776 | finalSquares[castleSide][i] != rookPos) | |
777 | { | |
778 | continue castlingCheck; | |
779 | } | |
780 | } | |
781 | ||
782 | // If this code is reached, castle is valid | |
783 | moves.push( new Move({ | |
784 | appear: [ | |
785 | new PiPo({x:x,y:finalSquares[castleSide][0],p:V.KING,c:c}), | |
786 | new PiPo({x:x,y:finalSquares[castleSide][1],p:V.ROOK,c:c})], | |
787 | vanish: [ | |
788 | new PiPo({x:x,y:y,p:V.KING,c:c}), | |
789 | new PiPo({x:x,y:rookPos,p:V.ROOK,c:c})], | |
790 | end: Math.abs(y - rookPos) <= 2 | |
791 | ? {x:x, y:rookPos} | |
792 | : {x:x, y:y + 2 * (castleSide==0 ? -1 : 1)} | |
793 | }) ); | |
794 | } | |
795 | ||
796 | return moves; | |
797 | } | |
798 | ||
1a788978 | 799 | //////////////////// |
1d184b4c BA |
800 | // MOVES VALIDATION |
801 | ||
f6dbe8e3 | 802 | // For the interface: possible moves for the current turn from square sq |
1d184b4c BA |
803 | getPossibleMovesFrom(sq) |
804 | { | |
1d184b4c BA |
805 | return this.filterValid( this.getPotentialMovesFrom(sq) ); |
806 | } | |
807 | ||
92342261 | 808 | // TODO: promotions (into R,B,N,Q) should be filtered only once |
1d184b4c BA |
809 | filterValid(moves) |
810 | { | |
811 | if (moves.length == 0) | |
812 | return []; | |
f6dbe8e3 BA |
813 | const color = this.turn; |
814 | return moves.filter(m => { | |
815 | this.play(m); | |
816 | const res = !this.underCheck(color); | |
817 | this.undo(m); | |
818 | return res; | |
819 | }); | |
1d184b4c BA |
820 | } |
821 | ||
26c1e3bd BA |
822 | // Search for all valid moves considering current turn |
823 | // (for engine and game end) | |
46302e64 | 824 | getAllValidMoves() |
1d184b4c | 825 | { |
46302e64 | 826 | const color = this.turn; |
1d184b4c | 827 | const oppCol = this.getOppCol(color); |
c6052161 | 828 | let potentialMoves = []; |
0b7d99ec | 829 | for (let i=0; i<V.size.x; i++) |
1d184b4c | 830 | { |
0b7d99ec | 831 | for (let j=0; j<V.size.y; j++) |
1d184b4c | 832 | { |
26c1e3bd | 833 | // Next condition "!= oppCol" to work with checkered variant |
0b7d99ec | 834 | if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol) |
26c1e3bd BA |
835 | { |
836 | Array.prototype.push.apply(potentialMoves, | |
837 | this.getPotentialMovesFrom([i,j])); | |
838 | } | |
1d184b4c BA |
839 | } |
840 | } | |
1d184b4c BA |
841 | return this.filterValid(potentialMoves); |
842 | } | |
9de73b71 | 843 | |
e64a4eff | 844 | // Stop at the first move found |
46302e64 | 845 | atLeastOneMove() |
e64a4eff | 846 | { |
46302e64 | 847 | const color = this.turn; |
e64a4eff | 848 | const oppCol = this.getOppCol(color); |
0b7d99ec | 849 | for (let i=0; i<V.size.x; i++) |
e64a4eff | 850 | { |
0b7d99ec | 851 | for (let j=0; j<V.size.y; j++) |
e64a4eff | 852 | { |
0b7d99ec | 853 | if (this.board[i][j] != V.EMPTY && this.getColor(i,j) != oppCol) |
e64a4eff BA |
854 | { |
855 | const moves = this.getPotentialMovesFrom([i,j]); | |
856 | if (moves.length > 0) | |
857 | { | |
9de73b71 | 858 | for (let k=0; k<moves.length; k++) |
e64a4eff | 859 | { |
9de73b71 | 860 | if (this.filterValid([moves[k]]).length > 0) |
e64a4eff BA |
861 | return true; |
862 | } | |
863 | } | |
864 | } | |
865 | } | |
866 | } | |
867 | return false; | |
868 | } | |
1d184b4c | 869 | |
26c1e3bd | 870 | // Check if pieces of color in 'colors' are attacking (king) on square x,y |
46302e64 | 871 | isAttacked(sq, colors) |
1d184b4c | 872 | { |
46302e64 BA |
873 | return (this.isAttackedByPawn(sq, colors) |
874 | || this.isAttackedByRook(sq, colors) | |
875 | || this.isAttackedByKnight(sq, colors) | |
876 | || this.isAttackedByBishop(sq, colors) | |
877 | || this.isAttackedByQueen(sq, colors) | |
878 | || this.isAttackedByKing(sq, colors)); | |
1d184b4c BA |
879 | } |
880 | ||
dda21a71 | 881 | // Is square x,y attacked by 'colors' pawns ? |
46302e64 | 882 | isAttackedByPawn([x,y], colors) |
1d184b4c | 883 | { |
46302e64 | 884 | for (let c of colors) |
1d184b4c | 885 | { |
46302e64 | 886 | let pawnShift = (c=="w" ? 1 : -1); |
0b7d99ec | 887 | if (x+pawnShift>=0 && x+pawnShift<V.size.x) |
1d184b4c | 888 | { |
46302e64 | 889 | for (let i of [-1,1]) |
1d184b4c | 890 | { |
0b7d99ec | 891 | if (y+i>=0 && y+i<V.size.y && this.getPiece(x+pawnShift,y+i)==V.PAWN |
46302e64 BA |
892 | && this.getColor(x+pawnShift,y+i)==c) |
893 | { | |
894 | return true; | |
895 | } | |
1d184b4c BA |
896 | } |
897 | } | |
898 | } | |
899 | return false; | |
900 | } | |
901 | ||
dda21a71 | 902 | // Is square x,y attacked by 'colors' rooks ? |
46302e64 | 903 | isAttackedByRook(sq, colors) |
1d184b4c | 904 | { |
0b7d99ec | 905 | return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]); |
1d184b4c BA |
906 | } |
907 | ||
dda21a71 | 908 | // Is square x,y attacked by 'colors' knights ? |
46302e64 | 909 | isAttackedByKnight(sq, colors) |
1d184b4c | 910 | { |
46302e64 | 911 | return this.isAttackedBySlideNJump(sq, colors, |
0b7d99ec | 912 | V.KNIGHT, V.steps[V.KNIGHT], "oneStep"); |
1d184b4c BA |
913 | } |
914 | ||
dda21a71 | 915 | // Is square x,y attacked by 'colors' bishops ? |
46302e64 | 916 | isAttackedByBishop(sq, colors) |
1d184b4c | 917 | { |
0b7d99ec | 918 | return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]); |
1d184b4c BA |
919 | } |
920 | ||
dda21a71 | 921 | // Is square x,y attacked by 'colors' queens ? |
46302e64 | 922 | isAttackedByQueen(sq, colors) |
1d184b4c | 923 | { |
a37076f1 BA |
924 | return this.isAttackedBySlideNJump(sq, colors, V.QUEEN, |
925 | V.steps[V.ROOK].concat(V.steps[V.BISHOP])); | |
1d184b4c BA |
926 | } |
927 | ||
dda21a71 | 928 | // Is square x,y attacked by 'colors' king(s) ? |
46302e64 | 929 | isAttackedByKing(sq, colors) |
1d184b4c | 930 | { |
a37076f1 BA |
931 | return this.isAttackedBySlideNJump(sq, colors, V.KING, |
932 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), "oneStep"); | |
1d184b4c BA |
933 | } |
934 | ||
1221ac47 | 935 | // Generic method for non-pawn pieces ("sliding or jumping"): |
dda21a71 | 936 | // is x,y attacked by a piece of color in array 'colors' ? |
46302e64 | 937 | isAttackedBySlideNJump([x,y], colors, piece, steps, oneStep) |
1d184b4c BA |
938 | { |
939 | for (let step of steps) | |
940 | { | |
941 | let rx = x+step[0], ry = y+step[1]; | |
0b7d99ec | 942 | while (V.OnBoard(rx,ry) && this.board[rx][ry] == V.EMPTY && !oneStep) |
1d184b4c BA |
943 | { |
944 | rx += step[0]; | |
945 | ry += step[1]; | |
946 | } | |
0b7d99ec BA |
947 | if (V.OnBoard(rx,ry) && this.getPiece(rx,ry) === piece |
948 | && colors.includes(this.getColor(rx,ry))) | |
1d184b4c BA |
949 | { |
950 | return true; | |
951 | } | |
952 | } | |
953 | return false; | |
954 | } | |
955 | ||
f6dbe8e3 BA |
956 | // Is color under check after his move ? |
957 | underCheck(color) | |
1d184b4c | 958 | { |
f6dbe8e3 | 959 | return this.isAttacked(this.kingPos[color], [this.getOppCol(color)]); |
1d184b4c BA |
960 | } |
961 | ||
1a788978 BA |
962 | ///////////////// |
963 | // MOVES PLAYING | |
4b5fe306 | 964 | |
1d184b4c BA |
965 | // Apply a move on board |
966 | static PlayOnBoard(board, move) | |
967 | { | |
968 | for (let psq of move.vanish) | |
0b7d99ec | 969 | board[psq.x][psq.y] = V.EMPTY; |
1d184b4c BA |
970 | for (let psq of move.appear) |
971 | board[psq.x][psq.y] = psq.c + psq.p; | |
972 | } | |
973 | // Un-apply the played move | |
974 | static UndoOnBoard(board, move) | |
975 | { | |
976 | for (let psq of move.appear) | |
0b7d99ec | 977 | board[psq.x][psq.y] = V.EMPTY; |
1d184b4c BA |
978 | for (let psq of move.vanish) |
979 | board[psq.x][psq.y] = psq.c + psq.p; | |
980 | } | |
981 | ||
4f7723a1 | 982 | // After move is played, update variables + flags |
1d184b4c BA |
983 | updateVariables(move) |
984 | { | |
dbcc32e9 BA |
985 | let piece = undefined; |
986 | let c = undefined; | |
987 | if (move.vanish.length >= 1) | |
988 | { | |
989 | // Usual case, something is moved | |
990 | piece = move.vanish[0].p; | |
991 | c = move.vanish[0].c; | |
992 | } | |
993 | else | |
994 | { | |
995 | // Crazyhouse-like variants | |
996 | piece = move.appear[0].p; | |
997 | c = move.appear[0].c; | |
998 | } | |
6e62b1c7 BA |
999 | if (c == "c") //if (!["w","b"].includes(c)) |
1000 | { | |
1001 | // 'c = move.vanish[0].c' doesn't work for Checkered | |
1002 | c = this.getOppCol(this.turn); | |
1003 | } | |
0b7d99ec | 1004 | const firstRank = (c == "w" ? V.size.x-1 : 0); |
1d184b4c BA |
1005 | |
1006 | // Update king position + flags | |
0b7d99ec | 1007 | if (piece == V.KING && move.appear.length > 0) |
1d184b4c BA |
1008 | { |
1009 | this.kingPos[c][0] = move.appear[0].x; | |
1010 | this.kingPos[c][1] = move.appear[0].y; | |
69f3d801 BA |
1011 | if (V.HasFlags) |
1012 | this.castleFlags[c] = [false,false]; | |
1d184b4c BA |
1013 | return; |
1014 | } | |
69f3d801 | 1015 | if (V.HasFlags) |
1d184b4c | 1016 | { |
69f3d801 BA |
1017 | // Update castling flags if rooks are moved |
1018 | const oppCol = this.getOppCol(c); | |
1019 | const oppFirstRank = (V.size.x-1) - firstRank; | |
1020 | if (move.start.x == firstRank //our rook moves? | |
1021 | && this.INIT_COL_ROOK[c].includes(move.start.y)) | |
1022 | { | |
1023 | const flagIdx = (move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1); | |
1024 | this.castleFlags[c][flagIdx] = false; | |
1025 | } | |
1026 | else if (move.end.x == oppFirstRank //we took opponent rook? | |
1027 | && this.INIT_COL_ROOK[oppCol].includes(move.end.y)) | |
1028 | { | |
1029 | const flagIdx = (move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1); | |
1030 | this.castleFlags[oppCol][flagIdx] = false; | |
1031 | } | |
1d184b4c BA |
1032 | } |
1033 | } | |
1034 | ||
1a788978 BA |
1035 | // After move is undo-ed *and flags resetted*, un-update other variables |
1036 | // TODO: more symmetry, by storing flags increment in move (?!) | |
d3334c3a | 1037 | unupdateVariables(move) |
1d184b4c | 1038 | { |
d3334c3a BA |
1039 | // (Potentially) Reset king position |
1040 | const c = this.getColor(move.start.x,move.start.y); | |
0b7d99ec | 1041 | if (this.getPiece(move.start.x,move.start.y) == V.KING) |
d3334c3a BA |
1042 | this.kingPos[c] = [move.start.x, move.start.y]; |
1043 | } | |
1d184b4c | 1044 | |
067c675b | 1045 | play(move) |
d3334c3a | 1046 | { |
a3c86ec9 BA |
1047 | // DEBUG: |
1048 | // if (!this.states) this.states = []; | |
067c675b BA |
1049 | // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen(); |
1050 | // this.states.push(stateFen); | |
dfb4afc1 | 1051 | |
2d7194bd BA |
1052 | if (V.HasFlags) |
1053 | move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo) | |
2d7194bd BA |
1054 | if (V.HasEnpassant) |
1055 | this.epSquares.push( this.getEpSquare(move) ); | |
0b7d99ec | 1056 | V.PlayOnBoard(this.board, move); |
388e4c40 | 1057 | this.turn = this.getOppCol(this.turn); |
b6487fb9 | 1058 | this.movesCount++; |
388e4c40 | 1059 | this.updateVariables(move); |
1d184b4c BA |
1060 | } |
1061 | ||
cd4cad04 | 1062 | undo(move) |
1d184b4c | 1063 | { |
2d7194bd BA |
1064 | if (V.HasEnpassant) |
1065 | this.epSquares.pop(); | |
2d7194bd BA |
1066 | if (V.HasFlags) |
1067 | this.disaggregateFlags(JSON.parse(move.flags)); | |
388e4c40 BA |
1068 | V.UndoOnBoard(this.board, move); |
1069 | this.turn = this.getOppCol(this.turn); | |
b6487fb9 | 1070 | this.movesCount--; |
388e4c40 | 1071 | this.unupdateVariables(move); |
a3c86ec9 BA |
1072 | |
1073 | // DEBUG: | |
067c675b BA |
1074 | // const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen(); |
1075 | // if (stateFen != this.states[this.states.length-1]) debugger; | |
a3c86ec9 | 1076 | // this.states.pop(); |
1d184b4c BA |
1077 | } |
1078 | ||
1a788978 | 1079 | /////////////// |
1d184b4c BA |
1080 | // END OF GAME |
1081 | ||
067c675b BA |
1082 | // What is the score ? (Interesting if game is over) |
1083 | getCurrentScore() | |
1af36beb | 1084 | { |
1af36beb | 1085 | if (this.atLeastOneMove()) // game not over |
1d184b4c | 1086 | return "*"; |
1d184b4c BA |
1087 | |
1088 | // Game over | |
46302e64 | 1089 | const color = this.turn; |
1d184b4c | 1090 | // No valid move: stalemate or checkmate? |
cf130369 | 1091 | if (!this.isAttacked(this.kingPos[color], [this.getOppCol(color)])) |
1d184b4c BA |
1092 | return "1/2"; |
1093 | // OK, checkmate | |
6e62b1c7 | 1094 | return (color == "w" ? "0-1" : "1-0"); |
1d184b4c BA |
1095 | } |
1096 | ||
1a788978 BA |
1097 | /////////////// |
1098 | // ENGINE PLAY | |
1d184b4c BA |
1099 | |
1100 | // Pieces values | |
1a788978 BA |
1101 | static get VALUES() |
1102 | { | |
1d184b4c BA |
1103 | return { |
1104 | 'p': 1, | |
1105 | 'r': 5, | |
1106 | 'n': 3, | |
1107 | 'b': 3, | |
1108 | 'q': 9, | |
1109 | 'k': 1000 | |
1110 | }; | |
1111 | } | |
1112 | ||
1a788978 BA |
1113 | // "Checkmate" (unreachable eval) |
1114 | static get INFINITY() { return 9999; } | |
9e42b4dd | 1115 | |
1a788978 BA |
1116 | // At this value or above, the game is over |
1117 | static get THRESHOLD_MATE() { return V.INFINITY; } | |
9e42b4dd | 1118 | |
1a788978 BA |
1119 | // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.) |
1120 | static get SEARCH_DEPTH() { return 3; } | |
3c09dc49 | 1121 | |
1d184b4c | 1122 | // Assumption: at least one legal move |
a6abf094 BA |
1123 | // NOTE: works also for extinction chess because depth is 3... |
1124 | getComputerMove() | |
1d184b4c | 1125 | { |
0b7d99ec | 1126 | const maxeval = V.INFINITY; |
46302e64 | 1127 | const color = this.turn; |
15952ada BA |
1128 | // Some variants may show a bigger moves list to the human (Switching), |
1129 | // thus the argument "computer" below (which is generally ignored) | |
1130 | let moves1 = this.getAllValidMoves("computer"); | |
a6abf094 BA |
1131 | |
1132 | // Can I mate in 1 ? (for Magnetic & Extinction) | |
1133 | for (let i of _.shuffle(_.range(moves1.length))) | |
1134 | { | |
1135 | this.play(moves1[i]); | |
0b7d99ec | 1136 | let finish = (Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE); |
067c675b | 1137 | if (!finish) |
0b7d99ec | 1138 | { |
067c675b BA |
1139 | const score = this.getCurrentScore(); |
1140 | if (["1-0","0-1"].includes(score)) | |
0b7d99ec BA |
1141 | finish = true; |
1142 | } | |
a6abf094 BA |
1143 | this.undo(moves1[i]); |
1144 | if (finish) | |
1145 | return moves1[i]; | |
1146 | } | |
1d184b4c | 1147 | |
06ddfe34 | 1148 | // Rank moves using a min-max at depth 2 |
1d184b4c BA |
1149 | for (let i=0; i<moves1.length; i++) |
1150 | { | |
26c1e3bd BA |
1151 | // Initial self evaluation is very low: "I'm checkmated" |
1152 | moves1[i].eval = (color=="w" ? -1 : 1) * maxeval; | |
1d184b4c | 1153 | this.play(moves1[i]); |
067c675b | 1154 | const score1 = this.getCurrentScore(); |
68f5ccc8 | 1155 | let eval2 = undefined; |
067c675b | 1156 | if (score1 == "*") |
1d184b4c | 1157 | { |
26c1e3bd BA |
1158 | // Initial enemy evaluation is very low too, for him |
1159 | eval2 = (color=="w" ? 1 : -1) * maxeval; | |
68f5ccc8 | 1160 | // Second half-move: |
15952ada | 1161 | let moves2 = this.getAllValidMoves("computer"); |
68f5ccc8 BA |
1162 | for (let j=0; j<moves2.length; j++) |
1163 | { | |
1164 | this.play(moves2[j]); | |
067c675b BA |
1165 | const score2 = this.getCurrentScore(); |
1166 | const evalPos = score2 == "*" | |
1167 | ? this.evalPosition() | |
1168 | : (score2=="1/2" ? 0 : (score2=="1-0" ? 1 : -1) * maxeval); | |
26c1e3bd BA |
1169 | if ((color == "w" && evalPos < eval2) |
1170 | || (color=="b" && evalPos > eval2)) | |
1171 | { | |
68f5ccc8 | 1172 | eval2 = evalPos; |
26c1e3bd | 1173 | } |
68f5ccc8 BA |
1174 | this.undo(moves2[j]); |
1175 | } | |
1176 | } | |
1177 | else | |
067c675b | 1178 | eval2 = (score1=="1/2" ? 0 : (score1=="1-0" ? 1 : -1) * maxeval); |
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; | |
69f3d801 | 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 | 1225 | const color = this.turn; |
067c675b BA |
1226 | const score = this.getCurrentScore(); |
1227 | if (score != "*") | |
1228 | return (score=="1/2" ? 0 : (score=="1-0" ? 1 : -1) * maxeval); | |
1d184b4c BA |
1229 | if (depth == 0) |
1230 | return this.evalPosition(); | |
15952ada | 1231 | const moves = this.getAllValidMoves("computer"); |
9e42b4dd | 1232 | let v = color=="w" ? -maxeval : maxeval; |
1d184b4c BA |
1233 | if (color == "w") |
1234 | { | |
1235 | for (let i=0; i<moves.length; i++) | |
1236 | { | |
1237 | this.play(moves[i]); | |
46302e64 | 1238 | v = Math.max(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
1239 | this.undo(moves[i]); |
1240 | alpha = Math.max(alpha, v); | |
1241 | if (alpha >= beta) | |
1242 | break; //beta cutoff | |
1243 | } | |
1244 | } | |
1245 | else //color=="b" | |
1246 | { | |
1247 | for (let i=0; i<moves.length; i++) | |
1248 | { | |
1249 | this.play(moves[i]); | |
46302e64 | 1250 | v = Math.min(v, this.alphabeta(depth-1, alpha, beta)); |
1d184b4c BA |
1251 | this.undo(moves[i]); |
1252 | beta = Math.min(beta, v); | |
1253 | if (alpha >= beta) | |
1254 | break; //alpha cutoff | |
1255 | } | |
1256 | } | |
1257 | return v; | |
1258 | } | |
1259 | ||
1260 | evalPosition() | |
1261 | { | |
1d184b4c | 1262 | let evaluation = 0; |
a6abf094 | 1263 | // Just count material for now |
0b7d99ec | 1264 | for (let i=0; i<V.size.x; i++) |
1d184b4c | 1265 | { |
0b7d99ec | 1266 | for (let j=0; j<V.size.y; j++) |
1d184b4c | 1267 | { |
0b7d99ec | 1268 | if (this.board[i][j] != V.EMPTY) |
1d184b4c BA |
1269 | { |
1270 | const sign = this.getColor(i,j) == "w" ? 1 : -1; | |
0b7d99ec | 1271 | evaluation += sign * V.VALUES[this.getPiece(i,j)]; |
1d184b4c BA |
1272 | } |
1273 | } | |
1274 | } | |
1275 | return evaluation; | |
1276 | } | |
1277 | ||
1a788978 BA |
1278 | ///////////////////////// |
1279 | // MOVES + GAME NOTATION | |
1280 | ///////////////////////// | |
1d184b4c BA |
1281 | |
1282 | // Context: just before move is played, turn hasn't changed | |
b6487fb9 | 1283 | // TODO: un-ambiguous notation (switch on piece type, check directions...) |
1d184b4c BA |
1284 | getNotation(move) |
1285 | { | |
0b7d99ec | 1286 | if (move.appear.length == 2 && move.appear[0].p == V.KING) //castle |
15952ada | 1287 | return (move.end.y < move.start.y ? "0-0-0" : "0-0"); |
1d184b4c BA |
1288 | |
1289 | // Translate final square | |
1a788978 | 1290 | const finalSquare = V.CoordsToSquare(move.end); |
1d184b4c | 1291 | |
270968d6 | 1292 | const piece = this.getPiece(move.start.x, move.start.y); |
0b7d99ec | 1293 | if (piece == V.PAWN) |
1d184b4c BA |
1294 | { |
1295 | // Pawn move | |
1296 | let notation = ""; | |
5bfb0956 | 1297 | if (move.vanish.length > move.appear.length) |
1d184b4c BA |
1298 | { |
1299 | // Capture | |
26c1e3bd | 1300 | const startColumn = V.CoordToColumn(move.start.y); |
1d184b4c BA |
1301 | notation = startColumn + "x" + finalSquare; |
1302 | } | |
1303 | else //no capture | |
1304 | notation = finalSquare; | |
26c1e3bd | 1305 | if (move.appear.length > 0 && move.appear[0].p != V.PAWN) //promotion |
1d184b4c BA |
1306 | notation += "=" + move.appear[0].p.toUpperCase(); |
1307 | return notation; | |
1308 | } | |
1309 | ||
1310 | else | |
1311 | { | |
1312 | // Piece movement | |
f3c10e18 BA |
1313 | return piece.toUpperCase() + |
1314 | (move.vanish.length > move.appear.length ? "x" : "") + finalSquare; | |
1d184b4c BA |
1315 | } |
1316 | } | |
dfb4afc1 | 1317 | |
6752407b BA |
1318 | // Complete the usual notation, may be required for de-ambiguification |
1319 | getLongNotation(move) | |
1320 | { | |
1a788978 BA |
1321 | // Not encoding move. But short+long is enough |
1322 | return V.CoordsToSquare(move.start) + V.CoordsToSquare(move.end); | |
6752407b BA |
1323 | } |
1324 | ||
dfb4afc1 | 1325 | // The score is already computed when calling this function |
b6487fb9 | 1326 | getPGN(moves, mycolor, score, fenStart, mode) |
dfb4afc1 BA |
1327 | { |
1328 | let pgn = ""; | |
edcd679a | 1329 | pgn += '[Site "vchess.club"]\n'; |
5e622704 | 1330 | const opponent = mode=="human" ? "Anonymous" : "Computer"; |
edcd679a BA |
1331 | pgn += '[Variant "' + variant + '"]\n'; |
1332 | pgn += '[Date "' + getDate(new Date()) + '"]\n'; | |
1333 | // TODO: later when users are a bit less anonymous, use better names | |
1334 | const whiteName = ["human","computer"].includes(mode) | |
1335 | ? (mycolor=='w'?'Myself':opponent) | |
1336 | : "analyze"; | |
1337 | const blackName = ["human","computer"].includes(mode) | |
1338 | ? (mycolor=='b'?'Myself':opponent) | |
1339 | : "analyze"; | |
1340 | pgn += '[White "' + whiteName + '"]\n'; | |
1341 | pgn += '[Black "' + blackName + '"]\n'; | |
b6487fb9 | 1342 | pgn += '[Fen "' + fenStart + '"]\n'; |
edcd679a | 1343 | pgn += '[Result "' + score + '"]\n\n'; |
dfb4afc1 | 1344 | |
b6487fb9 BA |
1345 | // Print moves |
1346 | for (let i=0; i<moves.length; i++) | |
6752407b BA |
1347 | { |
1348 | if (i % 2 == 0) | |
1349 | pgn += ((i/2)+1) + "."; | |
b6487fb9 | 1350 | pgn += moves[i].notation + " "; |
6752407b | 1351 | } |
6752407b | 1352 | |
edcd679a | 1353 | return pgn + "\n"; |
dfb4afc1 | 1354 | } |
1d184b4c | 1355 | } |