Certainly! Creating a simple chess game in Python can be an exciting project. Below, I'll guide you through creating a basic command-line chess game where two players can play against each other. We'll use the python-chess library, which handles the complexities of chess rules, move validation, and game state management.
If you’re interested in adding AI to play against the computer, we can extend the example later. But first, let's start with a two-player setup.
Step 1: Install the python-chess Library
First, you'll need to install the python-chess library. You can install it using pip:
bash
pip install python-chess
Step 2: Create the Chess Game
Below is a complete Python script that allows two players to play chess in the console. It displays the board, takes moves in UCI format (e.g., e2e4), and validates moves.
python
import chess
import chess.svg
import sys
def print_board(board):
# Display the board in the console
# We'll print ranks 8 to 1 and files a to h
print(" +------------------------+")
for rank in range(8, 0, -1):
line = f"{rank} |"
for file in range(1, 9):
square = chess.square(file - 1, rank - 1)
piece = board.piece_at(square)
if piece:
symbol = piece.symbol()
else:
symbol = '.'
line += f" {symbol}"
line += " |"
print(line)
print(" +------------------------+")
print(" a b c d e f g h")
def get_move(board):
while True:
move_input = input("Enter your move (e.g., e2e4): ")
try:
move = board.parse_san(move_input)
except:
try:
move = chess.Move.from_uci(move_input)
except:
move = None
if move in board.legal_moves:
return move
else:
print("Invalid move. Please try again.")
def main():
board = chess.Board()
print("Welcome to Command-Line Chess!")
print_board(board)
while not board.is_game_over():
if board.turn == chess.WHITE:
print("\nWhite's move:")
else:
print("\nBlack's move:")
move = get_move(board)
board.push(move)
print_board(board)
print("\nGame over.")
result = board.result()
if board.is_checkmate():
if board.turn == chess.WHITE:
print("Black wins by checkmate!")
else:
print("White wins by checkmate!")
elif board.is_stalemate():
print("Draw by stalemate.")
elif board.is_insufficient_material():
print("Draw due to insufficient material.")
elif board.is_seventyfive_moves():
print("Draw by seventy-five moves rule.")
elif board.is_fivefold_repetition():
print("Draw by fivefold repetition.")
else:
print(f"Result: {result}")
if __name__ == "__main__":
main()
Explanation of the Code
Importing Libraries:
chess: The main library to handle chess logic.
sys: For exiting the program if needed.
print_board Function:
Displays the current state of the board in the console in a human-readable format.
Iterates through each rank and file to print pieces or empty squares.
get_move Function:
Prompts the current player to enter a move.
Attempts to parse the input as Standard Algebraic Notation (SAN) first.
If that fails, it tries UCI (e.g., e2e4).
Validates whether the move is legal; if not, it asks again.
main Function:
Initializes the chess board.
Displays the board.
Enters a loop where it alternates between White and Black players, prompting for moves.
After each move, it updates and displays the board.
Checks for game termination conditions and announces the result.
Running the Game
Save the script to a file, say chess_game.py.
Open your terminal or command prompt.
Navigate to the directory containing chess_game.py.
Run the script using:
bash
python chess_game.py
Follow the on-screen prompts to play. Enter moves in UCI format (e.g., e2e4) or in SAN (e.g., e4).
Example Gameplay
code
Welcome to Command-Line Chess!
+------------------------+
8 | r n b q k b n r |
7 | p p p p p p p p |
6 | . . . . . . . . |
5 | . . . . . . . . |
4 | . . . . . . . . |
3 | . . . . . . . . |
2 | P P P P P P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
White's move:
Enter your move (e.g., e2e4): e2e4
+------------------------+
8 | r n b q k b n r |
7 | p p p p p p p p |
6 | . . . . . . . . |
5 | . . . . . . . . |
4 | . . . . P . . . |
3 | . . . . . . . . |
2 | P P P P . P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
Black's move:
Enter your move (e.g., e7e5): e7e5
...
Extending to Play Against an AI
If you want to play against the computer, you can integrate a simple AI using the Minimax algorithm with a basic evaluation function. For more advanced AI, consider using existing chess engines like Stockfish.
Here's a basic example of integrating a simple AI:
Step 1: Install Required Libraries
Ensure you have python-chess installed as shown before.
Step 2: Update the Code to Include AI
python
import chess
import chess.engine
import sys
def print_board(board):
# Same as before
print(" +------------------------+")
for rank in range(8, 0, -1):
line = f"{rank} |"
for file in range(1, 9):
square = chess.square(file - 1, rank - 1)
piece = board.piece_at(square)
if piece:
symbol = piece.symbol()
else:
symbol = '.'
line += f" {symbol}"
line += " |"
print(line)
print(" +------------------------+")
print(" a b c d e f g h")
def get_player_move(board):
while True:
move_input = input("Enter your move (e.g., e2e4): ")
try:
move = board.parse_san(move_input)
except:
try:
move = chess.Move.from_uci(move_input)
except:
move = None
if move in board.legal_moves:
return move
else:
print("Invalid move. Please try again.")
def get_ai_move(board, engine, time_limit=0.1):
# Use the engine to select the best move
result = engine.play(board, chess.engine.Limit(time=time_limit))
return result.move
def main():
board = chess.Board()
print("Welcome to Command-Line Chess against AI!")
print_board(board)
# Initialize the engine (Stockfish is recommended)
# Make sure you have Stockfish installed and provide the correct path
# You can download Stockfish from: https://stockfishchess.org/download/
engine_path = "/usr/local/bin/stockfish" # Update this path
try:
engine = chess.engine.SimpleEngine.popen_uci(engine_path)
except:
print("Error: Could not start the engine. Make sure Stockfish is installed and the path is correct.")
sys.exit(1)
try:
while not board.is_game_over():
if board.turn == chess.WHITE:
print("\nWhite's move:")
move = get_player_move(board)
else:
print("\nBlack (AI) is thinking...")
move = get_ai_move(board, engine)
print(f"AI plays: {board.san(move)}")
board.push(move)
print_board(board)
print("\nGame over.")
result = board.result()
if board.is_checkmate():
if board.turn == chess.WHITE:
print("Black (AI) wins by checkmate!")
else:
print("White wins by checkmate!")
elif board.is_stalemate():
print("Draw by stalemate.")
elif board.is_insufficient_material():
print("Draw due to insufficient material.")
elif board.is_seventyfive_moves():
print("Draw by seventy-five moves rule.")
elif board.is_fivefold_repetition():
print("Draw by fivefold repetition.")
else:
print(f"Result: {result}")
finally:
engine.quit()
if __name__ == "__main__":
main()
Explanation of the AI Integration
Initializing the Engine:
This example uses Stockfish, a powerful open-source chess engine.
Windows: It might be something like C:\\path\\to\\stockfish.exe
macOS/Linux: It might be /usr/local/bin/stockfish or similar.
Update the engine_path variable in the script with the correct path.
Run the Script:
bash
python chess_game_ai.py
Play the Game:
You play as White, and the AI plays as Black.
Enter your moves as before, and the AI will respond automatically.
Example Gameplay with AI
code
Welcome to Command-Line Chess against AI!
+------------------------+
8 | r n b q k b n r |
7 | p p p p p p p p |
6 | . . . . . . . . |
5 | . . . . . . . . |
4 | . . . . . . . . |
3 | . . . . . . . . |
2 | P P P P P P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
White's move:
Enter your move (e.g., e2e4): e2e4
+------------------------+
8 | r n b q k b n r |
7 | p p p p p p p p |
6 | . . . . . . . . |
5 | . . . . p . . . |
4 | . . . . P . . . |
3 | . . . . . . . . |
2 | P P P P . P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
Black (AI) is thinking...
AI plays: e5
+------------------------+
8 | r n b q k b n r |
7 | p p p p . p p p |
6 | . . . . . . . . |
5 | . . . . p . . . |
4 | . . . . P . . . |
3 | . . . . . . . . |
2 | P P P P . P P P |
1 | R N B Q K B N R |
+------------------------+
a b c d e f g h
White's move:
Enter your move (e.g., e2e4): ...
Additional Enhancements
Input Flexibility:
Allow moves in different formats (e.g., algebraic notation like Nf3).
Better Board Display:
Use libraries like prettytable or graphical libraries like pygame for a better UI.
Move History:
Keep track of and display move history.
Undo Moves:
Allow players to undo moves.
AI Difficulty Levels:
Adjust the AI's strength by changing the search depth or time limit.
Graphical User Interface (GUI):
For a more user-friendly experience, integrate a GUI using libraries like pygame, tkinter, or PyQt.
Conclusion
You've now created a basic command-line chess game in Python, with the option to play against another player or an AI opponent. The python-chess library simplifies handling chess logic, allowing you to focus on building features and enhancing the user experience. From here, you can expand the project further by adding a GUI, improving AI capabilities, or integrating online play functionalities.
Feel free to ask if you need more advanced features or have any questions!