Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ChessGame:
- def __init__(self):
- self.board = self.initialize_board()
- def initialize_board(self):
- # Initialize an empty 8x8 chessboard
- board = [[' ' for _ in range(8)] for _ in range(8)]
- # Place white pieces
- board[0] = ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
- board[1] = ['P'] * 8
- # Place black pieces
- board[7] = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r']
- board[6] = ['p'] * 8
- return board
- def print_board(self):
- # Print the current state of the chessboard with positions revealed
- for row_num, row in enumerate(self.board):
- row_display = []
- for col_num, piece in enumerate(row):
- if piece == ' ':
- row_display.append(f"{chr(col_num + ord('a'))}{8 - row_num} -")
- else:
- row_display.append(f"{chr(col_num + ord('a'))}{8 - row_num} {piece}")
- print(" ".join(row_display))
- def move_piece(self, piece, start_row, start_col, end_row, end_col):
- # Check if the move is valid
- if self.is_valid_move(piece, start_row, start_col, end_row, end_col):
- # Perform the move
- self.board[end_row][end_col] = piece
- self.board[start_row][start_col] = ' '
- print("Move successful!")
- else:
- print("Invalid move!")
- def convert_position(self, piece, position):
- # Convert algebraic notation to array indices
- row = 8 - int(position[1])
- col = ord(position[0]) - ord('a')
- if piece.islower(): # Check if it's a black piece
- row = 7 - row # Invert row for Black side
- return row, col
- def is_within_board(self, row, col):
- # Check if the given position is within the bounds of the board
- return 0 <= row < 8 and 0 <= col < 8
- def is_valid_move(self, piece, start_row, start_col, end_row, end_col):
- # Check if the move is valid for the given piece
- # Implementation of move validation omitted for brevity
- return True
- if __name__ == "__main__":
- game = ChessGame()
- while True:
- game.print_board()
- move = input("Enter your move (e.g., 'N c3 to e4'): ")
- if move.lower() == 'exit':
- break
- move_parts = move.split()
- piece = move_parts[0]
- start_position = move_parts[1]
- end_position = move_parts[3]
- start_row, start_col = game.convert_position(piece, start_position)
- end_row, end_col = game.convert_position(piece, end_position)
- game.move_piece(piece, start_row, start_col, end_row, end_col)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement