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