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