Basic Alpha Beta algorithm giving wrong evaluation | Python

I was in the process of optimizing my chess engine in python when I was doing some testing on this position (engine as black) with a depth of 4:
board and everything seemed fine until I looked at the evaluations for each position. When moving the black queen from h1 to h6, it gives the position a score of 69.5 for black which is clearly wrong because white can promote on the next move.

I rewrote my alpha beta function to its most basic form, like it’s written on the chess programming wiki,

Mine:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def search(self, depth: int, whiteTurn: bool, alpha: int, beta: int, baseDepth: int) -> float:
if depth == 0:
return self.evaluate(whiteTurn)
moves = []
squares = list(self.board.keys())
# finding legal moves this turn
if whiteTurn:
for square in squares:
# check for a piece
if self.board[square] != '0' and self.board[square].isupper():
squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square)
for move, score in squareMoves:
moves.append([ch.Move.from_uci(square + move), score])
moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)]
else:
for square in squares:
if self.board[square] != '0' and self.board[square].islower():
squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square)
for move, score in squareMoves:
moves.append([ch.Move.from_uci(square + move), score])
moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)]
for move in moves:
self.pythonBoard.push(move)
fenboard = self.pythonBoard.board_fen()
self.board = fenConverter(fenboard)
evaluation = -self.search(depth - 1, not whiteTurn, -beta, -alpha, baseDepth)
if depth == DEPTH:
print(evaluation, 'n', self.pythonBoard)
self.pythonBoard.pop()
self.board = fenConverter(self.pythonBoard.board_fen())
if evaluation >= beta:
return beta
if evaluation > alpha:
if depth == DEPTH:
self.move = move
self.materialValue = evaluation
alpha = evaluation
return alpha
</code>
<code>def search(self, depth: int, whiteTurn: bool, alpha: int, beta: int, baseDepth: int) -> float: if depth == 0: return self.evaluate(whiteTurn) moves = [] squares = list(self.board.keys()) # finding legal moves this turn if whiteTurn: for square in squares: # check for a piece if self.board[square] != '0' and self.board[square].isupper(): squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square) for move, score in squareMoves: moves.append([ch.Move.from_uci(square + move), score]) moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)] else: for square in squares: if self.board[square] != '0' and self.board[square].islower(): squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square) for move, score in squareMoves: moves.append([ch.Move.from_uci(square + move), score]) moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)] for move in moves: self.pythonBoard.push(move) fenboard = self.pythonBoard.board_fen() self.board = fenConverter(fenboard) evaluation = -self.search(depth - 1, not whiteTurn, -beta, -alpha, baseDepth) if depth == DEPTH: print(evaluation, 'n', self.pythonBoard) self.pythonBoard.pop() self.board = fenConverter(self.pythonBoard.board_fen()) if evaluation >= beta: return beta if evaluation > alpha: if depth == DEPTH: self.move = move self.materialValue = evaluation alpha = evaluation return alpha </code>
def search(self, depth: int, whiteTurn: bool, alpha: int, beta: int, baseDepth: int) -> float:
        if depth == 0:
            return self.evaluate(whiteTurn)
        moves = []
        squares = list(self.board.keys())
        # finding legal moves this turn
        if whiteTurn:
            for square in squares:
                # check for a piece
                if self.board[square] != '0' and self.board[square].isupper():
                    squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square)
                    for move, score in squareMoves:
                        moves.append([ch.Move.from_uci(square + move), score])
            moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)]

        else:
            for square in squares:
                if self.board[square] != '0' and self.board[square].islower():
                    squareMoves = self.orderMoves(findLegalMoves(self.pythonBoard.legal_moves, square), square)
                    for move, score in squareMoves:
                        moves.append([ch.Move.from_uci(square + move), score])
            moves = [move[0] for move in sorted(moves, key=lambda x: x[1], reverse=True)]
        for move in moves:
            self.pythonBoard.push(move)
            fenboard = self.pythonBoard.board_fen()
            self.board = fenConverter(fenboard)
            evaluation = -self.search(depth - 1, not whiteTurn, -beta, -alpha, baseDepth)
            if depth == DEPTH:
                print(evaluation, 'n', self.pythonBoard)
            self.pythonBoard.pop()
            self.board = fenConverter(self.pythonBoard.board_fen())
            if evaluation >= beta:
                return beta
            if evaluation > alpha:
                if depth == DEPTH:
                    self.move = move
                    self.materialValue = evaluation
                alpha = evaluation
        return alpha

Their pseudocode:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>int alphaBeta( int alpha, int beta, int depthleft ) {
if( depthleft == 0 ) return quiesce( alpha, beta );
bestValue = -infinity;
for ( all moves) {
score = -alphaBeta( -beta, -alpha, depthleft - 1 );
if( score > bestValue )
{
bestValue = score;
if( score > alpha )
alpha = score; // alpha acts like max in MiniMax
}
if( score >= beta )
return bestValue; // fail soft beta-cutoff, existing the loop here is also fine
}
return bestValue;
}
</code>
<code>int alphaBeta( int alpha, int beta, int depthleft ) { if( depthleft == 0 ) return quiesce( alpha, beta ); bestValue = -infinity; for ( all moves) { score = -alphaBeta( -beta, -alpha, depthleft - 1 ); if( score > bestValue ) { bestValue = score; if( score > alpha ) alpha = score; // alpha acts like max in MiniMax } if( score >= beta ) return bestValue; // fail soft beta-cutoff, existing the loop here is also fine } return bestValue; } </code>
int alphaBeta( int alpha, int beta, int depthleft ) {
   if( depthleft == 0 ) return quiesce( alpha, beta );
   bestValue = -infinity;
   for ( all moves)  {
      score = -alphaBeta( -beta, -alpha, depthleft - 1 );
      if( score > bestValue )
      {
         bestValue = score;
         if( score > alpha )
            alpha = score; // alpha acts like max in MiniMax
      }
      if( score >= beta )
         return bestValue;   //  fail soft beta-cutoff, existing the loop here is also fine
   }
   return bestValue;
}

with this evaluation function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>def evaluate(self, isWhite: bool) -> float:
"""
evaluate evaluates the position
"""
materialValue = 0
squares = list(self.board.keys())
if self.pythonBoard.is_stalemate():
return 0
if self.pythonBoard.outcome() != None:
if self.pythonBoard.is_checkmate():
return float('-inf')
for square in squares:
# if there's a piece on the square
if self.board[square] != '0':
name = self.board[square]
color = findColor(name)
moves = set()
piece = Piece(name, color, 0, moves)
if color == 'black':
if name == 'p':
vMap = pawnMap(square)
elif name == 'n':
vMap = knightMap(square)
elif name == 'b':
vMap = bishopMap(square)
elif name == 'q':
vMap = queenMap(square)
elif name == 'k':
if ((self.whitePieceCount['Q'] == 0 and self.whitePieceCount['R'] <= 1 and self.whitePieceCount['B'] + self.whitePieceCount['N'] <= 2) or
(self.whitePieceCount['B'] + self.whitePieceCount['N'] + self.whitePieceCount['R'] <= 2 and self.whitePieceCount['R'] <= 1)):
vMap = lateKingMap(square)
else:
vMap = earlyKingMap(square)
else:
vMap = rookMap(square)
materialValue += vMap.mapValue()
if color == 'white':
row = int(square[1])
newRow = str(9 - row)
square = square[0] + newRow
if name == 'P':
vMap = pawnMap(square)
elif name == 'N':
vMap = knightMap(square)
elif name == 'B':
vMap = bishopMap(square)
elif name == 'Q':
vMap = queenMap(square)
elif name == 'K':
if ((self.blackPieceCount['q'] == 0 and self.blackPieceCount['r'] <= 1 and self.blackPieceCount['b'] + self.blackPieceCount['n'] <= 2) or
(self.blackPieceCount['b'] + self.blackPieceCount['n'] + self.blackPieceCount['r'] <= 2 and self.blackPieceCount['r'] <= 1)):
vMap = lateKingMap(square)
else:
vMap = earlyKingMap(square)
else:
vMap = rookMap(square)
materialValue += -vMap.mapValue()
materialValue += piece.value * 10
if isWhite:
# materialValue += self.endGameEval(self.blackPieces, isWhite)
return materialValue
else:
# materialValue -= self.endGameEval(self.whitePieces, isWhite)
return -materialValue
</code>
<code>def evaluate(self, isWhite: bool) -> float: """ evaluate evaluates the position """ materialValue = 0 squares = list(self.board.keys()) if self.pythonBoard.is_stalemate(): return 0 if self.pythonBoard.outcome() != None: if self.pythonBoard.is_checkmate(): return float('-inf') for square in squares: # if there's a piece on the square if self.board[square] != '0': name = self.board[square] color = findColor(name) moves = set() piece = Piece(name, color, 0, moves) if color == 'black': if name == 'p': vMap = pawnMap(square) elif name == 'n': vMap = knightMap(square) elif name == 'b': vMap = bishopMap(square) elif name == 'q': vMap = queenMap(square) elif name == 'k': if ((self.whitePieceCount['Q'] == 0 and self.whitePieceCount['R'] <= 1 and self.whitePieceCount['B'] + self.whitePieceCount['N'] <= 2) or (self.whitePieceCount['B'] + self.whitePieceCount['N'] + self.whitePieceCount['R'] <= 2 and self.whitePieceCount['R'] <= 1)): vMap = lateKingMap(square) else: vMap = earlyKingMap(square) else: vMap = rookMap(square) materialValue += vMap.mapValue() if color == 'white': row = int(square[1]) newRow = str(9 - row) square = square[0] + newRow if name == 'P': vMap = pawnMap(square) elif name == 'N': vMap = knightMap(square) elif name == 'B': vMap = bishopMap(square) elif name == 'Q': vMap = queenMap(square) elif name == 'K': if ((self.blackPieceCount['q'] == 0 and self.blackPieceCount['r'] <= 1 and self.blackPieceCount['b'] + self.blackPieceCount['n'] <= 2) or (self.blackPieceCount['b'] + self.blackPieceCount['n'] + self.blackPieceCount['r'] <= 2 and self.blackPieceCount['r'] <= 1)): vMap = lateKingMap(square) else: vMap = earlyKingMap(square) else: vMap = rookMap(square) materialValue += -vMap.mapValue() materialValue += piece.value * 10 if isWhite: # materialValue += self.endGameEval(self.blackPieces, isWhite) return materialValue else: # materialValue -= self.endGameEval(self.whitePieces, isWhite) return -materialValue </code>
def evaluate(self, isWhite: bool) -> float:
        """
        evaluate evaluates the position
        """
        materialValue = 0
        squares = list(self.board.keys())
        if self.pythonBoard.is_stalemate():
            return 0
        if self.pythonBoard.outcome() != None:
            if self.pythonBoard.is_checkmate():
                return float('-inf')

        for square in squares:
            # if there's a piece on the square
            if self.board[square] != '0':
                name = self.board[square]
                color = findColor(name)
                moves = set()
                piece = Piece(name, color, 0, moves)
                if color == 'black':
                    if name == 'p':
                        vMap = pawnMap(square)
                    elif name == 'n':
                        vMap = knightMap(square)
                    elif name == 'b':
                        vMap = bishopMap(square)
                    elif name == 'q':
                        vMap = queenMap(square)
                    elif name == 'k':
                        if ((self.whitePieceCount['Q'] == 0 and self.whitePieceCount['R'] <= 1 and self.whitePieceCount['B'] + self.whitePieceCount['N'] <= 2) or
                            (self.whitePieceCount['B'] + self.whitePieceCount['N'] + self.whitePieceCount['R'] <= 2 and self.whitePieceCount['R'] <= 1)):
                            vMap = lateKingMap(square)
                        else:
                            vMap = earlyKingMap(square)
                    else:
                        vMap = rookMap(square)
                    materialValue += vMap.mapValue()
                if color == 'white':
                    row = int(square[1])
                    newRow = str(9 - row)
                    square = square[0] + newRow
                    if name == 'P':
                        vMap = pawnMap(square)
                    elif name == 'N':
                        vMap = knightMap(square)
                    elif name == 'B':
                        vMap = bishopMap(square)
                    elif name == 'Q':
                        vMap = queenMap(square)
                    elif name == 'K':
                        if ((self.blackPieceCount['q'] == 0 and self.blackPieceCount['r'] <= 1 and self.blackPieceCount['b'] + self.blackPieceCount['n'] <= 2) or
                            (self.blackPieceCount['b'] + self.blackPieceCount['n'] + self.blackPieceCount['r'] <= 2 and self.blackPieceCount['r'] <= 1)):
                            vMap = lateKingMap(square)
                        else:
                            vMap = earlyKingMap(square)
                    else:
                        vMap = rookMap(square)
                    materialValue += -vMap.mapValue()
                materialValue += piece.value * 10
        if isWhite:
            # materialValue += self.endGameEval(self.blackPieces, isWhite)
            return materialValue
        else:
            # materialValue -= self.endGameEval(self.whitePieces, isWhite)
            return -materialValue

Black’s piece values are negative and white’s are positive, so that’s why I return -materialValue for black. In all positions I tested with depth 1 to see if the evaluate function was wrong, it seemed to be working. All the values it gave were expected. I’m unsure how that could be the problem, but then the function I basically copied from the chess programming wiki didn’t work.

Otherwise, the move ordering is fine (shouldn’t affect the evaluation either way) and it finds all possible moves correctly.

New contributor

Victor Terme is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật