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