please make chess in python. assume the images are inside a folder called…
- User
please make chess in python. assume the images are inside a folder called pieces/black-queen.png for example
also make sure there is an ai opponent
- Assistant
please make chess in python. assume the images are inside a folder called pieces/black-queen.png for example
also make sure there is an ai opponent
Certainly! Below is a Python program that creates a basic chess game with a graphical interface using Pygame. It assumes that you have images for the chess pieces stored in a directory named pieces/ with filenames like black-queen.png. The game includes an AI opponent that makes random valid moves.
Please note that this is a simplified version of chess:
Install Pygame library:
pip install pygame
Ensure you have the images of the chess pieces in the pieces/ directory with names like:
black-pawn.pngblack-rook.pngblack-knight.pngblack-bishop.pngblack-queen.pngblack-king.pngwhite-pawn.pngwhite-rook.pngwhite-knight.pngwhite-bishop.pngwhite-queen.pngwhite-king.pngimport pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Define constants
WIDTH, HEIGHT = 640, 640
SQUARE_SIZE = WIDTH // 8
# Set up the drawing window
screen = pygame.display.set_mode([WIDTH, HEIGHT])
# Set up caption
pygame.display.set_caption('Chess')
# Load images
def load_images():
pieces = ['black-bishop', 'black-king', 'black-knight', 'black-pawn',
'black-queen', 'black-rook', 'white-bishop', 'white-king',
'white-knight', 'white-pawn', 'white-queen', 'white-rook']
images = {}
for piece in pieces:
images[piece] = pygame.transform.scale(
pygame.image.load(f'pieces/{piece}.png'), (SQUARE_SIZE, SQUARE_SIZE)
)
return images
images = load_images()
class Board:
def __init__(self):
# Initialize the board with pieces in starting positions
self.board = [
['black-rook', 'black-knight', 'black-bishop', 'black-queen', 'black-king', 'black-bishop', 'black-knight', 'black-rook'],
['black-pawn'] * 8,
[None] * 8,
[None] * 8,
[None] * 8,
[None] * 8,
['white-pawn'] * 8,
['white-rook', 'white-knight', 'white-bishop', 'white-queen', 'white-king', 'white-bishop', 'white-knight', 'white-rook']
]
self.white_to_move = True
self.move_log = []
def draw_pieces(self, screen, images):
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece:
screen.blit(images[piece], pygame.Rect(col*SQUARE_SIZE, row*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def make_move(self, start_sq, end_sq):
start_row, start_col = start_sq
end_row, end_col = end_sq
piece_moved = self.board[start_row][start_col]
piece_captured = self.board[end_row][end_col]
if self.is_valid_move(start_sq, end_sq, piece_moved):
self.board[end_row][end_col] = piece_moved
self.board[start_row][start_col] = None
self.move_log.append(((start_row, start_col), (end_row, end_col), piece_moved, piece_captured))
self.white_to_move = not self.white_to_move
return True
else:
return False
def is_valid_move(self, start_sq, end_sq, piece):
start_row, start_col = start_sq
end_row, end_col = end_sq
if start_row == end_row and start_col == end_col:
return False # Cannot move to the same square
target_piece = self.board[end_row][end_col]
if piece is None:
return False
color = 'white' if 'white' in piece else 'black'
if target_piece is not None and color in target_piece:
return False # Cannot capture own piece
piece_type = piece.replace(f"{color}-", "")
if target_piece is None or (color not in target_piece):
if piece_type == 'pawn':
return self.valid_pawn_move(start_sq, end_sq, color)
elif piece_type == 'rook':
return self.valid_rook_move(start_sq, end_sq)
elif piece_type == 'knight':
return self.valid_knight_move(start_sq, end_sq)
elif piece_type == 'bishop':
return self.valid_bishop_move(start_sq, end_sq)
elif piece_type == 'queen':
return self.valid_queen_move(start_sq, end_sq)
elif piece_type == 'king':
return self.valid_king_move(start_sq, end_sq)
return False
def valid_pawn_move(self, start_sq, end_sq, color):
start_row, start_col = start_sq
end_row, end_col = end_sq
direction = -1 if color == 'white' else 1
starting_row = 6 if color == 'white' else 1
if start_col == end_col:
if self.board[end_row][end_col] is None:
if end_row - start_row == direction:
return True
if start_row == starting_row and end_row - start_row == 2 * direction and self.board[start_row + direction][start_col] is None:
return True
elif abs(start_col - end_col) == 1 and end_row - start_row == direction:
if self.board[end_row][end_col] is not None and color not in self.board[end_row][end_col]:
return True
return False
def valid_rook_move(self, start_sq, end_sq):
start_row, start_col = start_sq
end_row, end_col = end_sq
if start_row == end_row:
step = 1 if end_col > start_col else -1
for col in range(start_col + step, end_col, step):
if self.board[start_row][col] is not None:
return False
return True
elif start_col == end_col:
step = 1 if end_row > start_row else -1
for row in range(start_row + step, end_row, step):
if self.board[row][start_col] is not None:
return False
return True
return False
def valid_knight_move(self, start_sq, end_sq):
start_row, start_col = start_sq
end_row, end_col = end_sq
row_diff = abs(end_row - start_row)
col_diff = abs(end_col - start_col)
return (row_diff == 2 and col_diff == 1) or (row_diff == 1 and col_diff == 2)
def valid_bishop_move(self, start_sq, end_sq):
start_row, start_col = start_sq
end_row, end_col = end_sq
if abs(end_row - start_row) == abs(end_col - start_col):
step_row = 1 if end_row > start_row else -1
step_col = 1 if end_col > start_col else -1
for i in range(1, abs(end_row - start_row)):
if self.board[start_row + i * step_row][start_col + i * step_col] is not None:
return False
return True
return False
def valid_queen_move(self, start_sq, end_sq):
return self.valid_rook_move(start_sq, end_sq) or self.valid_bishop_move(start_sq, end_sq)
def valid_king_move(self, start_sq, end_sq):
start_row, start_col = start_sq
end_row, end_col = end_sq
if max(abs(end_row - start_row), abs(end_col - start_col)) == 1:
return True
# Castling not implemented
return False
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 color in piece:
piece_moves = self.get_piece_moves((row, col), piece)
for move in piece_moves:
moves.append(((row, col), move))
return moves
def get_piece_moves(self, pos, piece):
moves = []
row, col = pos
for r in range(8):
for c in range(8):
if self.is_valid_move((row, col), (r, c), piece):
moves.append((r, c))
return moves
def get_ai_move(self):
moves = self.get_all_moves('black')
if moves:
return random.choice(moves)
else:
return None
# Draw the board
def draw_board(screen):
colors = [pygame.Color(235, 235, 208), pygame.Color(119, 148, 85)] # Light square, dark square
for row in range(8):
for col in range(8):
color = colors[(row+col)%2]
pygame.draw.rect(screen, color, pygame.Rect(col*SQUARE_SIZE, row*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))
def highlight_squares(screen, selected_sq):
if selected_sq:
row, col = selected_sq
s = pygame.Surface((SQUARE_SIZE, SQUARE_SIZE))
s.set_alpha(100)
s.fill(pygame.Color('blue'))
screen.blit(s, (col*SQUARE_SIZE, row*SQUARE_SIZE))
board = Board()
selected_piece = None
player_clicks = [] # Keep track of player clicks [(row,col), (row,col)]
game_over = False
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
location = pygame.mouse.get_pos() # (x,y) location of the mouse
col = location[0] // SQUARE_SIZE
row = location[1] // SQUARE_SIZE
if selected_piece:
player_clicks.append((row, col))
if len(player_clicks) == 2:
move_made = board.make_move(player_clicks[0], player_clicks[1])
if move_made:
selected_piece = None
player_clicks = []
# AI move
ai_move = board.get_ai_move()
if ai_move is not None:
board.make_move(ai_move[0], ai_move[1])
else:
game_over = True
print("You Win!")
else:
player_clicks = [ (row, col) ] # Invalid move, reset clicks
else:
piece = board.board[row][col]
if piece and 'white' in piece and board.white_to_move:
selected_piece = (row, col)
player_clicks.append((row, col))
# Draw everything
draw_board(screen)
highlight_squares(screen, selected_piece)
board.draw_pieces(screen, images)
# Update the display
pygame.display.flip()
# Quit Pygame
pygame.quit()
sys.exit()
Board class sets up the initial positions of the pieces.make_move method attempts to move a piece from a starting square to an ending square.is_valid_move method checks if a move is valid according to the piece's movement rules.valid_pawn_move, valid_rook_move, etc.) to validate moves.get_ai_move method generates all possible moves for the black pieces and randomly selects one.draw_board function draws the chessboard squares.draw_pieces method of the Board class places the pieces on the board.highlight_squares function highlights the selected square.Save the Code:
Save the provided code in a file, for example, chess_game.py.
Prepare the Images:
Ensure you have the pieces/ directory with all the necessary piece images in PNG format.
Run the Game:
python chess_game.py
Play the Game:
This code provides a foundational chess game in Python with a basic AI opponent and graphical interface. It can be used as a starting point for developing a more complete chess application by adding more features and improving existing functionalities.
If you have any questions or need further assistance with specific features, feel free to ask!