Fix issues with preset challenges
[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("/");
6808d7a1 431 for (let i = 0; i < fenRows.length; i++) {
1c9f093d 432 let k = 0; //column index on board
6808d7a1
BA
433 for (let j = 0; j < fenRows[i].length; j++) {
434 switch (fenRows[i].charAt(j)) {
435 case "k":
436 this.kingPos["b"] = [i, k];
437 this.INIT_COL_KING["b"] = k;
1c9f093d 438 break;
6808d7a1
BA
439 case "K":
440 this.kingPos["w"] = [i, k];
441 this.INIT_COL_KING["w"] = k;
1c9f093d 442 break;
6808d7a1
BA
443 case "r":
444 if (this.INIT_COL_ROOK["b"][0] < 0) this.INIT_COL_ROOK["b"][0] = k;
445 else this.INIT_COL_ROOK["b"][1] = k;
1c9f093d 446 break;
6808d7a1
BA
447 case "R":
448 if (this.INIT_COL_ROOK["w"][0] < 0) this.INIT_COL_ROOK["w"][0] = k;
449 else this.INIT_COL_ROOK["w"][1] = k;
1c9f093d 450 break;
6808d7a1 451 default: {
1c9f093d 452 const num = parseInt(fenRows[i].charAt(j));
6808d7a1
BA
453 if (!isNaN(num)) k += num - 1;
454 }
1c9f093d
BA
455 }
456 k++;
457 }
458 }
459 }
460
461 // Some additional variables from FEN (variant dependant)
6808d7a1 462 setOtherVariables(fen) {
1c9f093d
BA
463 // Set flags and enpassant:
464 const parsedFen = V.ParseFen(fen);
6808d7a1
BA
465 if (V.HasFlags) this.setFlags(parsedFen.flags);
466 if (V.HasEnpassant) {
467 const epSq =
468 parsedFen.enpassant != "-"
9bd6786b 469 ? this.getEpSquare(parsedFen.enpassant)
6808d7a1
BA
470 : undefined;
471 this.epSquares = [epSq];
1c9f093d
BA
472 }
473 // Search for king and rooks positions:
474 this.scanKingsRooks(fen);
475 }
476
477 /////////////////////
478 // GETTERS & SETTERS
479
6808d7a1
BA
480 static get size() {
481 return { x: 8, y: 8 };
1c9f093d
BA
482 }
483
0ba6420d 484 // Color of thing on square (i,j). 'undefined' if square is empty
6808d7a1 485 getColor(i, j) {
1c9f093d
BA
486 return this.board[i][j].charAt(0);
487 }
488
489 // Piece type on square (i,j). 'undefined' if square is empty
6808d7a1 490 getPiece(i, j) {
1c9f093d
BA
491 return this.board[i][j].charAt(1);
492 }
493
494 // Get opponent color
6808d7a1
BA
495 static GetOppCol(color) {
496 return color == "w" ? "b" : "w";
1c9f093d
BA
497 }
498
1c9f093d 499 // Pieces codes (for a clearer code)
6808d7a1
BA
500 static get PAWN() {
501 return "p";
502 }
503 static get ROOK() {
504 return "r";
505 }
506 static get KNIGHT() {
507 return "n";
508 }
509 static get BISHOP() {
510 return "b";
511 }
512 static get QUEEN() {
513 return "q";
514 }
515 static get KING() {
516 return "k";
517 }
1c9f093d
BA
518
519 // For FEN checking:
6808d7a1
BA
520 static get PIECES() {
521 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
1c9f093d
BA
522 }
523
524 // Empty square
6808d7a1
BA
525 static get EMPTY() {
526 return "";
527 }
1c9f093d
BA
528
529 // Some pieces movements
6808d7a1 530 static get steps() {
1c9f093d 531 return {
6808d7a1
BA
532 r: [
533 [-1, 0],
534 [1, 0],
535 [0, -1],
536 [0, 1]
537 ],
538 n: [
539 [-1, -2],
540 [-1, 2],
541 [1, -2],
542 [1, 2],
543 [-2, -1],
544 [-2, 1],
545 [2, -1],
546 [2, 1]
547 ],
548 b: [
549 [-1, -1],
550 [-1, 1],
551 [1, -1],
552 [1, 1]
553 ]
1c9f093d
BA
554 };
555 }
556
557 ////////////////////
558 // MOVES GENERATION
559
0ba6420d 560 // All possible moves from selected square
6808d7a1
BA
561 getPotentialMovesFrom([x, y]) {
562 switch (this.getPiece(x, y)) {
1c9f093d 563 case V.PAWN:
6808d7a1 564 return this.getPotentialPawnMoves([x, y]);
1c9f093d 565 case V.ROOK:
6808d7a1 566 return this.getPotentialRookMoves([x, y]);
1c9f093d 567 case V.KNIGHT:
6808d7a1 568 return this.getPotentialKnightMoves([x, y]);
1c9f093d 569 case V.BISHOP:
6808d7a1 570 return this.getPotentialBishopMoves([x, y]);
1c9f093d 571 case V.QUEEN:
6808d7a1 572 return this.getPotentialQueenMoves([x, y]);
1c9f093d 573 case V.KING:
6808d7a1 574 return this.getPotentialKingMoves([x, y]);
1c9f093d 575 }
6808d7a1 576 return []; //never reached
1c9f093d
BA
577 }
578
579 // Build a regular move from its initial and destination squares.
580 // tr: transformation
6808d7a1 581 getBasicMove([sx, sy], [ex, ey], tr) {
1c9f093d
BA
582 let mv = new Move({
583 appear: [
584 new PiPo({
585 x: ex,
586 y: ey,
6808d7a1
BA
587 c: tr ? tr.c : this.getColor(sx, sy),
588 p: tr ? tr.p : this.getPiece(sx, sy)
1c9f093d
BA
589 })
590 ],
591 vanish: [
592 new PiPo({
593 x: sx,
594 y: sy,
6808d7a1
BA
595 c: this.getColor(sx, sy),
596 p: this.getPiece(sx, sy)
1c9f093d
BA
597 })
598 ]
599 });
600
601 // The opponent piece disappears if we take it
6808d7a1 602 if (this.board[ex][ey] != V.EMPTY) {
1c9f093d
BA
603 mv.vanish.push(
604 new PiPo({
605 x: ex,
606 y: ey,
6808d7a1
BA
607 c: this.getColor(ex, ey),
608 p: this.getPiece(ex, ey)
1c9f093d
BA
609 })
610 );
611 }
1c5bfdf2 612
1c9f093d
BA
613 return mv;
614 }
615
616 // Generic method to find possible moves of non-pawn pieces:
617 // "sliding or jumping"
6808d7a1 618 getSlideNJumpMoves([x, y], steps, oneStep) {
1c9f093d 619 let moves = [];
6808d7a1 620 outerLoop: for (let step of steps) {
1c9f093d
BA
621 let i = x + step[0];
622 let j = y + step[1];
6808d7a1
BA
623 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
624 moves.push(this.getBasicMove([x, y], [i, j]));
d1be8046 625 if (oneStep) continue outerLoop;
1c9f093d
BA
626 i += step[0];
627 j += step[1];
628 }
6808d7a1
BA
629 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
630 moves.push(this.getBasicMove([x, y], [i, j]));
1c9f093d
BA
631 }
632 return moves;
633 }
634
635 // What are the pawn moves from square x,y ?
6808d7a1 636 getPotentialPawnMoves([x, y]) {
1c9f093d
BA
637 const color = this.turn;
638 let moves = [];
6808d7a1
BA
639 const [sizeX, sizeY] = [V.size.x, V.size.y];
640 const shiftX = color == "w" ? -1 : 1;
641 const firstRank = color == "w" ? sizeX - 1 : 0;
642 const startRank = color == "w" ? sizeX - 2 : 1;
643 const lastRank = color == "w" ? 0 : sizeX - 1;
1c9f093d
BA
644
645 // NOTE: next condition is generally true (no pawn on last rank)
6808d7a1
BA
646 if (x + shiftX >= 0 && x + shiftX < sizeX) {
647 const finalPieces =
648 x + shiftX == lastRank
649 ? [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN]
650 : [V.PAWN];
6808d7a1 651 if (this.board[x + shiftX][y] == V.EMPTY) {
71ef1664 652 // One square forward
6808d7a1
BA
653 for (let piece of finalPieces) {
654 moves.push(
655 this.getBasicMove([x, y], [x + shiftX, y], {
e727fe31 656 c: color,
6808d7a1
BA
657 p: piece
658 })
659 );
1c9f093d
BA
660 }
661 // Next condition because pawns on 1st rank can generally jump
6808d7a1
BA
662 if (
663 [startRank, firstRank].includes(x) &&
664 this.board[x + 2 * shiftX][y] == V.EMPTY
665 ) {
1c9f093d 666 // Two squares jump
6808d7a1 667 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
1c9f093d
BA
668 }
669 }
670 // Captures
6808d7a1
BA
671 for (let shiftY of [-1, 1]) {
672 if (
673 y + shiftY >= 0 &&
674 y + shiftY < sizeY &&
675 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
676 this.canTake([x, y], [x + shiftX, y + shiftY])
677 ) {
678 for (let piece of finalPieces) {
679 moves.push(
680 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
e727fe31 681 c: color,
6808d7a1
BA
682 p: piece
683 })
684 );
1c9f093d
BA
685 }
686 }
687 }
688 }
689
6808d7a1 690 if (V.HasEnpassant) {
1c9f093d
BA
691 // En passant
692 const Lep = this.epSquares.length;
6808d7a1
BA
693 const epSquare = this.epSquares[Lep - 1]; //always at least one element
694 if (
695 !!epSquare &&
696 epSquare.x == x + shiftX &&
697 Math.abs(epSquare.y - y) == 1
698 ) {
699 let enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
1c9f093d
BA
700 enpassantMove.vanish.push({
701 x: x,
702 y: epSquare.y,
6808d7a1
BA
703 p: "p",
704 c: this.getColor(x, epSquare.y)
1c9f093d
BA
705 });
706 moves.push(enpassantMove);
707 }
708 }
709
710 return moves;
711 }
712
713 // What are the rook moves from square x,y ?
6808d7a1 714 getPotentialRookMoves(sq) {
1c9f093d
BA
715 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
716 }
717
718 // What are the knight moves from square x,y ?
6808d7a1 719 getPotentialKnightMoves(sq) {
1c9f093d
BA
720 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
721 }
722
723 // What are the bishop moves from square x,y ?
6808d7a1 724 getPotentialBishopMoves(sq) {
1c9f093d
BA
725 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
726 }
727
728 // What are the queen moves from square x,y ?
6808d7a1
BA
729 getPotentialQueenMoves(sq) {
730 return this.getSlideNJumpMoves(
731 sq,
732 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
733 );
1c9f093d
BA
734 }
735
736 // What are the king moves from square x,y ?
6808d7a1 737 getPotentialKingMoves(sq) {
1c9f093d 738 // Initialize with normal moves
6808d7a1
BA
739 let moves = this.getSlideNJumpMoves(
740 sq,
741 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
742 "oneStep"
743 );
1c9f093d
BA
744 return moves.concat(this.getCastleMoves(sq));
745 }
746
6808d7a1
BA
747 getCastleMoves([x, y]) {
748 const c = this.getColor(x, y);
749 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
1c9f093d
BA
750 return []; //x isn't first rank, or king has moved (shortcut)
751
752 // Castling ?
753 const oppCol = V.GetOppCol(c);
754 let moves = [];
755 let i = 0;
9bd6786b 756 // King, then rook:
6808d7a1
BA
757 const finalSquares = [
758 [2, 3],
759 [V.size.y - 2, V.size.y - 3]
9bd6786b 760 ];
6808d7a1
BA
761 castlingCheck: for (
762 let castleSide = 0;
763 castleSide < 2;
764 castleSide++ //large, then small
765 ) {
766 if (!this.castleFlags[c][castleSide]) continue;
1c9f093d
BA
767 // If this code is reached, rooks and king are on initial position
768
2beba6db
BA
769 // Nothing on the path of the king ? (and no checks)
770 const finDist = finalSquares[castleSide][0] - y;
771 let step = finDist / Math.max(1, Math.abs(finDist));
772 i = y;
6808d7a1
BA
773 do {
774 if (
775 this.isAttacked([x, i], [oppCol]) ||
776 (this.board[x][i] != V.EMPTY &&
777 // NOTE: next check is enough, because of chessboard constraints
778 (this.getColor(x, i) != c ||
779 ![V.KING, V.ROOK].includes(this.getPiece(x, i))))
780 ) {
1c9f093d
BA
781 continue castlingCheck;
782 }
2beba6db 783 i += step;
6808d7a1 784 } while (i != finalSquares[castleSide][0]);
1c9f093d
BA
785
786 // Nothing on the path to the rook?
6808d7a1
BA
787 step = castleSide == 0 ? -1 : 1;
788 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) {
789 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
1c9f093d
BA
790 }
791 const rookPos = this.INIT_COL_ROOK[c][castleSide];
792
793 // Nothing on final squares, except maybe king and castling rook?
6808d7a1
BA
794 for (i = 0; i < 2; i++) {
795 if (
796 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
797 this.getPiece(x, finalSquares[castleSide][i]) != V.KING &&
798 finalSquares[castleSide][i] != rookPos
799 ) {
1c9f093d
BA
800 continue castlingCheck;
801 }
802 }
803
804 // If this code is reached, castle is valid
6808d7a1
BA
805 moves.push(
806 new Move({
807 appear: [
808 new PiPo({ x: x, y: finalSquares[castleSide][0], p: V.KING, c: c }),
809 new PiPo({ x: x, y: finalSquares[castleSide][1], p: V.ROOK, c: c })
810 ],
811 vanish: [
812 new PiPo({ x: x, y: y, p: V.KING, c: c }),
813 new PiPo({ x: x, y: rookPos, p: V.ROOK, c: c })
814 ],
815 end:
816 Math.abs(y - rookPos) <= 2
817 ? { x: x, y: rookPos }
818 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
819 })
820 );
1c9f093d
BA
821 }
822
823 return moves;
824 }
825
826 ////////////////////
827 // MOVES VALIDATION
828
829 // For the interface: possible moves for the current turn from square sq
6808d7a1
BA
830 getPossibleMovesFrom(sq) {
831 return this.filterValid(this.getPotentialMovesFrom(sq));
1c9f093d
BA
832 }
833
834 // TODO: promotions (into R,B,N,Q) should be filtered only once
6808d7a1
BA
835 filterValid(moves) {
836 if (moves.length == 0) return [];
1c9f093d
BA
837 const color = this.turn;
838 return moves.filter(m => {
839 this.play(m);
840 const res = !this.underCheck(color);
841 this.undo(m);
842 return res;
843 });
844 }
845
846 // Search for all valid moves considering current turn
847 // (for engine and game end)
6808d7a1 848 getAllValidMoves() {
1c9f093d 849 const color = this.turn;
1c9f093d 850 let potentialMoves = [];
6808d7a1
BA
851 for (let i = 0; i < V.size.x; i++) {
852 for (let j = 0; j < V.size.y; j++) {
d1be8046 853 if (this.getColor(i, j) == color) {
6808d7a1
BA
854 Array.prototype.push.apply(
855 potentialMoves,
856 this.getPotentialMovesFrom([i, j])
857 );
1c9f093d
BA
858 }
859 }
860 }
861 return this.filterValid(potentialMoves);
862 }
863
864 // Stop at the first move found
6808d7a1 865 atLeastOneMove() {
1c9f093d 866 const color = this.turn;
6808d7a1
BA
867 for (let i = 0; i < V.size.x; i++) {
868 for (let j = 0; j < V.size.y; j++) {
d1be8046 869 if (this.getColor(i, j) == color) {
6808d7a1
BA
870 const moves = this.getPotentialMovesFrom([i, j]);
871 if (moves.length > 0) {
872 for (let k = 0; k < moves.length; k++) {
873 if (this.filterValid([moves[k]]).length > 0) return true;
1c9f093d
BA
874 }
875 }
876 }
877 }
878 }
879 return false;
880 }
881
882 // Check if pieces of color in 'colors' are attacking (king) on square x,y
6808d7a1
BA
883 isAttacked(sq, colors) {
884 return (
885 this.isAttackedByPawn(sq, colors) ||
886 this.isAttackedByRook(sq, colors) ||
887 this.isAttackedByKnight(sq, colors) ||
888 this.isAttackedByBishop(sq, colors) ||
889 this.isAttackedByQueen(sq, colors) ||
890 this.isAttackedByKing(sq, colors)
891 );
1c9f093d
BA
892 }
893
d1be8046
BA
894 // Generic method for non-pawn pieces ("sliding or jumping"):
895 // is x,y attacked by a piece of color in array 'colors' ?
896 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
897 for (let step of steps) {
898 let rx = x + step[0],
899 ry = y + step[1];
900 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
901 rx += step[0];
902 ry += step[1];
903 }
904 if (
905 V.OnBoard(rx, ry) &&
906 this.getPiece(rx, ry) === piece &&
907 colors.includes(this.getColor(rx, ry))
908 ) {
909 return true;
910 }
911 }
912 return false;
913 }
914
1c9f093d 915 // Is square x,y attacked by 'colors' pawns ?
6808d7a1
BA
916 isAttackedByPawn([x, y], colors) {
917 for (let c of colors) {
d1be8046 918 const pawnShift = c == "w" ? 1 : -1;
6808d7a1
BA
919 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
920 for (let i of [-1, 1]) {
921 if (
922 y + i >= 0 &&
923 y + i < V.size.y &&
924 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
925 this.getColor(x + pawnShift, y + i) == c
926 ) {
1c9f093d
BA
927 return true;
928 }
929 }
930 }
931 }
932 return false;
933 }
934
935 // Is square x,y attacked by 'colors' rooks ?
6808d7a1 936 isAttackedByRook(sq, colors) {
1c9f093d
BA
937 return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
938 }
939
940 // Is square x,y attacked by 'colors' knights ?
6808d7a1
BA
941 isAttackedByKnight(sq, colors) {
942 return this.isAttackedBySlideNJump(
943 sq,
944 colors,
945 V.KNIGHT,
946 V.steps[V.KNIGHT],
947 "oneStep"
948 );
1c9f093d
BA
949 }
950
951 // Is square x,y attacked by 'colors' bishops ?
6808d7a1 952 isAttackedByBishop(sq, colors) {
1c9f093d
BA
953 return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]);
954 }
955
956 // Is square x,y attacked by 'colors' queens ?
6808d7a1
BA
957 isAttackedByQueen(sq, colors) {
958 return this.isAttackedBySlideNJump(
959 sq,
960 colors,
961 V.QUEEN,
962 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
963 );
1c9f093d
BA
964 }
965
966 // Is square x,y attacked by 'colors' king(s) ?
6808d7a1
BA
967 isAttackedByKing(sq, colors) {
968 return this.isAttackedBySlideNJump(
969 sq,
970 colors,
971 V.KING,
972 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
973 "oneStep"
974 );
1c9f093d
BA
975 }
976
1c9f093d 977 // Is color under check after his move ?
6808d7a1 978 underCheck(color) {
1c9f093d
BA
979 return this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]);
980 }
981
982 /////////////////
983 // MOVES PLAYING
984
985 // Apply a move on board
6808d7a1
BA
986 static PlayOnBoard(board, move) {
987 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
988 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
989 }
990 // Un-apply the played move
6808d7a1
BA
991 static UndoOnBoard(board, move) {
992 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
993 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
994 }
995
996 // After move is played, update variables + flags
6808d7a1 997 updateVariables(move) {
1c9f093d 998 let piece = undefined;
e727fe31 999 // TODO: update variables before move is played, and just use this.turn?
78d64531 1000 // (doesn't work in general, think MarseilleChess)
1c9f093d 1001 let c = undefined;
6808d7a1 1002 if (move.vanish.length >= 1) {
1c9f093d
BA
1003 // Usual case, something is moved
1004 piece = move.vanish[0].p;
1005 c = move.vanish[0].c;
6808d7a1 1006 } else {
1c9f093d
BA
1007 // Crazyhouse-like variants
1008 piece = move.appear[0].p;
1009 c = move.appear[0].c;
1010 }
78d64531
BA
1011 if (!['w','b'].includes(c)) {
1012 // Checkered, for example
1c9f093d
BA
1013 c = V.GetOppCol(this.turn);
1014 }
6808d7a1 1015 const firstRank = c == "w" ? V.size.x - 1 : 0;
1c9f093d
BA
1016
1017 // Update king position + flags
6808d7a1 1018 if (piece == V.KING && move.appear.length > 0) {
1c9f093d
BA
1019 this.kingPos[c][0] = move.appear[0].x;
1020 this.kingPos[c][1] = move.appear[0].y;
6808d7a1 1021 if (V.HasFlags) this.castleFlags[c] = [false, false];
1c9f093d
BA
1022 return;
1023 }
6808d7a1 1024 if (V.HasFlags) {
1c9f093d
BA
1025 // Update castling flags if rooks are moved
1026 const oppCol = V.GetOppCol(c);
6808d7a1
BA
1027 const oppFirstRank = V.size.x - 1 - firstRank;
1028 if (
1029 move.start.x == firstRank && //our rook moves?
1030 this.INIT_COL_ROOK[c].includes(move.start.y)
1031 ) {
1032 const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1;
1c9f093d 1033 this.castleFlags[c][flagIdx] = false;
6808d7a1
BA
1034 } else if (
1035 move.end.x == oppFirstRank && //we took opponent rook?
1036 this.INIT_COL_ROOK[oppCol].includes(move.end.y)
1037 ) {
1038 const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1;
1c9f093d
BA
1039 this.castleFlags[oppCol][flagIdx] = false;
1040 }
1041 }
1042 }
1043
1044 // After move is undo-ed *and flags resetted*, un-update other variables
1045 // TODO: more symmetry, by storing flags increment in move (?!)
6808d7a1 1046 unupdateVariables(move) {
1c9f093d 1047 // (Potentially) Reset king position
6808d7a1
BA
1048 const c = this.getColor(move.start.x, move.start.y);
1049 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1c9f093d
BA
1050 this.kingPos[c] = [move.start.x, move.start.y];
1051 }
1052
6808d7a1 1053 play(move) {
1c9f093d 1054 // DEBUG:
9bd6786b
BA
1055// if (!this.states) this.states = [];
1056// const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1057// this.states.push(stateFen);
6808d7a1
BA
1058
1059 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo)
1060 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1c9f093d
BA
1061 V.PlayOnBoard(this.board, move);
1062 this.turn = V.GetOppCol(this.turn);
1063 this.movesCount++;
1064 this.updateVariables(move);
1065 }
1066
6808d7a1
BA
1067 undo(move) {
1068 if (V.HasEnpassant) this.epSquares.pop();
1069 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1c9f093d
BA
1070 V.UndoOnBoard(this.board, move);
1071 this.turn = V.GetOppCol(this.turn);
1072 this.movesCount--;
1073 this.unupdateVariables(move);
1074
1075 // DEBUG:
9bd6786b
BA
1076// const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1077// if (stateFen != this.states[this.states.length-1]) debugger;
1078// this.states.pop();
1c9f093d
BA
1079 }
1080
1081 ///////////////
1082 // END OF GAME
1083
1084 // What is the score ? (Interesting if game is over)
6808d7a1
BA
1085 getCurrentScore() {
1086 if (this.atLeastOneMove())
1c9f093d
BA
1087 return "*";
1088
1089 // Game over
1090 const color = this.turn;
1091 // No valid move: stalemate or checkmate?
1092 if (!this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]))
1093 return "1/2";
1094 // OK, checkmate
6808d7a1 1095 return color == "w" ? "0-1" : "1-0";
1c9f093d
BA
1096 }
1097
1098 ///////////////
1099 // ENGINE PLAY
1100
1101 // Pieces values
6808d7a1 1102 static get VALUES() {
1c9f093d 1103 return {
6808d7a1
BA
1104 p: 1,
1105 r: 5,
1106 n: 3,
1107 b: 3,
1108 q: 9,
1109 k: 1000
1c9f093d
BA
1110 };
1111 }
1112
1113 // "Checkmate" (unreachable eval)
6808d7a1
BA
1114 static get INFINITY() {
1115 return 9999;
1116 }
1c9f093d
BA
1117
1118 // At this value or above, the game is over
6808d7a1
BA
1119 static get THRESHOLD_MATE() {
1120 return V.INFINITY;
1121 }
1c9f093d
BA
1122
1123 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
6808d7a1
BA
1124 static get SEARCH_DEPTH() {
1125 return 3;
1126 }
1c9f093d 1127
6808d7a1 1128 getComputerMove() {
1c9f093d
BA
1129 const maxeval = V.INFINITY;
1130 const color = this.turn;
a97bdbda 1131 let moves1 = this.getAllValidMoves();
c322a844 1132
6808d7a1 1133 if (moves1.length == 0)
e71161fb 1134 // TODO: this situation should not happen
41cb9b94 1135 return null;
1c9f093d 1136
b83a675a 1137 // Rank moves using a min-max at depth 2 (if search_depth >= 2!)
6808d7a1 1138 for (let i = 0; i < moves1.length; i++) {
b83a675a
BA
1139 if (V.SEARCH_DEPTH == 1) {
1140 moves1[i].eval = this.evalPosition();
1141 continue;
1142 }
1c9f093d 1143 // Initial self evaluation is very low: "I'm checkmated"
6808d7a1 1144 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1c9f093d
BA
1145 this.play(moves1[i]);
1146 const score1 = this.getCurrentScore();
1147 let eval2 = undefined;
6808d7a1 1148 if (score1 == "*") {
1c9f093d 1149 // Initial enemy evaluation is very low too, for him
6808d7a1 1150 eval2 = (color == "w" ? 1 : -1) * maxeval;
1c9f093d 1151 // Second half-move:
a97bdbda 1152 let moves2 = this.getAllValidMoves();
6808d7a1 1153 for (let j = 0; j < moves2.length; j++) {
1c9f093d
BA
1154 this.play(moves2[j]);
1155 const score2 = this.getCurrentScore();
6808d7a1
BA
1156 let evalPos = 0; //1/2 value
1157 switch (score2) {
1158 case "*":
1159 evalPos = this.evalPosition();
1160 break;
1161 case "1-0":
1162 evalPos = maxeval;
1163 break;
1164 case "0-1":
1165 evalPos = -maxeval;
1166 break;
1167 }
1168 if (
1169 (color == "w" && evalPos < eval2) ||
1170 (color == "b" && evalPos > eval2)
1171 ) {
1c9f093d
BA
1172 eval2 = evalPos;
1173 }
1174 this.undo(moves2[j]);
1175 }
6808d7a1
BA
1176 } else eval2 = score1 == "1/2" ? 0 : (score1 == "1-0" ? 1 : -1) * maxeval;
1177 if (
1178 (color == "w" && eval2 > moves1[i].eval) ||
1179 (color == "b" && eval2 < moves1[i].eval)
1180 ) {
1c9f093d
BA
1181 moves1[i].eval = eval2;
1182 }
1183 this.undo(moves1[i]);
1184 }
6808d7a1
BA
1185 moves1.sort((a, b) => {
1186 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1187 });
a97bdbda 1188// console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1c9f093d 1189
1c9f093d 1190 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
6808d7a1 1191 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
6808d7a1 1192 for (let i = 0; i < moves1.length; i++) {
1c9f093d
BA
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 });
b83a675a 1203 }
1c9f093d 1204
b83a675a 1205 let candidates = [0];
6808d7a1 1206 for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++)
1c9f093d 1207 candidates.push(j);
656b1878 1208 return moves1[candidates[randInt(candidates.length)]];
1c9f093d
BA
1209 }
1210
6808d7a1 1211 alphabeta(depth, alpha, beta) {
1c9f093d
BA
1212 const maxeval = V.INFINITY;
1213 const color = this.turn;
1214 const score = this.getCurrentScore();
1215 if (score != "*")
6808d7a1
BA
1216 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1217 if (depth == 0) return this.evalPosition();
a97bdbda 1218 const moves = this.getAllValidMoves();
6808d7a1
BA
1219 let v = color == "w" ? -maxeval : maxeval;
1220 if (color == "w") {
1221 for (let i = 0; i < moves.length; i++) {
1c9f093d 1222 this.play(moves[i]);
6808d7a1 1223 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1224 this.undo(moves[i]);
1225 alpha = Math.max(alpha, v);
6808d7a1 1226 if (alpha >= beta) break; //beta cutoff
1c9f093d 1227 }
1c5bfdf2 1228 }
6808d7a1 1229 else {
1c5bfdf2 1230 // color=="b"
6808d7a1 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};