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