Creating a complete GUI Chess game in Python involves handling the game logic (rules, moves, game state) and building an interactive interface for users to play the game. Below is a comprehensive implementation using the tkinter library for the GUI and incorporating the chess logic manually. This implementation uses Unicode characters for chess pieces, so no external images are required.
Features:
- Interactive Chessboard: Click on pieces to select and move them.
- Move Validation: Ensures only legal moves are allowed.
- Check and Checkmate Detection: Identifies when a player is in check or checkmate.
- Basic Game Flow: Alternates turns between White and Black.
Requirements:
Implementation:
import tkinter as tk
from tkinter import messagebox
# Define constants
BOARD_SIZE = 8
SQUARE_SIZE = 60
# Unicode characters for chess pieces
PIECES = {
'K': '♔',
'Q': '♕',
'R': '♖',
'B': '♗',
'N': '♘',
'P': '♙',
'k': '♚',
'q': '♛',
'r': '♜',
'b': '♝',
'n': '♞',
'p': '♟︎'
}
class ChessGame:
def __init__(self, root):
self.root = root
self.root.title("Python Chess")
self.canvas = tk.Canvas(root, width=BOARD_SIZE * SQUARE_SIZE, height=BOARD_SIZE * SQUARE_SIZE)
self.canvas.pack()
self.board = self.create_initial_board()
self.selected_piece = None
self.selected_pos = None
self.turn = 'white'
self.draw_board()
self.canvas.bind("<Button-1>", self.on_click)
def create_initial_board(self):
# Initialize the chess board with starting positions
board = [
['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
['p'] * BOARD_SIZE,
[''] * BOARD_SIZE,
[''] * BOARD_SIZE,
[''] * BOARD_SIZE,
[''] * BOARD_SIZE,
['P'] * BOARD_SIZE,
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
]
return board
def draw_board(self):
self.canvas.delete("all")
colors = ["#F0D9B5", "#B58863"]
for row in range(BOARD_SIZE):
for col in range(BOARD_SIZE):
color = colors[(row + col) % 2]
x1 = col * SQUARE_SIZE
y1 = row * SQUARE_SIZE
x2 = x1 + SQUARE_SIZE
y2 = y1 + SQUARE_SIZE
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="")
piece = self.board[row][col]
if piece:
self.canvas.create_text(
x1 + SQUARE_SIZE / 2,
y1 + SQUARE_SIZE / 2,
text=PIECES.get(piece, ''),
font=("Arial", 32),
tags="piece"
)
if self.selected_piece:
row, col = self.selected_pos
x1 = col * SQUARE_SIZE
y1 = row * SQUARE_SIZE
x2 = x1 + SQUARE_SIZE
y2 = y1 + SQUARE_SIZE
self.canvas.create_rectangle(x1, y1, x2, y2, outline="blue", width=3)
def on_click(self, event):
col = event.x // SQUARE_SIZE
row = event.y // SQUARE_SIZE
if row < 0 or row >= BOARD_SIZE or col < 0 or col >= BOARD_SIZE:
return
piece = self.board[row][col]
if self.selected_piece:
# Attempt to move
if self.move_piece(self.selected_pos, (row, col)):
self.selected_piece = None
self.selected_pos = None
self.turn = 'black' if self.turn == 'white' else 'white'
self.draw_board()
if self.is_in_checkmate(self.turn):
messagebox.showinfo("Checkmate", f"{self.turn.capitalize()} is in checkmate. Game over!")
else:
# Invalid move, deselect
self.selected_piece = None
self.selected_pos = None
self.draw_board()
else:
# Select a piece
if piece and self.is_piece_color(piece, self.turn):
self.selected_piece = piece
self.selected_pos = (row, col)
self.draw_board()
def is_piece_color(self, piece, color):
if color == 'white':
return piece.isupper()
else:
return piece.islower()
def move_piece(self, from_pos, to_pos):
fr, fc = from_pos
tr, tc = to_pos
piece = self.board[fr][fc]
target = self.board[tr][tc]
if self.is_legal_move(piece, from_pos, to_pos):
# Make the move
self.board[tr][tc] = piece
self.board[fr][fc] = ''
# Check if move puts king in check
if self.is_in_check(self.turn):
# Undo move
self.board[fr][fc] = piece
self.board[tr][tc] = target
return False
return True
return False
def is_legal_move(self, piece, from_pos, to_pos):
fr, fc = from_pos
tr, tc = to_pos
dr = tr - fr
dc = tc - fc
target = self.board[tr][tc]
# Basic move validation based on piece type
piece_type = piece.lower()
if piece_type == 'p':
direction = -1 if piece.isupper() else 1
start_row = 6 if piece.isupper() else 1
# Move forward
if dc == 0:
if dr == direction and not target:
return True
if fr == start_row and dr == 2 * direction and not target and not self.board[fr + direction][fc]:
return True
# Capture
if abs(dc) == 1 and dr == direction and target and self.is_opponent(piece, target):
return True
elif piece_type == 'r':
if fr == tr or fc == tc:
if self.is_path_clear(from_pos, to_pos):
return True
elif piece_type == 'n':
if (abs(dr), abs(dc)) in [(2, 1), (1, 2)]:
return True
elif piece_type == 'b':
if abs(dr) == abs(dc):
if self.is_path_clear(from_pos, to_pos):
return True
elif piece_type == 'q':
if fr == tr or fc == tc or abs(dr) == abs(dc):
if self.is_path_clear(from_pos, to_pos):
return True
elif piece_type == 'k':
if max(abs(dr), abs(dc)) == 1:
return True
return False
def is_opponent(self, piece, target):
return (piece.isupper() and target.islower()) or (piece.islower() and target.isupper())
def is_path_clear(self, from_pos, to_pos):
fr, fc = from_pos
tr, tc = to_pos
dr = tr - fr
dc = tc - fc
step_r = (dr > 0) - (dr < 0)
step_c = (dc > 0) - (dc < 0)
current_r = fr + step_r
current_c = fc + step_c
while (current_r, current_c) != (tr, tc):
if self.board[current_r][current_c]:
return False
current_r += step_r
current_c += step_c
return True
def find_king(self, color):
target = 'K' if color == 'white' else 'k'
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
if self.board[r][c] == target:
return (r, c)
return None
def is_in_check(self, color):
king_pos = self.find_king(color)
if not king_pos:
return True # King is missing, treated as in check
opponent = 'black' if color == 'white' else 'white'
# Check all opponent's pieces for attacks on king's position
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
piece = self.board[r][c]
if piece and self.is_piece_color(piece, opponent):
if self.is_legal_move(piece, (r, c), king_pos):
return True
return False
def is_in_checkmate(self, color):
if not self.is_in_check(color):
return False
# Check if any legal move can get out of check
for r in range(BOARD_SIZE):
for c in range(BOARD_SIZE):
piece = self.board[r][c]
if piece and self.is_piece_color(piece, color):
for tr in range(BOARD_SIZE):
for tc in range(BOARD_SIZE):
if self.move_piece((r, c), (tr, tc)):
# Undo move
self.board[r][c] = piece
self.board[tr][tc] = self.board[tr][tc] if (r, c) != (tr, tc) else ''
if not self.is_in_check(color):
return False
return True
def main():
root = tk.Tk()
game = ChessGame(root)
root.mainloop()
if __name__ == "__main__":
main()
How to Run:
- Save the Code: Copy the above code into a file named
chess_gui.py.
- Run the Script:
python chess_gui.py
- Play the Game:
- Click on a piece to select it.
- Click on a destination square to move the selected piece.
- The game alternates turns between White and Black.
- When a player is in checkmate, a message box will display the outcome.
Notes and Limitations:
- Simplified Rules: This implementation covers basic movement and capture rules. Advanced rules like castling, en passant, and pawn promotion are not included.
- Check Detection: The game detects when a player is in check and checkmate but does not highlight all possible moves to escape check.
- No AI Opponent: The game is designed for two human players. Implementing an AI opponent would require additional logic.
- Move Validation: While basic move validation is implemented, certain edge cases might not be fully handled.
Enhancements:
To make the game more robust and feature-rich, consider implementing the following:
- Castling: Add rules for castling both kingside and queenside.
- En Passant: Implement the en passant capture move for pawns.
- Pawn Promotion: Allow pawns to promote to other pieces upon reaching the opposite end of the board.
- Move History: Keep track of moves made during the game.
- AI Opponent: Integrate an AI to play against the user using algorithms like Minimax.
- GUI Improvements: Enhance the graphical interface with better visuals, animations, and highlighting possible moves.
This implementation serves as a foundational example to create a GUI-based Chess game in Python. You can build upon it to add more complex features and improve the user experience.