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