I'll create a simple chess engine in Python. This will be a basic implementation that includes move generation, evaluation, and a minimax search with alpha-beta pruning. Note that this won't be a strong engine (it won't compete with Stockfish!), but it will be able to play legal chess.
import copy
# Constants
WHITE = 1
BLACK = -1
EMPTY = 0
# Piece values
PAWN_VALUE = 100
KNIGHT_VALUE = 300
BISHOP_VALUE = 310
ROOK_VALUE = 500
QUEEN_VALUE = 900
KING_VALUE = 10000
# Piece representations
piece_symbols = {
0: '.',
1: 'P', -1: 'p', # Pawns
2: 'N', -2: 'n', # Knights
3: 'B', -3: 'b', # Bishops
4: 'R', -4: 'r', # Rooks
5: 'Q', -5: 'q', # Queens
6: 'K', -6: 'k' # Kings
}
class ChessBoard:
def __init__(self):
self.board = self.initial_board()
self.turn = WHITE
self.castling_rights = {'K': True, 'Q': True, 'k': True, 'q': True}
self.en_passant = None
self.halfmove_clock = 0
self.fullmove_number = 1
def initial_board(self):
# Create initial chess position
board = [[0 for _ in range(8)] for _ in range(8)]
# Place pawns
for i in range(8):
board[1][i] = -1 # Black pawns
board[6][i] = 1 # White pawns
# Place pieces
back_rank = [4, 2, 3, 5, 6, 3, 2, 4] # r n b q k b n r
for i in range(8):
board[0][i] = -back_rank[i] # Black pieces
board[7][i] = back_rank[i] # White pieces
return board
def print_board(self):
print(' a b c d e f g h')
for i in range(8):
print(f'{8-i} ', end='')
for j in range(8):
print(piece_symbols[self.board[i][j]], end=' ')
print(f'{8-i}')
print(' a b c d e f g h')
def get_legal_moves(self):
moves = []
for r in range(8):
for c in range(8):
piece = self.board[r][c]
if piece != 0 and self.get_color(piece) == self.turn:
moves.extend(self.get_piece_moves(r, c, piece))
return moves
def get_color(self, piece):
return WHITE if piece > 0 else BLACK
def get_piece_moves(self, r, c, piece):
moves = []
piece_type = abs(piece)
if piece_type == 1: # Pawn
moves.extend(self.get_pawn_moves(r, c))
elif piece_type == 2: # Knight
moves.extend(self.get_knight_moves(r, c))
elif piece_type == 3: # Bishop
moves.extend(self.get_bishop_moves(r, c))
elif piece_type == 4: # Rook
moves.extend(self.get_rook_moves(r, c))
elif piece_type == 5: # Queen
moves.extend(self.get_bishop_moves(r, c))
moves.extend(self.get_rook_moves(r, c))
elif piece_type == 6: # King
moves.extend(self.get_king_moves(r, c))
return moves
def get_pawn_moves(self, r, c):
moves = []
direction = -1 if self.turn == WHITE else 1
start_rank = 6 if self.turn == WHITE else 1
# One square forward
if self.is_valid_square(r + direction, c) and self.board[r + direction][c] == 0:
moves.append(((r, c), (r + direction, c)))
# Two squares forward from starting position
if r == start_rank and self.board[r + 2*direction][c] == 0:
moves.append(((r, c), (r + 2*direction, c)))
# Captures
for dc in [-1, 1]:
if self.is_valid_square(r + direction, c + dc):
target = self.board[r + direction][c + dc]
if target != 0 and self.get_color(target) != self.turn:
moves.append(((r, c), (r + direction, c + dc)))
# En passant
if (r + direction, c + dc) == self.en_passant:
moves.append(((r, c), (r + direction, c + dc)))
return moves
def get_knight_moves(self, r, c):
moves = []
knight_moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1)]
for dr, dc in knight_moves:
if self.is_valid_move(r, c, r + dr, c + dc):
moves.append(((r, c), (r + dr, c + dc)))
return moves
def get_bishop_moves(self, r, c):
moves = []
directions = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for dr, dc in directions:
moves.extend(self.get_sliding_moves(r, c, dr, dc))
return moves
def get_rook_moves(self, r, c):
moves = []
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dr, dc in directions:
moves.extend(self.get_sliding_moves(r, c, dr, dc))
return moves
def get_king_moves(self, r, c):
moves = []
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
if self.is_valid_move(r, c, r + dr, c + dc):
moves.append(((r, c), (r + dr, c + dc)))
return moves
def get_sliding_moves(self, r, c, dr, dc):
moves = []
nr, nc = r + dr, c + dc
while self.is_valid_square(nr, nc):
if self.board[nr][nc] == 0:
moves.append(((r, c), (nr, nc)))
elif self.get_color(self.board[nr][nc]) != self.turn:
moves.append(((r, c), (nr, nc)))
break
else:
break
nr, nc = nr + dr, nc + dc
return moves
def is_valid_square(self, r, c):
return 0 <= r < 8 and 0 <= c < 8
def is_valid_move(self, fr, fc, tr, tc):
if not self.is_valid_square(tr, tc):
return False
target = self.board[tr][tc]
if target == 0:
return True
return self.get_color(target) != self.turn
def make_move(self, move):
(fr, fc), (tr, tc) = move
piece = self.board[fr][fc]
# Handle en passant
if abs(piece) == 1 and (tr, tc) == self.en_passant:
capture_rank = tr + (1 if self.turn == WHITE else -1)
self.board[capture_rank][tc] = 0
# Move piece
self.board[tr][tc] = piece
self.board[fr][fc] = 0
# Handle pawn promotion (auto-queen for simplicity)
if abs(piece) == 1 and (tr == 0 or tr == 7):
self.board[tr][tc] = 5 * self.turn
# Update en passant square
self.en_passant = None
if abs(piece) == 1 and abs(tr - fr) == 2:
self.en_passant = (fr + (tr - fr)//2, fc)
self.turn = -self.turn
def evaluate(self):
score = 0
for r in range(8):
for c in range(8):
piece = self.board[r][c]
if piece != 0:
value = self.get_piece_value(abs(piece))
score += value if piece > 0 else -value
return score
def get_piece_value(self, piece_type):
values = {
1: PAWN_VALUE,
2: KNIGHT_VALUE,
3: BISHOP_VALUE,
4: ROOK_VALUE,
5: QUEEN_VALUE,
6: KING_VALUE
}
return values[piece_type]
class ChessEngine:
def __init__(self, depth=3):
self.depth = depth
def find_best_move(self, board):
best_move = None
best_value = float('-inf') if board.turn == WHITE else float('inf')
for move in board.get_legal_moves():
new_board = copy.deepcopy(board)
new_board.make_move(move)
value = self.minimax(new_board, self.depth - 1, float('-inf'), float('inf'), board.turn == BLACK)
if board.turn == 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 minimax(self, board, depth, alpha, beta, maximizing):
if depth == 0:
return board.evaluate()
if maximizing:
max_eval = float('-inf')
for move in board.get_legal_moves():
new_board = copy.deepcopy(board)
new_board.make_move(move)
eval = self.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 board.get_legal_moves():
new_board = copy.deepcopy(board)
new_board.make_move(move)
eval = self.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 main():
board = ChessBoard()
engine = ChessEngine(depth=3)
while True:
board.print_board()
if board.turn == WHITE:
# Human move
move = input("Enter your move (e.g., e2e4): ")
if len(move) != 4:
print("Invalid move format. Use algebraic notation (e.g., e2e4)")
continue
fr = (8 - int(move[1]), ord(move[0]) - ord('a'))
to = (8 - int(move[3]), ord(move[2]) - ord('a'))
move = (fr, to)
legal_moves = board.get_legal_moves()
if move not in legal_moves:
print("Illegal move!")
continue
board.make_move(move)
else:
# Engine move
print("Engine is thinking...")
move = engine.find_best_move(board)
if move:
(fr, fc), (tr, tc) = move
move_str = f"{chr(fc + ord('a'))}{8-fr}{chr(tc + ord('a'))}{8-tr}"
print(f"Engine move: {move_str}")
board.make_move(move)
else:
print("Game over!")
break
if __name__ == "__main__":
main()
This chess engine includes:
-
A ChessBoard class that handles:
- Board representation
- Move generation for all pieces
- Move execution
- Basic position evaluation
- Legal move checking
-
A ChessEngine class that implements:
- Minimax search with alpha-beta pruning
- Basic position evaluation based on material
-
A main game loop that allows:
- Human vs. Engine play
- Move input in algebraic notation (e.g., "e2e4")
- Basic visualization of the board
To use the engine:
- Run the script
- Enter moves in algebraic notation (e.g., "e2e4")
- The engine will respond with its move
Limitations of this implementation:
- It's relatively slow due to Python and the simple implementation
- The evaluation function is very basic (only considers material)
- It doesn't handle checkmate or stalemate detection
- It doesn't implement castling
- It auto-promotes pawns to queens
- The search depth is limited to make it playable
To make this engine stronger, you could:
- Add more sophisticated evaluation (piece-square tables, king safety, pawn structure, etc.)
- Implement move ordering to improve alpha-beta pruning
- Add quiescence search
- Implement transposition tables
- Add opening book support
- Implement proper endgame handling
- Add time management
- Port to a faster language like C++
This is a basic but functional chess engine that can play legal chess, though it won't play very strongly due to its simple evaluation and limited search depth.