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