Your code is good, but there are a few improvements to be made:
First, I would implement a better way to check for certain illegal configurations:
You could check for valid squares like:
valid_numbers = "12345678" valid_letters = "abcdefgh" squares_are_valid = True for square in chessboard: if not (square[0] in valid_letters and square[1] in valid_numbers: squares_are_valid = False break
or
squares_are_valid = all([square[0] in "abcdefgh" and square[1] in "12345678" for square in chessboard])
Then, you could check for valid piece names like:
valid_piece_names = ["pawn", "knight", "bishop", "rook", "queen", "king"] piece_names_are_valid = True for piece in chessboard.values(): if not (piece[0] in "wb" and piece[1:] in valid_piece_names): piece_names_are_valid = False break
or again with list comprehension like:
valid_piece_names = ["pawn", "knight", "bishop", "rook", "queen", "king"] piece_names_are_valid = all([piece[0] in "wb" and piece[1:] in valid_piece_names for piece in chessboard.values()])
You could check for the piece requirements like:
pieces = list(chessboard.values()) kings_are_valid = pieces.count("wking") == 1 and pieces.count("bking") = 1 white_pieces_are_valid = len([piece for piece in pieces if piece[0] == "w"]) <= 16 black_pieces_are_valid = len([piece for piece in pieces if piece[0] == "b"]) <= 16 pawns_are_valid = pieces.count("wpawn") <= 8 and pieces.count("bpawn") <= 8
(you can do these with for loops like shown above if you want to as well.)
Other things:
- You should be careful of your indentation, it seems off.
- You might want to name your functions in snake case, as it is the convention for python. (
is_valid_chess_board not isValidChessBoard.) - When commenting, you might want to put a space between the # and your comment, like:
# this is a comment not #this is a comment.