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