示例#1
0
def stockFish_init(request):
    stockfish = Stockfish(parameters={
        "Threads": 2,
        "Minimum Thinking Time": 30
    })
    stockfish.set_position(["e2e4", "e7e6"])
    #posición de Forsyth–Edwards Notation (FEN)
    stockfish.set_fen_position(
        "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")
    #coge el mejor movimiento
    stockfish.get_best_move(
    )  #stockfish.get_best_move_time(1000) en base al tiempo
    #nivel del motor
    stockfish.set_skill_level(15)
    #parámetros por defecto
    stockfish.get_parameters()
    #coge la posición FEN
    stockfish.get_fen_position()
    #coge el tablero por defecto del usuario
    stockfish.get_board_visual()
    #evalua jugada
    stockfish.get_evaluation()
    p = subprocess.Popen('stockfish-x64.exe',
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    p.stdin.write("position startpos moves e2e4 e7e5\n")
    p.stdin.write("go infinite\n")
    p.stdin.flush()
    time.sleep(1)
    print(p.communicate())
示例#2
0
def evaluation_from_board(board: chess.Board,
                          evaluation_depth: int = 22) -> Dict:
    board_fen = board.fen()
    stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish")
    stockfish.set_depth(evaluation_depth)  # set engine depth
    stockfish.set_fen_position(board_fen)
    return stockfish.get_evaluation()
示例#3
0
def Score(fen):
    stockfish = Stockfish("./stockfish_20090216_x64.exe", parameters={
                                                                        "Write Debug Log": "false",
                                                                        "Contempt": 0,
                                                                        "Min Split Depth": 30,
                                                                        "Threads": 1,
                                                                        "Ponder": "false",
                                                                        "Hash": 16,
                                                                        "MultiPV": 1,
                                                                        "Skill Level": 20,
                                                                        "Move Overhead": 30,
                                                                        "Minimum Thinking Time": 20,
                                                                        "Slow Mover": 84,
                                                                        "UCI_Chess960": "false",}
        )
    stockfish.set_fen_position(fen)
    score = stockfish.get_evaluation()
    print(score)


# fen = "2N5/8/2Q5/4k2p/1R6/7P/6P1/7K b - - 4 66"

# engine = init_stockfish_engine()
# print(StockfishScore(fen, engine))
# Score(fen)

# engine.quit()
示例#4
0
def generate_random_advantage_position(evaluation_depth: int):
    stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish")
    stockfish.set_depth(evaluation_depth)  # set engine depth
    while True:
        board = chess.Board()
        end_game = False
        for i in range(random.randint(10, 200)):
            move = random.choice(list(board.legal_moves))
            board.push(move)
            if board.is_game_over():
                end_game = True
                print("Final position")
                break

        if not end_game:
            board_fen = board.fen()
            stockfish.set_fen_position(board_fen)
            position_evaluation = stockfish.get_evaluation()
            print(
                f"Position_evaluation: {position_evaluation}, fen = {board_fen}"
            )

            if position_evaluation['type'] == 'cp' and abs(
                    position_evaluation["value"]) < 300 and abs(
                        position_evaluation["value"]
                    ) > 1000:  # rule out when no big advantage
                print(
                    f"position_evaluation: {position_evaluation}. Passing: rule out when no big advantage"
                )
                pass
            elif position_evaluation['type'] == 'mate' and position_evaluation[
                    'value'] <= 1:  # rule out mate in 1
                print(
                    f"position_evaluation: {position_evaluation}. Passing: rule out mate in 1"
                )
                pass
            else:
                if board.turn == chess.WHITE and position_evaluation[
                        "value"] <= 0:  # not an advantage white
                    print(f"Turn: {board.turn}")
                    print(
                        f"position_evaluation: {position_evaluation}. Passing: not an advantage for white"
                    )
                    pass
                elif board.turn == chess.BLACK and position_evaluation[
                        "value"] >= 0:  # not an advantage black
                    print(f"Turn: {board.turn}")
                    print(
                        f"position_evaluation: {position_evaluation}. Passing: not an advantage for black"
                    )
                    pass
                else:
                    yield board, board_fen, position_evaluation
示例#5
0
文件: trainer.py 项目: ItsFabby/chess
def gen_examples(randomness: float = 0.7,
                 randomness_decline: float = 0.95,
                 max_moves: int = 80,
                 table: str = c.DEFAULT_TABLE) -> None:
    """
    Generates training examples using Stockfish and stores them in a database in algebraic notation. Set up a MySQL 
    database first and set the connection in constants.py. Also make sure that Stockfish is installed correctly.

    :param table: Table the data is stored in.
    :param randomness: Starting Probability for proceeding with are random move instead of the best move. This is
        necessary to not simulate the same game each time.
    :param randomness_decline: Factor applied to the randomness with each move. Should be less than 1 to have less 
        randomness later in the game.
    :param max_moves: Stops the simulated game early to prevent too long end games.
    """
    game = Game()
    stockfish = Stockfish(c.STOCKFISH_PATH)
    examples = []
    moves = []
    for _ in range(max_moves):
        stockfish.set_position(moves)
        best_move = stockfish.get_best_move()

        value = _value(stockfish.get_evaluation())
        if best_move:
            examples.append((_truncate_fen(stockfish.get_fen_position()),
                             (best_move[:4], value)))

        if best_move and random.random() > randomness:
            move_alg = best_move
            move_tuple = _from_algebraic(move_alg)
        else:
            move_tuple = random.sample(game.game_legal_moves(), 1)[0]
            move_alg = _to_algebraic(move_tuple)

        if len(move_alg) == 5:
            print('pawn promotion')

        try:
            game.make_move(move_tuple[0], move_tuple[1])
            moves.append(move_alg)
        except ValueError:
            moves[-1] = moves[-1] + 'q'
            print(examples)

        randomness *= randomness_decline

        if game.game_winner():
            break
    db = Connector()
    db.insert_examples(examples, table)
示例#6
0
def evaluate_position_sf(fen_board, threads=2, depth=2):
    """Evaluate a position using stockfish, position must be in Forsyth–Edwards Notation.
    TODO - Pass arbitrary params, the default depth seems OOL with evaluate_position()"""
    stockfish_engine = Stockfish(parameters={"Threads": threads})
    stockfish_engine.set_fen_position(fen_board)
    return stockfish_engine.get_evaluation()
示例#7
0
 board = chess.Board()
 while play==True:
      
     '''
     print('where you movin from')
     froom=input()
     print('where too')
     to=input()
     moves.append(f'{froom}{to}')'''
     bd=sf.get_best_move()
     moves.append(bd)
     board.push(chess.Move.from_uci(bd))
     print(type(bd))
     sf.set_position(moves)
     print(sf.get_board_visual())
     state=sf.get_evaluation()
     print(board)
     
     if sf.get_best_move()==None:
         #if state['type']=='mate' and state['value']==0:
         if board.is_stalemate():
             print('stalemate my dude white')
             play=False
             stalemate=stalemate+1
             continue
         if board.is_game_over()==True:
             print('mate my dude white')
             play=False
             white=white+1
             continue