Certainly! Below is a simple chess engine written in Python. This engine implements basic move generation, a simple evaluation function, and a minimax algorithm with alpha-beta pruning for decision-making. This is a very basic engine and won't compete with advanced chess engines, but it demonstrates the core concepts.
import copy
# Define the chess board as an 8x8 list
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"]
]
# Piece values for evaluation
piece_values = {"P": 1, "N": 3, "B": 3, "R": 5, "Q": 9, "K": 1000}
def print_board(board):
for row in board:
print(" ".join(row))
print("\n")
def is_in_bounds(x, y):
return 0 <= x < 8 and 0 <= y < 8
def generate_moves(board, color):
moves = []
for i in range(8):
for j in range(8):
piece = board[i][j]
if piece and piece[0] == color:
if piece == "P": # Pawn moves
moves.extend(generate_pawn_moves(board, i, j, color))
elif piece == "N": # Knight moves
moves.extend(generate_knight_moves(board, i, j, color))
elif piece == "B": # Bishop moves
moves.extend(generate_bishop_moves(board, i, j, color))
elif piece == "R": # Rook moves
moves.extend(generate_rook_moves(board, i, j, color))
elif piece == "Q": # Queen moves
moves.extend(generate_queen_moves(board, i, j, color))
elif piece == "K": # King moves
moves.extend(generate_king_moves(board, i, j, color))
return moves
def generate_pawn_moves(board, x, y, color):
moves = []
direction = -1 if color == "W" else 1
# Move one square forward
if is_in_bounds(x + direction, y) and board[x + direction][y] == "":
moves.append(((x, y), (x + direction, y)))
# Move two squares forward from starting position
if ((color == "W" and x == 6) or (color == "B" and x == 1)) and board[x + 2 * direction][y] == "":
moves.append(((x, y), (x + 2 * direction, y)))
# Capture diagonally
for dy in [-1, 1]:
if is_in_bounds(x + direction, y + dy) and board[x + direction][y + dy] and board[x + direction][y + dy][0] != color:
moves.append(((x, y), (x + direction, y + dy)))
return moves
def generate_knight_moves(board, x, y, color):
moves = []
knight_moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
for dx, dy in knight_moves:
nx, ny = x + dx, y + dy
if is_in_bounds(nx, ny) and (board[nx][ny] == "" or board[nx][ny][0] != color):
moves.append(((x, y), (nx, ny)))
return moves
def generate_bishop_moves(board, x, y, color):
moves = []
directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
while is_in_bounds(nx, ny):
if board[nx][ny] == "":
moves.append(((x, y), (nx, ny)))
elif board[nx][ny][0] != color:
moves.append(((x, y), (nx, ny)))
break
else:
break
nx, ny = nx + dx, ny + dy
return moves
def generate_rook_moves(board, x, y, color):
moves = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
while is_in_bounds(nx, ny):
if board[nx][ny] == "":
moves.append(((x, y), (nx, ny)))
elif board[nx][ny][0] != color:
moves.append(((x, y), (nx, ny)))
break
else:
break
nx, ny = nx + dx, ny + dy
return moves
def generate_queen_moves(board, x, y, color):
return generate_bishop_moves(board, x, y, color) + generate_rook_moves(board, x, y, color)
def generate_king_moves(board, x, y, color):
moves = []
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
if is_in_bounds(nx, ny) and (board[nx][ny] == "" or board[nx][ny][0] != color):
moves.append(((x, y), (nx, ny)))
return moves
def make_move(board, move):
new_board = copy.deepcopy(board)
(x1, y1), (x2, y2) = move
new_board[x2][y2] = new_board[x1][y1]
new_board[x1][y1] = ""
return new_board
def evaluate_board(board):
score = 0
for i in range(8):
for j in range(8):
piece = board[i][j]
if piece:
value = piece_values.get(piece.upper(), 0)
score += value if piece.isupper() else -value
return score
def minimax(board, depth, alpha, beta, maximizing_player):
if depth == 0 or is_game_over(board):
return evaluate_board(board)
if maximizing_player:
max_eval = float("-inf")
for move in generate_moves(board, "W"):
new_board = make_move(board, move)
eval = minimax(new_board, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = float("inf")
for move in generate_moves(board, "B"):
new_board = make_move(board, move)
eval = minimax(new_board, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval
def is_game_over(board):
# This is a placeholder. A real engine would check for checkmate, stalemate, etc.
return False
def find_best_move(board, depth):
best_move = None
best_value = float("-inf") if "W" else float("inf")
alpha = float("-inf")
beta = float("inf")
for move in generate_moves(board, "W" if "W" else "B"):
new_board = make_move(board, move)
move_value = minimax(new_board, depth - 1, alpha, beta, not ("W" if "W" else "B"))
if ("W" if "W" else "B"):
if move_value > best_value:
best_value = move_value
best_move = move
alpha = max(alpha, best_value)
else:
if move_value < best_value:
best_value = move_value
best_move = move
beta = min(beta, best_value)
if beta <= alpha:
break
return best_move
# Example usage
print("Initial Board:")
print_board(board)
best_move = find_best_move(board, 3)
print(f"Best Move: {best_move}")
new_board = make_move(board, best_move)
print("Board after best move:")
print_board(new_board)
Explanation:
-
Board Representation:
- The board is represented as an 8x8 list of lists.
- Pieces are represented by their initials. Uppercase for white and lowercase for black.
-
Move Generation:
generate_moves calls specific functions to generate moves for each type of piece.
- Each piece type (
P, N, B, R, Q, K) has its own move generation function.
-
Making Moves:
make_move creates a copy of the board and applies the move.
-
Board Evaluation:
evaluate_board calculates a score based on material. Positive scores favour white; negative scores favour black.
-
Minimax with Alpha-Beta Pruning:
minimax recursively evaluates moves to a given depth, using alpha-beta pruning to improve efficiency.
-
Finding the Best Move:
find_best_move uses the minimax function to find the best move for the current player.
Notes:
- Depth: The depth parameter in
find_best_move determines how many moves ahead the engine will look. A higher depth takes more computation time.
- Game Over Check: The
is_game_over function is a placeholder. A complete engine would need to check for checkmate, stalemate, insufficient material, etc.
- Performance: This engine is very basic and not optimised for performance. Advanced engines use techniques like transposition tables, quiescence search, and more sophisticated evaluation functions.
To test the engine, you can run the script. It will print the initial board, calculate the best move for white at a depth of 3, and print the board after making that move.