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