Convert PGN to FEN string list in nodejs (chess notation)

I am creating a chess related application using nodejs. I tried to use chess.js as much as I can, but I think I ran into a checkpoint in terms of functionality. Before expanding this functionality, I wanted to make sure that there was no other tool that could do what I needed.

I am looking for a way to convert a PGN string to a FEN motion list. I was hoping to use load_pgn() in chess.js to load movements into an object, and then loop over each movement and call the fen() function to output the current FEN. However, chess.js does not seem to have the ability to go through the turn in the game. If I didn’t miss something.

I would prefer not to understand the syntax lines, but if necessary. Any suggestions?

Decision:

also see efirvida below for a solution

It seems to be something like this (untested). The function accepts a Chess object created using chess.js , which has already loaded PGN into it.

 function getMovesAsFENs(chessObj) { var moves = chessObj.history(); var newGame = new Chess(); var fens = []; for (var i = 0; i < moves.length; i++) { newGame.move(moves[i]); fens.push(newGame.fen()); } return fens; } 
+7
source share
3 answers

.load_pgn look at the .load_pgn page .load_pgn link

 var chess = new Chess(); pgn = ['[Event "Casual Game"]', '[Site "Berlin GER"]', '[Date "1852.??.??"]', '[EventDate "?"]', '[Round "?"]', '[Result "1-0"]', '[White "Adolf Anderssen"]', '[Black "Jean Dufresne"]', '[ECO "C52"]', '[WhiteElo "?"]', '[BlackElo "?"]', '[PlyCount "47"]', '', '1.e4 e5 2.Nf3 Nc6 3.Bc4 Bc5 4.b4 Bxb4 5.c3 Ba5 6.d4 exd4 7.O-O', 'd3 8.Qb3 Qf6 9.e5 Qg6 10.Re1 Nge7 11.Ba3 b5 12.Qxb5 Rb8 13.Qa4', 'Bb6 14.Nbd2 Bb7 15.Ne4 Qf5 16.Bxd3 Qh5 17.Nf6+ gxf6 18.exf6', 'Rg8 19.Rad1 Qxf3 20.Rxe7+ Nxe7 21.Qxd7+ Kxd7 22.Bf5+ Ke8', '23.Bd7+ Kf8 24.Bxe7# 1-0']; chess.load_pgn(pgn.join('\n')); // -> true chess.fen() // -> 1r3kr1/pbpBBp1p/1b3P2/8/8/2P2q2/P4PPP/3R2K1 b - - 0 24 

sort of

 moves = chess.history(); var chess1 = new Chess(); for (move in moves){ chess1.move(move); fen = chess1.fen() } 
+6
source

(Not quite an answer, just a comment that requires additional formatting.)

Your getMovesAsFENs function getMovesAsFENs also be written as:

 function getMovesAsFENs(chessObj) { return chessObj.history().map(function(move) { chessObj.move(move); return chessObj.fen(); }); } 

It may not matter to you, but it concerns my sense of accuracy.

+3
source

Here is the end-to-end answer with some ES6 sugar added to:

 const Chess = require('chess.js').Chess; const chess1 = new Chess(); const chess2 = new Chess(); const startPos = chess2.fen(); const pgn = `1.e4 c5 0-1`; chess1.load_pgn(pgn); let fens = chess1.history().map(move => { chess2.move(move); return chess2.fen(); }); //the above technique will not capture the fen of the starting position. therefore: fens = [startPos, ...fens]; //double checking everything fens.forEach(fen => console.log(fen)); 
+1
source

All Articles