__STYLES__
This report provides an overview of a Python-based chess piece capture program. The program's goal is to simulate capturing chess pieces by evaluating the validity of moves on a standard chessboard. The code handles both white and black pieces, ensuring that the movement and capture logic align with the rules for pawns and rooks, with room for expansion to other piece types. The program prompts users to input piece types and their positions, then evaluates whether a white piece can capture any of the black pieces based on chess rules.
The program consists of multiple functions designed to handle chessboard validation, user input, and specific chesspiece movements. Below is a summary of each function and its purpose.
is_valid_position(position: str) -> bool
True
if the position is valid, otherwise False
.get_piece_input(prompt: str, valid_pieces: List[str], existing_positions: Set[str]) -> Tuple[Optional[str], Optional[str]]
(None, None)
if the user enters "done".can_pawn_capture(pawn_pos: str, target_pos: str, is_white: bool) -> bool
True
if the pawn can capture the target, otherwise False
.can_rook_capture(rook_pos: str, target_pos: str, all_positions: Set[str]) -> bool
True
if the rook can capture the target, otherwise False
.main()
)2. Capture Evaluation Phase:
can_pawn_capture
) and rooks (can_rook_capture
).3. Output:
import re
from typing import Tuple, List, Set, Optional
def is_valid_position(position: str) -> bool:
return re.match(r'^[a-h][1-8]$', position) is not None
def get_piece_input(prompt: str, valid_pieces: List[str], existing_positions: Set[str]) -> Tuple[Optional[str], Optional[str]]:
while True:
user_input = input(prompt).lower().strip()
if user_input == "done":
return None, None
parts = user_input.split()
if len(parts) != 2:
print("Invalid input. Please use the format 'piece position' (e.g., 'rook e4').")
continue
piece, position = parts
if piece not in valid_pieces:
print(f"Invalid piece. Please choose from: {', '.join(valid_pieces)}")
continue
if not is_valid_position(position):
print("Invalid position. Please use a letter (a-h) followed by a number (1-8).")
continue
if position in existing_positions:
print(f"Position {position} is already occupied. Please choose a different position.")
continue
return piece, position
def can_pawn_capture(pawn_pos: str, target_pos: str, is_white: bool) -> bool:
pawn_col, pawn_row = ord(pawn_pos[0]), int(pawn_pos[1])
target_col, target_row = ord(target_pos[0]), int(target_pos[1])
col_diff = abs(pawn_col - target_col)
row_diff = target_row - pawn_row if is_white else pawn_row - target_row
return col_diff == 1 and row_diff == 1
def can_rook_capture(rook_pos: str, target_pos: str, all_positions: Set[str]) -> bool:
rook_col, rook_row = rook_pos[0], int(rook_pos[1])
target_col, target_row = target_pos[0], int(target_pos[1])
if rook_col == target_col:
start, end = min(rook_row, target_row) + 1, max(rook_row, target_row)
return all(f"{rook_col}{row}" not in all_positions for row in range(start, end))
elif rook_row == target_row:
start, end = min(rook_col, target_col), max(rook_col, target_col)
return all(f"{chr(col)}{rook_row}" not in all_positions for col in range(ord(start) + 1, ord(end)))
return False
def main():
valid_pieces = ["pawn", "rook", "knight", "bishop", "queen", "king"]
piece_limits = {"pawn": 8, "rook": 2, "knight": 2, "bishop": 2, "queen": 1, "king": 1}
existing_positions = set()
piece_counts = {piece: 0 for piece in valid_pieces}
print(f"Choose a white piece ({' or '.join(valid_pieces)}) and its position:")
white_piece, white_position = get_piece_input("Enter white piece and position: ", valid_pieces, existing_positions)
if white_piece is None:
print("You must enter a white piece before adding black pieces or finishing.")
return
existing_positions.add(white_position)
print(f"White {white_piece} added at {white_position}")
black_pieces = []
print("\nNow enter the black pieces (1-16). Type 'done' when finished:")
while len(black_pieces) < 16:
black_piece, black_position = get_piece_input("Enter black piece and position (or 'done'): ", valid_pieces, existing_positions)
if black_piece is None:
if not black_pieces:
print("You must add at least one black piece before finishing.")
continue
break
if piece_counts[black_piece] >= piece_limits[black_piece]:
print(f"Cannot add more than {piece_limits[black_piece]} {black_piece}(s).")
continue
black_pieces.append((black_piece, black_position))
existing_positions.add(black_position)
piece_counts[black_piece] += 1
print(f"Black {black_piece} added at {black_position}")
capturable_pieces = []
for black_piece, black_position in black_pieces:
if white_piece == "pawn" and can_pawn_capture(white_position, black_position, is_white=True):
capturable_pieces.append((black_piece, black_position))
elif white_piece == "rook" and can_rook_capture(white_position, black_position, existing_positions):
capturable_pieces.append((black_piece, black_position))
if capturable_pieces:
print("\nThe white piece can capture the following black pieces:")
for black_piece, black_position in capturable_pieces:
print(f"- {black_piece} at {black_position}")
else:
print("\nThe white piece cannot capture any black pieces.")
The program effectively handles piece capture logic for pawns and rooks while ensuring that all inputs are validated according to chess rules. It can be expanded to include other pieces such as knights, bishops, queens, and kings. This code serves as a useful foundation for more complex chess-related simulations and educational tools.
This report summarizes the capture mechanism and structure of the chess piece capture program and how it interacts with user inputs.