Sure! Below is a basic implementation of a chess game in Python using the Pygame library for graphics. This game allows a human player to play against the computer. The computer makes random valid moves. Please note that this is a simplified version and doesn't include advanced rules like en passant, castling, or pawn promotion.
First, make sure you have Pygame installed. You can install it using:
pip install pygame
Now, here's the code:
import pygame
import sys
import copy
import random
# Initialize Pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 640, 640
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Python Chess')
# Load images
IMAGES = {}
PIECES = ['wp', 'wr', 'wn', 'wb', 'wq', 'wk',
'bp', 'br', 'bn', 'bb', 'bq', 'bk']
for piece in PIECES:
IMAGES[piece] = pygame.transform.scale(pygame.image.load(f"images/{piece}.png"), (80, 80))
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (119, 136, 153)
# Board representation
def create_board():
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
# Draw board and pieces
def draw_board(window, board):
colors = [WHITE, GRAY]
for row in range(8):
for col in range(8):
color = colors[(row + col) % 2]
pygame.draw.rect(window, color, pygame.Rect(col*80, row*80, 80, 80))
piece = board[row][col]
if piece != '--':
window.blit(IMAGES[piece], pygame.Rect(col*80, row*80, 80, 80))
# Get valid moves for a piece
def get_valid_moves(board, row, col):
piece = board[row][col]
if piece == '--':
return []
moves = []
directions = []
if piece[1] == 'p': # Pawn moves
if piece[0] == 'w':
if row > 0 and board[row-1][col] == '--':
moves.append((row-1, col))
if row == 6 and board[row-1][col] == '--' and board[row-2][col] == '--':
moves.append((row-2, col))
# Captures
if row > 0 and col > 0 and board[row-1][col-1][0] == 'b':
moves.append((row-1, col-1))
if row > 0 and col < 7 and board[row-1][col+1][0] == 'b':
moves.append((row-1, col+1))
else:
if row < 7 and board[row+1][col] == '--':
moves.append((row+1, col))
if row == 1 and board[row+1][col] == '--' and board[row+2][col] == '--':
moves.append((row+2, col))
# Captures
if row < 7 and col > 0 and board[row+1][col-1][0] == 'w':
moves.append((row+1, col-1))
if row < 7 and col < 7 and board[row+1][col+1][0] == 'w':
moves.append((row+1, col+1))
elif piece[1] == 'r': # Rook moves
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
elif piece[1] == 'b': # Bishop moves
directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
elif piece[1] == 'q': # Queen moves
directions = [(-1, 0), (1, 0), (0, -1), (0, 1),
(-1, -1), (-1, 1), (1, -1), (1, 1)]
elif piece[1] == 'n': # Knight moves
knight_moves = [
(row-2, col-1), (row-2, col+1),
(row-1, col-2), (row-1, col+2),
(row+1, col-2), (row+1, col+2),
(row+2, col-1), (row+2, col+1)
]
for r, c in knight_moves:
if 0 <= r < 8 and 0 <= c < 8:
target = board[r][c]
if target == '--' or target[0] != piece[0]:
moves.append((r, c))
elif piece[1] == 'k': # King moves
for r in range(-1, 2):
for c in range(-1, 2):
if r == 0 and c == 0:
continue
row_dest, col_dest = row + r, col + c
if 0 <= row_dest < 8 and 0 <= col_dest < 8:
target = board[row_dest][col_dest]
if target == '--' or target[0] != piece[0]:
moves.append((row_dest, col_dest))
# For Rooks, Bishops, Queens
if directions:
for d in directions:
for i in range(1, 8):
row_dest, col_dest = row + d[0]*i, col + d[1]*i
if 0 <= row_dest < 8 and 0 <= col_dest < 8:
target = board[row_dest][col_dest]
if target == '--':
moves.append((row_dest, col_dest))
elif target[0] != piece[0]:
moves.append((row_dest, col_dest))
break
else:
break
else:
break
return moves
# Check if move is valid
def is_valid_move(moves, dest_row, dest_col):
return (dest_row, dest_col) in moves
# Main game loop
def main():
clock = pygame.time.Clock()
board = create_board()
selected_piece = None
turn = 'w' # 'w' for white's turn, 'b' for black's turn
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if turn == 'w':
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = pos[0] // 80
row = pos[1] // 80
if selected_piece:
s_row, s_col = selected_piece
valid_moves = get_valid_moves(board, s_row, s_col)
if is_valid_move(valid_moves, row, col):
board[row][col] = board[s_row][s_col]
board[s_row][s_col] = '--'
selected_piece = None
turn = 'b'
else:
selected_piece = None
else:
if board[row][col][0] == 'w':
selected_piece = (row, col)
else:
# Computer's turn
# Generate all possible moves
all_moves = []
for r in range(8):
for c in range(8):
if board[r][c][0] == 'b':
moves = get_valid_moves(board, r, c)
if moves:
all_moves.append(((r, c), moves))
if all_moves:
piece_pos, moves = random.choice(all_moves)
dest_row, dest_col = random.choice(moves)
board[dest_row][dest_col] = board[piece_pos[0]][piece_pos[1]]
board[piece_pos[0]][piece_pos[1]] = '--'
turn = 'w'
draw_board(WINDOW, board)
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
Important Notes:
-
Images: You need images for the chess pieces saved in an images folder in the same directory as your script. The images should be named as follows:
- White pieces:
wp.png (white pawn)
wr.png (white rook)
wn.png (white knight)
wb.png (white bishop)
wq.png (white queen)
wk.png (white king)
- Black pieces:
bp.png (black pawn)
br.png (black rook)
bn.png (black knight)
bb.png (black bishop)
bq.png (black queen)
bk.png (black king)
You can find suitable images online or create simple placeholders.
-
Simplifications:
- This implementation uses a very basic AI that selects random valid moves for the computer.
- Not all chess rules are implemented. Notably, castling, en passant, and pawn promotion are not handled.
- There's no check or checkmate detection. The game doesn't have an end condition.
-
How to Play:
- Run the script after ensuring that Pygame is installed and images are in place.
- Click on a white piece to select it, then click on the destination square to move.
- After the player's move, the computer will make its move automatically.
Tips for Improvement:
- Implement Full Chess Rules: Add logic to handle check, checkmate, stalemate, pawn promotion, en passant, and castling.
- Improve AI: Replace the random move selection with a basic chess engine using algorithms like Minimax with Alpha-Beta pruning.
- User Interface Enhancements: Highlight valid moves, indicate check/checkmate status, and provide options to restart or quit the game.
Feel free to ask if you have any questions or need further assistance with the code!