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