__STYLES__
Tools used in this project
Chess Piece Capture Program

About this project

Chess Piece Capture Program Report

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.

Code Overview

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.

  1. is_valid_position(position: str) -> bool
  • This function checks if the input position is valid on a chessboard. It uses a regular expression to ensure that the position adheres to the chess notation (e.g., ‘a1’, ‘h8’).
  • Input: A position string (e.g., “a4”).
  • Output: Returns True if the position is valid, otherwise False.
  1. get_piece_input(prompt: str, valid_pieces: List[str], existing_positions: Set[str]) -> Tuple[Optional[str], Optional[str]]
  • This function collects user input for a chess piece and its position, ensuring that the input is valid (the piece exists, the position is valid, and it’s not already occupied).
  • Input: A prompt string, a list of valid piece types, and a set of already occupied positions.
  • Output: A tuple containing the piece type and position or (None, None) if the user enters "done".
  1. can_pawn_capture(pawn_pos: str, target_pos: str, is_white: bool) -> bool
  • This function evaluates whether a pawn can capture a target piece based on the pawn’s position, the target position, and the pawn’s color.
  • Input: The pawn’s position, the target’s position, and whether the pawn is white or black.
  • Output: Returns True if the pawn can capture the target, otherwise False.
  1. can_rook_capture(rook_pos: str, target_pos: str, all_positions: Set[str]) -> bool
  • This function evaluates whether a rook can capture a target piece based on the rook’s position, the target’s position and whether other pieces obstruct its path.
  • Input: The rook’s position, the target’s position, and a set of all occupied positions on the board.
  • Output: Returns True if the rook can capture the target, otherwise False.
  1. Main Function Logic (main())
  • This is the core function of the program. It handles the flow of user inputs and evaluates the ability of white pieces (starting with pawns or rooks) to capture black pieces. It does the following:
  1. Prompts the user to input the white piece and position.
  2. Repeatedly collects black piece inputs and positions until the user types “done.”
  3. Evaluate whether the white piece can capture any of the black pieces.
  4. Outputs the result (a list of capturable black pieces or a message indicating that no captures are possible).

How the Program Works

  1. Input Phase:
  • The user first inputs a white piece (e.g., “rook”) and its position (e.g., “e4”).
  • The program checks if the position is valid and not already occupied.
  • After adding the white piece, the user then inputs black pieces and their positions (up to a maximum of 16 black pieces).
  • Each black piece is checked against the same validation rules.

2. Capture Evaluation Phase:

  • Once the user has entered the black pieces, the program evaluates if the white piece can capture any of them.
  • It does so by using movement logic specific to pawns (can_pawn_capture) and rooks (can_rook_capture).
  • The program checks the row and column differences between the white and black pieces to determine if a valid capture can occur.

3. Output:

  • If the white piece can capture any black pieces, the program prints a list of the capturable pieces and their positions.
  • If no captures are possible, the program informs the user.

Example Run

  • The user inputs a white pawn at “e4” and black pieces: a rook at “f5” and a knight at “d5”.
  • The program checks if the white pawn can capture the black pieces based on the pawn’s capture movement rules (diagonal, one-square move).
  • Since the black pieces are diagonally adjacent, the program determines that the white pawn can capture one or more black pieces and outputs the result.
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.")

Conclusion

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.

Future Improvements

  • Implement additional piece movements and capture logic for knights, bishops, queens, and kings.
  • Add a graphical user interface (GUI) for more intuitive user interaction.
  • Enhance input error handling and provide more detailed feedback for incorrect inputs.

This report summarizes the capture mechanism and structure of the chess piece capture program and how it interacts with user inputs.

Discussion and feedback(0 comments)
2000 characters remaining
Cookie SettingsWe use cookies to enhance your experience, analyze site traffic and deliver personalized content. Read our Privacy Policy.