I have an interesting problem with my chess application. The application reads PGN files, and at any time while viewing a game from the file, the function below, when called, iterates over the chessboard, gets the square names for each piece, and then constructs a string containing the description of which piece is where.
The function runs without errors, however it has a slight issue with respect to its performance: When the chess board is full, or close to full with 32 pieces, it runs pretty fast. Once the pieces go off the board and there remains a handful of pieces to describe, the function returns with a delay of around half a second. I have not tested the function with performance tools, but one can feel there is something strange going on: given the length of the function and its algorithm (please don't swear reading it), I can't understand why it will run faster when the board is full and slower when it's close to empty.
Can anyone spot what causes this issue? In addition, what can I try to optimize it?
def pos_text():
global node
#Dictionary of piece symbols to store their location on the board
d = {"K": [], "Q": [], "R": [], "B": [], "N": [], "P": [], "k": [], "q": [], "r": [], "b": [], "n": [], "p": []}
piece_letters = "KkQqRrNnBbPp"
#Iterates over the board and assigns square names to the individual piece symbols in d
for x in range(64):
sq = str(node.board().piece_at(x))
if sq in piece_letters:
d[sq].append(chess.SQUARE_NAMES[x])
# now makes a string containing the description of pieces:
pos = "White pieces:\nKing: %s\n" % d["K"][0]
if d["Q"]:
pos += "Queens: %s\n" % ", ".join(d["Q"]) if len(d["Q"]) >= 2 else "Queen: %s\n" % d["Q"][0]
if d["R"]:
pos += "Rooks: %s\n" % ", ".join(d["R"]) if len(d["R"]) >= 2 else "Rook: %s\n" % d["R"][0]
if d["B"]:
pos += "Bishops: %s\n" % ", ".join(d["B"]) if len(d["B"]) >= 2 else "Bishop: %s\n" % d["B"][0]
if d["N"]:
pos += "Knights: %s\n" % ", ".join(d["N"]) if len(d["N"]) >= 2 else "Knight: %s\n" % d["N"][0]
if d["P"]:
pos += "Pawns: %s\n" % ", ".join(d["P"]) if len(d["P"]) >= 2 else "Pawn: %s\n" % d["P"][0]
pos += "Black pieces:\nKing: %s\n" % d["k"][0]
if d["q"]:
pos += "Queens: %s\n" % ", ".join(d["q"]) if len(d["q"]) >= 2 else "Queen: %s\n" % d["q"][0]
if d["r"]:
pos += "Rooks: %s\n" % ", ".join(d["r"]) if len(d["r"]) >= 2 else "Rook: %s\n" % d["r"][0]
if d["b"]:
pos += "Bishops: %s\n" % ", ".join(d["b"]) if len(d["b"]) >= 2 else "Bishop: %s\n" % d["b"][0]
if d["n"]:
pos += "Knights: %s\n" % ", ".join(d["n"]) if len(d["n"]) >= 2 else "Knight: %s\n" % d["n"][0]
if d["p"]:
pos += "Pawns: %s\n" % ", ".join(d["p"]) if len(d["p"]) >= 2 else "Pawn: %s\n" % d["p"][0]
return pos