Creating a chess game in Python can be a fun project! Below, I'll give you a simple text-based version of a chess game using Python. This will allow two players to play chess in the console. To keep the code simple, it will not include all possible chess rules like castling, en passant, or pawn promotion.
First, make sure you have Python installed on your machine. Then you can run the following code:
python
class ChessBoard:
def __init__(self):
self.board = self.create_board()
self.turn = 'W'
def create_board(self):
# Create an 8x8 chess board
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 is_valid_move(self, start, end):
# Basic move validation
start_x, start_y = start
end_x, end_y = end
piece = self.board[start_x][start_y]
# For simplicity, let's assume any move is valid
if piece == '.':
return False
if (self.turn == 'W' and piece.islower()) or (self.turn == 'B' and piece.isupper()):
return False
return True
def move_piece(self, start, end):
start_x, start_y = start
end_x, end_y = end
if self.is_valid_move(start, end):
self.board[end_x][end_y] = self.board[start_x][start_y]
self.board[start_x][start_y] = '.'
self.turn = 'B' if self.turn == 'W' else 'W'
else:
print("Invalid move. Try again.")
def play(self):
while True:
self.print_board()
start = input(f"{self.turn}'s turn. Enter start position (e.g. 'e2'): ")
end = input("Enter end position (e.g. 'e4'): ")
# Convert input to board indices
start_x = 8 - int(start[1]) # Row number as per chess notation (1-8)
start_y = ord(start[0]) - ord('a') # Column (a-h)
end_x = 8 - int(end[1])
end_y = ord(end[0]) - ord('a')
self.move_piece((start_x, start_y), (end_x, end_y))
if __name__ == "__main__":
game = ChessBoard()
game.play()
Instructions to Play:
Run the Python script in your environment.
Players will be prompted to make moves in standard chess notation (e.g., e2 to e4).
Remember:
Use lowercase letters for black pieces (p, r, n, b, q, k).
Use uppercase letters for white pieces (P, R, N, B, Q, K).
Note:
This code is very basic and does not enforce full chess rules or handle check/checkmate situations.
The validation method is_valid_move allows any move, regardless of chess rules, for simplicity. You can expand this method to implement actual chess rules.
This program is intended for educational purposes and as a starting point for a more complex chess game.
Feel free to modify and expand upon the logic as needed!