TODO: debug Knightrelay, use generators + yield for moves generation
[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
BA
29
30// NOTE: x coords = top to bottom; y = left to right (from white player perspective)
6808d7a1 31export const ChessRules = class ChessRules {
1c9f093d
BA
32 //////////////
33 // MISC UTILS
34
20620465 35 // Some variants don't have flags:
6808d7a1
BA
36 static get HasFlags() {
37 return true;
20620465 38 }
1c9f093d 39
20620465 40 // Some variants don't have en-passant
6808d7a1
BA
41 static get HasEnpassant() {
42 return true;
20620465
BA
43 }
44
45 // Some variants cannot have analyse mode
8477e53d 46 static get CanAnalyze() {
20620465
BA
47 return true;
48 }
933fd1f9
BA
49 // Patch: issues with javascript OOP, objects can't access static fields.
50 get canAnalyze() {
51 return V.CanAnalyze;
52 }
20620465
BA
53
54 // Some variants show incomplete information,
55 // and thus show only a partial moves list or no list at all.
56 static get ShowMoves() {
57 return "all";
58 }
933fd1f9
BA
59 get showMoves() {
60 return V.ShowMoves;
61 }
1c9f093d 62
71ef1664
BA
63 // Some variants always show the same orientation
64 static get CanFlip() {
65 return true;
66 }
67 get canFlip() {
68 return V.CanFlip;
69 }
70
1c9f093d 71 // Turn "wb" into "B" (for FEN)
6808d7a1
BA
72 static board2fen(b) {
73 return b[0] == "w" ? b[1].toUpperCase() : b[1];
1c9f093d
BA
74 }
75
76 // Turn "p" into "bp" (for board)
6808d7a1
BA
77 static fen2board(f) {
78 return f.charCodeAt() <= 90 ? "w" + f.toLowerCase() : "b" + f;
1c9f093d
BA
79 }
80
89021f18 81 // Check if FEN describe a board situation correctly
6808d7a1 82 static IsGoodFen(fen) {
1c9f093d
BA
83 const fenParsed = V.ParseFen(fen);
84 // 1) Check position
6808d7a1 85 if (!V.IsGoodPosition(fenParsed.position)) return false;
1c9f093d 86 // 2) Check turn
6808d7a1 87 if (!fenParsed.turn || !V.IsGoodTurn(fenParsed.turn)) return false;
1c9f093d
BA
88 // 3) Check moves count
89 if (!fenParsed.movesCount || !(parseInt(fenParsed.movesCount) >= 0))
90 return false;
91 // 4) Check flags
92 if (V.HasFlags && (!fenParsed.flags || !V.IsGoodFlags(fenParsed.flags)))
93 return false;
94 // 5) Check enpassant
6808d7a1
BA
95 if (
96 V.HasEnpassant &&
97 (!fenParsed.enpassant || !V.IsGoodEnpassant(fenParsed.enpassant))
98 ) {
1c9f093d
BA
99 return false;
100 }
101 return true;
102 }
103
104 // Is position part of the FEN a priori correct?
6808d7a1
BA
105 static IsGoodPosition(position) {
106 if (position.length == 0) return false;
1c9f093d 107 const rows = position.split("/");
6808d7a1 108 if (rows.length != V.size.x) return false;
d7c00f6a 109 let kings = {};
6808d7a1 110 for (let row of rows) {
1c9f093d 111 let sumElts = 0;
6808d7a1 112 for (let i = 0; i < row.length; i++) {
d7c00f6a
BA
113 if (['K','k'].includes(row[i]))
114 kings[row[i]] = true;
6808d7a1
BA
115 if (V.PIECES.includes(row[i].toLowerCase())) sumElts++;
116 else {
1c9f093d 117 const num = parseInt(row[i]);
6808d7a1 118 if (isNaN(num)) return false;
1c9f093d
BA
119 sumElts += num;
120 }
121 }
6808d7a1 122 if (sumElts != V.size.y) return false;
1c9f093d 123 }
d7c00f6a
BA
124 // Both kings should be on board:
125 if (Object.keys(kings).length != 2)
126 return false;
1c9f093d
BA
127 return true;
128 }
129
130 // For FEN checking
6808d7a1
BA
131 static IsGoodTurn(turn) {
132 return ["w", "b"].includes(turn);
1c9f093d
BA
133 }
134
135 // For FEN checking
6808d7a1 136 static IsGoodFlags(flags) {
1c9f093d
BA
137 return !!flags.match(/^[01]{4,4}$/);
138 }
139
6808d7a1
BA
140 static IsGoodEnpassant(enpassant) {
141 if (enpassant != "-") {
142 const ep = V.SquareToCoords(enpassant);
143 if (isNaN(ep.x) || !V.OnBoard(ep)) return false;
1c9f093d
BA
144 }
145 return true;
146 }
147
148 // 3 --> d (column number to letter)
6808d7a1 149 static CoordToColumn(colnum) {
1c9f093d
BA
150 return String.fromCharCode(97 + colnum);
151 }
152
153 // d --> 3 (column letter to number)
6808d7a1 154 static ColumnToCoord(column) {
1c9f093d
BA
155 return column.charCodeAt(0) - 97;
156 }
157
158 // a4 --> {x:3,y:0}
6808d7a1 159 static SquareToCoords(sq) {
1c9f093d
BA
160 return {
161 // NOTE: column is always one char => max 26 columns
162 // row is counted from black side => subtraction
163 x: V.size.x - parseInt(sq.substr(1)),
164 y: sq[0].charCodeAt() - 97
165 };
166 }
167
168 // {x:0,y:4} --> e8
6808d7a1 169 static CoordsToSquare(coords) {
1c9f093d
BA
170 return V.CoordToColumn(coords.y) + (V.size.x - coords.x);
171 }
172
241bf8f2
BA
173 // Path to pieces
174 getPpath(b) {
175 return b; //usual pieces in pieces/ folder
176 }
177
1c9f093d 178 // Aggregates flags into one object
6808d7a1 179 aggregateFlags() {
1c9f093d
BA
180 return this.castleFlags;
181 }
182
183 // Reverse operation
6808d7a1 184 disaggregateFlags(flags) {
1c9f093d
BA
185 this.castleFlags = flags;
186 }
187
188 // En-passant square, if any
6808d7a1
BA
189 getEpSquare(moveOrSquare) {
190 if (!moveOrSquare) return undefined;
191 if (typeof moveOrSquare === "string") {
1c9f093d 192 const square = moveOrSquare;
6808d7a1 193 if (square == "-") return undefined;
1c9f093d
BA
194 return V.SquareToCoords(square);
195 }
196 // Argument is a move:
197 const move = moveOrSquare;
6808d7a1 198 const [sx, sy, ex] = [move.start.x, move.start.y, move.end.x];
41cb9b94 199 // NOTE: next conditions are first for Atomic, and last for Checkered
6808d7a1
BA
200 if (
201 move.appear.length > 0 &&
202 Math.abs(sx - ex) == 2 &&
203 move.appear[0].p == V.PAWN &&
204 ["w", "b"].includes(move.appear[0].c)
205 ) {
1c9f093d 206 return {
6808d7a1 207 x: (sx + ex) / 2,
1c9f093d
BA
208 y: sy
209 };
210 }
211 return undefined; //default
212 }
213
214 // Can thing on square1 take thing on square2
6808d7a1
BA
215 canTake([x1, y1], [x2, y2]) {
216 return this.getColor(x1, y1) !== this.getColor(x2, y2);
1c9f093d
BA
217 }
218
219 // Is (x,y) on the chessboard?
6808d7a1
BA
220 static OnBoard(x, y) {
221 return x >= 0 && x < V.size.x && y >= 0 && y < V.size.y;
1c9f093d
BA
222 }
223
224 // Used in interface: 'side' arg == player color
6808d7a1
BA
225 canIplay(side, [x, y]) {
226 return this.turn == side && this.getColor(x, y) == side;
1c9f093d
BA
227 }
228
229 // On which squares is color under check ? (for interface)
6808d7a1 230 getCheckSquares(color) {
1c9f093d
BA
231 return this.isAttacked(this.kingPos[color], [V.GetOppCol(color)])
232 ? [JSON.parse(JSON.stringify(this.kingPos[color]))] //need to duplicate!
233 : [];
234 }
235
236 /////////////
237 // FEN UTILS
238
239 // Setup the initial random (assymetric) position
6808d7a1
BA
240 static GenRandInitFen() {
241 let pieces = { w: new Array(8), b: new Array(8) };
1c9f093d 242 // Shuffle pieces on first and last rank
6808d7a1 243 for (let c of ["w", "b"]) {
1c9f093d
BA
244 let positions = ArrayFun.range(8);
245
246 // Get random squares for bishops
656b1878 247 let randIndex = 2 * randInt(4);
1c9f093d
BA
248 const bishop1Pos = positions[randIndex];
249 // The second bishop must be on a square of different color
656b1878 250 let randIndex_tmp = 2 * randInt(4) + 1;
1c9f093d
BA
251 const bishop2Pos = positions[randIndex_tmp];
252 // Remove chosen squares
6808d7a1
BA
253 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
254 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
1c9f093d
BA
255
256 // Get random squares for knights
656b1878 257 randIndex = randInt(6);
1c9f093d
BA
258 const knight1Pos = positions[randIndex];
259 positions.splice(randIndex, 1);
656b1878 260 randIndex = randInt(5);
1c9f093d
BA
261 const knight2Pos = positions[randIndex];
262 positions.splice(randIndex, 1);
263
264 // Get random square for queen
656b1878 265 randIndex = randInt(4);
1c9f093d
BA
266 const queenPos = positions[randIndex];
267 positions.splice(randIndex, 1);
268
269 // Rooks and king positions are now fixed,
270 // because of the ordering rook-king-rook
271 const rook1Pos = positions[0];
272 const kingPos = positions[1];
273 const rook2Pos = positions[2];
274
275 // Finally put the shuffled pieces in the board array
6808d7a1
BA
276 pieces[c][rook1Pos] = "r";
277 pieces[c][knight1Pos] = "n";
278 pieces[c][bishop1Pos] = "b";
279 pieces[c][queenPos] = "q";
280 pieces[c][kingPos] = "k";
281 pieces[c][bishop2Pos] = "b";
282 pieces[c][knight2Pos] = "n";
283 pieces[c][rook2Pos] = "r";
1c9f093d 284 }
e3e2cc44 285 // Add turn + flags + enpassant
6808d7a1
BA
286 return (
287 pieces["b"].join("") +
1c9f093d
BA
288 "/pppppppp/8/8/8/8/PPPPPPPP/" +
289 pieces["w"].join("").toUpperCase() +
6808d7a1 290 " w 0 1111 -"
e3e2cc44 291 );
1c9f093d
BA
292 }
293
294 // "Parse" FEN: just return untransformed string data
6808d7a1 295 static ParseFen(fen) {
1c9f093d 296 const fenParts = fen.split(" ");
6808d7a1 297 let res = {
1c9f093d
BA
298 position: fenParts[0],
299 turn: fenParts[1],
6808d7a1 300 movesCount: fenParts[2]
1c9f093d
BA
301 };
302 let nextIdx = 3;
6808d7a1
BA
303 if (V.HasFlags) Object.assign(res, { flags: fenParts[nextIdx++] });
304 if (V.HasEnpassant) Object.assign(res, { enpassant: fenParts[nextIdx] });
1c9f093d
BA
305 return res;
306 }
307
308 // Return current fen (game state)
6808d7a1
BA
309 getFen() {
310 return (
311 this.getBaseFen() +
312 " " +
313 this.getTurnFen() +
314 " " +
315 this.movesCount +
316 (V.HasFlags ? " " + this.getFlagsFen() : "") +
317 (V.HasEnpassant ? " " + this.getEnpassantFen() : "")
318 );
1c9f093d
BA
319 }
320
321 // Position part of the FEN string
6808d7a1 322 getBaseFen() {
1c9f093d 323 let position = "";
6808d7a1 324 for (let i = 0; i < V.size.x; i++) {
1c9f093d 325 let emptyCount = 0;
6808d7a1
BA
326 for (let j = 0; j < V.size.y; j++) {
327 if (this.board[i][j] == V.EMPTY) emptyCount++;
328 else {
329 if (emptyCount > 0) {
1c9f093d
BA
330 // Add empty squares in-between
331 position += emptyCount;
332 emptyCount = 0;
333 }
334 position += V.board2fen(this.board[i][j]);
335 }
336 }
6808d7a1 337 if (emptyCount > 0) {
1c9f093d
BA
338 // "Flush remainder"
339 position += emptyCount;
340 }
6808d7a1 341 if (i < V.size.x - 1) position += "/"; //separate rows
1c9f093d
BA
342 }
343 return position;
344 }
345
6808d7a1 346 getTurnFen() {
1c9f093d
BA
347 return this.turn;
348 }
349
350 // Flags part of the FEN string
6808d7a1 351 getFlagsFen() {
1c9f093d
BA
352 let flags = "";
353 // Add castling flags
6808d7a1
BA
354 for (let i of ["w", "b"]) {
355 for (let j = 0; j < 2; j++) flags += this.castleFlags[i][j] ? "1" : "0";
1c9f093d
BA
356 }
357 return flags;
358 }
359
360 // Enpassant part of the FEN string
6808d7a1 361 getEnpassantFen() {
1c9f093d 362 const L = this.epSquares.length;
6808d7a1
BA
363 if (!this.epSquares[L - 1]) return "-"; //no en-passant
364 return V.CoordsToSquare(this.epSquares[L - 1]);
1c9f093d
BA
365 }
366
367 // Turn position fen into double array ["wb","wp","bk",...]
6808d7a1 368 static GetBoard(position) {
1c9f093d
BA
369 const rows = position.split("/");
370 let board = ArrayFun.init(V.size.x, V.size.y, "");
6808d7a1 371 for (let i = 0; i < rows.length; i++) {
1c9f093d 372 let j = 0;
6808d7a1 373 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
1c9f093d
BA
374 const character = rows[i][indexInRow];
375 const num = parseInt(character);
a13cbc0f 376 // If num is a number, just shift j:
6808d7a1 377 if (!isNaN(num)) j += num;
a13cbc0f 378 // Else: something at position i,j
6808d7a1 379 else board[i][j++] = V.fen2board(character);
1c9f093d
BA
380 }
381 }
382 return board;
383 }
384
385 // Extract (relevant) flags from fen
6808d7a1 386 setFlags(fenflags) {
1c9f093d 387 // white a-castle, h-castle, black a-castle, h-castle
6808d7a1 388 this.castleFlags = { w: [true, true], b: [true, true] };
6808d7a1
BA
389 for (let i = 0; i < 4; i++)
390 this.castleFlags[i < 2 ? "w" : "b"][i % 2] = fenflags.charAt(i) == "1";
1c9f093d
BA
391 }
392
393 //////////////////
394 // INITIALIZATION
395
6808d7a1 396 constructor(fen) {
241bf8f2
BA
397 // In printDiagram() fen isn't supply because only getPpath() is used
398 if (fen)
399 this.re_init(fen);
37cdcbf3
BA
400 }
401
402 // Fen string fully describes the game state
6808d7a1 403 re_init(fen) {
1c9f093d
BA
404 const fenParsed = V.ParseFen(fen);
405 this.board = V.GetBoard(fenParsed.position);
406 this.turn = fenParsed.turn[0]; //[0] to work with MarseilleRules
407 this.movesCount = parseInt(fenParsed.movesCount);
408 this.setOtherVariables(fen);
409 }
410
411 // Scan board for kings and rooks positions
6808d7a1
BA
412 scanKingsRooks(fen) {
413 this.INIT_COL_KING = { w: -1, b: -1 };
414 this.INIT_COL_ROOK = { w: [-1, -1], b: [-1, -1] };
415 this.kingPos = { w: [-1, -1], b: [-1, -1] }; //squares of white and black king
1c9f093d 416 const fenRows = V.ParseFen(fen).position.split("/");
6808d7a1 417 for (let i = 0; i < fenRows.length; i++) {
1c9f093d 418 let k = 0; //column index on board
6808d7a1
BA
419 for (let j = 0; j < fenRows[i].length; j++) {
420 switch (fenRows[i].charAt(j)) {
421 case "k":
422 this.kingPos["b"] = [i, k];
423 this.INIT_COL_KING["b"] = k;
1c9f093d 424 break;
6808d7a1
BA
425 case "K":
426 this.kingPos["w"] = [i, k];
427 this.INIT_COL_KING["w"] = k;
1c9f093d 428 break;
6808d7a1
BA
429 case "r":
430 if (this.INIT_COL_ROOK["b"][0] < 0) this.INIT_COL_ROOK["b"][0] = k;
431 else this.INIT_COL_ROOK["b"][1] = k;
1c9f093d 432 break;
6808d7a1
BA
433 case "R":
434 if (this.INIT_COL_ROOK["w"][0] < 0) this.INIT_COL_ROOK["w"][0] = k;
435 else this.INIT_COL_ROOK["w"][1] = k;
1c9f093d 436 break;
6808d7a1 437 default: {
1c9f093d 438 const num = parseInt(fenRows[i].charAt(j));
6808d7a1
BA
439 if (!isNaN(num)) k += num - 1;
440 }
1c9f093d
BA
441 }
442 k++;
443 }
444 }
445 }
446
447 // Some additional variables from FEN (variant dependant)
6808d7a1 448 setOtherVariables(fen) {
1c9f093d
BA
449 // Set flags and enpassant:
450 const parsedFen = V.ParseFen(fen);
6808d7a1
BA
451 if (V.HasFlags) this.setFlags(parsedFen.flags);
452 if (V.HasEnpassant) {
453 const epSq =
454 parsedFen.enpassant != "-"
9bd6786b 455 ? this.getEpSquare(parsedFen.enpassant)
6808d7a1
BA
456 : undefined;
457 this.epSquares = [epSq];
1c9f093d
BA
458 }
459 // Search for king and rooks positions:
460 this.scanKingsRooks(fen);
461 }
462
463 /////////////////////
464 // GETTERS & SETTERS
465
6808d7a1
BA
466 static get size() {
467 return { x: 8, y: 8 };
1c9f093d
BA
468 }
469
0ba6420d 470 // Color of thing on square (i,j). 'undefined' if square is empty
6808d7a1 471 getColor(i, j) {
1c9f093d
BA
472 return this.board[i][j].charAt(0);
473 }
474
475 // Piece type on square (i,j). 'undefined' if square is empty
6808d7a1 476 getPiece(i, j) {
1c9f093d
BA
477 return this.board[i][j].charAt(1);
478 }
479
480 // Get opponent color
6808d7a1
BA
481 static GetOppCol(color) {
482 return color == "w" ? "b" : "w";
1c9f093d
BA
483 }
484
1c9f093d 485 // Pieces codes (for a clearer code)
6808d7a1
BA
486 static get PAWN() {
487 return "p";
488 }
489 static get ROOK() {
490 return "r";
491 }
492 static get KNIGHT() {
493 return "n";
494 }
495 static get BISHOP() {
496 return "b";
497 }
498 static get QUEEN() {
499 return "q";
500 }
501 static get KING() {
502 return "k";
503 }
1c9f093d
BA
504
505 // For FEN checking:
6808d7a1
BA
506 static get PIECES() {
507 return [V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN, V.KING];
1c9f093d
BA
508 }
509
510 // Empty square
6808d7a1
BA
511 static get EMPTY() {
512 return "";
513 }
1c9f093d
BA
514
515 // Some pieces movements
6808d7a1 516 static get steps() {
1c9f093d 517 return {
6808d7a1
BA
518 r: [
519 [-1, 0],
520 [1, 0],
521 [0, -1],
522 [0, 1]
523 ],
524 n: [
525 [-1, -2],
526 [-1, 2],
527 [1, -2],
528 [1, 2],
529 [-2, -1],
530 [-2, 1],
531 [2, -1],
532 [2, 1]
533 ],
534 b: [
535 [-1, -1],
536 [-1, 1],
537 [1, -1],
538 [1, 1]
539 ]
1c9f093d
BA
540 };
541 }
542
543 ////////////////////
544 // MOVES GENERATION
545
0ba6420d 546 // All possible moves from selected square
6808d7a1
BA
547 getPotentialMovesFrom([x, y]) {
548 switch (this.getPiece(x, y)) {
1c9f093d 549 case V.PAWN:
6808d7a1 550 return this.getPotentialPawnMoves([x, y]);
1c9f093d 551 case V.ROOK:
6808d7a1 552 return this.getPotentialRookMoves([x, y]);
1c9f093d 553 case V.KNIGHT:
6808d7a1 554 return this.getPotentialKnightMoves([x, y]);
1c9f093d 555 case V.BISHOP:
6808d7a1 556 return this.getPotentialBishopMoves([x, y]);
1c9f093d 557 case V.QUEEN:
6808d7a1 558 return this.getPotentialQueenMoves([x, y]);
1c9f093d 559 case V.KING:
6808d7a1 560 return this.getPotentialKingMoves([x, y]);
1c9f093d 561 }
6808d7a1 562 return []; //never reached
1c9f093d
BA
563 }
564
565 // Build a regular move from its initial and destination squares.
566 // tr: transformation
6808d7a1 567 getBasicMove([sx, sy], [ex, ey], tr) {
1c9f093d
BA
568 let mv = new Move({
569 appear: [
570 new PiPo({
571 x: ex,
572 y: ey,
6808d7a1
BA
573 c: tr ? tr.c : this.getColor(sx, sy),
574 p: tr ? tr.p : this.getPiece(sx, sy)
1c9f093d
BA
575 })
576 ],
577 vanish: [
578 new PiPo({
579 x: sx,
580 y: sy,
6808d7a1
BA
581 c: this.getColor(sx, sy),
582 p: this.getPiece(sx, sy)
1c9f093d
BA
583 })
584 ]
585 });
586
587 // The opponent piece disappears if we take it
6808d7a1 588 if (this.board[ex][ey] != V.EMPTY) {
1c9f093d
BA
589 mv.vanish.push(
590 new PiPo({
591 x: ex,
592 y: ey,
6808d7a1
BA
593 c: this.getColor(ex, ey),
594 p: this.getPiece(ex, ey)
1c9f093d
BA
595 })
596 );
597 }
598 return mv;
599 }
600
601 // Generic method to find possible moves of non-pawn pieces:
602 // "sliding or jumping"
6808d7a1 603 getSlideNJumpMoves([x, y], steps, oneStep) {
1c9f093d 604 let moves = [];
6808d7a1 605 outerLoop: for (let step of steps) {
1c9f093d
BA
606 let i = x + step[0];
607 let j = y + step[1];
6808d7a1
BA
608 while (V.OnBoard(i, j) && this.board[i][j] == V.EMPTY) {
609 moves.push(this.getBasicMove([x, y], [i, j]));
610 if (oneStep !== undefined) continue outerLoop;
1c9f093d
BA
611 i += step[0];
612 j += step[1];
613 }
6808d7a1
BA
614 if (V.OnBoard(i, j) && this.canTake([x, y], [i, j]))
615 moves.push(this.getBasicMove([x, y], [i, j]));
1c9f093d
BA
616 }
617 return moves;
618 }
619
620 // What are the pawn moves from square x,y ?
6808d7a1 621 getPotentialPawnMoves([x, y]) {
1c9f093d
BA
622 const color = this.turn;
623 let moves = [];
6808d7a1
BA
624 const [sizeX, sizeY] = [V.size.x, V.size.y];
625 const shiftX = color == "w" ? -1 : 1;
626 const firstRank = color == "w" ? sizeX - 1 : 0;
627 const startRank = color == "w" ? sizeX - 2 : 1;
628 const lastRank = color == "w" ? 0 : sizeX - 1;
629 const pawnColor = this.getColor(x, y); //can be different for checkered
1c9f093d
BA
630
631 // NOTE: next condition is generally true (no pawn on last rank)
6808d7a1
BA
632 if (x + shiftX >= 0 && x + shiftX < sizeX) {
633 const finalPieces =
634 x + shiftX == lastRank
635 ? [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN]
636 : [V.PAWN];
6808d7a1 637 if (this.board[x + shiftX][y] == V.EMPTY) {
71ef1664 638 // One square forward
6808d7a1
BA
639 for (let piece of finalPieces) {
640 moves.push(
641 this.getBasicMove([x, y], [x + shiftX, y], {
642 c: pawnColor,
643 p: piece
644 })
645 );
1c9f093d
BA
646 }
647 // Next condition because pawns on 1st rank can generally jump
6808d7a1
BA
648 if (
649 [startRank, firstRank].includes(x) &&
650 this.board[x + 2 * shiftX][y] == V.EMPTY
651 ) {
1c9f093d 652 // Two squares jump
6808d7a1 653 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
1c9f093d
BA
654 }
655 }
656 // Captures
6808d7a1
BA
657 for (let shiftY of [-1, 1]) {
658 if (
659 y + shiftY >= 0 &&
660 y + shiftY < sizeY &&
661 this.board[x + shiftX][y + shiftY] != V.EMPTY &&
662 this.canTake([x, y], [x + shiftX, y + shiftY])
663 ) {
664 for (let piece of finalPieces) {
665 moves.push(
666 this.getBasicMove([x, y], [x + shiftX, y + shiftY], {
667 c: pawnColor,
668 p: piece
669 })
670 );
1c9f093d
BA
671 }
672 }
673 }
674 }
675
6808d7a1 676 if (V.HasEnpassant) {
1c9f093d
BA
677 // En passant
678 const Lep = this.epSquares.length;
6808d7a1
BA
679 const epSquare = this.epSquares[Lep - 1]; //always at least one element
680 if (
681 !!epSquare &&
682 epSquare.x == x + shiftX &&
683 Math.abs(epSquare.y - y) == 1
684 ) {
685 let enpassantMove = this.getBasicMove([x, y], [epSquare.x, epSquare.y]);
1c9f093d
BA
686 enpassantMove.vanish.push({
687 x: x,
688 y: epSquare.y,
6808d7a1
BA
689 p: "p",
690 c: this.getColor(x, epSquare.y)
1c9f093d
BA
691 });
692 moves.push(enpassantMove);
693 }
694 }
695
696 return moves;
697 }
698
699 // What are the rook moves from square x,y ?
6808d7a1 700 getPotentialRookMoves(sq) {
1c9f093d
BA
701 return this.getSlideNJumpMoves(sq, V.steps[V.ROOK]);
702 }
703
704 // What are the knight moves from square x,y ?
6808d7a1 705 getPotentialKnightMoves(sq) {
1c9f093d
BA
706 return this.getSlideNJumpMoves(sq, V.steps[V.KNIGHT], "oneStep");
707 }
708
709 // What are the bishop moves from square x,y ?
6808d7a1 710 getPotentialBishopMoves(sq) {
1c9f093d
BA
711 return this.getSlideNJumpMoves(sq, V.steps[V.BISHOP]);
712 }
713
714 // What are the queen moves from square x,y ?
6808d7a1
BA
715 getPotentialQueenMoves(sq) {
716 return this.getSlideNJumpMoves(
717 sq,
718 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
719 );
1c9f093d
BA
720 }
721
722 // What are the king moves from square x,y ?
6808d7a1 723 getPotentialKingMoves(sq) {
1c9f093d 724 // Initialize with normal moves
6808d7a1
BA
725 let moves = this.getSlideNJumpMoves(
726 sq,
727 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
728 "oneStep"
729 );
1c9f093d
BA
730 return moves.concat(this.getCastleMoves(sq));
731 }
732
6808d7a1
BA
733 getCastleMoves([x, y]) {
734 const c = this.getColor(x, y);
735 if (x != (c == "w" ? V.size.x - 1 : 0) || y != this.INIT_COL_KING[c])
1c9f093d
BA
736 return []; //x isn't first rank, or king has moved (shortcut)
737
738 // Castling ?
739 const oppCol = V.GetOppCol(c);
740 let moves = [];
741 let i = 0;
9bd6786b 742 // King, then rook:
6808d7a1
BA
743 const finalSquares = [
744 [2, 3],
745 [V.size.y - 2, V.size.y - 3]
9bd6786b 746 ];
6808d7a1
BA
747 castlingCheck: for (
748 let castleSide = 0;
749 castleSide < 2;
750 castleSide++ //large, then small
751 ) {
752 if (!this.castleFlags[c][castleSide]) continue;
1c9f093d
BA
753 // If this code is reached, rooks and king are on initial position
754
2beba6db
BA
755 // Nothing on the path of the king ? (and no checks)
756 const finDist = finalSquares[castleSide][0] - y;
757 let step = finDist / Math.max(1, Math.abs(finDist));
758 i = y;
6808d7a1
BA
759 do {
760 if (
761 this.isAttacked([x, i], [oppCol]) ||
762 (this.board[x][i] != V.EMPTY &&
763 // NOTE: next check is enough, because of chessboard constraints
764 (this.getColor(x, i) != c ||
765 ![V.KING, V.ROOK].includes(this.getPiece(x, i))))
766 ) {
1c9f093d
BA
767 continue castlingCheck;
768 }
2beba6db 769 i += step;
6808d7a1 770 } while (i != finalSquares[castleSide][0]);
1c9f093d
BA
771
772 // Nothing on the path to the rook?
6808d7a1
BA
773 step = castleSide == 0 ? -1 : 1;
774 for (i = y + step; i != this.INIT_COL_ROOK[c][castleSide]; i += step) {
775 if (this.board[x][i] != V.EMPTY) continue castlingCheck;
1c9f093d
BA
776 }
777 const rookPos = this.INIT_COL_ROOK[c][castleSide];
778
779 // Nothing on final squares, except maybe king and castling rook?
6808d7a1
BA
780 for (i = 0; i < 2; i++) {
781 if (
782 this.board[x][finalSquares[castleSide][i]] != V.EMPTY &&
783 this.getPiece(x, finalSquares[castleSide][i]) != V.KING &&
784 finalSquares[castleSide][i] != rookPos
785 ) {
1c9f093d
BA
786 continue castlingCheck;
787 }
788 }
789
790 // If this code is reached, castle is valid
6808d7a1
BA
791 moves.push(
792 new Move({
793 appear: [
794 new PiPo({ x: x, y: finalSquares[castleSide][0], p: V.KING, c: c }),
795 new PiPo({ x: x, y: finalSquares[castleSide][1], p: V.ROOK, c: c })
796 ],
797 vanish: [
798 new PiPo({ x: x, y: y, p: V.KING, c: c }),
799 new PiPo({ x: x, y: rookPos, p: V.ROOK, c: c })
800 ],
801 end:
802 Math.abs(y - rookPos) <= 2
803 ? { x: x, y: rookPos }
804 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
805 })
806 );
1c9f093d
BA
807 }
808
809 return moves;
810 }
811
812 ////////////////////
813 // MOVES VALIDATION
814
815 // For the interface: possible moves for the current turn from square sq
6808d7a1
BA
816 getPossibleMovesFrom(sq) {
817 return this.filterValid(this.getPotentialMovesFrom(sq));
1c9f093d
BA
818 }
819
820 // TODO: promotions (into R,B,N,Q) should be filtered only once
6808d7a1
BA
821 filterValid(moves) {
822 if (moves.length == 0) return [];
1c9f093d
BA
823 const color = this.turn;
824 return moves.filter(m => {
825 this.play(m);
826 const res = !this.underCheck(color);
827 this.undo(m);
828 return res;
829 });
830 }
831
832 // Search for all valid moves considering current turn
833 // (for engine and game end)
6808d7a1 834 getAllValidMoves() {
1c9f093d
BA
835 const color = this.turn;
836 const oppCol = V.GetOppCol(color);
837 let potentialMoves = [];
6808d7a1
BA
838 for (let i = 0; i < V.size.x; i++) {
839 for (let j = 0; j < V.size.y; j++) {
1c9f093d 840 // Next condition "!= oppCol" to work with checkered variant
6808d7a1
BA
841 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) {
842 Array.prototype.push.apply(
843 potentialMoves,
844 this.getPotentialMovesFrom([i, j])
845 );
1c9f093d
BA
846 }
847 }
848 }
849 return this.filterValid(potentialMoves);
850 }
851
852 // Stop at the first move found
6808d7a1 853 atLeastOneMove() {
1c9f093d
BA
854 const color = this.turn;
855 const oppCol = V.GetOppCol(color);
6808d7a1
BA
856 for (let i = 0; i < V.size.x; i++) {
857 for (let j = 0; j < V.size.y; j++) {
858 if (this.board[i][j] != V.EMPTY && this.getColor(i, j) != oppCol) {
859 const moves = this.getPotentialMovesFrom([i, j]);
860 if (moves.length > 0) {
861 for (let k = 0; k < moves.length; k++) {
862 if (this.filterValid([moves[k]]).length > 0) return true;
1c9f093d
BA
863 }
864 }
865 }
866 }
867 }
868 return false;
869 }
870
871 // Check if pieces of color in 'colors' are attacking (king) on square x,y
6808d7a1
BA
872 isAttacked(sq, colors) {
873 return (
874 this.isAttackedByPawn(sq, colors) ||
875 this.isAttackedByRook(sq, colors) ||
876 this.isAttackedByKnight(sq, colors) ||
877 this.isAttackedByBishop(sq, colors) ||
878 this.isAttackedByQueen(sq, colors) ||
879 this.isAttackedByKing(sq, colors)
880 );
1c9f093d
BA
881 }
882
883 // Is square x,y attacked by 'colors' pawns ?
6808d7a1
BA
884 isAttackedByPawn([x, y], colors) {
885 for (let c of colors) {
886 let pawnShift = c == "w" ? 1 : -1;
887 if (x + pawnShift >= 0 && x + pawnShift < V.size.x) {
888 for (let i of [-1, 1]) {
889 if (
890 y + i >= 0 &&
891 y + i < V.size.y &&
892 this.getPiece(x + pawnShift, y + i) == V.PAWN &&
893 this.getColor(x + pawnShift, y + i) == c
894 ) {
1c9f093d
BA
895 return true;
896 }
897 }
898 }
899 }
900 return false;
901 }
902
903 // Is square x,y attacked by 'colors' rooks ?
6808d7a1 904 isAttackedByRook(sq, colors) {
1c9f093d
BA
905 return this.isAttackedBySlideNJump(sq, colors, V.ROOK, V.steps[V.ROOK]);
906 }
907
908 // Is square x,y attacked by 'colors' knights ?
6808d7a1
BA
909 isAttackedByKnight(sq, colors) {
910 return this.isAttackedBySlideNJump(
911 sq,
912 colors,
913 V.KNIGHT,
914 V.steps[V.KNIGHT],
915 "oneStep"
916 );
1c9f093d
BA
917 }
918
919 // Is square x,y attacked by 'colors' bishops ?
6808d7a1 920 isAttackedByBishop(sq, colors) {
1c9f093d
BA
921 return this.isAttackedBySlideNJump(sq, colors, V.BISHOP, V.steps[V.BISHOP]);
922 }
923
924 // Is square x,y attacked by 'colors' queens ?
6808d7a1
BA
925 isAttackedByQueen(sq, colors) {
926 return this.isAttackedBySlideNJump(
927 sq,
928 colors,
929 V.QUEEN,
930 V.steps[V.ROOK].concat(V.steps[V.BISHOP])
931 );
1c9f093d
BA
932 }
933
934 // Is square x,y attacked by 'colors' king(s) ?
6808d7a1
BA
935 isAttackedByKing(sq, colors) {
936 return this.isAttackedBySlideNJump(
937 sq,
938 colors,
939 V.KING,
940 V.steps[V.ROOK].concat(V.steps[V.BISHOP]),
941 "oneStep"
942 );
1c9f093d
BA
943 }
944
945 // Generic method for non-pawn pieces ("sliding or jumping"):
946 // is x,y attacked by a piece of color in array 'colors' ?
6808d7a1
BA
947 isAttackedBySlideNJump([x, y], colors, piece, steps, oneStep) {
948 for (let step of steps) {
949 let rx = x + step[0],
950 ry = y + step[1];
951 while (V.OnBoard(rx, ry) && this.board[rx][ry] == V.EMPTY && !oneStep) {
1c9f093d
BA
952 rx += step[0];
953 ry += step[1];
954 }
6808d7a1
BA
955 if (
956 V.OnBoard(rx, ry) &&
957 this.getPiece(rx, ry) === piece &&
958 colors.includes(this.getColor(rx, ry))
959 ) {
1c9f093d
BA
960 return true;
961 }
962 }
963 return false;
964 }
965
966 // Is color under check after his move ?
6808d7a1 967 underCheck(color) {
1c9f093d
BA
968 return this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]);
969 }
970
971 /////////////////
972 // MOVES PLAYING
973
974 // Apply a move on board
6808d7a1
BA
975 static PlayOnBoard(board, move) {
976 for (let psq of move.vanish) board[psq.x][psq.y] = V.EMPTY;
977 for (let psq of move.appear) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
978 }
979 // Un-apply the played move
6808d7a1
BA
980 static UndoOnBoard(board, move) {
981 for (let psq of move.appear) board[psq.x][psq.y] = V.EMPTY;
982 for (let psq of move.vanish) board[psq.x][psq.y] = psq.c + psq.p;
1c9f093d
BA
983 }
984
985 // After move is played, update variables + flags
6808d7a1 986 updateVariables(move) {
1c9f093d 987 let piece = undefined;
78d64531
BA
988 // TODO: update variables before move is played, and just use this.turn ?
989 // (doesn't work in general, think MarseilleChess)
1c9f093d 990 let c = undefined;
6808d7a1 991 if (move.vanish.length >= 1) {
1c9f093d
BA
992 // Usual case, something is moved
993 piece = move.vanish[0].p;
994 c = move.vanish[0].c;
6808d7a1 995 } else {
1c9f093d
BA
996 // Crazyhouse-like variants
997 piece = move.appear[0].p;
998 c = move.appear[0].c;
999 }
78d64531
BA
1000 if (!['w','b'].includes(c)) {
1001 // Checkered, for example
1c9f093d
BA
1002 c = V.GetOppCol(this.turn);
1003 }
6808d7a1 1004 const firstRank = c == "w" ? V.size.x - 1 : 0;
1c9f093d
BA
1005
1006 // Update king position + flags
6808d7a1 1007 if (piece == V.KING && move.appear.length > 0) {
1c9f093d
BA
1008 this.kingPos[c][0] = move.appear[0].x;
1009 this.kingPos[c][1] = move.appear[0].y;
6808d7a1 1010 if (V.HasFlags) this.castleFlags[c] = [false, false];
1c9f093d
BA
1011 return;
1012 }
6808d7a1 1013 if (V.HasFlags) {
1c9f093d
BA
1014 // Update castling flags if rooks are moved
1015 const oppCol = V.GetOppCol(c);
6808d7a1
BA
1016 const oppFirstRank = V.size.x - 1 - firstRank;
1017 if (
1018 move.start.x == firstRank && //our rook moves?
1019 this.INIT_COL_ROOK[c].includes(move.start.y)
1020 ) {
1021 const flagIdx = move.start.y == this.INIT_COL_ROOK[c][0] ? 0 : 1;
1c9f093d 1022 this.castleFlags[c][flagIdx] = false;
6808d7a1
BA
1023 } else if (
1024 move.end.x == oppFirstRank && //we took opponent rook?
1025 this.INIT_COL_ROOK[oppCol].includes(move.end.y)
1026 ) {
1027 const flagIdx = move.end.y == this.INIT_COL_ROOK[oppCol][0] ? 0 : 1;
1c9f093d
BA
1028 this.castleFlags[oppCol][flagIdx] = false;
1029 }
1030 }
1031 }
1032
1033 // After move is undo-ed *and flags resetted*, un-update other variables
1034 // TODO: more symmetry, by storing flags increment in move (?!)
6808d7a1 1035 unupdateVariables(move) {
1c9f093d 1036 // (Potentially) Reset king position
6808d7a1
BA
1037 const c = this.getColor(move.start.x, move.start.y);
1038 if (this.getPiece(move.start.x, move.start.y) == V.KING)
1c9f093d
BA
1039 this.kingPos[c] = [move.start.x, move.start.y];
1040 }
1041
6808d7a1 1042 play(move) {
1c9f093d 1043 // DEBUG:
9bd6786b
BA
1044// if (!this.states) this.states = [];
1045// const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1046// this.states.push(stateFen);
6808d7a1
BA
1047
1048 if (V.HasFlags) move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo)
1049 if (V.HasEnpassant) this.epSquares.push(this.getEpSquare(move));
1c9f093d
BA
1050 V.PlayOnBoard(this.board, move);
1051 this.turn = V.GetOppCol(this.turn);
1052 this.movesCount++;
1053 this.updateVariables(move);
1054 }
1055
6808d7a1
BA
1056 undo(move) {
1057 if (V.HasEnpassant) this.epSquares.pop();
1058 if (V.HasFlags) this.disaggregateFlags(JSON.parse(move.flags));
1c9f093d
BA
1059 V.UndoOnBoard(this.board, move);
1060 this.turn = V.GetOppCol(this.turn);
1061 this.movesCount--;
1062 this.unupdateVariables(move);
1063
1064 // DEBUG:
9bd6786b
BA
1065// const stateFen = this.getBaseFen() + this.getTurnFen() + this.getFlagsFen();
1066// if (stateFen != this.states[this.states.length-1]) debugger;
1067// this.states.pop();
1c9f093d
BA
1068 }
1069
1070 ///////////////
1071 // END OF GAME
1072
1073 // What is the score ? (Interesting if game is over)
6808d7a1
BA
1074 getCurrentScore() {
1075 if (this.atLeastOneMove())
1c9f093d
BA
1076 return "*";
1077
1078 // Game over
1079 const color = this.turn;
1080 // No valid move: stalemate or checkmate?
1081 if (!this.isAttacked(this.kingPos[color], [V.GetOppCol(color)]))
1082 return "1/2";
1083 // OK, checkmate
6808d7a1 1084 return color == "w" ? "0-1" : "1-0";
1c9f093d
BA
1085 }
1086
1087 ///////////////
1088 // ENGINE PLAY
1089
1090 // Pieces values
6808d7a1 1091 static get VALUES() {
1c9f093d 1092 return {
6808d7a1
BA
1093 p: 1,
1094 r: 5,
1095 n: 3,
1096 b: 3,
1097 q: 9,
1098 k: 1000
1c9f093d
BA
1099 };
1100 }
1101
1102 // "Checkmate" (unreachable eval)
6808d7a1
BA
1103 static get INFINITY() {
1104 return 9999;
1105 }
1c9f093d
BA
1106
1107 // At this value or above, the game is over
6808d7a1
BA
1108 static get THRESHOLD_MATE() {
1109 return V.INFINITY;
1110 }
1c9f093d
BA
1111
1112 // Search depth: 2 for high branching factor, 4 for small (Loser chess, eg.)
6808d7a1
BA
1113 static get SEARCH_DEPTH() {
1114 return 3;
1115 }
1c9f093d 1116
1c9f093d 1117 // NOTE: works also for extinction chess because depth is 3...
6808d7a1 1118 getComputerMove() {
1c9f093d
BA
1119 const maxeval = V.INFINITY;
1120 const color = this.turn;
1121 // Some variants may show a bigger moves list to the human (Switching),
1122 // thus the argument "computer" below (which is generally ignored)
1123 let moves1 = this.getAllValidMoves("computer");
c322a844 1124
6808d7a1
BA
1125 if (moves1.length == 0)
1126 //TODO: this situation should not happen
41cb9b94 1127 return null;
1c9f093d
BA
1128
1129 // Can I mate in 1 ? (for Magnetic & Extinction)
6808d7a1 1130 for (let i of shuffle(ArrayFun.range(moves1.length))) {
1c9f093d 1131 this.play(moves1[i]);
6808d7a1
BA
1132 let finish = Math.abs(this.evalPosition()) >= V.THRESHOLD_MATE;
1133 if (!finish) {
1c9f093d 1134 const score = this.getCurrentScore();
6808d7a1 1135 if (["1-0", "0-1"].includes(score)) finish = true;
1c9f093d
BA
1136 }
1137 this.undo(moves1[i]);
6808d7a1 1138 if (finish) return moves1[i];
1c9f093d
BA
1139 }
1140
1141 // Rank moves using a min-max at depth 2
6808d7a1 1142 for (let i = 0; i < moves1.length; i++) {
1c9f093d 1143 // Initial self evaluation is very low: "I'm checkmated"
6808d7a1 1144 moves1[i].eval = (color == "w" ? -1 : 1) * maxeval;
1c9f093d
BA
1145 this.play(moves1[i]);
1146 const score1 = this.getCurrentScore();
1147 let eval2 = undefined;
6808d7a1 1148 if (score1 == "*") {
1c9f093d 1149 // Initial enemy evaluation is very low too, for him
6808d7a1 1150 eval2 = (color == "w" ? 1 : -1) * maxeval;
1c9f093d
BA
1151 // Second half-move:
1152 let moves2 = this.getAllValidMoves("computer");
6808d7a1 1153 for (let j = 0; j < moves2.length; j++) {
1c9f093d
BA
1154 this.play(moves2[j]);
1155 const score2 = this.getCurrentScore();
6808d7a1
BA
1156 let evalPos = 0; //1/2 value
1157 switch (score2) {
1158 case "*":
1159 evalPos = this.evalPosition();
1160 break;
1161 case "1-0":
1162 evalPos = maxeval;
1163 break;
1164 case "0-1":
1165 evalPos = -maxeval;
1166 break;
1167 }
1168 if (
1169 (color == "w" && evalPos < eval2) ||
1170 (color == "b" && evalPos > eval2)
1171 ) {
1c9f093d
BA
1172 eval2 = evalPos;
1173 }
1174 this.undo(moves2[j]);
1175 }
6808d7a1
BA
1176 } else eval2 = score1 == "1/2" ? 0 : (score1 == "1-0" ? 1 : -1) * maxeval;
1177 if (
1178 (color == "w" && eval2 > moves1[i].eval) ||
1179 (color == "b" && eval2 < moves1[i].eval)
1180 ) {
1c9f093d
BA
1181 moves1[i].eval = eval2;
1182 }
1183 this.undo(moves1[i]);
1184 }
6808d7a1
BA
1185 moves1.sort((a, b) => {
1186 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1187 });
1c9f093d
BA
1188
1189 let candidates = [0]; //indices of candidates moves
6808d7a1 1190 for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++)
1c9f093d 1191 candidates.push(j);
0c3fe8a6 1192 let currentBest = moves1[candidates[randInt(candidates.length)]];
1c9f093d 1193
1c9f093d 1194 // Skip depth 3+ if we found a checkmate (or if we are checkmated in 1...)
6808d7a1 1195 if (V.SEARCH_DEPTH >= 3 && Math.abs(moves1[0].eval) < V.THRESHOLD_MATE) {
656b1878
BA
1196 // From here, depth >= 3: may take a while, so we control time
1197 const timeStart = Date.now();
6808d7a1
BA
1198 for (let i = 0; i < moves1.length; i++) {
1199 if (Date.now() - timeStart >= 5000)
1200 //more than 5 seconds
1c9f093d
BA
1201 return currentBest; //depth 2 at least
1202 this.play(moves1[i]);
1203 // 0.1 * oldEval : heuristic to avoid some bad moves (not all...)
6808d7a1
BA
1204 moves1[i].eval =
1205 0.1 * moves1[i].eval +
1206 this.alphabeta(V.SEARCH_DEPTH - 1, -maxeval, maxeval);
1c9f093d
BA
1207 this.undo(moves1[i]);
1208 }
6808d7a1
BA
1209 moves1.sort((a, b) => {
1210 return (color == "w" ? 1 : -1) * (b.eval - a.eval);
1211 });
1212 } else return currentBest;
c322a844 1213 console.log(moves1.map(m => { return [this.getNotation(m), m.eval]; }));
1c9f093d
BA
1214
1215 candidates = [0];
6808d7a1 1216 for (let j = 1; j < moves1.length && moves1[j].eval == moves1[0].eval; j++)
1c9f093d 1217 candidates.push(j);
656b1878 1218 return moves1[candidates[randInt(candidates.length)]];
1c9f093d
BA
1219 }
1220
6808d7a1 1221 alphabeta(depth, alpha, beta) {
1c9f093d
BA
1222 const maxeval = V.INFINITY;
1223 const color = this.turn;
1224 const score = this.getCurrentScore();
1225 if (score != "*")
6808d7a1
BA
1226 return score == "1/2" ? 0 : (score == "1-0" ? 1 : -1) * maxeval;
1227 if (depth == 0) return this.evalPosition();
1c9f093d 1228 const moves = this.getAllValidMoves("computer");
6808d7a1
BA
1229 let v = color == "w" ? -maxeval : maxeval;
1230 if (color == "w") {
1231 for (let i = 0; i < moves.length; i++) {
1c9f093d 1232 this.play(moves[i]);
6808d7a1 1233 v = Math.max(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1234 this.undo(moves[i]);
1235 alpha = Math.max(alpha, v);
6808d7a1 1236 if (alpha >= beta) break; //beta cutoff
1c9f093d 1237 }
6808d7a1
BA
1238 } //color=="b"
1239 else {
1240 for (let i = 0; i < moves.length; i++) {
1c9f093d 1241 this.play(moves[i]);
6808d7a1 1242 v = Math.min(v, this.alphabeta(depth - 1, alpha, beta));
1c9f093d
BA
1243 this.undo(moves[i]);
1244 beta = Math.min(beta, v);
6808d7a1 1245 if (alpha >= beta) break; //alpha cutoff
1c9f093d
BA
1246 }
1247 }
1248 return v;
1249 }
1250
6808d7a1 1251 evalPosition() {
1c9f093d
BA
1252 let evaluation = 0;
1253 // Just count material for now
6808d7a1
BA
1254 for (let i = 0; i < V.size.x; i++) {
1255 for (let j = 0; j < V.size.y; j++) {
1256 if (this.board[i][j] != V.EMPTY) {
1257 const sign = this.getColor(i, j) == "w" ? 1 : -1;
c322a844
BA
1258
1259
1260//TODO: debug in KnightRelay
1261if (isNaN(V.VALUES[this.getPiece(i, j)])) {
1262 console.log(i + " " + j);
1263 console.log(this.getPiece(i, j));
1264 console.log(this.board);
1265 console.log("ajout " + sign + " * "+ V.VALUES[this.getPiece(i, j)]);
1266 debugger;
1267}
1268
1269
6808d7a1 1270 evaluation += sign * V.VALUES[this.getPiece(i, j)];
1c9f093d
BA
1271 }
1272 }
1273 }
1274 return evaluation;
1275 }
1276
1277 /////////////////////////
1278 // MOVES + GAME NOTATION
1279 /////////////////////////
1280
1281 // Context: just before move is played, turn hasn't changed
1282 // TODO: un-ambiguous notation (switch on piece type, check directions...)
6808d7a1
BA
1283 getNotation(move) {
1284 if (move.appear.length == 2 && move.appear[0].p == V.KING)
1cd3e362 1285 // Castle
6808d7a1 1286 return move.end.y < move.start.y ? "0-0-0" : "0-0";
1c9f093d
BA
1287
1288 // Translate final square
1289 const finalSquare = V.CoordsToSquare(move.end);
1290
1291 const piece = this.getPiece(move.start.x, move.start.y);
6808d7a1 1292 if (piece == V.PAWN) {
1c9f093d
BA
1293 // Pawn move
1294 let notation = "";
6808d7a1 1295 if (move.vanish.length > move.appear.length) {
1c9f093d
BA
1296 // Capture
1297 const startColumn = V.CoordToColumn(move.start.y);
1298 notation = startColumn + "x" + finalSquare;
78d64531 1299 }
6808d7a1
BA
1300 else notation = finalSquare;
1301 if (move.appear.length > 0 && move.appear[0].p != V.PAWN)
78d64531 1302 // Promotion
1c9f093d
BA
1303 notation += "=" + move.appear[0].p.toUpperCase();
1304 return notation;
1305 }
6808d7a1
BA
1306 // Piece movement
1307 return (
1308 piece.toUpperCase() +
1309 (move.vanish.length > move.appear.length ? "x" : "") +
1310 finalSquare
1311 );
1312 }
1313};