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