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