Giraffes are Fake
Giraffes are Fake

Reputation: 25

How can I manipulate this chess notation with python?

I'm trying to use some chess related libraries in python (e.g. chessnut and chess) and they use the following notation

r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4

I've searched about it and didn't find anything. How can I manipulate this and how can I transform the standart algebraic notation (e.g. "d4 Nc6 e4 e5 f4 f6 dxe5 fxe5") into this new one?

Upvotes: 1

Views: 1619

Answers (3)

LittleCoder
LittleCoder

Reputation: 421

For FEN info : https://en.wikipedia.org/wiki/Forsyth–Edwards_Notation

There are two ways to obtain a FEN from a san in python : With a .pgn file :

import chess
import chess.pgn

pgn = open("your_pgn_file.pgn")
game = chess.pgn.read_game(pgn)
board = game.board()

for move in game.mainline_moves():
    board.push(move)
print(board.fen())

or from a single san mainline :

import chess

board = chess.Board()
san_mainline = "d4 Nc6 e4 e5 f4 f6 dxe5 fxe5"

for move in san_mainline.split():
    board.push_san(move)
print(board.fen())

Upvotes: 2

its5Q
its5Q

Reputation: 110

You can use python-chess to do the job. Here is the code that takes the SAN string and makes those moves on a board:

import chess
san = 'd4 Nc6 e4 e5 f4 f6 dxe5 fxe5'
board = chess.Board()
for move_san in san.split(' '):
    board.push_san(move_san)

Upvotes: 1

creanion
creanion

Reputation: 2743

That notation is called FEN (Forsyth–Edwards Notation), and it looks like python-chess knows about it and can parse it.

This notation is not really equivalent to a list of moves - this is for specifying a position, which might also be a starting position. There's no complete record of how the game reached that point.

Python-chess can turn any board position you've loaded into it - for example using PGN notation - into this notation though.

Upvotes: 3

Related Questions