The user wants a chess game with an AI opponent. This is a complex request that involves:
- Chess board representation
- Chess piece movement rules
- Legal move generation
- Game state management (check, checkmate, stalemate)
- AI opponent using some algorithm (minimax with alpha-beta pruning is standard)
- Visual representation
Since this is a GUI application, I'll use Tkinter which is built into Python. Let me create a complete chess game with:
- A graphical chess board
- All piece movements properly implemented
- Move validation
- Check and checkmate detection
- An AI opponent using minimax with alpha-beta pruning
- Piece selection and move highlighting
- Captured pieces display
- Game status display
Let me write a comprehensive chess game:
import tkinter as tk
from tkinter import messagebox
import copy
# Piece values for AI evaluation
PIECE_VALUES = {
'P': 100, 'N': 320, 'B': 330, 'R': 500, 'Q': 900, 'K': 20000,
'p': -100, 'n': -320, 'b': -330, 'r': -500, 'q': -900, 'k': -20000
}
# Position tables for better AI evaluation
PAWN_TABLE = [
[0, 0, 0, 0, 0, 0, 0, 0],
[50, 50, 50, 50, 50, 50, 50, 50],
[10, 10, 20, 30, 30, 20, 10, 10],
[5, 5, 10, 25, 25, 10, 5, 5],
[0, 0, 0, 20, 20, 0, 0, 0],
[5, -5,-10, 0, 0,-10, -5, 5],
[5, 10, 10,-20,-20, 10, 10, 5],
[0, 0, 0, 0, 0, 0, 0, 0]
]
KNIGHT_TABLE = [
[-50,-40,-30,-30,-30,-30,-40,-50],
[-40,-20, 0, 0, 0, 0,-20,-40],
[-30, 0, 10, 15, 15, 10, 0,-30],
[-30, 5, 15, 20, 20, 15, 5,-30],
[-30, 0, 15, 20, 20, 15, 0,-30],
[-30, 5, 10, 15, 15, 10, 5,-30],
[-40,-20, 0, 5, 5, 0,-20,-40],
[-50,-40,-30,-30,-30,-30,-40,-50]
]
BISHOP_TABLE = [
[-20,-10,-10,-10,-10,-10,-10,-20],
[-10, 0, 0, 0, 0, 0, 0,-10],
[-10, 0, 5, 10, 10, 5, 0,-10],
[-10, 5, 5, 10, 10, 5, 5,-10],
[-10, 0, 10, 10, 10, 10, 0,-10],
[-10, 10, 10, 10, 10, 10, 10,-10],
[-10, 5, 0, 0, 0, 0, 5,-10],
[-20,-10,-10,-10,-10,-10,-10,-20]
]
ROOK_TABLE = [
[0, 0, 0, 0, 0, 0, 0, 0],
[5, 10, 10, 10, 10, 10, 10, 5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[0, 0, 0, 5, 5, 0, 0, 0]
]
QUEEN_TABLE = [
[-20,-10,-10, -5, -5,-10,-10,-20],
[-10, 0, 0, 0, 0, 0, 0,-10],
[-10, 0, 5, 5, 5, 5, 0,-10],
[-5, 0, 5, 5, 5, 5, 0, -5],
[0, 0, 5, 5, 5, 5, 0, -5],
[-10, 5, 5, 5, 5, 5, 0,-10],
[-10, 0, 5, 0, 0, 0, 0,-10],
[-20,-10,-10, -5, -5,-10,-10,-20]
]
KING_TABLE = [
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-20,-30,-30,-40,-40,-30,-30,-20],
[-10,-20,-20,-20,-20,-20,-20,-10],
[20, 20, 0, 0, 0, 0, 20, 20],
[20, 30, 10, 0, 0, 10, 30, 20]
]
class ChessGame:
def __init__(self):
self.board = self.initialize_board()
self.current_player = 'white'
self.selected_piece = None
self.valid_moves = []
self.move_history = []
self.captured_white = []
self.captured_black = []
self.game_over = False
self.white_king_moved = False
self.black_king_moved = False
self.white_rook_moved = {'left': False, 'right': False}
self.black_rook_moved = {'left': False, 'right': False}
def initialize_board(self):
board = [['' for _ in range(8)] for _ in range(8)]
# Black pieces (top)
board[0] = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
board[1] = ['p'] * 8
# White pieces (bottom)
board[6] = ['P'] * 8
board[7] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
return board
def get_piece_color(self, piece):
if piece == '':
return None
return 'white' if piece.isupper() else 'black'
def get_valid_moves(self, row, col, check_for_check=True):
piece = self.board[row][col]
if piece == '':
return []
color = self.get_piece_color(piece)
moves = []
piece_type = piece.upper()
if piece_type == 'P':
moves = self.get_pawn_moves(row, col, color)
elif piece_type == 'R':
moves = self.get_rook_moves(row, col, color)
elif piece_type == 'N':
moves = self.get_knight_moves(row, col, color)
elif piece_type == 'B':
moves = self.get_bishop_moves(row, col, color)
elif piece_type == 'Q':
moves = self.get_queen_moves(row, col, color)
elif piece_type == 'K':
moves = self.get_king_moves(row, col, color)
if check_for_check:
moves = [m for m in moves if not self.would_be_in_check(row, col, m[0], m[1], color)]
return moves
def get_pawn_moves(self, row, col, color):
moves = []
direction = -1 if color == 'white' else 1
start_row = 6 if color == 'white' else 1
# Forward move
new_row = row + direction
if 0 <= new_row < 8 and self.board[new_row][col] == '':
moves.append((new_row, col))
# Double move from start
if row == start_row:
new_row2 = row + 2 * direction
if self.board[new_row2][col] == '':
moves.append((new_row2, col))
# Captures
for dc in [-1, 1]:
new_col = col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target != '' and self.get_piece_color(target) != color:
moves.append((new_row, new_col))
return moves
def get_rook_moves(self, row, col, color):
moves = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
while 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '':
moves.append((new_row, new_col))
elif self.get_piece_color(target) != color:
moves.append((new_row, new_col))
break
else:
break
new_row += dr
new_col += dc
return moves
def get_knight_moves(self, row, col, color):
moves = []
jumps = [(-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1)]
for dr, dc in jumps:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '' or self.get_piece_color(target) != color:
moves.append((new_row, new_col))
return moves
def get_bishop_moves(self, row, col, color):
moves = []
directions = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
while 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '':
moves.append((new_row, new_col))
elif self.get_piece_color(target) != color:
moves.append((new_row, new_col))
break
else:
break
new_row += dr
new_col += dc
return moves
def get_queen_moves(self, row, col, color):
return self.get_rook_moves(row, col, color) + self.get_bishop_moves(row, col, color)
def get_king_moves(self, row, col, color):
moves = []
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '' or self.get_piece_color(target) != color:
moves.append((new_row, new_col))
# Castling
if color == 'white' and not self.white_king_moved:
if not self.white_rook_moved['right']:
if self.board[7][5] == '' and self.board[7][6] == '':
if not self.is_in_check('white'):
if not self.would_be_in_check(7, 4, 7, 5, 'white'):
if not self.would_be_in_check(7, 4, 7, 6, 'white'):
moves.append((7, 6))
if not self.white_rook_moved['left']:
if self.board[7][1] == '' and self.board[7][2] == '' and self.board[7][3] == '':
if not self.is_in_check('white'):
if not self.would_be_in_check(7, 4, 7, 3, 'white'):
if not self.would_be_in_check(7, 4, 7, 2, 'white'):
moves.append((7, 2))
elif color == 'black' and not self.black_king_moved:
if not self.black_rook_moved['right']:
if self.board[0][5] == '' and self.board[0][6] == '':
if not self.is_in_check('black'):
if not self.would_be_in_check(0, 4, 0, 5, 'black'):
if not self.would_be_in_check(0, 4, 0, 6, 'black'):
moves.append((0, 6))
if not self.black_rook_moved['left']:
if self.board[0][1] == '' and self.board[0][2] == '' and self.board[0][3] == '':
if not self.is_in_check('black'):
if not self.would_be_in_check(0, 4, 0, 3, 'black'):
if not self.would_be_in_check(0, 4, 0, 2, 'black'):
moves.append((0, 2))
return moves
def find_king(self, color):
king = 'K' if color == 'white' else 'k'
for row in range(8):
for col in range(8):
if self.board[row][col] == king:
return (row, col)
return None
def is_in_check(self, color):
king_pos = self.find_king(color)
if king_pos is None:
return True
opponent_color = 'black' if color == 'white' else 'white'
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == opponent_color:
moves = self.get_valid_moves(row, col, check_for_check=False)
if king_pos in moves:
return True
return False
def would_be_in_check(self, from_row, from_col, to_row, to_col, color):
# Make temporary move
original_piece = self.board[to_row][to_col]
moving_piece = self.board[from_row][from_col]
self.board[to_row][to_col] = moving_piece
self.board[from_row][from_col] = ''
in_check = self.is_in_check(color)
# Undo move
self.board[from_row][from_col] = moving_piece
self.board[to_row][to_col] = original_piece
return in_check
def make_move(self, from_row, from_col, to_row, to_col):
piece = self.board[from_row][from_col]
captured = self.board[to_row][to_col]
color = self.get_piece_color(piece)
# Track captured pieces
if captured != '':
if self.get_piece_color(captured) == 'white':
self.captured_white.append(captured)
else:
self.captured_black.append(captured)
# Handle castling
if piece.upper() == 'K':
if color == 'white':
self.white_king_moved = True
if to_col - from_col == 2: # Kingside castling
self.board[7][5] = 'R'
self.board[7][7] = ''
elif from_col - to_col == 2: # Queenside castling
self.board[7][3] = 'R'
self.board[7][0] = ''
else:
self.black_king_moved = True
if to_col - from_col == 2:
self.board[0][5] = 'r'
self.board[0][7] = ''
elif from_col - to_col == 2:
self.board[0][3] = 'r'
self.board[0][0] = ''
# Track rook moves for castling
if piece.upper() == 'R':
if color == 'white':
if from_col == 0:
self.white_rook_moved['left'] = True
elif from_col == 7:
self.white_rook_moved['right'] = True
else:
if from_col == 0:
self.black_rook_moved['left'] = True
elif from_col == 7:
self.black_rook_moved['right'] = True
# Handle pawn promotion
if piece.upper() == 'P':
if (color == 'white' and to_row == 0) or (color == 'black' and to_row == 7):
piece = 'Q' if color == 'white' else 'q'
# Make the move
self.board[to_row][to_col] = piece
self.board[from_row][from_col] = ''
# Record move
self.move_history.append((from_row, from_col, to_row, to_col, captured))
# Switch player
self.current_player = 'black' if self.current_player == 'white' else 'white'
# Check for checkmate or stalemate
self.check_game_over()
return True
def check_game_over(self):
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == self.current_player:
if self.get_valid_moves(row, col):
return
# No valid moves - game over
self.game_over = True
def is_checkmate(self):
return self.game_over and self.is_in_check(self.current_player)
def is_stalemate(self):
return self.game_over and not self.is_in_check(self.current_player)
def evaluate_board(self):
score = 0
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '':
# Material value
score += PIECE_VALUES[piece]
# Position value
piece_type = piece.upper()
is_white = piece.isupper()
if piece_type == 'P':
pos_value = PAWN_TABLE[row][col] if is_white else PAWN_TABLE[7-row][col]
elif piece_type == 'N':
pos_value = KNIGHT_TABLE[row][col] if is_white else KNIGHT_TABLE[7-row][col]
elif piece_type == 'B':
pos_value = BISHOP_TABLE[row][col] if is_white else BISHOP_TABLE[7-row][col]
elif piece_type == 'R':
pos_value = ROOK_TABLE[row][col] if is_white else ROOK_TABLE[7-row][col]
elif piece_type == 'Q':
pos_value = QUEEN_TABLE[row][col] if is_white else QUEEN_TABLE[7-row][col]
elif piece_type == 'K':
pos_value = KING_TABLE[row][col] if is_white else KING_TABLE[7-row][col]
else:
pos_value = 0
if is_white:
score += pos_value
else:
score -= pos_value
return score
def get_all_moves(self, color):
moves = []
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == color:
piece_moves = self.get_valid_moves(row, col)
for move in piece_moves:
moves.append((row, col, move[0], move[1]))
return moves
class ChessAI:
def __init__(self, depth=3):
self.depth = depth
self.nodes_evaluated = 0
def minimax(self, game, depth, alpha, beta, maximizing):
self.nodes_evaluated += 1
if depth == 0 or game.game_over:
return game.evaluate_board(), None
color = 'white' if maximizing else 'black'
moves = game.get_all_moves(color)
if not moves:
if game.is_in_check(color):
return (-100000 if maximizing else 100000), None
return 0, None # Stalemate
best_move = None
if maximizing:
max_eval = float('-inf')
for move in moves:
# Save state
old_board = copy.deepcopy(game.board)
old_king_moved = (game.white_king_moved, game.black_king_moved)
old_rook_moved = (copy.deepcopy(game.white_rook_moved), copy.deepcopy(game.black_rook_moved))
old_player = game.current_player
old_game_over = game.game_over
old_captured = (copy.copy(game.captured_white), copy.copy(game.captured_black))
game.make_move(move[0], move[1], move[2], move[3])
eval_score, _ = self.minimax(game, depth - 1, alpha, beta, False)
# Restore state
game.board = old_board
game.white_king_moved, game.black_king_moved = old_king_moved
game.white_rook_moved, game.black_rook_moved = old_rook_moved
game.current_player = old_player
game.game_over = old_game_over
game.captured_white, game.captured_black = old_captured
if eval_score > max_eval:
max_eval = eval_score
best_move = move
alpha = max(alpha, eval_score)
if beta <= alpha:
break
return max_eval, best_move
else:
min_eval = float('inf')
for move in moves:
# Save state
old_board = copy.deepcopy(game.board)
old_king_moved = (game.white_king_moved, game.black_king_moved)
old_rook_moved = (copy.deepcopy(game.white_rook_moved), copy.deepcopy(game.black_rook_moved))
old_player = game.current_player
old_game_over = game.game_over
old_captured = (copy.copy(game.captured_white), copy.copy(game.captured_black))
game.make_move(move[0], move[1], move[2], move[3])
eval_score, _ = self.minimax(game, depth - 1, alpha, beta, True)
# Restore state
game.board = old_board
game.white_king_moved, game.black_king_moved = old_king_moved
game.white_rook_moved, game.black_rook_moved = old_rook_moved
game.current_player = old_player
game.game_over = old_game_over
game.captured_white, game.captured_black = old_captured
if eval_score < min_eval:
min_eval = eval_score
best_move = move
beta = min(beta, eval_score)
if beta <= alpha:
break
return min_eval, best_move
def get_best_move(self, game):
self.nodes_evaluated = 0
_, best_move = self.minimax(game, self.depth, float('-inf'), float('inf'), False)
return best_move
class ChessGUI:
def __init__(self, root):
self.root = root
self.root.title("Chess Game - Play Against AI")
self.game = ChessGame()
self.ai = ChessAI(depth=3)
self.square_size = 70
self.board_offset = 50
self.piece_symbols = {
'K': '♔', 'Q': '♕', 'R': '♖', 'B': '♗', 'N': '♘', 'P': '♙',
'k': '♚', 'q': '♛', 'r': '♜', 'b': '♝', 'n': '♞', 'p': '♟'
}
self.setup_ui()
self.draw_board()
def setup_ui(self):
# Main frame
self.main_frame = tk.Frame(self.root, bg='#2c3e50')
self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Title
title = tk.Label(self.main_frame, text="♔ Chess Game ♚",
font=('Arial', 24, 'bold'), bg='#2c3e50', fg='white')
title.pack(pady=10)
# Game frame
self.game_frame = tk.Frame(self.main_frame, bg='#2c3e50')
self.game_frame.pack()
# Captured pieces (black)
self.captured_black_frame = tk.Frame(self.game_frame, bg='#2c3e50')
self.captured_black_frame.pack()
self.captured_black_label = tk.Label(self.captured_black_frame, text="",
font=('Arial', 16), bg='#2c3e50', fg='white')
self.captured_black_label.pack()
# Canvas for board
canvas_size = self.square_size * 8 + self.board_offset * 2
self.canvas = tk.Canvas(self.game_frame, width=canvas_size, height=canvas_size,
bg='#2c3e50', highlightthickness=0)
self.canvas.pack(pady=10)
self.canvas.bind('<Button-1>', self.on_click)
# Captured pieces (white)
self.captured_white_frame = tk.Frame(self.game_frame, bg='#2c3e50')
self.captured_white_frame.pack()
self.captured_white_label = tk.Label(self.captured_white_frame, text="",
font=('Arial', 16), bg='#2c3e50', fg='white')
self.captured_white_label.pack()
# Status label
self.status_label = tk.Label(self.main_frame, text="Your turn (White)",
font=('Arial', 14), bg='#2c3e50', fg='white')
self.status_label.pack(pady=10)
# Control buttons
self.control_frame = tk.Frame(self.main_frame, bg='#2c3e50')
self.control_frame.pack(pady=10)
self.new_game_btn = tk.Button(self.control_frame, text="New Game",
command=self.new_game, font=('Arial', 12),
bg='#3498db', fg='white', width=12)
self.new_game_btn.pack(side=tk.LEFT, padx=5)
self.difficulty_var = tk.StringVar(value="Medium")
self.difficulty_menu = tk.OptionMenu(self.control_frame, self.difficulty_var,
"Easy", "Medium", "Hard", command=self.set_difficulty)
self.difficulty_menu.config(font=('Arial', 12), bg='#3498db', fg='white', width=12)
self.difficulty_menu.pack(side=tk.LEFT, padx=5)
# Instructions
instructions = tk.Label(self.main_frame,
text="Click a piece to select it, then click a highlighted square to move.",
font=('Arial', 10), bg='#2c3e50', fg='#bdc3c7')
instructions.pack(pady=5)
def set_difficulty(self, level):
if level == "Easy":
self.ai.depth = 2
elif level == "Medium":
self.ai.depth = 3
else:
self.ai.depth = 4
def draw_board(self):
self.canvas.delete('all')
# Draw squares
light_color = '#f0d9b5'
dark_color = '#b58863'
for row in range(8):
for col in range(8):
x1 = self.board_offset + col * self.square_size
y1 = self.board_offset + row * self.square_size
x2 = x1 + self.square_size
y2 = y1 + self.square_size
color = light_color if (row + col) % 2 == 0 else dark_color
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline='')
# Highlight selected piece
if self.game.selected_piece:
row, col = self.game.selected_piece
x1 = self.board_offset + col * self.square_size
y1 = self.board_offset + row * self.square_size
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill='#7b61ff', outline='')
# Highlight valid moves
for move_row, move_col in self.game.valid_moves:
x1 = self.board_offset + move_col * self.square_size
y1 = self.board_offset + move_row * self.square_size
cx = x1 + self.square_size // 2
cy = y1 + self.square_size // 2
if self.game.board[move_row][move_col] == '':
# Empty square - draw circle
r = self.square_size // 5
self.canvas.create_oval(cx - r, cy - r, cx + r, cy + r,
fill='#7b61ff', outline='')
else:
# Capture - highlight square
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill='#ff6b6b', outline='', stipple='gray50')
# Highlight king in check
if self.game.is_in_check(self.game.current_player):
king_pos = self.game.find_king(self.game.current_player)
if king_pos:
row, col = king_pos
x1 = self.board_offset + col * self.square_size
y1 = self.board_offset + row * self.square_size
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill='#e74c3c', outline='')
# Draw pieces
for row in range(8):
for col in range(8):
piece = self.game.board[row][col]
if piece:
x = self.board_offset + col * self.square_size + self.square_size // 2
y = self.board_offset + row * self.square_size + self.square_size // 2
symbol = self.piece_symbols.get(piece, piece)
color = 'white' if piece.isupper() else 'black'
# Draw piece shadow
self.canvas.create_text(x + 1, y + 1, text=symbol,
font=('Arial', 42), fill='#555555')
# Draw piece
self.canvas.create_text(x, y, text=symbol,
font=('Arial', 42), fill=color)
# Draw coordinates
for i in range(8):
# Files (a-h)
x = self.board_offset + i * self.square_size + self.square_size // 2
self.canvas.create_text(x, self.board_offset // 2, text=chr(ord('a') + i),
font=('Arial', 12), fill='white')
self.canvas.create_text(x, self.board_offset + 8 * self.square_size + self.board_offset // 2,
text=chr(ord('a') + i), font=('Arial', 12), fill='white')
# Ranks (1-8)
y = self.board_offset + i * self.square_size + self.square_size // 2
self.canvas.create_text(self.board_offset // 2, y, text=str(8 - i),
font=('Arial', 12), fill='white')
self.canvas.create_text(self.board_offset + 8 * self.square_size + self.board_offset // 2, y,
text=str(8 - i), font=('Arial', 12), fill='white')
# Update captured pieces display
white_captured = ' '.join([self.piece_symbols[p] for p in self.game.captured_white])
black_captured = ' '.join([self.piece_symbols[p] for p in self.game.captured_black])
self.captured_white_label.config(text=white_captured if white_captured else "No pieces captured")
self.captured_black_label.config(text=black_captured if black_captured else "No pieces captured")
# Update status
if self.game.game_over:
if self.game.is_checkmate():
winner = "Black" if self.game.current_player == 'white' else "White"
self.status_label.config(text=f"Checkmate! {winner} wins!")
elif self.game.is_stalemate():
self.status_label.config(text="Stalemate! It's a draw!")
elif self.game.is_in_check(self.game.current_player):
self.status_label.config(text=f"{'Your' if self.game.current_player == 'white' else 'AI'} turn - CHECK!")
else:
self.status_label.config(text=f"{'Your' if self.game.current_player == 'white' else 'AI'} turn ({self.game.current_player.title()})")
def on_click(self, event):
if self.game.game_over or self.game.current_player != 'white':
return
# Convert click to board coordinates
col = (event.x - self.board_offset) // self.square_size
row = (event.y - self.board_offset) // self.square_size
if not (0 <= row < 8 and 0 <= col < 8):
return
# If a piece is selected and clicked on a valid move
if self.game.selected_piece and (row, col) in self.game.valid_moves:
from_row, from_col = self.game.selected_piece
self.game.make_move(from_row, from_col, row, col)
self.game.selected_piece = None
self.game.valid_moves = []
self.draw_board()
if not self.game.game_over:
self.root.after(500, self.ai_move)
else:
# Select a piece
piece = self.game.board[row][col]
if piece and self.game.get_piece_color(piece) == 'white':
self.game.selected_piece = (row, col)
self.game.valid_moves = self.game.get_valid_moves(row, col)
else:
self.game.selected_piece = None
self.game.valid_moves = []
self.draw_board()
def ai_move(self):
if self.game.game_over or self.game.current_player != 'black':
return
self.status_label.config(text="AI is thinking...")
self.root.update()
best_move = self.ai.get_best_move(self.game)
if best_move:
self.game.make_move(best_move[0], best_move[1], best_move[2], best_move[3])
self.draw_board()
def new_game(self):
self.game = ChessGame()
self.draw_board()
def main():
root = tk.Tk()
root.configure(bg='#2c3e50')
root.resizable(False, False)
gui = ChessGUI(root)
# Center window
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f'+{x}+{y}')
root.mainloop()
if __name__ == "__main__":
main()
This is a complete chess game with:
- Full GUI using Tkinter
- All chess rules including castling and pawn promotion
- Move highlighting
- Check and checkmate detection
- AI opponent using minimax with alpha-beta pruning
- Adjustable difficulty
- Position evaluation tables for better AI play
Let me make sure everything is correct and the code works properly.
Chess Game with AI Opponent
Here's a complete chess game with a graphical interface and AI opponent using minimax algorithm with alpha-beta pruning.
Installation
No external packages needed - uses only Python's built-in tkinter library:
# tkinter comes pre-installed with Python on most systems
# If you're on Linux and it's missing:
sudo apt-get install python3-tk
Complete Code
import tkinter as tk
from tkinter import messagebox
import copy
# Piece values for AI evaluation
PIECE_VALUES = {
'P': 100, 'N': 320, 'B': 330, 'R': 500, 'Q': 900, 'K': 20000,
'p': -100, 'n': -320, 'b': -330, 'r': -500, 'q': -900, 'k': -20000
}
# Position tables for better AI evaluation
PAWN_TABLE = [
[0, 0, 0, 0, 0, 0, 0, 0],
[50, 50, 50, 50, 50, 50, 50, 50],
[10, 10, 20, 30, 30, 20, 10, 10],
[5, 5, 10, 25, 25, 10, 5, 5],
[0, 0, 0, 20, 20, 0, 0, 0],
[5, -5,-10, 0, 0,-10, -5, 5],
[5, 10, 10,-20,-20, 10, 10, 5],
[0, 0, 0, 0, 0, 0, 0, 0]
]
KNIGHT_TABLE = [
[-50,-40,-30,-30,-30,-30,-40,-50],
[-40,-20, 0, 0, 0, 0,-20,-40],
[-30, 0, 10, 15, 15, 10, 0,-30],
[-30, 5, 15, 20, 20, 15, 5,-30],
[-30, 0, 15, 20, 20, 15, 0,-30],
[-30, 5, 10, 15, 15, 10, 5,-30],
[-40,-20, 0, 5, 5, 0,-20,-40],
[-50,-40,-30,-30,-30,-30,-40,-50]
]
BISHOP_TABLE = [
[-20,-10,-10,-10,-10,-10,-10,-20],
[-10, 0, 0, 0, 0, 0, 0,-10],
[-10, 0, 5, 10, 10, 5, 0,-10],
[-10, 5, 5, 10, 10, 5, 5,-10],
[-10, 0, 10, 10, 10, 10, 0,-10],
[-10, 10, 10, 10, 10, 10, 10,-10],
[-10, 5, 0, 0, 0, 0, 5,-10],
[-20,-10,-10,-10,-10,-10,-10,-20]
]
ROOK_TABLE = [
[0, 0, 0, 0, 0, 0, 0, 0],
[5, 10, 10, 10, 10, 10, 10, 5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[-5, 0, 0, 0, 0, 0, 0, -5],
[0, 0, 0, 5, 5, 0, 0, 0]
]
QUEEN_TABLE = [
[-20,-10,-10, -5, -5,-10,-10,-20],
[-10, 0, 0, 0, 0, 0, 0,-10],
[-10, 0, 5, 5, 5, 5, 0,-10],
[-5, 0, 5, 5, 5, 5, 0, -5],
[0, 0, 5, 5, 5, 5, 0, -5],
[-10, 5, 5, 5, 5, 5, 0,-10],
[-10, 0, 5, 0, 0, 0, 0,-10],
[-20,-10,-10, -5, -5,-10,-10,-20]
]
KING_TABLE = [
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-30,-40,-40,-50,-50,-40,-40,-30],
[-20,-30,-30,-40,-40,-30,-30,-20],
[-10,-20,-20,-20,-20,-20,-20,-10],
[20, 20, 0, 0, 0, 0, 20, 20],
[20, 30, 10, 0, 0, 10, 30, 20]
]
class ChessGame:
"""Core chess game logic"""
def __init__(self):
self.board = self.initialize_board()
self.current_player = 'white'
self.selected_piece = None
self.valid_moves = []
self.move_history = []
self.captured_white = []
self.captured_black = []
self.game_over = False
self.white_king_moved = False
self.black_king_moved = False
self.white_rook_moved = {'left': False, 'right': False}
self.black_rook_moved = {'left': False, 'right': False}
self.en_passant_target = None
def initialize_board(self):
"""Set up the initial chess board position"""
board = [['' for _ in range(8)] for _ in range(8)]
# Black pieces (top)
board[0] = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
board[1] = ['p'] * 8
# White pieces (bottom)
board[6] = ['P'] * 8
board[7] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
return board
def get_piece_color(self, piece):
"""Return the color of a piece"""
if piece == '':
return None
return 'white' if piece.isupper() else 'black'
def get_valid_moves(self, row, col, check_for_check=True):
"""Get all valid moves for a piece at given position"""
piece = self.board[row][col]
if piece == '':
return []
color = self.get_piece_color(piece)
moves = []
piece_type = piece.upper()
if piece_type == 'P':
moves = self.get_pawn_moves(row, col, color)
elif piece_type == 'R':
moves = self.get_rook_moves(row, col, color)
elif piece_type == 'N':
moves = self.get_knight_moves(row, col, color)
elif piece_type == 'B':
moves = self.get_bishop_moves(row, col, color)
elif piece_type == 'Q':
moves = self.get_queen_moves(row, col, color)
elif piece_type == 'K':
moves = self.get_king_moves(row, col, color)
if check_for_check:
moves = [m for m in moves if not self.would_be_in_check(row, col, m[0], m[1], color)]
return moves
def get_pawn_moves(self, row, col, color):
"""Get valid pawn moves"""
moves = []
direction = -1 if color == 'white' else 1
start_row = 6 if color == 'white' else 1
# Forward move
new_row = row + direction
if 0 <= new_row < 8 and self.board[new_row][col] == '':
moves.append((new_row, col))
# Double move from start
if row == start_row:
new_row2 = row + 2 * direction
if self.board[new_row2][col] == '':
moves.append((new_row2, col))
# Captures
for dc in [-1, 1]:
new_col = col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target != '' and self.get_piece_color(target) != color:
moves.append((new_row, new_col))
# En passant
if self.en_passant_target == (new_row, new_col):
moves.append((new_row, new_col))
return moves
def get_rook_moves(self, row, col, color):
"""Get valid rook moves"""
moves = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
while 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '':
moves.append((new_row, new_col))
elif self.get_piece_color(target) != color:
moves.append((new_row, new_col))
break
else:
break
new_row += dr
new_col += dc
return moves
def get_knight_moves(self, row, col, color):
"""Get valid knight moves"""
moves = []
jumps = [(-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1)]
for dr, dc in jumps:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '' or self.get_piece_color(target) != color:
moves.append((new_row, new_col))
return moves
def get_bishop_moves(self, row, col, color):
"""Get valid bishop moves"""
moves = []
directions = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
while 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '':
moves.append((new_row, new_col))
elif self.get_piece_color(target) != color:
moves.append((new_row, new_col))
break
else:
break
new_row += dr
new_col += dc
return moves
def get_queen_moves(self, row, col, color):
"""Get valid queen moves (combination of rook and bishop)"""
return self.get_rook_moves(row, col, color) + self.get_bishop_moves(row, col, color)
def get_king_moves(self, row, col, color):
"""Get valid king moves including castling"""
moves = []
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1)]
for dr, dc in directions:
new_row, new_col = row + dr, col + dc
if 0 <= new_row < 8 and 0 <= new_col < 8:
target = self.board[new_row][new_col]
if target == '' or self.get_piece_color(target) != color:
moves.append((new_row, new_col))
# Castling
if color == 'white' and not self.white_king_moved and not self.is_in_check('white'):
# Kingside
if not self.white_rook_moved['right']:
if self.board[7][5] == '' and self.board[7][6] == '':
if not self.would_be_in_check(7, 4, 7, 5, 'white'):
if not self.would_be_in_check(7, 4, 7, 6, 'white'):
moves.append((7, 6))
# Queenside
if not self.white_rook_moved['left']:
if self.board[7][1] == '' and self.board[7][2] == '' and self.board[7][3] == '':
if not self.would_be_in_check(7, 4, 7, 3, 'white'):
if not self.would_be_in_check(7, 4, 7, 2, 'white'):
moves.append((7, 2))
elif color == 'black' and not self.black_king_moved and not self.is_in_check('black'):
# Kingside
if not self.black_rook_moved['right']:
if self.board[0][5] == '' and self.board[0][6] == '':
if not self.would_be_in_check(0, 4, 0, 5, 'black'):
if not self.would_be_in_check(0, 4, 0, 6, 'black'):
moves.append((0, 6))
# Queenside
if not self.black_rook_moved['left']:
if self.board[0][1] == '' and self.board[0][2] == '' and self.board[0][3] == '':
if not self.would_be_in_check(0, 4, 0, 3, 'black'):
if not self.would_be_in_check(0, 4, 0, 2, 'black'):
moves.append((0, 2))
return moves
def find_king(self, color):
"""Find the position of the king"""
king = 'K' if color == 'white' else 'k'
for row in range(8):
for col in range(8):
if self.board[row][col] == king:
return (row, col)
return None
def is_in_check(self, color):
"""Check if the given color's king is in check"""
king_pos = self.find_king(color)
if king_pos is None:
return True
opponent_color = 'black' if color == 'white' else 'white'
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == opponent_color:
moves = self.get_valid_moves(row, col, check_for_check=False)
if king_pos in moves:
return True
return False
def would_be_in_check(self, from_row, from_col, to_row, to_col, color):
"""Check if a move would leave the king in check"""
# Make temporary move
original_piece = self.board[to_row][to_col]
moving_piece = self.board[from_row][from_col]
self.board[to_row][to_col] = moving_piece
self.board[from_row][from_col] = ''
in_check = self.is_in_check(color)
# Undo move
self.board[from_row][from_col] = moving_piece
self.board[to_row][to_col] = original_piece
return in_check
def make_move(self, from_row, from_col, to_row, to_col):
"""Execute a move on the board"""
piece = self.board[from_row][from_col]
captured = self.board[to_row][to_col]
color = self.get_piece_color(piece)
# Track captured pieces
if captured != '':
if self.get_piece_color(captured) == 'white':
self.captured_white.append(captured)
else:
self.captured_black.append(captured)
# Handle en passant capture
if piece.upper() == 'P' and self.en_passant_target == (to_row, to_col):
captured_pawn_row = from_row
captured_pawn = self.board[captured_pawn_row][to_col]
if self.get_piece_color(captured_pawn) == 'white':
self.captured_white.append(captured_pawn)
else:
self.captured_black.append(captured_pawn)
self.board[captured_pawn_row][to_col] = ''
# Update en passant target
self.en_passant_target = None
if piece.upper() == 'P' and abs(to_row - from_row) == 2:
self.en_passant_target = ((from_row + to_row) // 2, to_col)
# Handle castling
if piece.upper() == 'K':
if color == 'white':
self.white_king_moved = True
if to_col - from_col == 2: # Kingside
self.board[7][5] = 'R'
self.board[7][7] = ''
elif from_col - to_col == 2: # Queenside
self.board[7][3] = 'R'
self.board[7][0] = ''
else:
self.black_king_moved = True
if to_col - from_col == 2:
self.board[0][5] = 'r'
self.board[0][7] = ''
elif from_col - to_col == 2:
self.board[0][3] = 'r'
self.board[0][0] = ''
# Track rook moves for castling rights
if piece.upper() == 'R':
if color == 'white':
if from_col == 0:
self.white_rook_moved['left'] = True
elif from_col == 7:
self.white_rook_moved['right'] = True
else:
if from_col == 0:
self.black_rook_moved['left'] = True
elif from_col == 7:
self.black_rook_moved['right'] = True
# Handle pawn promotion (auto-promote to queen)
if piece.upper() == 'P':
if (color == 'white' and to_row == 0) or (color == 'black' and to_row == 7):
piece = 'Q' if color == 'white' else 'q'
# Make the move
self.board[to_row][to_col] = piece
self.board[from_row][from_col] = ''
# Record move
self.move_history.append((from_row, from_col, to_row, to_col, captured))
# Switch player
self.current_player = 'black' if self.current_player == 'white' else 'white'
# Check for game over conditions
self.check_game_over()
return True
def check_game_over(self):
"""Check if the game has ended"""
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == self.current_player:
if self.get_valid_moves(row, col):
return
# No valid moves - game over
self.game_over = True
def is_checkmate(self):
"""Check if current player is in checkmate"""
return self.game_over and self.is_in_check(self.current_player)
def is_stalemate(self):
"""Check if current player is in stalemate"""
return self.game_over and not self.is_in_check(self.current_player)
def evaluate_board(self):
"""Evaluate the board position for AI"""
score = 0
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '':
# Material value
score += PIECE_VALUES[piece]
# Position value
piece_type = piece.upper()
is_white = piece.isupper()
position_tables = {
'P': PAWN_TABLE, 'N': KNIGHT_TABLE, 'B': BISHOP_TABLE,
'R': ROOK_TABLE, 'Q': QUEEN_TABLE, 'K': KING_TABLE
}
if piece_type in position_tables:
table = position_tables[piece_type]
pos_value = table[row][col] if is_white else table[7-row][col]
if is_white:
score += pos_value
else:
score -= pos_value
# Bonus for controlling center
center_squares = [(3, 3), (3, 4), (4, 3), (4, 4)]
for r, c in center_squares:
piece = self.board[r][c]
if piece:
if piece.isupper():
score += 10
else:
score -= 10
return score
def get_all_moves(self, color):
"""Get all possible moves for a color"""
moves = []
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != '' and self.get_piece_color(piece) == color:
piece_moves = self.get_valid_moves(row, col)
for move in piece_moves:
moves.append((row, col, move[0], move[1]))
return moves
class ChessAI:
"""AI opponent using minimax with alpha-beta pruning"""
def __init__(self, depth=3):
self.depth = depth
self.nodes_evaluated = 0
def minimax(self, game, depth, alpha, beta, maximizing):
"""Minimax algorithm with alpha-beta pruning"""
self.nodes_evaluated += 1
if depth == 0 or game.game_over:
evaluation = game.evaluate_board()
if game.is_checkmate():
# Adjust score based on who is checkmated
if game.current_player == 'white':
evaluation -= 100000 + depth # Black wins
else:
evaluation += 100000 + depth # White wins
return evaluation, None
color = 'white' if maximizing else 'black'
moves = game.get_all_moves(color)
if not moves:
if game.is_in_check(color):
return (-100000 if maximizing else 100000), None
return 0, None # Stalemate
# Move ordering: prioritize captures and checks
def move_priority(move):
score = 0
target = game.board[move[2]][move[3]]
if target:
score += abs(PIECE_VALUES.get(target, 0))
return -score
moves.sort(key=move_priority)
best_move = moves[0] if moves else None
if maximizing:
max_eval = float('-inf')
for move in moves:
# Save state
old_board = copy.deepcopy(game.board)
old_king_moved = (game.white_king_moved, game.black_king_moved)
old_rook_moved = (copy.deepcopy(game.white_rook_moved),
copy.deepcopy(game.black_rook_moved))
old_player = game.current_player
old_game_over = game.game_over
old_captured = (copy.copy(game.captured_white),
copy.copy(game.captured_black))
old_en_passant = game.en_passant_target
game.make_move(move[0], move[1], move[2], move[3])
eval_score, _ = self.minimax(game, depth - 1, alpha, beta, False)
# Restore state
game.board = old_board
game.white_king_moved, game.black_king_moved = old_king_moved
game.white_rook_moved, game.black_rook_moved = old_rook_moved
game.current_player = old_player
game.game_over = old_game_over
game.captured_white, game.captured_black = old_captured
game.en_passant_target = old_en_passant
if eval_score > max_eval:
max_eval = eval_score
best_move = move
alpha = max(alpha, eval_score)
if beta <= alpha:
break
return max_eval, best_move
else:
min_eval = float('inf')
for move in moves:
# Save state
old_board = copy.deepcopy(game.board)
old_king_moved = (game.white_king_moved, game.black_king_moved)
old_rook_moved = (copy.deepcopy(game.white_rook_moved),
copy.deepcopy(game.black_rook_moved))
old_player = game.current_player
old_game_over = game.game_over
old_captured = (copy.copy(game.captured_white),
copy.copy(game.captured_black))
old_en_passant = game.en_passant_target
game.make_move(move[0], move[1], move[2], move[3])
eval_score, _ = self.minimax(game, depth - 1, alpha, beta, True)
# Restore state
game.board = old_board
game.white_king_moved, game.black_king_moved = old_king_moved
game.white_rook_moved, game.black_rook_moved = old_rook_moved
game.current_player = old_player
game.game_over = old_game_over
game.captured_white, game.captured_black = old_captured
game.en_passant_target = old_en_passant
if eval_score < min_eval:
min_eval = eval_score
best_move = move
beta = min(beta, eval_score)
if beta <= alpha:
break
return min_eval, best_move
def get_best_move(self, game):
"""Get the best move for the AI"""
self.nodes_evaluated = 0
_, best_move = self.minimax(game, self.depth, float('-inf'), float('inf'), False)
return best_move
class ChessGUI:
"""Graphical user interface for the chess game"""
def __init__(self, root):
self.root = root
self.root.title("♔ Chess - Play Against AI ♚")
self.game = ChessGame()
self.ai = ChessAI(depth=3)
self.square_size = 70
self.board_offset = 50
self.piece_symbols = {
'K': '♔', 'Q': '♕', 'R': '♖', 'B': '♗', 'N': '♘', 'P': '♙',
'k': '♚', 'q': '♛', 'r': '♜', 'b': '♝', 'n': '♞', 'p': '♟'
}
self.setup_ui()
self.draw_board()
def setup_ui(self):
"""Set up the user interface"""
# Main frame
self.main_frame = tk.Frame(self.root, bg='#2c3e50')
self.main_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
# Title
title = tk.Label(self.main_frame, text="♔ Chess Game ♚",
font=('Segoe UI Symbol', 28, 'bold'),
bg='#2c3e50', fg='#ecf0f1')
title.pack(pady=10)
# Game frame
self.game_frame = tk.Frame(self.main_frame, bg='#2c3e50')
self.game_frame.pack()
# Captured pieces (by black)
self.captured_black_frame = tk.Frame(self.game_frame, bg='#2c3e50')
self.captured_black_frame.pack(pady=5)
self.captured_black_label = tk.Label(self.captured_black_frame, text="",
font=('Segoe UI Symbol', 18),
bg='#2c3e50', fg='#bdc3c7')
self.captured_black_label.pack()
# Canvas for board
canvas_size = self.square_size * 8 + self.board_offset * 2
self.canvas = tk.Canvas(self.game_frame, width=canvas_size, height=canvas_size,
bg='#2c3e50', highlightthickness=2,
highlightbackground='#34495e')
self.canvas.pack(pady=10)
self.canvas.bind('<Button-1>', self.on_click)
# Captured pieces (by white)
self.captured_white_frame = tk.Frame(self.game_frame, bg='#2c3e50')
self.captured_white_frame.pack(pady=5)
self.captured_white_label = tk.Label(self.captured_white_frame, text="",
font=('Segoe UI Symbol', 18),
bg='#2c3e50', fg='#bdc3c7')
self.captured_white_label.pack()
# Status label
self.status_label = tk.Label(self.main_frame, text="Your turn (White)",
font=('Arial', 14, 'bold'),
bg='#2c3e50', fg='#3498db')
self.status_label.pack(pady=10)
# Control frame
self.control_frame = tk.Frame(self.main_frame, bg='#2c3e50')
self.control_frame.pack(pady=10)
# New Game button
self.new_game_btn = tk.Button(self.control_frame, text="🔄 New Game",
command=self.new_game, font=('Arial', 12, 'bold'),
bg='#27ae60', fg='white', width=12,
activebackground='#2ecc71', cursor='hand2')
self.new_game_btn.pack(side=tk.LEFT, padx=5)
# Difficulty selector
self.difficulty_frame = tk.Frame(self.control_frame, bg='#2c3e50')
self.difficulty_frame.pack(side=tk.LEFT, padx=5)
tk.Label(self.difficulty_frame, text="Difficulty:",
font=('Arial', 10), bg='#2c3e50', fg='white').pack(side=tk.LEFT)
self.difficulty_var = tk.StringVar(value="Medium")
self.difficulty_menu = tk.OptionMenu(self.difficulty_frame, self.difficulty_var,
"Easy", "Medium", "Hard",
command=self.set_difficulty)
self.difficulty_menu.config(font=('Arial', 10), bg='#3498db', fg='white',
width=8, cursor='hand2')
self.difficulty_menu.pack(side=tk.LEFT, padx=5)
# Flip board button
self.flip_btn = tk.Button(self.control_frame, text="🔃 Flip Board",
command=self.flip_board, font=('Arial', 12, 'bold'),
bg='#9b59b6', fg='white', width=12,
activebackground='#8e44ad', cursor='hand2')
self.flip_btn.pack(side=tk.LEFT, padx=5)
# Instructions
instructions_frame = tk.Frame(self.main_frame, bg='#2c3e50')
instructions_frame.pack(pady=10)
instructions = tk.Label(instructions_frame,
text="Click a piece to select it, then click a highlighted square to move.",
font=('Arial', 10), bg='#2c3e50', fg='#95a5a6')
instructions.pack()
self.flipped = False
def set_difficulty(self, level):
"""Set AI difficulty level"""
if level == "Easy":
self.ai.depth = 2
elif level == "Medium":
self.ai.depth = 3
else: # Hard
self.ai.depth = 4
def flip_board(self):
"""Flip the board perspective"""
self.flipped = not self.flipped
self.draw_board()
def draw_board(self):
"""Draw the chess board and pieces"""
self.canvas.delete('all')
# Colors
light_color = '#f0d9b5'
dark_color = '#b58863'
selected_color = '#7b61ff'
move_color = '#444444'
capture_color = '#ff6b6b'
check_color = '#e74c3c'
# Draw squares
for row in range(8):
for col in range(8):
display_row = 7 - row if self.flipped else row
display_col = 7 - col if self.flipped else col
x1 = self.board_offset + display_col * self.square_size
y1 = self.board_offset + display_row * self.square_size
x2 = x1 + self.square_size
y2 = y1 + self.square_size
color = light_color if (row + col) % 2 == 0 else dark_color
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline='')
# Highlight selected piece
if self.game.selected_piece:
row, col = self.game.selected_piece
if self.flipped:
row, col = 7 - row, 7 - col
x1 = self.board_offset + col * self.square_size
y1 = self.board_offset + row * self.square_size
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill=selected_color, outline='')
# Highlight valid moves
for move_row, move_col in self.game.valid_moves:
display_row = 7 - move_row if self.flipped else move_row
display_col = 7 - move_col if self.flipped else move_col
x1 = self.board_offset + display_col * self.square_size
y1 = self.board_offset + display_row * self.square_size
cx = x1 + self.square_size // 2
cy = y1 + self.square_size // 2
if self.game.board[move_row][move_col] == '':
# Empty square - draw circle indicator
r = self.square_size // 5
self.canvas.create_oval(cx - r, cy - r, cx + r, cy + r,
fill=move_color, outline='')
else:
# Capture - highlight with corner triangles
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill='', outline=capture_color, width=4)
# Highlight king in check
if self.game.is_in_check(self.game.current_player):
king_pos = self.game.find_king(self.game.current_player)
if king_pos:
row, col = king_pos
if self.flipped:
row, col = 7 - row, 7 - col
x1 = self.board_offset + col * self.square_size
y1 = self.board_offset + row * self.square_size
self.canvas.create_rectangle(x1, y1, x1 + self.square_size, y1 + self.square_size,
fill=check_color, outline='')
# Draw pieces
for row in range(8):
for col in range(8):
piece = self.game.board[row][col]
if piece:
display_row = 7 - row if self.flipped else row
display_col = 7 - col if self.flipped else col
x = self.board_offset + display_col * self.square_size + self.square_size // 2
y = self.board_offset + display_row * self.square_size + self.square_size // 2
symbol = self.piece_symbols.get(piece, piece)
# Draw shadow
self.canvas.create_text(x + 2, y + 2, text=symbol,
font=('Segoe UI Symbol', 38), fill='#333333')
# Draw piece
piece_color = '#ffffff' if piece.isupper() else '#000000'
self.canvas.create_text(x, y, text=symbol,
font=('Segoe UI Symbol', 38), fill=piece_color)
# Draw coordinates
for i in range(8):
# Files (a-h)
file_char = chr(ord('a') + (7 - i if self.flipped else i))
x = self.board_offset + i * self.square_size + self.square_size // 2
self.canvas.create_text(x, self.board_offset // 2, text=file_char,
font=('Arial', 12, 'bold'), fill='#bdc3c7')
self.canvas.create_text(x, self.board_offset + 8 * self.square_size + self.board_offset // 2,
text=file_char, font=('Arial', 12, 'bold'), fill='#bdc3c7')
# Ranks (1-8)
rank_num = str(8 - (7 - i if self.flipped else i))
y = self.board_offset + i * self.square_size + self.square_size // 2
self.canvas.create_text(self.board_offset // 2, y, text=rank_num,
font=('Arial', 12, 'bold'), fill='#bdc3c7')
self.canvas.create_text(self.board_offset + 8 * self.square_size + self.board_offset // 2, y,
text=rank_num, font=('Arial', 12, 'bold'), fill='#bdc3c7')
# Update captured pieces display
self.update_captured_display()
# Update status
self.update_status()
def update_captured_display(self):
"""Update the captured pieces display"""
white_captured = ' '.join([self.piece_symbols[p] for p in sorted(self.game.captured_white)])
black_captured = ' '.join([self.piece_symbols[p] for p in sorted(self.game.captured_black)])
self.captured_white_label.config(
text=f"Captured by White: {white_captured}" if white_captured else "Captured by White: -"
)
self.captured_black_label.config(
text=f"Captured by Black: {black_captured}" if black_captured else "Captured by Black: -"
)
def update_status(self):
"""Update the game status display"""
if self.game.game_over:
if self.game.is_checkmate():
winner = "Black" if self.game.current_player == 'white' else "White"
self.status_label.config(text=f"Checkmate! {winner} wins! 🏆", fg='#f39c12')
elif self.game.is_stalemate():
self.status_label.config(text="Stalemate! It's a draw! 🤝", fg='#f39c12')
elif self.game.is_in_check(self.game.current_player):
player = "Your" if self.game.current_player == 'white' else "AI's"
self.status_label.config(text=f"{player} turn - CHECK! ⚠️", fg='#e74c3c')
else:
player = "Your" if self.game.current_player == 'white' else "AI's"
self.status_label.config(text=f"{player} turn ({self.game.current_player.title()})",
fg='#3498db')
def on_click(self, event):
"""Handle mouse click on the board"""
if self.game.game_over or self.game.current_player != 'white':
return
# Convert click to board coordinates
col = (event.x - self.board_offset) // self.square_size
row = (event.y - self.board_offset) // self.square_size
if self.flipped:
row, col = 7 - row, 7 - col
if not (0 <= row < 8 and 0 <= col < 8):
return
# If a piece is selected and clicked on a valid move
if self.game.selected_piece and (row, col) in self.game.valid_moves:
from_row, from_col = self.game.selected_piece
self.game.make_move(from_row, from_col, row, col)
self.game.selected_piece = None
self.game.valid_moves = []
self.draw_board()
if not self.game.game_over:
self.root.after(300, self.ai_move)
else:
# Select a piece
piece = self.game.board[row][col]
if piece and self.game.get_piece_color(piece) == 'white':
self.game.selected_piece = (row, col)
self.game.valid_moves = self.game.get_valid_moves(row, col)
else:
self.game.selected_piece = None
self.game.valid_moves = []
self.draw_board()
def ai_move(self):
"""Execute AI's move"""
if self.game.game_over or self.game.current_player != 'black':
return
self.status_label.config(text="AI is thinking... 🤔", fg='#9b59b6')
self.root.update()
best_move = self.ai.get_best_move(self.game)
if best_move:
# Highlight AI's move briefly
self.game.selected_piece = (best_move[0], best_move[1])
self.game.valid_moves = [(best_move[2], best_move[3])]
self.draw_board()
self.root.update()
self.root.after(200)
self.game.selected_piece = None
self.game.valid_moves = []
self.game.make_move(best_move[0], best_move[1], best_move[2], best_move[3])
self.draw_board()
def new_game(self):
"""Start a new game"""
self.game = ChessGame()
self.flipped = False
self.draw_board()
def main():
"""Main function to run the chess game"""
root = tk.Tk()
root.configure(bg='#2c3e50')
root.resizable(False, False)
gui = ChessGUI(root)
# Center window on screen
root.update_idletasks()
width = root.winfo_width()
height = root.winfo_height()
x = (root.winfo_screenwidth() // 2) - (width // 2)
y = (root.winfo_screenheight() // 2) - (height // 2)
root.geometry(f'+{x}+{y}')
root.mainloop()
if __name__ == "__main__":
main()
How to Run
python chess_game.py
Features
| Feature | Description |
|---|
| ♟️ Full Chess Rules | All standard moves, castling, en passant, pawn promotion |
| 🤖 AI Opponent | Minimax algorithm with alpha-beta pruning |
| 📊 Difficulty Levels | Easy (depth 2), Medium (depth 3), Hard (depth 4) |
| 🎨 Visual Feedback | Highlighted moves, check warnings, selected pieces |
| 📜 Move History | Captured pieces display |
| 🔄 Board Flip | View from either side |
Screenshot Description
The game displays:
- An 8x8 chess board with alternating light/dark squares
- Unicode chess symbols for pieces
- Purple highlighting for selected pieces
- Dot indicators for valid moves
- Red highlighting for captures
- Red background when king is in check
- Status bar showing current player and game state
- Captured pieces displayed above/below the board
AI Details
The AI uses:
- Minimax algorithm with alpha-beta pruning for efficiency
- Piece-square tables for positional evaluation
- Material counting with standard piece values
- Center control bonuses
- Move ordering (captures first) to improve pruning