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