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