dig dug
dig dug

Reputation: 36

python-chess: replace . with #

A python-chess board can return an ascii representation of the board with dots as empty squares based on this part of its source code:

def __str__(self) -> str:
    builder = []

    for square in SQUARES_180:
        piece = self.piece_at(square)

        if piece:
            builder.append(piece.symbol())
        else:
            builder.append(".")

        if BB_SQUARES[square] & BB_FILE_H:
            if square != H1:
                builder.append("\n")
        else:
            builder.append(" ")

    return "".join(builder)

Let's say we generate a board and pass it to the print function:

>>> import chess
>>> board = chess.Board("rnbq1rk1/ppp1ppbp/3p1np1/8/2PPP3/2N2N2/PP2BPPP/R1BQK2R b KQ - 3 6")
>>> print(board)
r n b q . r k .
p p p . p p b p
. . . p . n p .
. . . . . . . .
. . P P P . . .
. . N . . N . .
P P . . B P P P
R . B Q K . . R

But we want to replace all the dots with hashes:

r n b q # r k #
p p p # p p b p
# # # p # n p #
# # # # # # # #
# # P P P # # #
# # N # # N # #
P P # # B P P P
R # B Q K # # R

The regular expression library won't handle the board object:

>>> import re
>>> re.sub(r'\.', r'#', board)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/re.py", line 192, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

Cloning the object method in a custom function:

def hashboard(board) -> str:
    builder = []
    for square in chess.SQUARES_180:
        piece = board.piece_at(square)
        if piece:
            builder.append(piece.symbol())
        else:
            builder.append("#")
        if chess.BB_SQUARES[square] & chess.BB_FILE_H:
            if square != chess.H1:
                builder.append("\n")
        else:
            builder.append(" ")
    return "".join(builder)

A solution:

>>> print(hashboard(board))
r n b q # r k #
p p p # p p b p
# # # p # n p #
# # # # # # # #
# # P P P # # #
# # N # # N # #
P P # # B P P P
R # B Q K # # R

Could I have done better? I'm an amateur, self-taught programmer. I appreciate any feedback.

Upvotes: 0

Views: 350

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177610

board is an instance of a chess.Board class object. The __str__ method returns the string that re.sub (or just .replace, in this simple case) can act on.

This works:

print(str(board).replace('.', '#'))

Upvotes: 4

Related Questions