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