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