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