The user wants a chess game with an AI opponent.
This is a classic programming task. I need to decide on a few key things:
-
Language: Python is the standard choice for this because it's readable and has good libraries for logic and simple UIs. C++ is faster but might be overkill for a simple example. Java is okay but verbose. I'll stick with Python.
-
Interface:
- Console: Too hard to visualize.
- GUI (Tkinter/Pygame): Good, but requires writing a lot of code for drawing the board and handling mouse clicks.
- Text-based (but with a representation): Easy to debug but not fun to play.
- External Library (python-chess): This is the best approach for a practical answer. Writing a complete legal move generator, castling logic, en passant, and checkmate detection from scratch is thousands of lines of error-prone code. Using
python-chess handles the board state and rules, allowing the user (and me) to focus on the AI part and the Game Loop.
- Alternative: If I cannot use external libraries (assuming a constraint of "pure standard library"), I have to build a very simplified version.
- Decision: I will provide a solution using
python-chess for the logic because it's the professional and robust way to do it in Python. I will also implement a simple ASCII board print function so they can run it without needing a complex GUI library like Pygame, though python-chess supports SVG generation for Jupyter notebooks. For a standalone script, ASCII is safest.
-
AI Logic:
- Random: Too easy, not really "AI".
- Minimax: The classic algorithm.
- Alpha-Beta Pruning: Optimization for Minimax.
- Evaluation Function: Material count (Pawn=1, Knight=3, etc.) + Positional bonuses (optional, but makes it smarter).
-
Structure of the Program:
- Imports:
chess (needs pip install python-chess), random (maybe not needed if doing minimax), time (for pacing).
- Evaluation Function: Assign values to pieces.
- Minimax Algorithm: Recursive function to look ahead N moves. Needs depth limit.
- Game Loop:
- Print board.
- Check for game over.
- Get user input (Human move).
- Make move.
- Check for game over.
- Calculate AI move.
- Make move.
- Repeat.
-
Refining the Code:
- I need to make sure the minimax implementation is correct (maximizing for white, minimizing for black, or vice versa depending on who is AI).
- Let's make the AI play Black for simplicity.
- Evaluation function:
- Pawn: 10
- Knight/Bishop: 30
- Rook: 50
- Queen: 90
- King: 900
- Self-Correction: Standard values are usually 1, 3, 3, 5, 9. Let's use 1, 3, 3, 5, 9, 100 to keep numbers small.
-
Drafting the Minimax logic:
def minimax(board, depth, maximizingPlayer):
if depth == 0 or board.is_game_over():
return evaluate(board)
if maximizingPlayer:
maxEval = -infinity
for move in board.legal_moves:
board.push(move)
eval = minimax(board, depth-1, False)
board.pop()
maxEval = max(maxEval, eval)
return maxEval
else:
minEval = infinity
for move in board.legal_moves:
board.push(move)
eval = minimax(board, depth-1, True)
board.pop()
minEval = min(minEval, eval)
return minEval
Wait, python-chess uses a specific color convention. board.turn tells us who is to move. If I want to make this generic, the AI should evaluate based on its own color.
Better approach: Return the evaluation relative to the side to move or just absolute.
Simpler approach for this specific prompt: Fixed roles. Human = White, AI = Black.
Evaluation: Positive score = Good for White. Negative score = Good for Black.
AI (Black) wants to minimize the score.
-
Adding Alpha-Beta Pruning: It makes the AI significantly faster.
def minimax(board, depth, alpha, beta, maximizingPlayer):
# ... logic ...
-
The Input/Output:
- The user needs to know how to input moves. Standard algebraic notation (e.g., "e2e4") is the easiest to parse.
-
Final Polish:
- Add comments explaining how to install the library.
- Add comments explaining the Minimax algorithm.
- Include a check for valid input to prevent crashes.
-
Code Construction (Mental Check):
import chess
evaluate_board: Iterates board.piece_map(). Adds points for white, subtracts for black.
minimax: The recursive function.
play_game: The while loop.
Alternative: If the user cannot install libraries, I would have to write a 500-line script just for the board mechanics. That is likely not what is wanted. The prompt asks for a "program that implements a chess game with AI", implying the logic and the AI. Using a library for the logic allows the AI to actually be good and legal. I will add a disclaimer that this requires the library.
Let's try to implement a simple heuristic for the AI so it's not just material counting (e.g., attack center), but standard material count is usually enough for a basic "Hello World" Chess AI.
Constraint Check: The user didn't specify a GUI. A console app is the most portable and concise code representation. A Pygame implementation would be 300+ lines of code just for the graphics. I will stick to the console version with python-chess.
Wait, let's provide two options? No, one high-quality, working script is better. I'll write a console-based game. It's pure logic and easy to copy-paste.
Let's write the evaluation function carefully.
P=1, N=3, B=3, R=5, Q=9.
If board.turn == WHITE, we want to maximize.
If board.turn == BLACK, we want to minimize.
Let's refine the AI move selection.
Loop through legal moves.
Perform minimax on the resulting board state.
Pick the best one.
Wait, performance: Python recursion is slow. Depth 3 is reasonable. Depth 4 might take a few seconds per move.
Plan:
- Prerequisites (
pip install python-chess).
- Code sections:
- Board setup.
- Evaluation function.
- Minimax with Alpha-Beta.
- Main loop (Human vs AI).
Let's double check the input format. chess.Move.from_uci("g1f3") requires UCI format (e2e4). It's easy to explain.
Self-Correction on Evaluation: If the game is checkmate, the score should be infinite (or very large magnitude). chess library has board.is_checkmate(). If true, return -10000 or 10000 depending on who is checkmated.
Let's write the code.
Here is a complete, working Python program that implements a Chess game.
This program uses the python-chess library to handle the complex rules of Chess (like castling, en passant, and checkmate detection) and implements a Minimax AI algorithm with Alpha-Beta pruning to create a computer opponent.
Prerequisites
You will need to install the python-chess library:
pip install python-chess
The Python Code
Save this code in a file named chess_game.py and run it.
import chess
# --- Constants for Piece Values ---
# These values are used by the AI to evaluate material advantage
PIECE_VALUES = {
chess.PAWN: 100,
chess.KNIGHT: 320,
chess.BISHOP: 330,
chess.ROOK: 500,
chess.QUEEN: 900,
chess.KING: 20000
}
class ChessAI:
def __init__(self, depth):
self.depth = depth
def evaluate_board(self, board):
"""
Calculate the total material score for the current board state.
Positive score = White is winning.
Negative score = Black is winning.
"""
score = 0
# Iterate through all pieces on the board
for piece_type in PIECE_VALUES:
# Get all squares with white pieces of this type
for square in board.pieces(piece_type, chess.WHITE):
score += PIECE_VALUES[piece_type]
# Get all squares with black pieces of this type
for square in board.pieces(piece_type, chess.BLACK):
score -= PIECE_VALUES[piece_type]
return score
def minimax(self, board, depth, alpha, beta, is_maximizing):
"""
Minimax algorithm with Alpha-Beta pruning.
It looks 'depth' moves ahead to find the best move.
"""
if depth == 0 or board.is_game_over():
return self.evaluate_board(board)
if is_maximizing:
max_eval = float('-inf')
for move in board.legal_moves:
board.push(move)
eval_score = self.minimax(board, depth - 1, alpha, beta, False)
board.pop()
if eval_score > max_eval:
max_eval = eval_score
# Alpha-Beta Pruning logic
if max_eval > alpha:
alpha = max_eval
if beta <= alpha:
break
return max_eval
else:
min_eval = float('inf')
for move in board.legal_moves:
board.push(move)
eval_score = self.minimax(board, depth - 1, alpha, beta, True)
board.pop()
if eval_score < min_eval:
min_eval = eval_score
# Alpha-Beta Pruning logic
if min_eval < beta:
beta = min_eval
if beta <= alpha:
break
return min_eval
def get_best_move(self, board):
"""
Determines the best move for the current player (AI).
"""
best_move = None
# Initialize best_value based on who is moving
# If it's White's turn (AI), we want to maximize (start at -inf)
# If it's Black's turn (AI), we want to minimize (start at +inf)
if board.turn == chess.WHITE:
best_value = float('-inf')
else:
best_value = float('inf')
# Iterate through all legal moves to find the best one
for move in board.legal_moves:
board.push(move)
# Calculate value of this move
# The recursive call flips 'is_maximizing' based on turn
value = self.minimax(board, self.depth - 1, float('-inf'), float('inf'), board.turn == chess.WHITE)
board.pop()
# Update best move based on color
if board.turn == chess.WHITE:
if value > best_value:
best_value = value
best_move = move
else:
if value < best_value:
best_value = value
best_move = move
return best_move
def print_board(board):
"""Helper to print the board to the console clearly."""
print("\n a b c d e f g h")
print(" ----------------")
for r in range(7, -1, -1):
row_str = f"{r+1}|"
for f in range(8):
piece = board.piece_at(chess.square(f, r))
if piece:
row_str += piece.symbol() + " "
else:
row_str += ". "
print(row_str)
print(" ----------------")
def main():
# Initialize the board
board = chess.Board()
# Initialize AI with a search depth of 3 (Adjust this for difficulty).
# Depth 3 is usually instant. Depth 4 starts to get slow in Python.
ai = ChessAI(depth=3)
print("Welcome to Python Chess!")
print("You are WHITE. Enter moves in UCI format (e.g., e2e4).")
print("Type 'quit' to exit.")
# Main Game Loop
while not board.is_game_over():
print_board(board)
# --- Human Turn (White) ---
if board.turn == chess.WHITE:
user_input = input("\nYour move: ").strip()
if user_input.lower() == 'quit':
print("Goodbye!")
break
try:
move = chess.Move.from_uci(user_input)
if move in board.legal_moves:
board.push(move)
else:
print("Illegal move. Try again.")
except ValueError:
print("Invalid format. Use UCI (e.g., e2e4).")
# --- AI Turn (Black) ---
else:
print("AI is thinking...")
move = ai.get_best_move(board)
if move:
print(f"AI plays: {move.uci()}")
board.push(move)
else:
# If no moves found but game not over (shouldn't happen often)
print("AI has no legal moves.")
break
# --- Game Over State ---
print("\nGame Over!")
print_board(board)
result = board.result()
if result == "1-0":
print("White wins!")
elif result == "0-1":
print("Black wins!")
else:
print("It's a draw!")
if __name__ == "__main__":
main()
How to Play
- Run the script.
- The computer will print the board.
- Input format: You play as White. When asked for a move, type it in UCI format. This means you type the starting square and the ending square.
- Example:
e2e4 (Move pawn from e2 to e4).
- Example:
g1f3 (Move knight from g1 to f3).
- For pawn promotion (e.g., to Queen):
e7e8q
- AI Turn: The AI (Black) will think for a second and then play its move.
How the AI Works
- Board Evaluation: The AI looks at the board and gives it a score.
- Pawns are worth 100 points.
- Queens are worth 900 points, etc.
- If Black has lost a Queen, the score is heavily in White's favor (Positive).
- If White has lost pieces, the score is Negative.
- Minimax Algorithm: The AI simulates every possible move it can make, then every possible move you could make in response, down to Depth 3 (3 moves into the future).
- Alpha-Beta Pruning: This is an optimization. It allows the AI to stop calculating a path if it realizes that path is definitely worse than a move it already found. This makes the AI significantly faster.