Creating a simple chess game in Python can be quite involved, but I will provide a basic implementation with a console-based interface. This implementation will allow two players to play against each other. For simplicity, it doesn’t include advanced features like castling, pawn promotion, or en passant captures, and it doesn’t check for check or checkmate conditions.
python
class ChessBoard:
def __init__(self):
self.board = self.create_board()
self.current_turn = 'White'
def create_board(self):
board = [
['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
['.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
]
return board
def print_board(self):
for row in self.board:
print(' '.join(row))
print()
def move_piece(self, start, end):
row_start, col_start = start
row_end, col_end = end
piece = self.board[row_start][col_start]
if piece == '.' or (piece.islower() and self.current_turn == 'White') or (piece.isupper() and self.current_turn == 'Black'):
print("Invalid move. It's not your turn or the piece doesn't belong to you.")
return False
self.board[row_end][col_end] = piece
self.board[row_start][col_start] = '.'
self.current_turn = 'Black' if self.current_turn == 'White' else 'White'
return True
def parse_position(pos):
col = ord(pos[0].lower()) - ord('a')
row = 8 - int(pos[1]) # Convert to 0-index
return row, col
def main():
game = ChessBoard()
while True:
game.print_board()
print(f"{game.current_turn}'s turn.")
move = input("Enter your move (e.g. e2 e4): ")
try:
start_pos, end_pos = move.split()
start = parse_position(start_pos)
end = parse_position(end_pos)
if not (0 <= start[0] < 8 and 0 <= start[1] < 8 and 0 <= end[0] < 8 and 0 <= end[1] < 8):
print("Invalid move. Position out of bounds.")
continue
if game.move_piece(start, end):
continue
except (ValueError, IndexError):
print("Invalid input. Format should be 'e2 e4'. Please try again.")
if __name__ == "__main__":
main()
How to Run
Copy the above code into a Python file, e.g., chess.py.
Run the script using Python 3.x: python chess.py.
Players will take turns entering moves in the format e2 e4.