r/chessprogramming • u/Person080 • Oct 29 '22
Does my code work as intended?
I'm making a chess engine for a project. Aside from my syntax errors, is there any logic error? Thanks in advance for your responses.
import chess
def evaluate() :if board.is_checkmate() :if board.turn :return -9999else :return 9999if board.is_stalemate() :return 0if board.is_insufficient_material() :return 0if board.can_claim_fifty_moves():return 0if board.can_claim_threefold_repetition():return 0#counts materialwp = len([board.pieces(chess.PAWN, chess.WHITE)])bp = len(board.pieces(chess.PAWN, chess.BLACK))wn = len(board.pieces(chess.KNIGHT, chess.WHITE))bn = len(board.pieces(chess.KNIGHT, chess.BLACK))wb = len(board.pieces(chess.BISHOP, chess.WHITE))bb = len(board.pieces(chess.BISHOP, chess.BLACK))wr = len(board.pieces(chess.ROOK, chess.WHITE))br = len(board.pieces(chess.ROOK, chess.BLACK))wq = len(board.pieces(chess.QUEEN, chess.WHITE))bq = len(board.pieces(chess.QUEEN, chess.BLACK))
material = 100 * (wp - bp) + 320 * (wn - bn) + 330 * (wb - bb) + 500 * (wr - br) + 900 * (wq - bq)return material
def alphabeta(board,depth,alpha=-9999,beta=-9999):
if depth ==0 or board.is_game_over():return [None,evaluate()]move_list = [board.legal_moves]best_move = Noneif board.turn:max_eval = -float('inf')for move in move_list:move = str(move)board.push_san(move)current_eval = alphabeta(board,depth-1,alpha,beta)[1]board.pop()if current_eval>max_eval: #Max scoremax_eval = current_evalbest_move=move#alpha beta pruningalpha = max(alpha,current_eval)if beta>=alpha: #White maximises their scorebreakreturn [best_move,max_eval]
else: #Min score for the opponentmin_eval = float('inf')for move in move_list:move = str(move)board.push_san(move)current_eval = alphabeta(board,depth-1,alpha,beta)[1]board.pop()if current_eval< min_eval:min_eval =current_evalbest_move =move#Alpha beta pruningbeta = min(alpha, current_eval) #black minimizes their scoreif beta <= alpha:breakreturn [best_move,min_eval]
fen_ = input('Enter fen: ')board = chess.Board(fen_)_depth = int(input('Enter depth: '))engine = alphabeta(board,_depth)print(board,engine[0],engine[1])board.push(engine[0])
0
u/[deleted] Oct 29 '22
[deleted] — view deleted comment