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