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