Below is an updated version of the Tkinter GUI chess game that not only uses Unicode symbols for pieces but also includes basic chess move validation (in line with standard chess or "BHESS" rules) for each piece type. This code validates moves for pawns, knights, bishops, rooks, queens, and kings (with castling and en passant not implemented). It also checks that a piece does not capture another piece of the same color and that paths are clear when required. (Keep in mind that full chess rule support is a complex topic; this version covers many of the basics.)
Below is the code:
import tkinter as tk
# Size (in pixels) for each board square.
SQUARE_SIZE = 80
BOARD_SIZE = 8
# Unicode chess pieces for display.
PIECE_UNICODE = {
'wK': '♔', 'wQ': '♕', 'wR': '♖', 'wB': '♗', 'wN': '♘', 'wP': '♙',
'bK': '♚', 'bQ': '♛', 'bR': '♜', 'bB': '♝', 'bN': '♞', 'bP': '♟'
}
def create_starting_board():
"""
Returns a 2D list representing the starting position on a chess board.
Empty squares are represented by an empty string.
"""
board = [
['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'],
['bP'] * 8,
[''] * 8,
[''] * 8,
[''] * 8,
[''] * 8,
['wP'] * 8,
['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']
]
return board
def path_clear(board, src_row, src_col, dest_row, dest_col):
"""
Returns True if all squares between the source and destination (excluding both)
are empty. Works for moves along a rank, file, or diagonal.
"""
row_step = dest_row - src_row
col_step = dest_col - src_col
# Normalize the step values (direction)
if row_step != 0:
row_step = (row_step // abs(row_step))
if col_step != 0:
col_step = (col_step // abs(col_step))
row, col = src_row + row_step, src_col + col_step
while (row, col) != (dest_row, dest_col):
if board[row][col] != "":
return False
row += row_step
col += col_step
return True
def is_legal_move(board, src_row, src_col, dest_row, dest_col):
"""
Verify if a move from (src_row, src_col) to (dest_row, dest_col)
is legal according to basic chess rules.
This function covers:
- Pawn basic moves (one or initial two squares forward) and simple captures.
- Knight moves.
- Bishop diagonal moves (with clear path).
- Rook straight-line moves (with clear path).
- Queen (combining bishop and rook moves).
- King moves (one square in any direction).
Note: Special moves (en passant, castling, pawn promotion) are not implemented.
"""
piece = board[src_row][src_col]
if not piece:
return False
color = piece[0] # 'w' or 'b'
p_type = piece[1] # K, Q, R, B, N, P
dest_piece = board[dest_row][dest_col]
# Prevent capturing your own piece.
if dest_piece and dest_piece[0] == color:
return False
d_row = dest_row - src_row
d_col = dest_col - src_col
# Pawn Moves
if p_type == 'P':
# For white, pawns move upward (row decreases). For black, row increases.
direction = -1 if color == 'w' else 1
start_row = 6 if color == 'w' else 1
# Single step forward into an empty square.
if d_col == 0 and d_row == direction and board[dest_row][dest_col] == "":
return True
# Double step from the pawn's initial position.
if (src_row == start_row and d_col == 0 and d_row == 2 * direction and
board[src_row + direction][src_col] == "" and board[dest_row][dest_col] == ""):
return True
# Capture diagonally if an opponent piece exists.
if abs(d_col) == 1 and d_row == direction and board[dest_row][dest_col] != "":
return True
return False
# Knight Moves (L-shaped)
elif p_type == 'N':
if (abs(d_row), abs(d_col)) in [(2, 1), (1, 2)]:
return True
return False
# Bishop Moves
elif p_type == 'B':
if abs(d_row) == abs(d_col):
return path_clear(board, src_row, src_col, dest_row, dest_col)
return False
# Rook Moves
elif p_type == 'R':
if d_row == 0 or d_col == 0:
return path_clear(board, src_row, src_col, dest_row, dest_col)
return False
# Queen Moves (combines rook and bishop)
elif p_type == 'Q':
if abs(d_row) == abs(d_col) or d_row == 0 or d_col == 0:
return path_clear(board, src_row, src_col, dest_row, dest_col)
return False
# King Moves (one square any direction; castling not implemented)
elif p_type == 'K':
if max(abs(d_row), abs(d_col)) == 1:
return True
return False
return False # Default catch-all
class ChessGUI:
def __init__(self, master):
self.master = master
master.title("Chess Game - Human vs Human")
self.canvas = tk.Canvas(master, width=SQUARE_SIZE * BOARD_SIZE,
height=SQUARE_SIZE * BOARD_SIZE)
self.canvas.pack()
# Initialize the board and GUI state.
self.board = create_starting_board()
self.selected = None # Holds the source square on the first click.
# Bind the mouse click event.
self.canvas.bind("<Button-1>", self.handle_click)
self.draw_board()
def draw_board(self):
"""Redraw the entire board and pieces on the canvas."""
self.canvas.delete("all")
# Define colors for light and dark squares.
colors = ["#EEEED2", "#769656"]
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
x1 = col * SQUARE_SIZE
y1 = row * SQUARE_SIZE
x2 = x1 + SQUARE_SIZE
y2 = y1 + SQUARE_SIZE
# Determine square color.
color = colors[(row + col) % 2]
# If this square is selected, change its color to highlight it.
if self.selected == (row, col):
color = "#BACA44" # Highlight color
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="black")
piece = self.board[row][col]
if piece:
# Draw the Unicode symbol for the piece.
symbol = PIECE_UNICODE.get(piece, piece)
self.canvas.create_text(x1 + SQUARE_SIZE/2, y1 + SQUARE_SIZE/2,
text=symbol, font=("Arial", 36))
def handle_click(self, event):
"""Process a mouse click on the board."""
col = event.x // SQUARE_SIZE
row = event.y // SQUARE_SIZE
if self.selected is None:
# First click: Select a source square if it contains a piece.
if self.board[row][col] != "":
self.selected = (row, col)
self.draw_board()
else:
print("Please select a square with a piece.")
else:
# Second click: Attempt to move the selected piece.
src_row, src_col = self.selected
dest_row, dest_col = row, col
if is_legal_move(self.board, src_row, src_col, dest_row, dest_col):
piece = self.board[src_row][src_col]
self.board[src_row][src_col] = ""
self.board[dest_row][dest_col] = piece
print(f"Moved {piece} from ({src_row}, {src_col}) to ({dest_row}, {dest_col})")
else:
print("Illegal move attempted.")
# Reset selection and update the board.
self.selected = None
self.draw_board()
if __name__ == "__main__":
root = tk.Tk()
gui = ChessGUI(root)
root.mainloop()