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