Search code examples
pythonimagechessfen

Generate Chess Board Diagram from an array of positions in Python?


I have an array which corresponds to the positions of pieces on a chessboard, like so:

['em', 'bn', 'em', 'wr', 'em', 'wp', 'em', 'em']
['br', 'em', 'bp', 'em', 'em', 'bn', 'wn', 'em']
['em', 'em', 'bp', 'bp', 'bp', 'em', 'wp', 'bp']
['bp', 'bp', 'em', 'bp', 'wn', 'em', 'wp', 'em']
....

The 'b' and 'w' signify black and white.

n: knight
r: rook
p: pawn
b: bishop
k: king
q: queen

I want to know if there exists some utility which can take this array or something similar and generate a picture of a chessboard. There exist lots of board generators that work on FEN or PGN notation but I don't have access to that. I did do a lot of searching on Google but I couldn't find anything.

Thank you!


Solution

  • It is not difficult to convert your representation to a standard one. For example, you can convert to FEN with a function like this:

    import io
    
    def board_to_fen(board):
        # Use StringIO to build string more efficiently than concatenating
        with io.StringIO() as s:
            for row in board:
                empty = 0
                for cell in row:
                    c = cell[0]
                    if c in ('w', 'b'):
                        if empty > 0:
                            s.write(str(empty))
                            empty = 0
                        s.write(cell[1].upper() if c == 'w' else cell[1].lower())
                    else:
                        empty += 1
                if empty > 0:
                    s.write(str(empty))
                s.write('/')
            # Move one position back to overwrite last '/'
            s.seek(s.tell() - 1)
            # If you do not have the additional information choose what to put
            s.write(' w KQkq - 0 1')
            return s.getvalue()
    

    Testing it on some board data:

    board = [
        ['bk', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
        ['em', 'bn', 'em', 'wr', 'em', 'wp', 'em', 'em'],
        ['br', 'em', 'bp', 'em', 'em', 'bn', 'wn', 'em'],
        ['em', 'em', 'bp', 'bp', 'bp', 'em', 'wp', 'bp'],
        ['bp', 'bp', 'em', 'bp', 'wn', 'em', 'wp', 'em'],
        ['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
        ['em', 'em', 'em', 'wk', 'em', 'em', 'em', 'em'],
        ['em', 'em', 'em', 'em', 'em', 'em', 'em', 'em'],
    ]
    print(board_to_fen(board))
    # k7/1n1R1P2/r1p2nN1/2ppp1Pp/pp1pN1P1/8/3K4/8 w KQkq - 0 1
    

    Visualizing the FEN string for example in Chess.com produces:

    Board