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