Search code examples
pythoncharacterchess

How to space text printed in the python console?


I'm making a chess game, and I want it to be fully rendered in the print console. Yes, I know it makes more sense to do some PyGame or TKinter but that's not my goal.

I found some chess emojis that are built-in to Windows, so that's what I'm using for the pieces. Below is my code:

letters = ["::", "wP", "wB", "wN", "wR", "wQ", "wK", "bP", "bB", "bN", "bR", "bQ", "bK"]
symbols = ["*", "♙", "♗", "♘", "♖", "♕", "♔", "♟", "♝", "♞", "♜", "♛", "♚"]
board = [
    ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
    ["bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP"],
    ["::", "::", "::", "::", "::", "::", "::", "::"],
    ["::", "::", "::", "::", "::", "::", "::", "::"],
    ["::", "::", "::", "::", "::", "::", "::", "::"],
    ["::", "::", "::", "::", "::", "::", "::", "::"],
    ["wP", "wP", "wP", "wP", "wP", "wP", "wP", "wP"],
    ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]
]

def compile_board(board_grid):
    compiled_board = """"""
    for rank in board_grid:
        for square in rank:
            compiled_board += f"{symbols[letters.index(square)]} "
        compiled_board += "\n"
    return compiled_board

print_board = compile_board(board)
print(print_board)

And if you run it, you can see that the symbols don't line up. I think this comes down to the fact that emojis have different dimensions than characters.

I tried using letters (eg: black knight would be bN, white bishop would be wB) and using "::" as the spacer, and everything lined up perfectly. So I know it isn't a problem with my code. I really don't want to remove the characters and just use letters. I also want to ahve something marking each square (even if empty) so that bishop and queen movements are visible.

So I guess my question is: how can I make custom-length characters, or format an existing character to match the width of the emojis?


Solution

  • You can use full width unicode characters. Here is an example of using full width A as the spacing:

    symbols = ["\uff21", "♙", "♗", "♘", "♖", "♕", "♔", "♟", "♝", "♞", "♜", "♛", "♚"]
    

    And it prints like so:

    ♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜ 
    ♟ ♟ ♟ ♟ ♟ ♟ ♟ ♟ 
    A A A A A A A A 
    A A A A A A A A 
    A A A A A A A A 
    A A A A A A A A 
    ♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙ 
    ♖ ♘ ♗ ♕ ♔ ♗ ♘ ♖