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