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