Update TODO
[vchess.git] / client / src / base_rules.js
CommitLineData
92342261
BA
1// (Orthodox) Chess rules are defined in ChessRules class.
2// Variants generally inherit from it, and modify some parts.
3
e2732923 4import { ArrayFun } from "@/utils/array";
0c3fe8a6 5import { randInt, shuffle } from "@/utils/alea";
e2732923 6
910d631b 7// class "PiPo": Piece + Position
6808d7a1 8export const PiPo = class PiPo {
1c9f093d 9 // o: {piece[p], color[c], posX[x], posY[y]}
6808d7a1 10 constructor(o) {
1c9f093d
BA
11 this.p = o.p;
12 this.c = o.c;
13 this.x = o.x;
14 this.y = o.y;
15 }
6808d7a1 16};
1d184b4c 17
6808d7a1 18export const Move = class Move {
1c9f093d
BA
19 // o: {appear, vanish, [start,] [end,]}
20 // appear,vanish = arrays of PiPo
21 // start,end = coordinates to apply to trigger move visually (think castle)
6808d7a1 22 constructor(o) {
1c9f093d
BA
23 this.appear = o.appear;
24 this.vanish = o.vanish;
6808d7a1
BA
25 this.start = o.start ? o.start : { x: o.vanish[0].x, y: o.vanish[0].y };
26 this.end = o.end ? o.end : { x: o.appear[0].x, y: o.appear[0].y };
1c9f093d 27 }
6808d7a1 28};
1d184b4c 29
2c5d7b20
BA
30// NOTE: x coords = top to bottom; y = left to right
31// (from white player perspective)
6808d7a1 32export const ChessRules = class ChessRules {
1c9f093d
BA
33 //////////////
34 // MISC UTILS
35
20620465 36 // Some variants don't have flags:
6808d7a1
BA
37 static get HasFlags() {
38 return true;
20620465 39 }
1c9f093d 40
3a2a7b5f
BA
41 // Or castle
42 static get HasCastle() {
43 return V.HasFlags;
44 }
45
32f6285e
BA
46 // Pawns specifications
47 static get PawnSpecs() {
48 return {
49 directions: { 'w': -1, 'b': 1 },
472c0c4f 50 initShift: { w: 1, b: 1 },
32f6285e 51 twoSquares: true,
472c0c4f 52 threeSquares: false,
32f6285e
BA
53 promotions: [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN],
54 canCapture: true,
55 captureBackward: false,
56 bidirectional: false
57 };
58 }
59
60 // En-passant captures need a stack of squares:
6808d7a1
BA
61 static get HasEnpassant() {
62 return true;
20620465
BA
63 }
64
65 // Some variants cannot have analyse mode
8477e53d 66 static get CanAnalyze() {
20620465
BA
67 return true;
68 }
933fd1f9
BA
69 // Patch: issues with javascript OOP, objects can't access static fields.
70 get canAnalyze() {
71 return V.CanAnalyze;
72 }
20620465
BA
73
74 // Some variants show incomplete information,
75 // and thus show only a partial moves list or no list at all.
76 static get ShowMoves() {
77 return "all";
78 }
933fd1f9
BA
79 get showMoves() {
80 return V.ShowMoves;
81 }
1c9f093d 82
5246b49d
BA
83 // Used for Monochrome variant (TODO: harmonize: !canFlip ==> showFirstTurn)
84 get showFirstTurn() {
85 return false;
86 }
87
71ef1664
BA
88 // Some variants always show the same orientation
89 static get CanFlip() {
90 return true;
91 }
92 get canFlip() {
93 return V.CanFlip;
94 }
95
107dc1bd
BA
96 // For (generally old) variants without checkered board
97 static get Monochrome() {
98 return false;
99 }
100
101 // Some variants require lines drawing
102 static get Lines() {
103 if (V.Monochrome) {
104 let lines = [];
105 // Draw all inter-squares lines
106 for (let i = 0; i <= V.size.x; i++)
107 lines.push([[i, 0], [i, V.size.y]]);
108 for (let j = 0; j <= V.size.y; j++)
109 lines.push([[0, j], [V.size.x, j]]);
110 return lines;
111 }
112 return null;
113 }
114
61656127
BA
115 // Some variants use click infos:
116 doClick() {
117 return null;
118 }
119
14edde72
BA
120 static get IMAGE_EXTENSION() {
121 // All pieces should be in the SVG format
122 return ".svg";
123 }
124
1c9f093d 125 // Turn "wb" into "B" (for FEN)
6808d7a1
BA
126 static board2fen(b) {
127 return b[0] == "w" ? b[1].toUpperCase() : b[1];
1c9f093d
BA
128 }
129
130 // Turn "p" into "bp" (for board)
6808d7a1
BA
131 static fen2board(f) {
132 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
1c9f093d
BA
133 }
134
68e19a44 135 // Check if FEN describes a board situation correctly
6808d7a1 136 static IsGoodFen(fen) {
1c9f093d
BA
137 const fenParsed = V.ParseFen(fen);
138 // 1) Check position
6808d7a1 139 if (!V.IsGoodPosition(fenParsed.position)) return false;
1c9f093d 140 // 2) Check turn
6808d7a1 141 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
1c9f093d
BA
142 // 3) Check moves count
143 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
144 return false;
145 // 4) Check flags
146 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
147 return false;
148 // 5) Check enpassant
6808d7a1
BA
149 if (
150 V.HasEnpassant &&
151 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
152 ) {
1c9f093d
BA
153 return false;
154 }
155 return true;
156 }
157
158 // Is position part of the FEN a priori correct?
6808d7a1
BA
159 static IsGoodPosition(position) {
160 if (position.length == 0) return false;
1c9f093d 161 const rows = position.split("/");
6808d7a1 162 if (rows.length != V.size.x) return false;
6f2f9437 163 let kings = { "k": 0, "K": 0 };
6808d7a1 164 for (let row of rows) {
1c9f093d 165 let sumElts = 0;
6808d7a1 166 for (let i = 0; i < row.length; i++) {
6f2f9437 167 if (['K','k'].includes(row[i])) kings[row[i]]++;
6808d7a1
BA
168 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
169 else {
1c9f093d 170 const num = parseInt(row[i]);
6808d7a1 171 if (isNaN(num)) return false;
1c9f093d
BA
172 sumElts += num;
173 }
174 }
6808d7a1 175 if (sumElts != V.size.y) return false;
1c9f093d 176 }
6f2f9437
BA
177 // Both kings should be on board. Exactly one per color.
178 if (Object.values(kings).some(v => v != 1)) return false;
1c9f093d
BA
179 return true;
180 }
181
182 // For FEN checking
6808d7a1
BA
183 static IsGoodTurn(turn) {
184 return ["w", "b"].includes(turn);
1c9f093d
BA
185 }
186
187 // For FEN checking
6808d7a1 188 static IsGoodFlags(flags) {
3a2a7b5f
BA
189 // NOTE: a little too permissive to work with more variants
190 return !!flags.match(/^[a-z]{4,4}$/);
1c9f093d
BA
191 }
192
472c0c4f 193 // NOTE: not with regexp to adapt to different board sizes. (TODO?)
6808d7a1
BA
194 static IsGoodEnpassant(enpassant) {
195 if (enpassant != "-") {
196 const ep = V.SquareToCoords(enpassant);
197 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
1c9f093d
BA
198 }
199 return true;
200 }
201
202 // 3 --> d (column number to letter)
6808d7a1 203 static CoordToColumn(colnum) {
1c9f093d
BA
204 return String.fromCharCode(97 + colnum);
205 }
206
207 // d --> 3 (column letter to number)
6808d7a1 208 static ColumnToCoord(column) {
1c9f093d
BA
209 return column.charCodeAt(0) - 97;
210 }
211
212 // a4 --> {x:3,y:0}
6808d7a1 213 static SquareToCoords(sq) {
1c9f093d
BA
214 return {
215 // NOTE: column is always one char => max 26 columns
216 // row is counted from black side => subtraction
217 x: V.size.x - parseInt(sq.substr(1)),
218 y: sq[0].charCodeAt() - 97
219 };
220 }
221
222 // {x:0,y:4} --> e8
6808d7a1 223 static CoordsToSquare(coords) {
1c9f093d
BA
224 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
225 }
226
305ede7e 227 // Path to pieces (standard ones in pieces/ folder)
241bf8f2 228 getPpath(b) {
305ede7e 229 return b;
241bf8f2
BA
230 }
231
3a2a7b5f 232 // Path to promotion pieces (usually the same)
c7550017
BA
233 getPPpath(m) {
234 return this.getPpath(m.appear[0].c + m.appear[0].p);
3a2a7b5f
BA
235 }
236
1c9f093d 237 // Aggregates flags into one object
6808d7a1 238 aggregateFlags() {
1c9f093d
BA
239 return this.castleFlags;
240 }
241
242 // Reverse operation
6808d7a1 243 disaggregateFlags(flags) {
1c9f093d
BA
244 this.castleFlags = flags;
245 }
246
247 // En-passant square, if any
6808d7a1
BA
248 getEpSquare(moveOrSquare) {
249 if (!moveOrSquare) return undefined;
250 if (typeof moveOrSquare === "string") {
1c9f093d 251 const square = moveOrSquare;
6808d7a1 252 if (square == "-") return undefined;
1c9f093d
BA
253 return V.SquareToCoords(square);
254 }
255 // Argument is a move:
256 const move = moveOrSquare;
1c5bfdf2
BA
257 const s = move.start,
258 e = move.end;
6808d7a1 259 if (
1c5bfdf2 260 s.y == e.y &&
0d5335de
BA
261 Math.abs(s.x - e.x) == 2 &&
262 // Next conditions for variants like Atomic or Rifle, Recycle...
263 (move.appear.length > 0 && move.appear[0].p == V.PAWN) &&
264 (move.vanish.length > 0 && move.vanish[0].p == V.PAWN)
6808d7a1 265 ) {
1c9f093d 266 return {
1c5bfdf2
BA
267 x: (s.x + e.x) / 2,
268 y: s.y
1c9f093d
BA
269 };
270 }
271 return undefined; //default
272 }
273
274 // Can thing on square1 take thing on square2
6808d7a1
BA
275 canTake([x1, y1], [x2, y2]) {
276 return this.getColor(x1, y1) !== this.getColor(x2, y2);
1c9f093d
BA
277 }
278
279 // Is (x,y) on the chessboard?
6808d7a1
BA
280 static OnBoard(x, y) {
281 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
1c9f093d
BA
282 }
283
284 // Used in interface: 'side' arg == player color
6808d7a1
BA
285 canIplay(side, [x, y]) {
286 return this.turn == side && this.getColor(x, y) == side;
1c9f093d
BA
287 }
288
289 // On which squares is color under check ? (for interface)
af34341d
BA
290 getCheckSquares() {
291 const color = this.turn;
b0a0468a
BA
292 return (
293 this.underCheck(color)
2c5d7b20
BA
294 // kingPos must be duplicated, because it may change:
295 ? [JSON.parse(JSON.stringify(this.kingPos[color]))]
b0a0468a
BA
296 : []
297 );
1c9f093d
BA
298 }
299
300 /////////////
301 // FEN UTILS
302
7ba4a5bc
BA
303 // Setup the initial random (asymmetric) position
304 static GenRandInitFen(randomness) {
7ba4a5bc
BA
305 if (randomness == 0)
306 // Deterministic:
3a2a7b5f 307 return "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0 ahah -";
7ba4a5bc 308
6808d7a1 309 let pieces = { w: new Array(8), b: new Array(8) };
3a2a7b5f 310 let flags = "";
7ba4a5bc 311 // Shuffle pieces on first (and last rank if randomness == 2)
6808d7a1 312 for (let c of ["w", "b"]) {
7ba4a5bc
BA
313 if (c == 'b' && randomness == 1) {
314 pieces['b'] = pieces['w'];
3a2a7b5f 315 flags += flags;
7ba4a5bc
BA
316 break;
317 }
318
1c9f093d
BA
319 let positions = ArrayFun.range(8);
320
321 // Get random squares for bishops
656b1878 322 let randIndex = 2 * randInt(4);
1c9f093d
BA
323 const bishop1Pos = positions[randIndex];
324 // The second bishop must be on a square of different color
656b1878 325 let randIndex_tmp = 2 * randInt(4) + 1;
1c9f093d
BA
326 const bishop2Pos = positions[randIndex_tmp];
327 // Remove chosen squares
6808d7a1
BA
328 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
329 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
1c9f093d
BA
330
331 // Get random squares for knights
656b1878 332 randIndex = randInt(6);
1c9f093d
BA
333 const knight1Pos = positions[randIndex];
334 positions.splice(randIndex, 1);
656b1878 335 randIndex = randInt(5);
1c9f093d
BA
336 const knight2Pos = positions[randIndex];
337 positions.splice(randIndex, 1);
338
339 // Get random square for queen
656b1878 340 randIndex = randInt(4);
1c9f093d
BA
341 const queenPos = positions[randIndex];
342 positions.splice(randIndex, 1);
343
344 // Rooks and king positions are now fixed,
345 // because of the ordering rook-king-rook
346 const rook1Pos = positions[0];
347 const kingPos = positions[1];
348 const rook2Pos = positions[2];
349
350 // Finally put the shuffled pieces in the board array
6808d7a1
BA
351 pieces[c][rook1Pos] = "r";
352 pieces[c][knight1Pos] = "n";
353 pieces[c][bishop1Pos] = "b";
354 pieces[c][queenPos] = "q";
355 pieces[c][kingPos] = "k";
356 pieces[c][bishop2Pos] = "b";
357 pieces[c][knight2Pos] = "n";
358 pieces[c][rook2Pos] = "r";
3a2a7b5f 359 flags += V.CoordToColumn(rook1Pos) + V.CoordToColumn(rook2Pos);
1c9f093d 360 }
e3e2cc44 361 // Add turn + flags + enpassant
6808d7a1
BA
362 return (
363 pieces["b"].join("") +
1c9f093d
BA
364 "/pppppppp/8/8/8/8/PPPPPPPP/" +
365 pieces["w"].join("").toUpperCase() +
3a2a7b5f 366 " w 0 " + flags + " -"
e3e2cc44 367 );
1c9f093d
BA
368 }
369
370 // "Parse" FEN: just return untransformed string data
6808d7a1 371 static ParseFen(fen) {
1c9f093d 372 const fenParts = fen.split(" ");
6808d7a1 373 let res = {
1c9f093d
BA
374 position: fenParts[0],
375 turn: fenParts[1],
6808d7a1 376 movesCount: fenParts[2]
1c9f093d
BA
377 };
378 let nextIdx = 3;
6808d7a1
BA
379 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
380 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
1c9f093d
BA
381 return res;
382 }
383
384 // Return current fen (game state)
6808d7a1
BA
385 getFen() {
386 return (
f9c36b2d
BA
387 this.getBaseFen() + " " +
388 this.getTurnFen() + " " +
6808d7a1
BA
389 this.movesCount +
390 (V.HasFlags ? " " + this.getFlagsFen() : "") +
391 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
392 );
1c9f093d
BA
393 }
394
f9c36b2d
BA
395 getFenForRepeat() {
396 // Omit movesCount, only variable allowed to differ
397 return (
398 this.getBaseFen() + "_" +
399 this.getTurnFen() +
400 (V.HasFlags ? "_" + this.getFlagsFen() : "") +
401 (V.HasEnpassant ? "_" + this.getEnpassantFen() : "")
402 );
403 }
404
1c9f093d 405 // Position part of the FEN string
6808d7a1 406 getBaseFen() {
6f2f9437
BA
407 const format = (count) => {
408 // if more than 9 consecutive free spaces, break the integer,
409 // otherwise FEN parsing will fail.
410 if (count <= 9) return count;
411 // Currently only boards of size up to 11 or 12:
412 return "9" + (count - 9);
413 };
1c9f093d 414 let position = "";
6808d7a1 415 for (let i = 0; i < V.size.x; i++) {
1c9f093d 416 let emptyCount = 0;
6808d7a1
BA
417 for (let j = 0; j < V.size.y; j++) {
418 if (this.board[i][j] == V.EMPTY) emptyCount++;
419 else {
420 if (emptyCount > 0) {
1c9f093d 421 // Add empty squares in-between
6f2f9437 422 position += format(emptyCount);
1c9f093d
BA
423 emptyCount = 0;
424 }
425 position += V.board2fen(this.board[i][j]);
426 }
427 }
6808d7a1 428 if (emptyCount > 0) {
1c9f093d 429 // "Flush remainder"
6f2f9437 430 position += format(emptyCount);
1c9f093d 431 }
6808d7a1 432 if (i < V.size.x - 1) position += "/"; //separate rows
1c9f093d
BA
433 }
434 return position;
435 }
436
6808d7a1 437 getTurnFen() {
1c9f093d
BA
438 return this.turn;
439 }
440
441 // Flags part of the FEN string
6808d7a1 442 getFlagsFen() {
1c9f093d 443 let flags = "";
3a2a7b5f
BA
444 // Castling flags
445 for (let c of ["w", "b"])
446 flags += this.castleFlags[c].map(V.CoordToColumn).join("");
1c9f093d
BA
447 return flags;
448 }
449
450 // Enpassant part of the FEN string
6808d7a1 451 getEnpassantFen() {
1c9f093d 452 const L = this.epSquares.length;
6808d7a1
BA
453 if (!this.epSquares[L - 1]) return "-"; //no en-passant
454 return V.CoordsToSquare(this.epSquares[L - 1]);
1c9f093d
BA
455 }
456
457 // Turn position fen into double array ["wb","wp","bk",...]
6808d7a1 458 static GetBoard(position) {
1c9f093d
BA
459 const rows = position.split("/");
460 let board = ArrayFun.init(V.size.x, V.size.y, "");
6808d7a1 461 for (let i = 0; i < rows.length; i++) {
1c9f093d 462 let j = 0;
6808d7a1 463 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
1c9f093d
BA
464 const character = rows[i][indexInRow];
465 const num = parseInt(character);
a13cbc0f 466 // If num is a number, just shift j:
6808d7a1 467 if (!isNaN(num)) j += num;
a13cbc0f 468 // Else: something at position i,j
6808d7a1 469 else board[i][j++] = V.fen2board(character);
1c9f093d
BA
470 }
471 }
472 return board;
473 }
474
475 // Extract (relevant) flags from fen
6808d7a1 476 setFlags(fenflags) {
1c9f093d 477 // white a-castle, h-castle, black a-castle, h-castle
bb688df5 478 this.castleFlags = { w: [-1, -1], b: [-1, -1] };
3a2a7b5f
BA
479 for (let i = 0; i < 4; i++) {
480 this.castleFlags[i < 2 ? "w" : "b"][i % 2] =
481 V.ColumnToCoord(fenflags.charAt(i));
482 }
1c9f093d
BA
483 }
484
485 //////////////////
486 // INITIALIZATION
487
37cdcbf3 488 // Fen string fully describes the game state
b627d118
BA
489 constructor(fen) {
490 if (!fen)
491 // In printDiagram() fen isn't supply because only getPpath() is used
492 // TODO: find a better solution!
493 return;
1c9f093d
BA
494 const fenParsed = V.ParseFen(fen);
495 this.board = V.GetBoard(fenParsed.position);
af34341d 496 this.turn = fenParsed.turn;
1c9f093d
BA
497 this.movesCount = parseInt(fenParsed.movesCount);
498 this.setOtherVariables(fen);
499 }
500
3a2a7b5f
BA
501 // Scan board for kings positions
502 scanKings(fen) {
6808d7a1 503 this.INIT_COL_KING = { w: -1, b: -1 };
2c5d7b20
BA
504 // Squares of white and black king:
505 this.kingPos = { w: [-1, -1], b: [-1, -1] };
1c9f093d 506 const fenRows = V.ParseFen(fen).position.split("/");
90e814b6 507 const startRow = { 'w': V.size.x - 1, 'b': 0 };
6808d7a1 508 for (let i = 0; i < fenRows.length; i++) {
1c9f093d 509 let k = 0; //column index on board
6808d7a1
BA
510 for (let j = 0; j < fenRows[i].length; j++) {
511 switch (fenRows[i].charAt(j)) {
512 case "k":
513 this.kingPos["b"] = [i, k];
514 this.INIT_COL_KING["b"] = k;
1c9f093d 515 break;
6808d7a1
BA
516 case "K":
517 this.kingPos["w"] = [i, k];
518 this.INIT_COL_KING["w"] = k;
1c9f093d 519 break;
6808d7a1 520 default: {
1c9f093d 521 const num = parseInt(fenRows[i].charAt(j));
6808d7a1
BA
522 if (!isNaN(num)) k += num - 1;
523 }
1c9f093d
BA
524 }
525 k++;
526 }
527 }
528 }
529
530 // Some additional variables from FEN (variant dependant)
6808d7a1 531 setOtherVariables(fen) {
1c9f093d
BA
532 // Set flags and enpassant:
533 const parsedFen = V.ParseFen(fen);
6808d7a1
BA
534 if (V.HasFlags) this.setFlags(parsedFen.flags);
535 if (V.HasEnpassant) {
536 const epSq =
537 parsedFen.enpassant != "-"
9bd6786b 538 ? this.getEpSquare(parsedFen.enpassant)
6808d7a1
BA
539 : undefined;
540 this.epSquares = [epSq];
1c9f093d 541 }
3a2a7b5f
BA
542 // Search for kings positions:
543 this.scanKings(fen);
1c9f093d
BA
544 }
545
546 /////////////////////
547 // GETTERS & SETTERS
548
6808d7a1
BA
549 static get size() {
550 return { x: 8, y: 8 };
1c9f093d
BA
551 }
552
0ba6420d 553 // Color of thing on square (i,j). 'undefined' if square is empty
6808d7a1 554 getColor(i, j) {
1c9f093d
BA
555 return this.board[i][j].charAt(0);
556 }
557
558 // Piece type on square (i,j). 'undefined' if square is empty
6808d7a1 559 getPiece(i, j) {
1c9f093d
BA
560 return this.board[i][j].charAt(1);
561 }
562
563 // Get opponent color
6808d7a1
BA
564 static GetOppCol(color) {
565 return color == "w" ? "b" : "w";
1c9f093d
BA
566 }
567
1c9f093d 568 // Pieces codes (for a clearer code)
6808d7a1
BA
569 static get PAWN() {
570 return "p";
571 }
572 static get ROOK() {
573 return "r";
574 }
575 static get KNIGHT() {
576 return "n";
577 }
578 static get BISHOP() {
579 return "b";
580 }
581 static get QUEEN() {
582 return "q";
583 }
584 static get KING() {
585 return "k";
586 }
1c9f093d
BA
587
588 // For FEN checking:
6808d7a1
BA
589 static get PIECES() {
590 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
1c9f093d
BA
591 }
592
593 // Empty square
6808d7a1
BA
594 static get EMPTY() {
595 return "";
596 }
1c9f093d
BA
597
598 // Some pieces movements
6808d7a1 599 static get steps() {
1c9f093d 600 return {
6808d7a1
BA
601 r: [
602 [-1, 0],
603 [1, 0],
604 [0, -1],
605 [0, 1]
606 ],
607 n: [
608 [-1, -2],
609 [-1, 2],
610 [1, -2],
611 [1, 2],
612 [-2, -1],
613 [-2, 1],
614 [2, -1],
615 [2, 1]
616 ],
617 b: [
618 [-1, -1],
619 [-1, 1],
620 [1, -1],
621 [1, 1]
622 ]
1c9f093d
BA
623 };
624 }
625
626 ////////////////////
627 // MOVES GENERATION
628
0ba6420d 629 // All possible moves from selected square
6808d7a1
BA
630 getPotentialMovesFrom([x, y]) {
631 switch (this.getPiece(x, y)) {
1c9f093d 632 case V.PAWN:
6808d7a1 633 return this.getPotentialPawnMoves([x, y]);
1c9f093d 634 case V.ROOK:
6808d7a1 635 return this.getPotentialRookMoves([x, y]);
1c9f093d 636 case V.KNIGHT:
6808d7a1 637 return this.getPotentialKnightMoves([x, y]);
1c9f093d 638 case V.BISHOP:
6808d7a1 639 return this.getPotentialBishopMoves([x, y]);
1c9f093d 640 case V.QUEEN:
6808d7a1 641 return this.getPotentialQueenMoves([x, y]);
1c9f093d 642 case V.KING:
6808d7a1 643 return this.getPotentialKingMoves([x, y]);
1c9f093d 644 }
6808d7a1 645 return []; //never reached
1c9f093d
BA
646 }
647
648 // Build a regular move from its initial and destination squares.
649 // tr: transformation
6808d7a1 650 getBasicMove([sx, sy], [ex, ey], tr) {
1c58eb76
BA
651 const initColor = this.getColor(sx, sy);
652 const initPiece = this.getPiece(sx, sy);
1c9f093d
BA
653 let mv = new Move({
654 appear: [
655 new PiPo({
656 x: ex,
657 y: ey,
1c58eb76
BA
658 c: tr ? tr.c : initColor,
659 p: tr ? tr.p : initPiece
1c9f093d
BA
660 })
661 ],
662 vanish: [
663 new PiPo({
664 x: sx,
665 y: sy,
1c58eb76
BA
666 c: initColor,
667 p: initPiece
1c9f093d
BA
668 })
669 ]
670 });
671
672 // The opponent piece disappears if we take it
6808d7a1 673 if (this.board[ex][ey] != V.EMPTY) {
1c9f093d
BA
674 mv.vanish.push(
675 new PiPo({
676 x: ex,
677 y: ey,
6808d7a1
BA
678 c: this.getColor(ex, ey),
679 p: this.getPiece(ex, ey)
1c9f093d
BA
680 })
681 );
682 }
1c5bfdf2 683
1c9f093d
BA
684 return mv;
685 }
686
687 // Generic method to find possible moves of non-pawn pieces:
688 // "sliding or jumping"
6808d7a1 689 getSlideNJumpMoves([x, y], steps, oneStep) {
1c9f093d 690 let moves = [];
6808d7a1 691 outerLoop: for (let step of steps) {
1c9f093d
BA
692 let i = x + step[0];
693 let j = y + step[1];
6808d7a1
BA
694 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
695 moves.push(this.getBasicMove([x, y], [i, j]));
d1be8046 696 if (oneStep) continue outerLoop;
1c9f093d
BA
697 i += step[0];
698 j += step[1];
699 }
6808d7a1
BA
700 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
701 moves.push(this.getBasicMove([x, y], [i, j]));
1c9f093d
BA
702 }
703 return moves;
704 }
705
32f6285e
BA
706 // Special case of en-passant captures: treated separately
707 getEnpassantCaptures([x, y], shiftX) {
708 const Lep = this.epSquares.length;
709 const epSquare = this.epSquares[Lep - 1]; //always at least one element
710 let enpassantMove = null;
711 if (
712 !!epSquare &&
713 epSquare.x == x + shiftX &&
714 Math.abs(epSquare.y - y) == 1
715 ) {
716 enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
717 enpassantMove.vanish.push({
718 x: x,
719 y: epSquare.y,
8c1ec210 720 // Captured piece is usually a pawn, but next line seems harmless
6f2f9437 721 p: this.getPiece(x, epSquare.y),
32f6285e
BA
722 c: this.getColor(x, epSquare.y)
723 });
724 }
725 return !!enpassantMove ? [enpassantMove] : [];
726 }
727
1c58eb76
BA
728 // Consider all potential promotions:
729 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
730 let finalPieces = [V.PAWN];
af34341d 731 const color = this.turn; //this.getColor(x1, y1);
1c58eb76
BA
732 const lastRank = (color == "w" ? 0 : V.size.x - 1);
733 if (x2 == lastRank) {
734 // promotions arg: special override for Hiddenqueen variant
735 if (!!promotions) finalPieces = promotions;
736 else if (!!V.PawnSpecs.promotions)
737 finalPieces = V.PawnSpecs.promotions;
738 }
739 let tr = null;
740 for (let piece of finalPieces) {
741 tr = (piece != V.PAWN ? { c: color, p: piece } : null);
742 moves.push(this.getBasicMove([x1, y1], [x2, y2], tr));
743 }
744 }
745
1c9f093d 746 // What are the pawn moves from square x,y ?
32f6285e 747 getPotentialPawnMoves([x, y], promotions) {
af34341d 748 const color = this.turn; //this.getColor(x, y);
6808d7a1 749 const [sizeX, sizeY] = [V.size.x, V.size.y];
32f6285e 750 const pawnShiftX = V.PawnSpecs.directions[color];
1c58eb76 751 const firstRank = (color == "w" ? sizeX - 1 : 0);
32f6285e
BA
752
753 // Pawn movements in shiftX direction:
754 const getPawnMoves = (shiftX) => {
755 let moves = [];
756 // NOTE: next condition is generally true (no pawn on last rank)
757 if (x + shiftX >= 0 && x + shiftX < sizeX) {
758 if (this.board[x + shiftX][y] == V.EMPTY) {
759 // One square forward
1c58eb76 760 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
32f6285e
BA
761 // Next condition because pawns on 1st rank can generally jump
762 if (
763 V.PawnSpecs.twoSquares &&
472c0c4f
BA
764 (
765 (color == 'w' && x >= V.size.x - 1 - V.PawnSpecs.initShift['w'])
766 ||
767 (color == 'b' && x <= V.PawnSpecs.initShift['b'])
768 )
32f6285e 769 ) {
472c0c4f
BA
770 if (this.board[x + 2 * shiftX][y] == V.EMPTY) {
771 // Two squares jump
772 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
773 if (
774 V.PawnSpecs.threeSquares &&
775 this.board[x + 3 * shiftX][y] == V.EMPTY
776 ) {
777 // Three squares jump
778 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
779 }
780 }
32f6285e
BA
781 }
782 }
783 // Captures
784 if (V.PawnSpecs.canCapture) {
785 for (let shiftY of [-1, 1]) {
786 if (
787 y + shiftY >= 0 &&
788 y + shiftY < sizeY
789 ) {
790 if (
791 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
792 this.canTake([x, y], [x + shiftX, y + shiftY])
793 ) {
1c58eb76
BA
794 this.addPawnMoves(
795 [x, y], [x + shiftX, y + shiftY],
796 moves, promotions
797 );
32f6285e
BA
798 }
799 if (
800 V.PawnSpecs.captureBackward &&
801 x - shiftX >= 0 && x - shiftX < V.size.x &&
802 this.board[x - shiftX][y + shiftY] != V.EMPTY &&
803 this.canTake([x, y], [x - shiftX, y + shiftY])
804 ) {
1c58eb76
BA
805 this.addPawnMoves(
806 [x, y], [x + shiftX, y + shiftY],
807 moves, promotions
808 );
32f6285e
BA
809 }
810 }
1c9f093d
BA
811 }
812 }
813 }
32f6285e 814 return moves;
1c9f093d
BA
815 }
816
32f6285e
BA
817 let pMoves = getPawnMoves(pawnShiftX);
818 if (V.PawnSpecs.bidirectional)
819 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
820
6808d7a1 821 if (V.HasEnpassant) {
32f6285e
BA
822 // NOTE: backward en-passant captures are not considered
823 // because no rules define them (for now).
824 Array.prototype.push.apply(
825 pMoves,
826 this.getEnpassantCaptures([x, y], pawnShiftX)
827 );
1c9f093d 828 }
294fe29f 829
32f6285e 830 return pMoves;
1c9f093d
BA
831 }
832
833 // What are the rook moves from square x,y ?
6808d7a1 834 getPotentialRookMoves(sq) {
1c9f093d
BA
835 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
836 }
837
838 // What are the knight moves from square x,y ?
6808d7a1 839 getPotentialKnightMoves(sq) {
1c9f093d
BA
840 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
841 }
842
843 // What are the bishop moves from square x,y ?
6808d7a1 844 getPotentialBishopMoves(sq) {
1c9f093d
BA
845 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
846 }
847
848 // What are the queen moves from square x,y ?
6808d7a1
BA
849 getPotentialQueenMoves(sq) {
850 return this.getSlideNJumpMoves(
851 sq,
852 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
853 );
1c9f093d
BA
854 }
855
856 // What are the king moves from square x,y ?
6808d7a1 857 getPotentialKingMoves(sq) {
1c9f093d 858 // Initialize with normal moves
c583ef1c 859 let moves = this.getSlideNJumpMoves(
6808d7a1
BA
860 sq,
861 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
862 "oneStep"
863 );
c583ef1c
BA
864 if (V.HasCastle) moves = moves.concat(this.getCastleMoves(sq));
865 return moves;
1c9f093d
BA
866 }
867
a6836242
BA
868 // "castleInCheck" arg to let some variants castle under check
869 getCastleMoves([x, y], castleInCheck) {
6808d7a1
BA
870 const c = this.getColor(x, y);
871 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
1c9f093d
BA
872 return []; //x isn't first rank, or king has moved (shortcut)
873
874 // Castling ?
875 const oppCol = V.GetOppCol(c);
876 let moves = [];
877 let i = 0;
9bd6786b 878 // King, then rook:
6808d7a1
BA
879 const finalSquares = [
880 [2, 3],
881 [V.size.y - 2, V.size.y - 3]
9bd6786b 882 ];
6808d7a1
BA
883 castlingCheck: for (
884 let castleSide = 0;
885 castleSide < 2;
886 castleSide++ //large, then small
887 ) {
3a2a7b5f 888 if (this.castleFlags[c][castleSide] >= V.size.y) continue;
3f22c2c3 889 // If this code is reached, rook and king are on initial position
1c9f093d 890
2c5d7b20 891 // NOTE: in some variants this is not a rook
32f6285e 892 const rookPos = this.castleFlags[c][castleSide];
61656127
BA
893 if (this.board[x][rookPos] == V.EMPTY || this.getColor(x, rookPos) != c)
894 // Rook is not here, or changed color (see Benedict)
32f6285e
BA
895 continue;
896
2beba6db 897 // Nothing on the path of the king ? (and no checks)
61656127 898 const castlingPiece = this.getPiece(x, rookPos);
2beba6db
BA
899 const finDist = finalSquares[castleSide][0] - y;
900 let step = finDist / Math.max(1, Math.abs(finDist));
901 i = y;
6808d7a1
BA
902 do {
903 if (
5e1bc651
BA
904 // NOTE: "castling" arg is used by some variants (Monster),
905 // where "isAttacked" is overloaded in an infinite-recursive way.
906 (!castleInCheck && this.isAttacked([x, i], oppCol, "castling")) ||
6808d7a1
BA
907 (this.board[x][i] != V.EMPTY &&
908 // NOTE: next check is enough, because of chessboard constraints
909 (this.getColor(x, i) != c ||
a6836242 910 ![V.KING, castlingPiece].includes(this.getPiece(x, i))))
6808d7a1 911 ) {
1c9f093d
BA
912 continue castlingCheck;
913 }
2beba6db 914 i += step;
6808d7a1 915 } while (i != finalSquares[castleSide][0]);
1c9f093d
BA
916
917 // Nothing on the path to the rook?
6808d7a1 918 step = castleSide == 0 ? -1 : 1;
3a2a7b5f 919 for (i = y + step; i != rookPos; i += step) {
6808d7a1 920 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
1c9f093d 921 }
1c9f093d
BA
922
923 // Nothing on final squares, except maybe king and castling rook?
6808d7a1
BA
924 for (i = 0; i < 2; i++) {
925 if (
5e1bc651 926 finalSquares[castleSide][i] != rookPos &&
6808d7a1 927 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
5e1bc651
BA
928 (
929 this.getPiece(x, finalSquares[castleSide][i]) != V.KING ||
930 this.getColor(x, finalSquares[castleSide][i]) != c
931 )
6808d7a1 932 ) {
1c9f093d
BA
933 continue castlingCheck;
934 }
935 }
936
937 // If this code is reached, castle is valid
6808d7a1
BA
938 moves.push(
939 new Move({
940 appear: [
2c5d7b20
BA
941 new PiPo({
942 x: x,
943 y: finalSquares[castleSide][0],
944 p: V.KING,
945 c: c
946 }),
947 new PiPo({
948 x: x,
949 y: finalSquares[castleSide][1],
950 p: castlingPiece,
951 c: c
952 })
6808d7a1
BA
953 ],
954 vanish: [
955 new PiPo({ x: x, y: y, p: V.KING, c: c }),
a6836242 956 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
6808d7a1
BA
957 ],
958 end:
959 Math.abs(y - rookPos) <= 2
960 ? { x: x, y: rookPos }
961 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
962 })
963 );
1c9f093d
BA
964 }
965
966 return moves;
967 }
968
969 ////////////////////
970 // MOVES VALIDATION
971
972 // For the interface: possible moves for the current turn from square sq
6808d7a1
BA
973 getPossibleMovesFrom(sq) {
974 return this.filterValid(this.getPotentialMovesFrom(sq));
1c9f093d
BA
975 }
976
977 // TODO: promotions (into R,B,N,Q) should be filtered only once
6808d7a1
BA
978 filterValid(moves) {
979 if (moves.length == 0) return [];
1c9f093d
BA
980 const color = this.turn;
981 return moves.filter(m => {
982 this.play(m);
983 const res = !this.underCheck(color);
984 this.undo(m);
985 return res;
986 });
987 }
988
5e1bc651 989 getAllPotentialMoves() {
1c9f093d 990 const color = this.turn;
1c9f093d 991 let potentialMoves = [];
6808d7a1
BA
992 for (let i = 0; i < V.size.x; i++) {
993 for (let j = 0; j < V.size.y; j++) {
156986e6 994 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
6808d7a1
BA
995 Array.prototype.push.apply(
996 potentialMoves,
997 this.getPotentialMovesFrom([i, j])
998 );
1c9f093d
BA
999 }
1000 }
1001 }
5e1bc651
BA
1002 return potentialMoves;
1003 }
1004
1005 // Search for all valid moves considering current turn
1006 // (for engine and game end)
1007 getAllValidMoves() {
1008 return this.filterValid(this.getAllPotentialMoves());
1c9f093d
BA
1009 }
1010
1011 // Stop at the first move found
2c5d7b20 1012 // TODO: not really, it explores all moves from a square (one is enough).
6808d7a1 1013 atLeastOneMove() {
1c9f093d 1014 const color = this.turn;
6808d7a1
BA
1015 for (let i = 0; i < V.size.x; i++) {
1016 for (let j = 0; j < V.size.y; j++) {
665eed90 1017 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) == color) {
6808d7a1
BA
1018 const moves = this.getPotentialMovesFrom([i, j]);
1019 if (moves.length > 0) {
107dc1bd 1020 for (let k = 0; k < moves.length; k++)
6808d7a1 1021 if (this.filterValid([moves[k]]).length > 0) return true;
1c9f093d
BA
1022 }
1023 }
1024 }
1025 }
1026 return false;
1027 }
1028
68e19a44
BA
1029 // Check if pieces of given color are attacking (king) on square x,y
1030 isAttacked(sq, color) {
6808d7a1 1031 return (
68e19a44
BA
1032 this.isAttackedByPawn(sq, color) ||
1033 this.isAttackedByRook(sq, color) ||
1034 this.isAttackedByKnight(sq, color) ||
1035 this.isAttackedByBishop(sq, color) ||
1036 this.isAttackedByQueen(sq, color) ||
1037 this.isAttackedByKing(sq, color)
6808d7a1 1038 );
1c9f093d
BA
1039 }
1040
d1be8046 1041 // Generic method for non-pawn pieces ("sliding or jumping"):
68e19a44
BA
1042 // is x,y attacked by a piece of given color ?
1043 isAttackedBySlideNJump([x, y], color, piece, steps, oneStep) {
d1be8046
BA
1044 for (let step of steps) {
1045 let rx = x + step[0],
1046 ry = y + step[1];
1047 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1048 rx += step[0];
1049 ry += step[1];
1050 }
1051 if (
1052 V.OnBoard(rx, ry) &&
68e19a44
BA
1053 this.getPiece(rx, ry) == piece &&
1054 this.getColor(rx, ry) == color
d1be8046
BA
1055 ) {
1056 return true;
1057 }
1058 }
1059 return false;
1060 }
1061
68e19a44 1062 // Is square x,y attacked by 'color' pawns ?
107dc1bd 1063 isAttackedByPawn(sq, color) {
68e19a44 1064 const pawnShift = (color == "w" ? 1 : -1);
107dc1bd
BA
1065 return this.isAttackedBySlideNJump(
1066 sq,
1067 color,
1068 V.PAWN,
1069 [[pawnShift, 1], [pawnShift, -1]],
1070 "oneStep"
1071 );
1c9f093d
BA
1072 }
1073
68e19a44
BA
1074 // Is square x,y attacked by 'color' rooks ?
1075 isAttackedByRook(sq, color) {
1076 return this.isAttackedBySlideNJump(sq, color, V.ROOK, V.steps[V.ROOK]);
1c9f093d
BA
1077 }
1078
68e19a44
BA
1079 // Is square x,y attacked by 'color' knights ?
1080 isAttackedByKnight(sq, color) {
6808d7a1
BA
1081 return this.isAttackedBySlideNJump(
1082 sq,
68e19a44 1083 color,
6808d7a1
BA
1084 V.KNIGHT,
1085 V.steps[V.KNIGHT],
1086 "oneStep"
1087 );
1c9f093d
BA
1088 }
1089
68e19a44
BA
1090 // Is square x,y attacked by 'color' bishops ?
1091 isAttackedByBishop(sq, color) {
1092 return this.isAttackedBySlideNJump(sq, color, V.BISHOP, V.steps[V.BISHOP]);
1c9f093d
BA
1093 }
1094
68e19a44
BA
1095 // Is square x,y attacked by 'color' queens ?
1096 isAttackedByQueen(sq, color) {
6808d7a1
BA
1097 return this.isAttackedBySlideNJump(
1098 sq,
68e19a44 1099 color,
6808d7a1
BA
1100 V.QUEEN,
1101 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
1102 );
1c9f093d
BA
1103 }
1104
68e19a44
BA
1105 // Is square x,y attacked by 'color' king(s) ?
1106 isAttackedByKing(sq, color) {
6808d7a1
BA
1107 return this.isAttackedBySlideNJump(
1108 sq,
68e19a44 1109 color,
6808d7a1
BA
1110 V.KING,
1111 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
1112 "oneStep"
1113 );
1c9f093d
BA
1114 }
1115
1c9f093d 1116 // Is color under check after his move ?
6808d7a1 1117 underCheck(color) {
1c58eb76 1118 return this.isAttacked(this.kingPos[color], V.GetOppCol(color));
1c9f093d
BA
1119 }
1120
1121 /////////////////
1122 // MOVES PLAYING
1123
1124 // Apply a move on board
6808d7a1
BA
1125 static PlayOnBoard(board, move) {
1126 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
1127 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
1128 }
1129 // Un-apply the played move
6808d7a1
BA
1130 static UndoOnBoard(board, move) {
1131 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
1132 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
1133 }
1134
3a2a7b5f
BA
1135 prePlay() {}
1136
1137 play(move) {
1138 // DEBUG:
1139// if (!this.states) this.states = [];
1c58eb76 1140// const stateFen = this.getFen() + JSON.stringify(this.kingPos);
3a2a7b5f
BA
1141// this.states.push(stateFen);
1142
1143 this.prePlay(move);
2c5d7b20
BA
1144 // Save flags (for undo)
1145 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags());
3a2a7b5f
BA
1146 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1147 V.PlayOnBoard(this.board, move);
1148 this.turn = V.GetOppCol(this.turn);
1149 this.movesCount++;
1150 this.postPlay(move);
1151 }
1152
bb688df5 1153 updateCastleFlags(move, piece) {
1c58eb76
BA
1154 const c = V.GetOppCol(this.turn);
1155 const firstRank = (c == "w" ? V.size.x - 1 : 0);
1156 // Update castling flags if rooks are moved
c7550017 1157 const oppCol = this.turn;
1c58eb76 1158 const oppFirstRank = V.size.x - 1 - firstRank;
bb688df5
BA
1159 if (piece == V.KING && move.appear.length > 0)
1160 this.castleFlags[c] = [V.size.y, V.size.y];
1161 else if (
1c58eb76
BA
1162 move.start.x == firstRank && //our rook moves?
1163 this.castleFlags[c].includes(move.start.y)
1164 ) {
1165 const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1);
1166 this.castleFlags[c][flagIdx] = V.size.y;
305ede7e
BA
1167 }
1168 // NOTE: not "else if" because a rook could take an opposing rook
1169 if (
1c58eb76
BA
1170 move.end.x == oppFirstRank && //we took opponent rook?
1171 this.castleFlags[oppCol].includes(move.end.y)
1172 ) {
1173 const flagIdx = (move.end.y == this.castleFlags[oppCol][0] ? 0 : 1);
1174 this.castleFlags[oppCol][flagIdx] = V.size.y;
1175 }
1176 }
1177
1c9f093d 1178 // After move is played, update variables + flags
3a2a7b5f
BA
1179 postPlay(move) {
1180 const c = V.GetOppCol(this.turn);
1c9f093d 1181 let piece = undefined;
3a2a7b5f 1182 if (move.vanish.length >= 1)
1c9f093d
BA
1183 // Usual case, something is moved
1184 piece = move.vanish[0].p;
3a2a7b5f 1185 else
1c9f093d
BA
1186 // Crazyhouse-like variants
1187 piece = move.appear[0].p;
1c9f093d
BA
1188
1189 // Update king position + flags
6808d7a1 1190 if (piece == V.KING && move.appear.length > 0) {
1c9f093d
BA
1191 this.kingPos[c][0] = move.appear[0].x;
1192 this.kingPos[c][1] = move.appear[0].y;
1c9f093d 1193 }
bb688df5 1194 if (V.HasCastle) this.updateCastleFlags(move, piece);
1c9f093d
BA
1195 }
1196
3a2a7b5f 1197 preUndo() {}
1c9f093d 1198
6808d7a1 1199 undo(move) {
3a2a7b5f 1200 this.preUndo(move);
6808d7a1
BA
1201 if (V.HasEnpassant) this.epSquares.pop();
1202 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1c9f093d
BA
1203 V.UndoOnBoard(this.board, move);
1204 this.turn = V.GetOppCol(this.turn);
1205 this.movesCount--;
3a2a7b5f 1206 this.postUndo(move);
1c9f093d
BA
1207
1208 // DEBUG:
1c58eb76 1209// const stateFen = this.getFen() + JSON.stringify(this.kingPos);
9bd6786b
BA
1210// if (stateFen != this.states[this.states.length-1]) debugger;
1211// this.states.pop();
1c9f093d
BA
1212 }
1213
3a2a7b5f
BA
1214 // After move is undo-ed *and flags resetted*, un-update other variables
1215 // TODO: more symmetry, by storing flags increment in move (?!)
1216 postUndo(move) {
1217 // (Potentially) Reset king position
1218 const c = this.getColor(move.start.x, move.start.y);
1219 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1220 this.kingPos[c] = [move.start.x, move.start.y];
1221 }
1222
1c9f093d
BA
1223 ///////////////
1224 // END OF GAME
1225
1226 // What is the score ? (Interesting if game is over)
6808d7a1 1227 getCurrentScore() {
bb688df5 1228 if (this.atLeastOneMove()) return "*";
1c9f093d
BA
1229 // Game over
1230 const color = this.turn;
1231 // No valid move: stalemate or checkmate?
bb688df5 1232 if (!this.underCheck(color)) return "1/2";
1c9f093d 1233 // OK, checkmate
68e19a44 1234 return (color == "w" ? "0-1" : "1-0");
1c9f093d
BA
1235 }
1236
1237 ///////////////
1238 // ENGINE PLAY
1239
1240 // Pieces values
6808d7a1 1241 static get VALUES() {
1c9f093d 1242 return {
6808d7a1
BA
1243 p: 1,
1244 r: 5,
1245 n: 3,
1246 b: 3,
1247 q: 9,
1248 k: 1000
1c9f093d
BA
1249 };
1250 }
1251
1252 // "Checkmate" (unreachable eval)
6808d7a1
BA
1253 static get INFINITY() {
1254 return 9999;
1255 }
1c9f093d
BA
1256
1257 // At this value or above, the game is over
6808d7a1
BA
1258 static get THRESHOLD_MATE() {
1259 return V.INFINITY;
1260 }
1c9f093d 1261
2c5d7b20 1262 // Search depth: 1,2 for e.g. higher branching factor, 4 for smaller
6808d7a1
BA
1263 static get SEARCH_DEPTH() {
1264 return 3;
1265 }
1c9f093d 1266
af34341d
BA
1267 // 'movesList' arg for some variants to provide a custom list
1268 getComputerMove(movesList) {
1c9f093d
BA
1269 const maxeval = V.INFINITY;
1270 const color = this.turn;
af34341d 1271 let moves1 = movesList || this.getAllValidMoves();
c322a844 1272
6808d7a1 1273 if (moves1.length == 0)
e71161fb 1274 // TODO: this situation should not happen
41cb9b94 1275 return null;
1c9f093d 1276
b83a675a 1277 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
6808d7a1 1278 for (let i = 0; i < moves1.length; i++) {
afbf3ca7
BA
1279 this.play(moves1[i]);
1280 const score1 = this.getCurrentScore();
1281 if (score1 != "*") {
1282 moves1[i].eval =
1283 score1 == "1/2"
1284 ? 0
1285 : (score1 == "1-0" ? 1 : -1) * maxeval;
1286 }
1287 if (V.SEARCH_DEPTH == 1 || score1 != "*") {
1288 if (!moves1[i].eval) moves1[i].eval = this.evalPosition();
1289 this.undo(moves1[i]);
b83a675a
BA
1290 continue;
1291 }
1c9f093d 1292 // Initial self evaluation is very low: "I'm checkmated"
6808d7a1 1293 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
afbf3ca7
BA
1294 // Initial enemy evaluation is very low too, for him
1295 let eval2 = (color == "w" ? 1 : -1) * maxeval;
1296 // Second half-move:
1297 let moves2 = this.getAllValidMoves();
1298 for (let j = 0; j < moves2.length; j++) {
1299 this.play(moves2[j]);
1300 const score2 = this.getCurrentScore();
1301 let evalPos = 0; //1/2 value
1302 switch (score2) {
1303 case "*":
1304 evalPos = this.evalPosition();
1305 break;
1306 case "1-0":
1307 evalPos = maxeval;
1308 break;
1309 case "0-1":
1310 evalPos = -maxeval;
1311 break;
1c9f093d 1312 }
afbf3ca7
BA
1313 if (
1314 (color == "w" && evalPos < eval2) ||
1315 (color == "b" && evalPos > eval2)
1316 ) {
1317 eval2 = evalPos;
1318 }
1319 this.undo(moves2[j]);
1320 }
6808d7a1
BA
1321 if (
1322 (color == "w" && eval2 > moves1[i].eval) ||
1323 (color == "b" && eval2 < moves1[i].eval)
1324 ) {
1c9f093d
BA
1325 moves1[i].eval = eval2;
1326 }
1327 this.undo(moves1[i]);
1328 }
6808d7a1
BA
1329 moves1.sort((a, b) => {
1330 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1331 });
a97bdbda 1332// console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1c9f093d 1333
1c9f093d 1334 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
6808d7a1 1335 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
6808d7a1 1336 for (let i = 0; i < moves1.length; i++) {
1c9f093d
BA
1337 this.play(moves1[i]);
1338 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
6808d7a1
BA
1339 moves1[i].eval =
1340 0.1 * moves1[i].eval +
1341 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1c9f093d
BA
1342 this.undo(moves1[i]);
1343 }
6808d7a1
BA
1344 moves1.sort((a, b) => {
1345 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1346 });
b83a675a 1347 }
1c9f093d 1348
b83a675a 1349 let candidates = [0];
d54f6261
BA
1350 for (let i = 1; i < moves1.length && moves1[i].eval == moves1[0].eval; i++)
1351 candidates.push(i);
656b1878 1352 return moves1[candidates[randInt(candidates.length)]];
1c9f093d
BA
1353 }
1354
6808d7a1 1355 alphabeta(depth, alpha, beta) {
1c9f093d
BA
1356 const maxeval = V.INFINITY;
1357 const color = this.turn;
1358 const score = this.getCurrentScore();
1359 if (score != "*")
6808d7a1
BA
1360 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1361 if (depth == 0) return this.evalPosition();
a97bdbda 1362 const moves = this.getAllValidMoves();
6808d7a1
BA
1363 let v = color == "w" ? -maxeval : maxeval;
1364 if (color == "w") {
1365 for (let i = 0; i < moves.length; i++) {
1c9f093d 1366 this.play(moves[i]);
6808d7a1 1367 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1368 this.undo(moves[i]);
1369 alpha = Math.max(alpha, v);
6808d7a1 1370 if (alpha >= beta) break; //beta cutoff
1c9f093d 1371 }
1c5bfdf2 1372 }
6808d7a1 1373 else {
1c5bfdf2 1374 // color=="b"
6808d7a1 1375 for (let i = 0; i < moves.length; i++) {
1c9f093d 1376 this.play(moves[i]);
6808d7a1 1377 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1378 this.undo(moves[i]);
1379 beta = Math.min(beta, v);
6808d7a1 1380 if (alpha >= beta) break; //alpha cutoff
1c9f093d
BA
1381 }
1382 }
1383 return v;
1384 }
1385
6808d7a1 1386 evalPosition() {
1c9f093d
BA
1387 let evaluation = 0;
1388 // Just count material for now
6808d7a1
BA
1389 for (let i = 0; i < V.size.x; i++) {
1390 for (let j = 0; j < V.size.y; j++) {
1391 if (this.board[i][j] != V.EMPTY) {
1392 const sign = this.getColor(i, j) == "w" ? 1 : -1;
1393 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1c9f093d
BA
1394 }
1395 }
1396 }
1397 return evaluation;
1398 }
1399
1400 /////////////////////////
1401 // MOVES + GAME NOTATION
1402 /////////////////////////
1403
1404 // Context: just before move is played, turn hasn't changed
1405 // TODO: un-ambiguous notation (switch on piece type, check directions...)
6808d7a1
BA
1406 getNotation(move) {
1407 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1cd3e362 1408 // Castle
6808d7a1 1409 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1c9f093d
BA
1410
1411 // Translate final square
1412 const finalSquare = V.CoordsToSquare(move.end);
1413
1414 const piece = this.getPiece(move.start.x, move.start.y);
6808d7a1 1415 if (piece == V.PAWN) {
1c9f093d
BA
1416 // Pawn move
1417 let notation = "";
6808d7a1 1418 if (move.vanish.length > move.appear.length) {
1c9f093d
BA
1419 // Capture
1420 const startColumn = V.CoordToColumn(move.start.y);
1421 notation = startColumn + "x" + finalSquare;
78d64531 1422 }
6808d7a1
BA
1423 else notation = finalSquare;
1424 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
78d64531 1425 // Promotion
1c9f093d
BA
1426 notation += "=" + move.appear[0].p.toUpperCase();
1427 return notation;
1428 }
6808d7a1
BA
1429 // Piece movement
1430 return (
1431 piece.toUpperCase() +
1432 (move.vanish.length > move.appear.length ? "x" : "") +
1433 finalSquare
1434 );
1435 }
2c5d7b20
BA
1436
1437 static GetUnambiguousNotation(move) {
1438 // Machine-readable format with all the informations about the move
1439 return (
1440 (!!move.start && V.OnBoard(move.start.x, move.start.y)
1441 ? V.CoordsToSquare(move.start)
1442 : "-"
1443 ) + "." +
1444 (!!move.end && V.OnBoard(move.end.x, move.end.y)
1445 ? V.CoordsToSquare(move.end)
1446 : "-"
1447 ) + " " +
1448 (!!move.appear && move.appear.length > 0
1449 ? move.appear.map(a =>
1450 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1451 : "-"
1452 ) + "/" +
1453 (!!move.vanish && move.vanish.length > 0
1454 ? move.vanish.map(a =>
1455 a.c + a.p + V.CoordsToSquare({ x: a.x, y: a.y })).join(".")
1456 : "-"
1457 )
1458 );
1459 }
6808d7a1 1460};