Chess Board Implementation
Here's a complete implementation of a chess board that knows all the rules, allows capturing, and enables two humans to play a full game:
class ChessBoard:
def __init__(self):
self.board = self.initialize_board()
self.current_player = 'white'
self.game_over = False
self.move_history = []
self.captured_pieces = {'white': [], 'black': []}
self.en_passant_target = None
self.castling_rights = {
'white': {'kingside': True, 'queenside': True},
'black': {'kingside': True, 'queenside': True}
}
self.check_status = {'white': False, 'black': False}
self.checkmate = False
self.stalemate = False
def initialize_board(self):
# Create an 8x8 chess board with pieces in starting position
board = [[None for _ in range(8)] for _ in range(8)]
# Place pawns
for col in range(8):
board[1][col] = {'type': 'pawn', 'color': 'black', 'moved': False}
board[6][col] = {'type': 'pawn', 'color': 'white', 'moved': False}
# Place rooks
board[0][0] = {'type': 'rook', 'color': 'black', 'moved': False}
board[0][7] = {'type': 'rook', 'color': 'black', 'moved': False}
board[7][0] = {'type': 'rook', 'color': 'white', 'moved': False}
board[7][7] = {'type': 'rook', 'color': 'white', 'moved': False}
# Place knights
board[0][1] = {'type': 'knight', 'color': 'black'}
board[0][6] = {'type': 'knight', 'color': 'black'}
board[7][1] = {'type': 'knight', 'color': 'white'}
board[7][6] = {'type': 'knight', 'color': 'white'}
# Place bishops
board[0][2] = {'type': 'bishop', 'color': 'black'}
board[0][5] = {'type': 'bishop', 'color': 'black'}
board[7][2] = {'type': 'bishop', 'color': 'white'}
board[7][5] = {'type': 'bishop', 'color': 'white'}
# Place queens
board[0][3] = {'type': 'queen', 'color': 'black'}
board[7][3] = {'type': 'queen', 'color': 'white'}
# Place kings
board[0][4] = {'type': 'king', 'color': 'black', 'moved': False}
board[7][4] = {'type': 'king', 'color': 'white', 'moved': False}
return board
def display_board(self):
print("\n a b c d e f g h")
print(" +-----------------+")
for row in range(8):
print(f"{8-row}|", end="")
for col in range(8):
piece = self.board[row][col]
if piece is None:
print(" ", end=" ")
else:
# Use Unicode chess symbols
symbol = self.get_piece_symbol(piece)
print(symbol, end=" ")
print(f"|{8-row}")
print(" +-----------------+")
print(" a b c d e f g h")
# Display current player
print(f"\nCurrent player: {self.current_player}")
# Display captured pieces
print("Captured pieces:")
print(f"White: {[self.get_piece_symbol(p) for p in self.captured_pieces['white']]}")
print(f"Black: {[self.get_piece_symbol(p) for p in self.captured_pieces['black']]}")
# Display game status
if self.check_status[self.current_player]:
print("CHECK!")
if self.checkmate:
print("CHECKMATE!")
print(f"Winner: {'black' if self.current_player == 'white' else 'white'}")
if self.stalemate:
print("STALEMATE! Game is a draw.")
def get_piece_symbol(self, piece):
symbols = {
'king': {'white': '♔', 'black': '♚'},
'queen': {'white': '♕', 'black': '♛'},
'rook': {'white': '♖', 'black': '♜'},
'bishop': {'white': '♗', 'black': '♝'},
'knight': {'white': '♘', 'black': '♞'},
'pawn': {'white': '♙', 'black': '♟'}
}
return symbols[piece['type']][piece['color']]
def parse_move(self, move_str):
# Convert algebraic notation to board coordinates
if move_str.lower() == 'o-o':
return 'kingside_castle'
elif move_str.lower() == 'o-o-o':
return 'queenside_castle'
try:
col_from = ord(move_str[0].lower()) - ord('a')
row_from = 8 - int(move_str[1])
col_to = ord(move_str[2].lower()) - ord('a')
row_to = 8 - int(move_str[3])
if not (0 <= col_from <= 7 and 0 <= row_from <= 7 and 0 <= col_to <= 7 and 0 <= row_to <= 7):
return None
return (row_from, col_from, row_to, col_to)
except:
return None
def is_valid_move(self, from_row, from_col, to_row, to_col):
piece = self.board[from_row][from_col]
if piece is None or piece['color'] != self.current_player:
return False
target = self.board[to_row][to_col]
if target is not None and target['color'] == piece['color']:
return False
# Check piece-specific movement rules
if piece['type'] == 'pawn':
return self.is_valid_pawn_move(from_row, from_col, to_row, to_col)
elif piece['type'] == 'rook':
return self.is_valid_rook_move(from_row, from_col, to_row, to_col)
elif piece['type'] == 'knight':
return self.is_valid_knight_move(from_row, from_col, to_row, to_col)
elif piece['type'] == 'bishop':
return self.is_valid_bishop_move(from_row, from_col, to_row, to_col)
elif piece['type'] == 'queen':
return self.is_valid_queen_move(from_row, from_col, to_row, to_col)
elif piece['type'] == 'king':
return self.is_valid_king_move(from_row, from_col, to_row, to_col)
return False
def is_valid_pawn_move(self, from_row, from_col, to_row, to_col):
piece = self.board[from_row][from_col]
direction = -1 if piece['color'] == 'white' else 1
start_row = 6 if piece['color'] == 'white' else 1
# Forward move
if from_col == to_col:
# Single step forward
if to_row == from_row + direction and self.board[to_row][to_col] is None:
return True
# Double step from starting position
if (from_row == start_row and to_row == from_row + 2*direction and
self.board[from_row + direction][from_col] is None and
self.board[to_row][to_col] is None):
return True
# Capture
elif abs(to_col - from_col) == 1 and to_row == from_row + direction:
# Normal capture
if self.board[to_row][to_col] is not None and self.board[to_row][to_col]['color'] != piece['color']:
return True
# En passant
if (self.en_passant_target is not None and
to_row == self.en_passant_target[0] and
to_col == self.en_passant_target[1]):
return True
return False
def is_valid_rook_move(self, from_row, from_col, to_row, to_col):
# Must move in straight line
if from_row != to_row and from_col != to_col:
return False
# Check if path is clear
if from_row == to_row: # Horizontal move
step = 1 if to_col > from_col else -1
for col in range(from_col + step, to_col, step):
if self.board[from_row][col] is not None:
return False
else: # Vertical move
step = 1 if to_row > from_row else -1
for row in range(from_row + step,