def get_uci_move(self, action, player): source = action // (self.n * self.n) target = action % (self.n * self.n) if player == -1: return chess.Move(chess.square_mirror(source), chess.square_mirror(target)) return chess.Move(source, target)
def mirror_move(move): """ mirrors the passed chess move :param move: chess move object :return: mirrored move """ start_square = chess.square_mirror(move.from_square) end_square = chess.square_mirror(move.to_square) return chess.Move(start_square, end_square, move.promotion, move.drop)
def __init__(self, path): ft = self.ft = fasttext.load_model(path) vectors = (ft.get_output_matrix() @ ft.get_input_matrix().T).T rows, _cols = vectors.shape # Add counts and evals vectors = np.hstack([np.ones(rows).reshape(rows, 1), vectors]) # maybe its an occ model? self.occ = False # Start with bias. No bias for eval. bias = np.hstack([[0], vectors[0]]) # Parse remaining words piece_to_vec = defaultdict(lambda: 0) castling = {} for w, v in zip(ft.words[1:], vectors[1:]): sq = getattr(chess, w[:2].upper()) if w.endswith('-Occ'): self.occ = True for color in chess.COLORS: for piece_type in chess.PIECE_TYPES: piece_to_vec[piece_type, color, sq] += np.hstack([[0], v]) elif w.endswith('-C'): e = pst.castling[sq] castling[sq] = np.hstack([[e], v]) else: p = chess.Piece.from_symbol(w[2]) e = pst.piece[p.piece_type - 1] * (1 if p.color else -1) e += pst.pst[0 if p.color else 1][p.piece_type - 1][sq] #print(w[2], p, e) piece_to_vec[p.piece_type, p.color, sq] += np.hstack([[e], v]) # Convert to two-colours # We keep a record of the board from both perspectives piece_to_vec2 = {} for (piece_type, color, sq), v in piece_to_vec.items(): inv = piece_to_vec[piece_type, not color, chess.square_mirror(sq)] piece_to_vec2[piece_type, color, sq] = np.vstack([v, inv]) self.bias = np.vstack([bias, bias]) self.piece_to_vec = piece_to_vec2 self.castling = { sq: np.vstack([v, castling[chess.square_mirror(sq)]]) for sq, v in castling.items() } # Parse labels self.moves = [ chess.Move.from_uci(label_uci[len('__label__'):]) for label_uci in ft.labels ] # Adding 2 to the move ids, since the first entry will be the count, # and the second entry will be the evaluation self.move_to_id = {move: i + 2 for i, move in enumerate(self.moves)}
def prepare_example(board, move, score): if board.turn == chess.WHITE: vec_board = board_to_vec(board) vec_move = move.from_square + move.to_square * 64 else: vec_board = board_to_vec(board.mirror()) vec_move = chess.square_mirror( move.from_square) + chess.square_mirror(move.to_square) * 64 #print(score, pscore(score)) return vec_board, vec_move, pscore(score)
def mirror_move(move: chess.Move): """ Mirrors a move given as python chess notation :param move: Move object :return: Mirrored move """ from_square = chess.square_mirror(move.from_square) to_square = chess.square_mirror(move.to_square) return chess.Move(from_square, to_square, move.promotion, move.drop)
def init_board_value(board): ''' Evaluates value of the starting board using piece squares tables and weights assigned to each piece type ''' global board_value # First, calculate total material on board white_pawns = len(board.pieces(chess.PAWN, chess.WHITE)) # Number of white pawns on board black_pawns = len(board.pieces(chess.PAWN, chess.BLACK)) white_knights = len(board.pieces(chess.KNIGHT, chess.WHITE)) black_knights = len(board.pieces(chess.KNIGHT, chess.BLACK)) white_bishops = len(board.pieces(chess.BISHOP, chess.WHITE)) black_bishops = len(board.pieces(chess.BISHOP, chess.BLACK)) white_rooks = len(board.pieces(chess.ROOK, chess.WHITE)) black_rooks = len(board.pieces(chess.ROOK, chess.BLACK)) white_queen = len(board.pieces(chess.QUEEN, chess.WHITE)) black_queen = len(board.pieces(chess.QUEEN, chess.BLACK)) white_king = len(board.pieces(chess.KING, chess.WHITE)) black_king = len(board.pieces(chess.KING, chess.BLACK)) # Calc material value using weights given here: https://www.chessprogramming.org/Simplified_Evaluation_Function total_material = (100*(white_pawns - black_pawns) + 320*(white_knights - black_knights) + 330*(white_bishops - black_bishops) + 500*(white_rooks - black_rooks) + 900*(white_queen - black_queen)) # Calculate the positional values of the pieces using piece-square tables pawn_table = pst.pawn_ps knight_table = pst.knight_ps bishop_table = pst.bishop_ps rook_table = pst.rook_ps queen_table = pst.queen_ps pawn_pos_val = (sum(pawn_table[i] for i in board.pieces(chess.PAWN, chess.WHITE)) + sum(-pawn_table[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK))) knight_pos_val = (sum(knight_table[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)) + sum(-knight_table[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK))) bishop_pos_val = (sum(bishop_table[i] for i in board.pieces(chess.BISHOP, chess.WHITE)) + sum(-bishop_table[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK))) rook_pos_val = (sum(rook_table[i] for i in board.pieces(chess.ROOK, chess.WHITE)) + sum(-rook_table[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK))) queen_pos_val = (sum(queen_table[i] for i in board.pieces(chess.QUEEN, chess.WHITE)) + sum(-queen_table[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK))) board_value = (total_material + pawn_pos_val + knight_pos_val + bishop_pos_val + rook_pos_val + queen_pos_val) return board_value
def squares_to_numbers(move, mirror=True): '''converts a move in uci form (i.e. a1b1) to its squares returns two ints in the above case 0, 1 can be mirrored, which will return 56, 57''' first_square = str(move)[0:2].upper() second_square = str(move)[2:4].upper() first_square_num = getattr(chess, first_square) second_square_num = getattr(chess, second_square) if mirror is True: first_square_num = chess.square_mirror(first_square_num) second_square_num = chess.square_mirror(second_square_num) return (first_square_num, second_square_num)
def FEN_to_one_hot(FEN, min_move_number=None, max_move_number=None): """ Creates a one hot encoded flat array for a given chess board. :param FEN: The representation of chess board. :param min_move_number: Return None if board has not reached this move number. :param max_move_number: Return None if board has exceeded this move number. :return: a one hot encoded flat array for a given chess board. """ # Default values for min/max move number if not given: if min_move_number is None: min_move_number = -1 if max_move_number is None: max_move_number = 500 board = chess.Board(FEN) white_turn = board.turn base_board = chess.BaseBoard(board.board_fen()) if board.fullmove_number < min_move_number or board.fullmove_number > max_move_number: return None, None, None # Mirror board if blacks turn. # This avoids the problem of "white-to-play" vs. "black-to-play" when training. if not board.turn: board = board.mirror() base_board = base_board.mirror() # Create one hot encoded board: attack_matrix = np.zeros(64) pieces = [] for pos in chess.SQUARES: white_attack = base_board.is_attacked_by(chess.WHITE, pos) black_attack = base_board.is_attacked_by(chess.BLACK, pos) # No attackers = 0, white attack = 1, black attack = 2, both = 3 if white_attack: attack_matrix[chess.square_mirror(pos)] += 1 if black_attack: attack_matrix[chess.square_mirror(pos)] += 2 pieces.extend(piece_dict[str(board.piece_at(pos))]) pieces = np.asarray(pieces) # pieces = np.reshape(pieces, (-1, 96)) # attack_matrix = np.reshape(attack_matrix, (-1, 8)) return pieces, attack_matrix, white_turn
def evaluate_position_i(game_data): board = game_data.board if board.is_checkmate(): print("Checkmate detected") return -MATE if board.turn == chess.WHITE else MATE if board.is_stalemate(): return 0 total = 0 for piece in PIECES: # print(piece) pieces_white = board.pieces(piece, chess.WHITE) pieces_black = board.pieces(piece, chess.BLACK) count_white = len(pieces_white) count_black = len(pieces_black) material = (count_white - count_black) * PIECE_VALUES[piece] table = PIECE_POS_VALUES_MG[piece] pos_white = sum([table[i] for i in pieces_white]) pos_black = sum([table[chess.square_mirror(i)] for i in pieces_black]) positional = pos_white - pos_black # print(f"pos_white {pos_white}") # print(f"pos_black {pos_black}") # print(f"material {material}") # print(f"positional {positional}") total += material + positional # print(f"total: {total}") return total
def evaluate(board, colorAI): pieceSumAI = 0 pieceSumPlayer = 0 if (board.is_checkmate()): txt = board.result().split("-") if (txt[0] == colorAI): return 1000000 else: return -100000 for piece in pieceValue: aiPieces = board.pieces(piece, colorAI) testeA = 0 for p in aiPieces: testeA += pieceValue[piece] + applyOnTable(board, piece, colorAI, chess.square_mirror(p)) pieceSumAI += testeA playerPieces = board.pieces(piece, not colorAI) testeB = 0 for p in playerPieces: testeB += -pieceValue[piece] + applyOnTable( board, piece, not colorAI, p) pieceSumPlayer += testeB return pieceSumAI + pieceSumPlayer
def find_move(self, board, debug=False): # Should we flip the board to make sure it always gets it from white? vec_board = board_to_vec(board if board.turn == chess.WHITE else board.mirror()) vec_board = tensor_sketch(vec_board, self.sketches) probs = self.move_clf.predict_proba([vec_board])[0] score = self.score_clf.predict([vec_board])[0] for n, (mp, from_to) in enumerate( sorted((-p, ft) for ft, p in enumerate(probs))): to_square, from_square = divmod(from_to, 64) if board.turn == chess.BLACK: from_square = chess.square_mirror(from_square) to_square = chess.square_mirror(to_square) move = chess.Move(from_square, to_square) if move in board.legal_moves: print(f'Choice move {n}, p={-mp}') return move, score
def eval_fn(self, board): res = 0 for p in chess.PIECE_TYPES: for wp in board.pieces(p, chess.WHITE): res += self.get_weigth_piece(chess.piece_symbol(p), wp) for bp in board.pieces(p, chess.BLACK): res -= self.get_weigth_piece(chess.piece_symbol(p), chess.square_mirror(bp)) return res
def psq_individual(pos, piece): global psq_table symbol = piece.piece_type if piece.color == chess.BLACK: return psq_table[symbol][pos] return psq_table[symbol][chess.square_mirror(pos)]
def testSquareOf(self): for i, w in enumerate(self.boardWidget.cellWidgets()): self.assertEqual(self.boardWidget.squareOf(w), chess.square_mirror(i)) self.boardWidget.flip() for i, w in enumerate(self.boardWidget.cellWidgets()): self.assertEqual( self.boardWidget.squareOf(w), chess.square(7 - chess.square_file(i), chess.square_rank(i)))
def testCellIndexOfSquare(self): for i in range(64): self.assertEqual(self.boardWidget.cellIndexOfSquare(i), chess.square_mirror(i)) self.boardWidget.flipped = True for i in range(64): self.assertEqual( self.boardWidget.cellIndexOfSquare(i), chess.square(7 - chess.square_file(i), chess.square_rank(i)))
def get_piece_value(piece, square, is_white): square = square if is_white else chess.square_mirror(square) y = chess.square_rank(square) x = chess.square_file(square) piece_val = PIECE_VALUES[piece.piece_type] pos = (y * 8) + x piece_pos_val = PIECE_POS_VALUES_MG[piece.piece_type][pos] sign = 1 if is_white else -1 return sign * (piece_val + piece_pos_val)
def testCellWidgetAtSquare(self): for i, w in enumerate(self.boardWidget.cellWidgets()): self.assertIs( w, self.boardWidget.cellWidgetAtSquare(chess.square_mirror(i))) self.boardWidget.flip() for i, w in enumerate(self.boardWidget.cellWidgets()): self.assertIs( w, self.boardWidget.cellWidgetAtSquare( chess.square(7 - chess.square_file(i), chess.square_rank(i))))
def squareOf(self, w: CellWidget) -> chess.Square: """ Returns ------- chess.Square The square number corresponding to the given cell widget. """ i = self._boardLayout.indexOf(w) if not self.flipped: return chess.square_mirror(i) return chess.square(7 - chess.square_file(i), chess.square_rank(i))
def evaluation(board): if isinstance(endState(board), int): return endState(board) valuesList = [len(board.pieces(chess.PAWN, chess.WHITE)), len(board.pieces(chess.PAWN, chess.BLACK)), len(board.pieces(chess.KNIGHT, chess.WHITE)), len(board.pieces(chess.KNIGHT, chess.BLACK)), len(board.pieces(chess.BISHOP, chess.WHITE)), len(board.pieces(chess.BISHOP, chess.BLACK)), len(board.pieces(chess.ROOK, chess.WHITE)), len(board.pieces(chess.ROOK, chess.BLACK)), len(board.pieces(chess.QUEEN, chess.WHITE)), len(board.pieces(chess.QUEEN, chess.BLACK))] pawnMove = sum([pawnEarly[i] for i in board.pieces(chess.PAWN, chess.WHITE)]) + sum( [-pawnEarly[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK)]) knightMove = sum([knightEarly[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)]) + sum( [-knightEarly[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK)]) bishopMove = sum([bishopEarly[i] for i in board.pieces(chess.BISHOP, chess.WHITE)]) + sum( [-bishopEarly[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK)]) rookMove = sum([rookEarly[i] for i in board.pieces(chess.ROOK, chess.WHITE)]) + sum( [-rookEarly[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK)]) queenMove = sum([queenEarly[i] for i in board.pieces(chess.QUEEN, chess.WHITE)]) + sum( [-queenEarly[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK)]) kingMove = sum([kingEarly[i] for i in board.pieces(chess.KING, chess.WHITE)]) + sum( [-kingEarly[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK)]) moveList = [pawnMove, knightMove, bishopMove, rookMove, queenMove, kingMove] return evalFunction(valuesList, moveList)
def evaluate(self): wp = len(self.board.pieces(chess.PAWN, chess.WHITE)) bp = len(self.board.pieces(chess.PAWN, chess.BLACK)) wn = len(self.board.pieces(chess.KNIGHT, chess.WHITE)) bn = len(self.board.pieces(chess.KNIGHT, chess.BLACK)) wb = len(self.board.pieces(chess.BISHOP, chess.WHITE)) bb = len(self.board.pieces(chess.BISHOP, chess.BLACK)) wr = len(self.board.pieces(chess.ROOK, chess.WHITE)) br = len(self.board.pieces(chess.ROOK, chess.BLACK)) wq = len(self.board.pieces(chess.QUEEN, chess.WHITE)) bq = len(self.board.pieces(chess.QUEEN, chess.BLACK)) material = 100*(wp-bp)+320*(wn-bn)+330*(wb-bb)+500*(wr-br)+900*(wq-bq) pawnsq = sum([self.pawntable[i] for i in self.board.pieces(chess.PAWN, chess.WHITE)]) pawnsq= pawnsq + sum([-self.pawntable[chess.square_mirror(i)] for i in self.board.pieces(chess.PAWN, chess.BLACK)]) knightsq = sum([self.knightstable[i] for i in self.board.pieces(chess.KNIGHT, chess.WHITE)]) knightsq = knightsq + sum([-self.knightstable[chess.square_mirror(i)] for i in self.board.pieces(chess.KNIGHT, chess.BLACK)]) bishopsq= sum([self.bishopstable[i] for i in self.board.pieces(chess.BISHOP, chess.WHITE)]) bishopsq= bishopsq + sum([-self.bishopstable[chess.square_mirror(i)] for i in self.board.pieces(chess.BISHOP, chess.BLACK)]) rooksq = sum([self.rookstable[i] for i in self.board.pieces(chess.ROOK, chess.WHITE)]) rooksq = rooksq + sum([-self.rookstable[chess.square_mirror(i)] for i in self.board.pieces(chess.ROOK, chess.BLACK)]) queensq = sum([self.queenstable[i] for i in self.board.pieces(chess.QUEEN, chess.WHITE)]) queensq = queensq + sum([-self.queenstable[chess.square_mirror(i)] for i in self.board.pieces(chess.QUEEN, chess.BLACK)]) kingsq = sum([self.kingstable[i] for i in self.board.pieces(chess.KING, chess.WHITE)]) kingsq = kingsq + sum([-self.kingstable[chess.square_mirror(i)] for i in self.board.pieces(chess.KING, chess.BLACK)]) eval = material + pawnsq + knightsq + bishopsq+ rooksq+ queensq + kingsq return -eval
def evaluate_piece_positions(board, colour): score = 0 for piece_type in range(chess.PAWN, chess.QUEEN + 1): for square in board.pieces(piece_type, colour): score += piece_square_table[piece_type][ square] if colour == chess.WHITE else piece_square_table[ piece_type][chess.square_mirror(square)] for square in board.pieces(piece_type, not colour): score -= piece_square_table[piece_type][ square] if colour == chess.BLACK else piece_square_table[ piece_type][chess.square_mirror(square)] endgame = is_endgame(board) for square in board.pieces(chess.KING, colour): score += piece_square_table[chess.KING][endgame][ square] if colour == chess.WHITE else piece_square_table[ chess.KING][endgame][chess.square_mirror(square)] for square in board.pieces(chess.KING, not colour): score -= piece_square_table[chess.KING][endgame][ square] if colour == chess.BLACK else piece_square_table[ chess.KING][endgame][chess.square_mirror(square)] return score
def piece_table_evaluation_function(board): difference = 0 for p in types: for piece in board.pieces(piece_mapper[p], chess.WHITE): difference += pst[p][piece] for piece in board.pieces(piece_mapper[p], chess.BLACK): difference -= pst[p][chess.square_mirror(piece)] if (board.turn): difference *= -1 return difference
def valorMid(self, numPiezas): #Uso diferentes valores materiales y de tablas valorMaterial = 82 * (numPiezas["peonB"] - numPiezas["peonN"]) +337 * (numPiezas["caballoB"] - numPiezas["caballoN"]) +365 * (numPiezas["alfilB"] - numPiezas["alfilN"]) +477 * (numPiezas["torreB"] - numPiezas["torreN"]) +1025 * (numPiezas["reinaB"] - numPiezas["reinaN"]) peonPos = sum([ h.mg_pawn_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.PAWN, chess.WHITE) ]) + sum([ -h.mg_pawn_table[i] for i in self.tablero.pieces(chess.PAWN, chess.BLACK) ]) caballoPos = sum([ h.mg_knight_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.KNIGHT, chess.WHITE) ]) + sum([ -h.mg_knight_table[i] for i in self.tablero.pieces(chess.KNIGHT, chess.BLACK) ]) alfilPos = sum([ h.mg_bishop_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.BISHOP, chess.WHITE) ]) + sum([ -h.mg_bishop_table[i] for i in self.tablero.pieces(chess.BISHOP, chess.BLACK) ]) torrePos = sum([ h.mg_rook_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.ROOK, chess.WHITE) ]) + sum([ -h.mg_rook_table[i] for i in self.tablero.pieces(chess.ROOK, chess.BLACK) ]) reinaPos = sum([ h.mg_queen_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.QUEEN, chess.WHITE) ]) + sum([ -h.mg_queen_table[i] for i in self.tablero.pieces(chess.QUEEN, chess.BLACK) ]) reyPos = sum([ h.mg_king_table[chess.square_mirror(i)] for i in self.tablero.pieces(chess.KING, chess.WHITE) ]) + sum([ -h.mg_king_table[i] for i in self.tablero.pieces(chess.KING, chess.BLACK) ]) valorEval = valorMaterial + peonPos + caballoPos + alfilPos + torrePos + reinaPos + reyPos #Esto lo hago porque lo bueno para mí es malo para mi oponente if self.tablero.turn: return valorEval else: return -valorEval
def cellIndexOfSquare(self, square: chess.Square) -> Optional[chess.Square]: """ Returns ------- Optional[`chess.Square`] The index of the widget at the given square number if we started counting from the top left corner of the board. """ if not self._flipped: return chess.square_mirror(square) return chess.square(7 - chess.square_file(square), chess.square_rank(square))
def init_evaluate_board(): global boardvalue wp = 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) pawnsq = sum([pawntable[i] for i in board.pieces(chess.PAWN, chess.WHITE)]) pawnsq = pawnsq + sum([ -pawntable[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK) ]) knightsq = sum( [knightstable[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)]) knightsq = knightsq + sum([ -knightstable[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK) ]) bishopsq = sum( [bishopstable[i] for i in board.pieces(chess.BISHOP, chess.WHITE)]) bishopsq = bishopsq + sum([ -bishopstable[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK) ]) rooksq = sum( [rookstable[i] for i in board.pieces(chess.ROOK, chess.WHITE)]) rooksq = rooksq + sum([ -rookstable[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK) ]) queensq = sum( [queenstable[i] for i in board.pieces(chess.QUEEN, chess.WHITE)]) queensq = queensq + sum([ -queenstable[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK) ]) kingsq = sum( [kingstable[i] for i in board.pieces(chess.KING, chess.WHITE)]) kingsq = kingsq + sum([ -kingstable[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK) ]) boardvalue = material + pawnsq + knightsq + bishopsq + rooksq + queensq + kingsq return boardvalue
def init_evaluate_board(): global boardvalue global material global whitematerial global blackmaterial global totalmaterial wp = 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)) whitematerial = 100*(wp)+320*(wn)+330*(wb)+500*(wr)+900*(wq) blackmaterial = 100*(bp)+320*(bn)+330*(bb)+500*(br)+900*(bq) totalmaterial = 100*(wp+bp)+320*(wn+bn)+330*(wb+bb)+500*(wr+br)+900*(wq+bq) material = 100*(wp-bp)+320*(wn-bn)+330*(wb-bb)+500*(wr-br)+900*(wq-bq) pawnsq = sum([pawntable[i] for i in board.pieces(chess.PAWN, chess.WHITE)]) pawnsq= pawnsq + sum([-pawntable[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK)]) knightsq = sum([knightstable[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)]) knightsq = knightsq + sum([-knightstable[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK)]) bishopsq= sum([bishopstable[i] for i in board.pieces(chess.BISHOP, chess.WHITE)]) bishopsq= bishopsq + sum([-bishopstable[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK)]) rooksq = sum([rookstable[i] for i in board.pieces(chess.ROOK, chess.WHITE)]) rooksq = rooksq + sum([-rookstable[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK)]) queensq = sum([queenstable[i] for i in board.pieces(chess.QUEEN, chess.WHITE)]) queensq = queensq + sum([-queenstable[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK)]) kingsq = sum([kingstable[i] for i in board.pieces(chess.KING, chess.WHITE)]) kingsq = kingsq + sum([-kingstable[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK)]) kingsqendgame = sum([kingstableendgame[i] for i in board.pieces(chess.KING, chess.WHITE)]) kingsqendgame = kingsqendgame + sum([-kingstableendgame[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK)]) if game == "middlegame": boardvalue = material + pawnsq + knightsq + bishopsq + rooksq + queensq + kingsq if game == "endgame": boardvalue = material + pawnsq + knightsq + bishopsq + rooksq + queensq + kingsqendgame return boardvalue
def evaluation(board: chess.Board) -> int: # material score wp = len(board.pieces(chess.PAWN, chess.WHITE)) bp = len(board.pieces(chess.PAWN, chess.BLACK)) wb = len(board.pieces(chess.BISHOP, chess.WHITE)) bb = len(board.pieces(chess.BISHOP, chess.BLACK)) wn = len(board.pieces(chess.KNIGHT, chess.WHITE)) bn = len(board.pieces(chess.KNIGHT, chess.BLACK)) wq = len(board.pieces(chess.QUEEN, chess.WHITE)) bq = len(board.pieces(chess.QUEEN, chess.BLACK)) wr = len(board.pieces(chess.ROOK, chess.WHITE)) br = len(board.pieces(chess.ROOK, chess.BLACK)) wk = len(board.pieces(chess.KING, chess.WHITE)) bk = len(board.pieces(chess.KING, chess.BLACK)) pure_material = 100 * (wp - bp) + 320 * (wn - bn) + 350 * ( wb - bb) + 500 * (wr - br) + 900 * (wq - bq) + 9999 * (wk - bk) pawn_pos = sum(eval.pawns_table[i] for i in board.pieces(chess.PAWN, chess.WHITE)) pawn_pos += sum(-eval.pawns_table[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK)) knight_pos = sum(eval.knights_table[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)) knight_pos += sum(-eval.knights_table[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK)) bishop_pos = sum(eval.bishops_table[i] for i in board.pieces(chess.BISHOP, chess.WHITE)) bishop_pos += sum(-eval.bishops_table[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK)) rook_pos = sum(eval.rooks_table[i] for i in board.pieces(chess.ROOK, chess.WHITE)) rook_pos += sum(-eval.rooks_table[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK)) queen_pos = sum(eval.queens_table[i] for i in board.pieces(chess.QUEEN, chess.WHITE)) queen_pos += sum(-eval.queens_table[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK)) kings_pos = sum(eval.kings_table[i] for i in board.pieces(chess.KING, chess.WHITE)) kings_pos += sum(-eval.kings_table[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK)) score = pure_material + pawn_pos + knight_pos + bishop_pos + rook_pos + queen_pos + kings_pos if board.turn: return score else: return -score
def evaluate_board(board): if board.is_checkmate(): if board.turn: return -9999 else: return 9999 if board.is_stalemate(): return 0 if board.is_insufficient_material(): return 0 # p : pawn / n : knight / b : bishop / r : rock / q : queen wp = 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) pawnsq = sum([pawntable[i] for i in board.pieces(chess.PAWN, chess.WHITE)]) pawnsq= pawnsq + sum([-pawntable[chess.square_mirror(i)] for i in board.pieces(chess.PAWN, chess.BLACK)]) knightsq = sum([knightstable[i] for i in board.pieces(chess.KNIGHT, chess.WHITE)]) knightsq = knightsq + sum([-knightstable[chess.square_mirror(i)] for i in board.pieces(chess.KNIGHT, chess.BLACK)]) bishopsq= sum([bishopstable[i] for i in board.pieces(chess.BISHOP, chess.WHITE)]) bishopsq= bishopsq + sum([-bishopstable[chess.square_mirror(i)] for i in board.pieces(chess.BISHOP, chess.BLACK)]) rooksq = sum([rookstable[i] for i in board.pieces(chess.ROOK, chess.WHITE)]) rooksq = rooksq + sum([-rookstable[chess.square_mirror(i)] for i in board.pieces(chess.ROOK, chess.BLACK)]) queensq = sum([queenstable[i] for i in board.pieces(chess.QUEEN, chess.WHITE)]) queensq = queensq + sum([-queenstable[chess.square_mirror(i)] for i in board.pieces(chess.QUEEN, chess.BLACK)]) kingsq = sum([kingstable[i] for i in board.pieces(chess.KING, chess.WHITE)]) kingsq = kingsq + sum([-kingstable[chess.square_mirror(i)] for i in board.pieces(chess.KING, chess.BLACK)]) boardvalue = material + pawnsq + knightsq + bishopsq + rooksq + queensq + kingsq eval = boardvalue if board.turn: return eval else: return -eval
def _non_pawn_pieces_on_origin_squares(self, color: chess.Color): origins = { chess.A1: chess.ROOK, chess.B1: chess.KNIGHT, chess.C1: chess.BISHOP, chess.D1: chess.QUEEN, chess.E1: chess.KING, chess.F1: chess.BISHOP, chess.G1: chess.KNIGHT, chess.H1: chess.KNIGHT, } piece_types = [] for square, expected in origins.items(): if color == chess.BLACK: square = chess.square_mirror(square) piece_type = self.board.piece_type_at(square) if piece_type == expected: piece_types.append(piece_type) return piece_types
def heur(board: ChessState) -> int: """Evaluation function for a given ChessState. The upper- and lower-bounds for the value returned are 10000 and -10000. A value of 0 indicates an equal position.""" if board.is_checkmate(): if board.turn: #black won return -10000 else: #white won return 10000 elif board.is_stalemate() or board.is_insufficient_material(): return 0 #get piece positions white_pawns = board.pieces(chess.PAWN, chess.WHITE) black_pawns = board.pieces(chess.PAWN, chess.BLACK) white_knights = board.pieces(chess.KNIGHT, chess.WHITE) black_knights = board.pieces(chess.KNIGHT, chess.BLACK) white_bishops = board.pieces(chess.BISHOP, chess.WHITE) black_bishops = board.pieces(chess.BISHOP, chess.BLACK) white_rooks = board.pieces(chess.ROOK, chess.WHITE) black_rooks = board.pieces(chess.ROOK, chess.BLACK) white_queens = board.pieces(chess.QUEEN, chess.WHITE) black_queens = board.pieces(chess.QUEEN, chess.BLACK) white_king = board.pieces(chess.KING, chess.WHITE) black_king = board.pieces(chess.KING, chess.BLACK) num_of_pieces = len(black_knights) + len(black_bishops) + len(black_rooks) +\ len(white_knights) + len(white_bishops) + len(white_rooks) + len(white_queens) \ + len(black_queens) + len(white_king) + len(black_king) + len(white_pawns) + len(black_pawns) #returns number of pinned pieces from piece_set * value_of_pin def pinned_eval(piece_set, color, value_of_pin): cum_eval = 0 for piece in piece_set: if board.is_pinned(color, piece): cum_eval = cum_eval + value_of_pin return cum_eval pinned_value = pinned_eval(white_pawns, chess.WHITE, -20) + pinned_eval(black_pawns, chess.BLACK, 20) + \ pinned_eval(white_knights, chess.WHITE, -30) + pinned_eval(black_knights, chess.BLACK, 30) +\ pinned_eval(white_bishops,chess.WHITE, -30) + pinned_eval(black_bishops,chess.BLACK, 30) +\ pinned_eval(white_rooks,chess.WHITE, -150) + pinned_eval(black_bishops,chess.BLACK, 150) +\ pinned_eval(white_queens,chess.WHITE, -400) + pinned_eval(black_bishops,chess.BLACK, 400) #returns value representing how many pieces of any type in list_of_pieces_to_attack are being attacked by any piece in piece_set def attacking_eval(piece_set, list_of_pieces_to_attack, list_of_value_of_attack): cum_eval = 0 for piece in piece_set: attacked = board.attacks(piece) for i in range(0, len(list_of_pieces_to_attack)): num_of_attacks_on_piece_type = len( attacked.intersection(list_of_pieces_to_attack[i])) cum_eval = cum_eval + num_of_attacks_on_piece_type * list_of_value_of_attack[ i] return cum_eval attacking_value = attacking_eval(white_knights, [black_queens,black_rooks,black_bishops], [20, 10, 5]) + \ attacking_eval(white_bishops, [black_queens, black_rooks, black_bishops], [20, 10, 2]) + \ attacking_eval(white_pawns, [black_queens, black_rooks, black_bishops, black_knights], [30, 20, 10, 10]) +\ attacking_eval(white_rooks, [black_queens], [20]) + \ attacking_eval(black_knights, [white_queens, white_rooks, white_bishops], [-20, -10, -5]) + \ attacking_eval(black_bishops, [white_queens, white_rooks, white_bishops], [-20, -10, -2]) + \ attacking_eval(black_pawns, [white_queens, white_rooks, white_bishops, white_knights], [-30, -20, -10, -10]) + \ attacking_eval(black_rooks, [white_queens], [-20]) num_black_minor_pieces = len(black_knights) + len(black_bishops) + len( black_rooks) num_white_minor_pieces = len(white_knights) + len(white_bishops) + len( white_rooks) #boolean if board is in endgame endgame = (len(white_queens) + len(black_queens) is 0) or ( len(white_queens) is 1 and len(black_queens) is 1 and num_black_minor_pieces is 1 and num_white_minor_pieces is 1) kingstable = kingstable_endgame if endgame else kingstable_middlegame #bishop pair is more valuable white_value_of_bishops = 375 if len(white_bishops) >= 2 and len( black_bishops) < 2 else 360 black_value_of_bishops = 375 if len(black_bishops) >= 2 and len( white_bishops) < 2 else 360 #calculates value of material in centipawns with standard valuations from https://en.wikipedia.org/wiki/Chess_piece_relative_value white_material = 100 * len(white_pawns) + 350 * len( white_knights) + white_value_of_bishops * len( white_bishops) + 525 * len(white_rooks) + 900 * len(white_queens) black_material = 100 * len(black_pawns) + 350 * len( black_knights) + black_value_of_bishops * len( black_bishops) + 525 * len(black_rooks) + 900 * len(black_queens) #sums values of all the positions of the pieces on the board from the tables square_values = sum([pawntable[i] for i in white_pawns]) - sum([pawntable[chess.square_mirror(i)] for i in black_pawns]) +\ sum([knightstable[i] for i in white_knights]) - sum([knightstable[chess.square_mirror(i)] for i in black_knights]) +\ sum([bishopstable[i] for i in white_bishops]) - sum([bishopstable[chess.square_mirror(i)] for i in black_bishops])+\ sum([rookstable[i] for i in white_rooks]) - sum([rookstable[chess.square_mirror(i)] for i in black_rooks])+\ sum([queenstable[i] for i in white_queens]) - sum([queenstable[chess.square_mirror(i)] for i in black_queens])+\ sum([kingstable[i] for i in white_king]) - sum([kingstable[chess.square_mirror(i)] for i in black_king]) return white_material - black_material + square_values + pinned_value + attacking_value