Ask ChatGPT to draw a chessboard

Discussion of chess software programming and technical issues.

Moderator: Ras

dangi12012
Posts: 1062
Joined: Tue Apr 28, 2020 10:03 pm
Full name: Daniel Infuehr

Ask ChatGPT to draw a chessboard

Post by dangi12012 »

pip install matplotlib
pip install python-chess

A few iterations of QA:

Code: Select all

import chess
import matplotlib.pyplot as plt
import numpy as np

# Define a dictionary that maps ASCII chess pieces to Unicode characters
piece_unicode = {
    chess.PAWN: '♟',
    chess.KNIGHT: '♞',
    chess.BISHOP: '♝',
    chess.ROOK: '♜',
    chess.QUEEN: '♛',
    chess.KING: '♚'
}

def plot_chess_board(board):
    board_colors = np.zeros((8, 8))
    for rank in range(8):
        for file in range(8):
            if (rank + file) % 2 == 0:
                board_colors[rank, file] = 0  # light square
            else:
                board_colors[rank, file] = 1 # dark square

    plt.imshow(board_colors, cmap='tab20', extent=[0, 8, 0, 8], alpha = 1)

    for square, piece in board.piece_map().items():
        if piece.color == chess.WHITE:
            color = 'white'
        else:
            color = 'black'
        plt.text(chess.square_file(square) + 0.5, 7.5 - chess.square_rank(square), piece_unicode[piece.piece_type], fontsize=24, ha='center', va='center', color=color)

    plt.xticks(range(9), [''] + list('abcdefgh'))
    plt.yticks(range(9), [''] + list(reversed(range(1, 9))))
    plt.xlim(0, 8)
    plt.ylim(0, 8)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()

if __name__ == '__main__':
    starting_board = chess.Board()
    plot_chess_board(starting_board)
Which is arguably quite cool. Edit:
"Use less lines of code version:"

Code: Select all

import chess
import matplotlib.pyplot as plt
import numpy as np

def plot_chess_board(board):
    piece_unicode = {chess.PAWN: '♟', chess.KNIGHT: '♞', chess.BISHOP: '♝', chess.ROOK: '♜', chess.QUEEN: '♛', chess.KING: '♚'}
    board_colors = np.zeros((8, 8))
    board_colors[1::2, ::2] = 1
    board_colors[::2, 1::2] = 1

    plt.imshow(board_colors, cmap='tab20', extent=[0, 8, 0, 8], alpha=1)

    for square, piece in board.piece_map().items():
        color = 'white' if piece.color == chess.WHITE else 'black'
        plt.text(chess.square_file(square) + 0.5, 7.5 - chess.square_rank(square), piece_unicode[piece.piece_type], fontsize=24, ha='center', va='center', color=color)

    plt.xticks(range(9), [''] + list('abcdefgh'))
    plt.yticks(range(9), [''] + list(reversed(range(1, 9))))
    plt.xlim(0, 8)
    plt.ylim(0, 8)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.show()

if __name__ == '__main__':
    starting_board = chess.Board()
    plot_chess_board(starting_board)
Worlds-fastest-Bitboard-Chess-Movegenerator
Daniel Inführ - Software Developer