Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript chess notation conversion function

I am looking for a javascript library to convert PGN files with move notations including piece and destination like:

... 3. cxd5 Qxd5 ...

Into notation only with the square co-ordinates, like:

... 3. c4-d5 h5-d5 ...

Without a library, it would be a fair amount of work to make this rock solid, as it would have to step through each move, and validate legal moves to determine which piece can reach the destination square.

Is there anything in javascript to help me, or in another language that I could easily port?

like image 591
Billy Moon Avatar asked Mar 13 '13 01:03

Billy Moon


1 Answers

Preface: I am not really a chess player nor do I entirely understand PGN. However, I do think that this is correct. Let me know if I'm off at all.

Since you said you want to do this server side I looked for node.js chess packages. There were a bunch of good looking candidates from nodejs modules tagged chess. I ended up using jhlywa / chess.js.

app.js

var cjs = require('./chess.js'),
  chess = new cjs.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'],
  i = 1,
  moveHistory;

chess.load_pgn(pgn.join('\n'));
moveHistory = chess.history({ verbose: true });

while (moveHistory.length > 0) {
  var p1Move = moveHistory.shift(),
    p2Move = moveHistory.shift(),
    p1c = p1Move.from + '-' + p1Move.to,
    p2c = (p2Move == undefined) ? '' : p2Move.from + '-' + p2Move.to;
  console.log(i + '. ' + p1c + ' ' + p2c );
  i++;
}

Output from console.log:

1. e2-e4 e7-e5
2. g1-f3 b8-c6
3. f1-c4 f8-c5
4. b2-b4 c5-b4
5. c2-c3 b4-a5
6. d2-d4 e5-d4
7. e1-g1 d4-d3
8. d1-b3 d8-f6
9. e4-e5 f6-g6
10. f1-e1 g8-e7
11. c1-a3 b7-b5
12. b3-b5 a8-b8
13. b5-a4 a5-b6
14. b1-d2 c8-b7
15. d2-e4 g6-f5
16. c4-d3 f5-h5
17. e4-f6 g7-f6
18. e5-f6 h8-g8
19. a1-d1 h5-f3
20. e1-e7 c6-e7
21. a4-d7 e8-d7
22. d3-f5 d7-e8
23. f5-d7 e8-f8
24. a3-e7 
like image 114
ryan Avatar answered Oct 31 '22 21:10

ryan