Can somebody please teach me how to create a chessboard in Python properly. I have tried different sizes, different images but I keep getting a black screen as soon as I run the code. Your help will higly be appreciated! Here's the code. Chess pieces set can be downloaded here commons.wikimedia.org/wiki/Category:PNG_chess_pieces/Standard_transparent
import pygame
import sys
SQUARE_SIZE = 80
BOARD_SIZE = SQUARE_SIZE * 8
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
pygame.init()
WINDOW_SIZE = (600, 600)
screen = pygame.display.set_mode(WINDOW_SIZE)
# Define the starting position of the pieces
START_POSITION = [
["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"]
]
class ChessPiece:
"""
A class to represent a chess piece.
Attributes:
color (str): The color of the piece ('w' for white, 'b' for black).
piece_type (str): The type of the piece ('p' for pawn, 'r' for rook, 'n' for knight,
'b' for bishop, 'q' for queen, 'k' for king).
image (pygame.Surface): The image of the piece.
"""
def __init__(self, color, piece_type, image):
"""
Initialize the ChessPiece object.
Args:
color (str): The color of the piece ('w' for white, 'b' for black).
piece_type (str): The type of the piece ('p' for pawn, 'r' for rook, 'n' for knight,
'b' for bishop, 'q' for queen, 'k' for king).
image (pygame.Surface): The image of the piece.
"""
self.color = color
self.piece_type = piece_type
self.image = image
def __repr__(self):
"""
Return a string representation of the ChessPiece object.
Returns:
str: A string representation of the ChessPiece object.
"""
return f'{self.color}{self.piece_type}'
class ChessBoard:
def __init__(self):
self.board = START_POSITION
self.move_history = []
self.captured_pieces = {'w': [], 'b': []}
self.white_to_move = True
self.images = {}
self.load_images()
def load_images(self):
for color in ['w', 'b']:
for piece in ['p', 'r', 'n', 'b', 'q', 'k']:
self.images[color + piece] = pygame.image.load(f"pieces/{color}{piece}.png")
def get_piece(self, row, col):
piece_code = self.board[row][col]
if piece_code == ' ' or piece_code == '.':
return None
color = piece_code[0]
piece_type = piece_code[1]
return ChessPiece(color, piece_type)
def get_all_moves(self, color):
moves = []
for row in range(8):
for col in range(8):
piece = self.get_piece(row, col)
if piece is not None and piece.color == color:
piece_moves = piece.get_moves(row, col, self.board)
moves.extend(piece_moves)
return moves
def make_move(self, move):
start_row, start_col = move.start_pos
end_row, end_col = move.end_pos
start_piece = self.board[start_row][start_col]
end_piece = self.board[end_row][end_col]
self.board[start_row][start_col] = ' '
self.board[end_row][end_col] = start_piece
self.move_history.append(move)
if end_piece != ' ':
color = end_piece[0]
self.captured_pieces[color].append(end_piece[1])
self.white_to_move = not self.white_to_move
def draw(self, screen):
# Draw the squares on the board
for row in range(8):
for col in range(8):
color = (191, 128, 64) if (row + col) % 2 == 0 else (255, 206, 158)
pygame.draw.rect(screen, color, pygame.Rect(col * 80, row * 80, 80, 80))
# Draw the pieces on the board
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != ' ':
img = self.images[piece]
screen.blit(img, pygame.Rect(col * 80, row * 80, 80, 80))
# Draw the captured pieces
def draw_captured_pieces(self, surface):
white_captured = [piece for piece in self.captured_pieces if piece.isupper()]
black_captured = [piece for piece in self.captured_pieces if piece.islower()]
x = y = 0
for piece in white_captured:
if x > 7:
y += 1
x = 0
surface.blit(self.piece_images[piece], (x * SQUARE_SIZE + BOARD_SIZE + 10, y * SQUARE_SIZE + 10))
x += 1
x = y = 0
for piece in black_captured:
if x > 7:
y += 1
x = 0
surface.blit(self.piece_images[piece], (x * SQUARE_SIZE + BOARD_SIZE + 10, y * SQUARE_SIZE + 60))
x += 1
def draw_board(self):
for row in range(8):
for col in range(8):
color = self.get_square_color(row, col)
pygame.draw.rect(self.screen, color, pygame.Rect(col*SQUARE_SIZE, row*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
piece = self.board[row][col]
if piece:
image = self.images[piece.get_image_name()]
self.screen.blit(image, pygame.Rect(col*SQUARE_SIZE, row*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def run(self):
while not self.done:
self.clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
self.draw_board()
self.draw_captured_pieces()
self.draw_move_history()
pygame.display.flip()
pygame.quit()
# Draw the move history
def draw_move_history(self, surface):
font = pygame.font.SysFont("arial", 16)
x, y = BOARD_SIZE + 10, 200
for move in self.move_history:
if move[1] is not None:
notation = self.get_notation(move)
text = f"{move[0]}. {notation}"
else:
text = move[0]
text_surface = font.render(text, True, BLACK)
surface.blit(text_surface, (x, y))
y += text_surface.get_height() + 5
# Draw the user interface
def draw(self, surface):
surface.fill(WHITE)
self.draw_board(surface)
self.draw_valid_moves(surface)
self.draw_pieces(surface)
self.draw_captured_pieces(surface)
self.draw_move_history(surface)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Draw the game board, pieces, and other elements here
pygame.display.update()
I tried different file extensions, tried to change background colour for the board, I messed around with the square sizes but I kept getting the annoying black screen. I tried different places for the lines
# Draw the game board, pieces, and other elements here
pygame.display.update()
Somehow I won't get rid of the black screen after running the code.
This code does not continue to the execution flow. You encapsulated the main loop inside the class definition. But the class definition is not executed until you instantiate it. Add this condition to the end of your code and then put your mainloop there.