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