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