Exemplo n.º 1
0
def find_mate(boardFEN):  #Should only be used if mate is possible
    board = chess.Board(boardFEN)
    engine = chess.engine.SimpleEngine.popen_uci(engine_name("stockfish"))
    info = engine.analyse(board, chess.engine.Limit(
        depth=20))  #Limit the possible checkmate found to be under 20 moves

    board_states = []  #List of every board state in FEN notation during mate
    board_states.append(boardFEN)

    game = chess.pgn.Game()
    game.setup(boardFEN)
    x = 0
    if not (info["score"].is_mate()):
        engine.quit()
        return None  #The score given is not a mate, therefore, the function cannot return a mate. Therefore, it returns None
    for i in info["pv"]:  #Loop through every move and add them to the lists
        if x == 0:
            node = game.add_main_variation(
                i)  #If first loop, create the main line found by engine
            x = x + 1
        else:
            node = node.add_main_variation(
                i)  #Add to the main line if not first loop
        board.push(i)
        board_states.append(
            board.fen())  #Add the FEN board state after the move was made
    engine.quit()
    return game
Exemplo n.º 2
0
def main():
    train_data = []
    for x in range(num_games):
        print("Starting game:" + str(x))
        board = chess.Board()
        while not board.is_game_over() and board.fullmove_number < 20:
            legal_moves = board.legal_moves
            data = []
            if board.turn == chess.BLACK:
                for move in legal_moves:
                    board.push(move)
                    # Estimate moves
                    info = engine.analyse(
                        board, chess.engine.Limit(time=0.0100, depth=6))
                    board.pop()
                    data.append((move, str(info["score"])))
                train_data.append(([to_X(board)], to_Y(data)))

            # Make best move
            result = engine.play(board, chess.engine.Limit(time=0.100))
            board.push(result.move)
            # Make random move
            # board.push(random.choice(data)[0])
        if (x + 1) % 96 == 0:
            train_data_formatted = split_data(train_data)
            model.fit([train_data_formatted[0]], [train_data_formatted[1]],
                      epochs=1050,
                      batch_size=32,
                      callbacks=callbacks,
                      verbose=2)
            train_data = []
            model.save("checkpoints/" + model_name +
                       datetime.now().strftime("D%d-H%H-M%M") + ".h5")
            model.save("models/" + model_name + ".h5")
    engine.quit()
Exemplo n.º 3
0
def main(w_strat='fit_alphabeta', b_strat='fit_alphabeta'):
    engine = chess.engine.SimpleEngine.popen_uci('../Stockfish/src/stockfish')

    try:
        print(f"Opened engine {engine.id.get('name')}")

        game = Game(engine)
        board = chess.variant.RacingKingsBoard()

        print(f"Playing {w_strat} vs {b_strat}")

        while True:
            strategy = w_strat if board.turn else b_strat
            m = make_move(game, board, strategy)
            t = "WHITE" if board.turn else "BLACK"
            print(f"Move: {t} {m}")
            # print("States eval {}".format(node_counts[-1]))
            board.push(m)
            print(board)
            if board.is_variant_draw() or board.is_game_over():
                break

        if board.is_variant_draw():
            result = '1/2-1/2'
        else:
            result = board.result()

        print(f"Game over: {w_strat} {result} {b_strat}")

    finally:
        engine.quit()
Exemplo n.º 4
0
def main():
    board = chess.Board()
    engine = chess.engine.SimpleEngine.popen_uci("/usr/games/stockfish")
    #engine = chess.engine.SimpleEngine.popen_uci("~/.local/lib/python3.7/site-packages/stockfish")
    #create test matrix
    positions = create_colormap()
    positions[6][4] = 0
    positions[4][4] = 1
    print(board)
    print("\n")
    move = decode_move(board, positions)
    board.push(move)
    print(board)

    result = engine.play(board, chess.engine.Limit(time=0.5))
    board.push(result.move)
    print("\n")
    print(board)
    engine.quit()
    print("\nTesting board novelty functions")

    print("first")
    print(previous_board(board, 2, 1))
    print("initial")
    print(previous_board(board, 2, 0))
    print("original")
    print(board)
Exemplo n.º 5
0
def play_game(ws):
    board = generate_board(10)
    ws.send(json.dumps({"player": "random", "type": "player"}))
    engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")
    for state in board.states:
        analysis = engine.analyse(board, chess.engine.Limit(time=MOVE_GAP / 3))
        ws.send(
            json.dumps({
                "pieces": state,
                "score": analysis.score.white().score(),
                "type": "update"
            }))

    ws.send(json.dumps({"player": "nonrandom", "type": "player"}))

    while not board.is_game_over(claim_draw=True):
        result = engine.play(board, chess.engine.Limit(time=MOVE_GAP))
        analysis = engine.analyse(board, chess.engine.Limit(time=MOVE_GAP))
        print("score is:", analysis.score, "fen is", board.fen())
        board.push(result.move)
        ws.send(
            json.dumps({
                "pieces": board.get_pieces(),
                "score": analysis.score.white().score(),
                "type": "update"
            }))

    if board.is_checkmate():
        ws.send(json.dumps({"winner": not board.turn(), "type": "winner"}))
    else:
        ws.send(json.dumps({"winner": None, "type": "winner"}))
    engine.quit()
Exemplo n.º 6
0
def main():

    ser = serial.Serial('/dev/ttyACM0', 9600)

    engine = chess.engine.SimpleEngine.popen_uci("/usr/games/stockfish")
    board = chess.Board()

    print("----- GAME START -----\n")

    while not board.is_game_over():
        result = engine.play(board, chess.engine.Limit(time=0.500))

        print(result.move)
        arduino_move = result.move.uci()
        print(type(arduino_move.encode()))
        ser.write(arduino_move.encode())

        board.push(result.move)
        print("AI Move\n")
        print(board)
        print(" ")
        user_choice = input("User Move: ")
        board = check_input(user_choice, board)

    engine.quit()
Exemplo n.º 7
0
def best_move():
    fen = request.args.get('fen', '')
    if fen in cache:
        return cache[fen]

    board = chess.Board(fen)
    if board.is_game_over():
        return {}

    engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")

    result = engine.play(board, chess.engine.Limit(time=1.00))
    move = result.move
    san = board.san(move)
    board.push(move)  # Commiting the move to the board

    # Analyze (NEW). Not activated. TODO
    #info = engine.analyse(board, chess.engine.Limit(time=0.5))
    #score = info["score"]
    #mate_score = score.is_mate()
    #if score.is_mate():
    #    eval = f"{score.white().mate()}#"
    #else:
    #    eval = f"{score.white().score()}"

    engine.quit()

    result = {"san": san, "fen": board.fen()}
    cache[fen] = result
    return result
Exemplo n.º 8
0
def read_window_break_if_closed(engine):
    button, value = window.Read()
    if button == sg.WIN_CLOSED:
        # if user closes window
        engine.quit()
        sys.exit()
    return button, value
Exemplo n.º 9
0
def process_curent_game(session):
    board = chess.Board()
    engine = chess.engine.SimpleEngine.popen_uci("engine/stockfish")

    limit = chess.engine.Limit(time=2)
    local_opponents_last_move = None
    while True:
        try:
            cur_games = berserk.clients.Games(session).get_ongoing()
        except:
            continue

        if not cur_games:
            break
        else:
            cur_game = cur_games[0]

        if cur_game['isMyTurn']:
            remote_last_move = cur_game['lastMove']
            if not remote_last_move:
                my_move = engine.play(board, limit).move.uci()
                board.push_uci(my_move)
                screen_utils.field.move(my_move, cur_game['color'])
            elif remote_last_move != local_opponents_last_move:
                local_opponents_last_move = remote_last_move
                board.push_uci(remote_last_move)
                my_move = engine.play(board, limit).move.uci()
                board.push_uci(my_move)
                screen_utils.field.move(my_move, cur_game['color'])

    engine.quit()
Exemplo n.º 10
0
def main(opponent=chess.BLACK):
    try:
        engine = chess.engine.SimpleEngine.popen_uci('Stockfish/src/stockfish')
        print(f"Opened engine {engine.id.get('name')}")

        game = Game(engine, opponent=opponent)
        board = chess.variant.RacingKingsBoard()

        import pdb
        pdb.set_trace()
        while True:
            m = make_move(board, game, opponent)
            t = "WHITE" if board.turn else "BLACK"
            print(f"Move: {t} {m}")
            board.push(m)
            print(board)
            if board.is_game_over():
                break

        print(
            f"Game over: {board.result()} "
            f"({'stockfish' if opponent==chess.WHITE else 'agent'} v {'stockfish' if opponent==chess.BLACK else 'agent'})"
        )

    finally:
        engine.quit()
Exemplo n.º 11
0
def main():
    counter = positions_db.count_not_evaluated_positions()
    print('Number of not yet evaluated positions: {0}'.format(counter))

    if not counter:
        print('Nothing to do, quiting.')
        return

    engine = chess.engine.SimpleEngine.popen_uci(engine_path())
    engine.configure({'Threads': 6})

    while True:
        record = positions_db.get_not_evaluated_position()
        if record is None:
            break
        position_id, fen = record

        (score, bestmove, is_bestmove_capture, is_bestmove_check, is_check) = evaluate_position(engine, fen)
        positions_db.update_position_evaluation(
            position_id,
            score,
            bestmove,
            is_bestmove_capture,
            is_bestmove_check,
            is_check)

    engine.quit()
def chess_moves_publishing(boards):
    
    pub = rospy.Publisher('chess_next_moves', String, queue_size=10)
    rospy.init_node('chess_moves', anonymous=True)
    
    while not board.is_game_over():
        while not rospy.is_shutdown():     
            result = engine.play(boards, chess.engine.Limit(time=0.100))
            next_move = str(result.move)
            recipient_square = boards.piece_at(squares_integers[next_move[2:]])
            boards.push(result.move)
            pieceCount = update_piece_count(boards)

            if (recipient_square is None):
                rospy.loginfo(next_move)
                pub.publish(next_move)

            else:
                rospy.loginfo(next_move + 's')
                pieceCount -= 1
                pub.publish(next_move + 's')

            rospy.sleep(235)
            print(pieceCount)
            generate_human_move(pieceCount)
            rospy.sleep(5)

    engine.quit()
Exemplo n.º 13
0
def display_results(num_illegal_moves,
                    first_illegal_move,
                    total_black_moves,
                    final_illegal_moves,
                    winners,
                    bot_arr,
                    comp_arr,
                    num,
                    args):

    z = np.array(first_illegal_move)
    curated_first_illegal = z[z != -1]
    n_without_illegal = z.shape[0] - curated_first_illegal.shape[0]

    move_evals = eval_moves(bot_arr, comp_arr)

    with open('bot_scores.pkl', 'wb') as f:
        pickle.dump(bot_arr, f)

    with open('comp_scores.pkl', 'wb') as f:
        pickle.dump(comp_arr, f)

    print(f'Analyzed {num + 1} games...')
    print('On average, ChePT made:')
    print(f'\t\t\t{int(np.mean(total_black_moves))} moves per game.')
    print(f'\t\t\tFirst illegal move on move {int(np.mean(curated_first_illegal))}.')
    print(f'\t\t\t{int(np.mean(num_illegal_moves))} attempted illegal moves per game.')
    print(f'\t\t\t{int(np.mean(final_illegal_moves))} final illegal moves per game.')

    print('')
    print(f'ChePT had {n_without_illegal} games with no illegal moves.')
    attempt_percent = np.round(np.mean(np.array(num_illegal_moves) / np.array(total_black_moves)) * 100, 3)
    final_percent = np.round(np.mean(np.array(final_illegal_moves) / np.array(total_black_moves)) * 100, 3)
    print(f'ChePT attempts to make an illegal move {attempt_percent}% of the time')
    print(f'ChePT finally makes an illegal move {final_percent}% of the time')

    n_bot_wins = np.sum(np.array(winners) == 'BOT')
    n_draws = np.sum(np.array(winners) == 'DRAW')

    print(f'\nChePT managed to win {n_bot_wins} games.')
    print(f'ChePT managed to draw {n_draws} games.')

    results = {'Number of games': num + 1,
               'Number of moves': int(np.mean(total_black_moves)),
               'First illegal move': int(np.mean(curated_first_illegal)),
               'Attempted illegal moves': int(np.mean(num_illegal_moves)),
               'Games without illegal moves': n_without_illegal,
               'Final illegal moves': int(np.mean(final_illegal_moves)),
               'Percent attempted illegal moves': float(attempt_percent),
               'Percent final illegal moves': float(final_percent),
               'Wins': int(n_bot_wins),
               'Draws': int(n_draws),
               'Average move evaluation': float(move_evals['full_avg']),
               'Average early game move evaluation': float(move_evals['early_avg']),
               'Average mid game move evaluation': float(move_evals['mid_avg']),
               'Average late game move evaluation': float(move_evals['late_avg'])}

    save_results(results, args)

    engine.quit()
Exemplo n.º 14
0
def test_uci(python='python3', protocol='uci'):
    def new_engine():
        #python = '/usr/local/bin/python3'
        d = pathlib.Path(__file__).parent
        if protocol ==  'uci':
            args = [python, '-u', str(d / 'uci.py')]
            return chess.engine.SimpleEngine.popen_uci(args, debug=True)
        else:
            args = [python, '-u', str(d / 'xboard.py')]
            return chess.engine.SimpleEngine.popen_xboard(args, debug=True)

    limits = [
        chess.engine.Limit(time=1),
        chess.engine.Limit(nodes=1000),
        chess.engine.Limit(white_clock=1, black_clock=1),
        chess.engine.Limit(
            white_clock=1,
            black_clock=1,
            white_inc=1,
            black_inc=1,
            remaining_moves=2)
    ]

    for limit in limits:
        engine = new_engine()
        board = chess.Board()
        while not board.is_game_over() and len(board.move_stack) < 3:
            result = engine.play(board, limit)
            board.push(result.move)
        engine.quit()
Exemplo n.º 15
0
    def get(self):
        ret_dict = {}
        parser = reqparse.RequestParser()
        parser.add_argument('fen', type=str)
        parser.add_argument('svg', type=str)
        args = parser.parse_args()

        engine = chess.engine.SimpleEngine.popen_uci(stockfish_path)

        board = chess.Board(fen=args['fen'])
        info = engine.analyse(board, chess.engine.Limit(time=0.100))

        next_move_limit = chess.engine.Limit(time=2.0)
        next_move = engine.play(board, next_move_limit)

        engine.quit()
        ret_dict = {
            'current_score': str(info["score"]),
            'next_move_suggestion': str(next_move.move),
            'next_move_suggestions': str(next_move.info),
            'board_before': str(board),
        }

        if ('svg' in args and args['svg'] == '1'):
            ret_dict['svg'] = chess.svg.board(board=board,
                                              lastmove=next_move.move)

        return ret_dict
Exemplo n.º 16
0
def main(args):
    before = datetime.now()

    # Initialize
    remaining_work = Value('i', args.npositions)
    finished_work = Value('i', 0)
    position_lock = Lock()

    # Check if the engine supports FRC
    engine = chess.engine.SimpleEngine.popen_uci(args.engine)
    supports_frc = 'UCI_Chess960' in engine.options
    engine.quit()

    # Start generating data with all threads
    training_files = []
    processes = []
    parts = os.path.splitext(args.output)
    for pid in range(0, args.nthreads):
        training_file = parts[0] + '_' + str(pid) + parts[1]
        training_files.append(training_file)

        process_args = (pid, training_file, remaining_work, finished_work,
                        position_lock, supports_frc, args)
        processes.append(Process(target=process_func, args=process_args))
        processes[pid].start()

    # Handle progress output
    while True:
        time.sleep(PROGRESS_INTERVAL)

        position_lock.acquire()
        pos_generated = finished_work.value
        position_lock.release()
        print(f'\r{pos_generated}/{args.npositions}', end='')

        if pos_generated == args.npositions:
            break
    print('\n')

    # Wait for all threads to exit
    for p in processes:
        p.join()

    # Merge data from all threads into one file
    if args.format == 'plain':
        with open(args.output, 'w') as wfd:
            for f in training_files:
                with open(f, 'r') as fd:
                    shutil.copyfileobj(fd, wfd)
    else:
        with open(args.output, 'wb') as wfd:
            for f in training_files:
                with open(f, 'rb') as fd:
                    shutil.copyfileobj(fd, wfd)
    for f in training_files:
        os.remove(f)

    after = datetime.now()
    print(f'Time: {after-before}')
Exemplo n.º 17
0
    def run(self,
            reduced: Callable,
            square_filter: Callable,
            echo: int = 1,
            depth: int = 20) -> pd.DataFrame:
        engine = self.engine_maker()
        result = pd.DataFrame(columns=[
            'SideThatMoved', 'SideToMove', 'Score', 'PovScore',
            'HalfMoveConfiguration', 'FEN', 'LastWhiteMove', 'LastBlackMove',
            'ViewForWhite', 'ViewForBlack', 'Zeros', 'ZerosWithEcho'
        ])

        for curr_move in range(0, len(self.moves)):
            bm_offset = (curr_move + 1) % 2
            adjusted_wm = (curr_move // 2) * 2
            adjusted_bm = curr_move - bm_offset

            side = bool(
                bm_offset)  # white: 1, black: 0, same as in python-chess
            if not self.first_move_by_white:
                adjusted_wm, adjusted_bm = adjusted_bm, adjusted_wm  # not tested!

            last_white_move = self.moves[adjusted_wm]
            last_black_move = self.moves[
                adjusted_bm] if adjusted_bm > -1 else None

            white = self.msw(range(adjusted_wm - (echo * 2), adjusted_wm + 1),
                             chess.WHITE, square_filter)
            black = self.msb(range(adjusted_bm - (echo * 2), adjusted_bm + 1),
                             chess.BLACK, square_filter)
            zeros_white = reduced(
                self.msz(range(curr_move, curr_move + 1), chess.WHITE,
                         square_filter).result)
            zeros_black = reduced(
                self.msz(range(curr_move, curr_move + 1), chess.BLACK,
                         square_filter).result)

            reduced_white = reduced(white.result)
            reduced_black = reduced(black.result)

            # would be nice if engine.analyse could be made to run async/in parallel
            current_board = white.board if side else black.board
            score = engine.analyse(current_board,
                                   chess.engine.Limit(depth=depth))['score']

            result.loc[curr_move] = [
                'White' if side else 'Black', 'Black' if side else 'White',
                int(score.pov(chess.WHITE).__str__()),
                int(score.pov(score.turn).__str__()),
                (curr_move, adjusted_wm, adjusted_bm),
                current_board.fen(), last_white_move, last_black_move,
                reduced_white, reduced_black,
                cda.countZeros(np.logical_or(zeros_white, zeros_black)),
                cda.countZeros(np.logical_or(reduced_white, reduced_black))
            ]

        engine.quit(
        )  # This is important, otherwise we leak opened file objects!
        return result
Exemplo n.º 18
0
def report():
    moves = request.args.get('moves', '').split(',')
    engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish")
    analyzer = Analyzer(moves, engine)
    result = jsonify({
        "moves": [analyzer.analyzeIndex(index) for index in range(len(moves))]
    })
    engine.quit()
    return result
Exemplo n.º 19
0
def compare_model(time, stockfish=True):

    if stockfish:
        engine = chess.engine.SimpleEngine.popen_uci(
            "/home/albb762/chessai/stockfish/Linux/stockfish_10_x64")

        engine.configure({'Skill Level': 1})

    first = 0
    second = 0
    draw = 0
    for i in range(time):

        print(i)
        flag = 'stockfish'
        board = chess.Board()
        if random.randint(0, 1):
            board, _ = v.play_one_step(board)
            battle = 'model vs stockfish:'
            flag = 'model'

        while True:
            if not board.is_game_over():
                if stockfish:
                    result = engine.play(
                        board, chess.engine.Limit(time=0.00100, depth=1))
                    board.push(result.move)
                else:
                    board.push(random.choice(list(board.legal_moves)))
            else:
                break
            if not board.is_game_over():
                board, _ = v.play_one_step(board)
            else:
                break
        res = board.result()
        if flag == 'stockfish':
            if '1-0' == res:
                first += 1
            if '0-1' == res:
                second += 1
            if '1/2-1/2' == res:
                draw += 1
        if flag == 'model':
            if '1-0' == res:
                second += 1
            if '0-1' == res:
                first += 1
            if '1/2-1/2' == res:
                draw += 1
    if stockfish:
        print('stockfish vs model : ', first, second, draw)
    else:
        print('random vs model : ', first, second, draw)

    engine.quit()
Exemplo n.º 20
0
def make_move(psg_board, window, move_str, line, engine):
    if move_str == '0-0':
        move_str = castling_short(move_str, psg_board, window)
    elif move_str == '0-0-0':
        move_str = castling_long(move_str, psg_board, window)
    # en passante
    elif 'ep' in move_str:
        if board.turn:
            move_str = move_str[0:4]
            enemy_pawn = move_str[2] + str(int(move_str[3]) - 1)
            make_move_gui(move_str[0:2] + enemy_pawn, psg_board, window)
            make_move_gui(enemy_pawn + move_str[2:4], psg_board, window)
        else:
            move_str = move_str[0:4]
            enemy_pawn = move_str[2] + str(int(move_str[3]) + 1)
            make_move_gui(move_str[0:2] + enemy_pawn, psg_board, window)
            make_move_gui(enemy_pawn + move_str[2:4], psg_board, window)
    elif '=' in move_str:
        move_str = promotion(move_str, psg_board, window)
    else:
        make_move_gui(move_str, psg_board, window)

    move = chess.Move.from_uci(move_str)

    if not (board.is_legal(move) != board.is_castling(move)):
        if board.turn:
            sg.Popup(f'ERROR: {line} is not a legal move from white.\n')
        else:
            sg.Popup(f'ERROR: {line} is not a legal move from black.\n')
        engine.quit()
        sys.exit()

    board.push(move)

    analyzed_score = engine.analyse(board, chess.engine.Limit(time=0.2))
    score = analyzed_score.get('score')
    depth = analyzed_score.get('depth')
    window.FindElement('_score_').Update(
        f'Score of your board is {score} with a analyzed depth of {depth}.',
        append=True)
    window.FindElement('_movelist_').Update(line + '\n', append=True)

    best_move = engine.play(board, chess.engine.Limit(time=0.2)).move
    window.FindElement('_best_move_').Update(
        f'{best_move} with a analyzed depth of {depth}.', append=True)

    if (board.is_checkmate()):
        sg.Popup('Checkmate!',
                 board.result(),
                 'Thank you for playing',
                 title='Game Over!')
        engine.quit()
        sys.exit()

    if (board.is_check()):
        sg.Popup('Check')
Exemplo n.º 21
0
 def stockfish_move(self, turn="w"):
     fen = self.convert_board_to_FEN(turn=turn)
     root_moves = [chess.Move.from_uci(mv) for mv in self.legal_moves(turn)]
     engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_DIR)
     board = chess.Board(fen)
     result = engine.play(board,
                          chess.engine.Limit(time=0.5, depth=1),
                          root_moves=root_moves)
     engine.quit()
     return str(result.move)
Exemplo n.º 22
0
    def expertChoice(self):
        engine = chess.engine.SimpleEngine.popen_uci(
            "C:\WinBoard-4.8.0\Stockfish\stockfish_20090216_x64_bmi2.exe")
        result = engine.play(self.board, chess.engine.Limit(time=0.01))
        engine.quit()
        action = 1
        if result != None and result.move != None:
            action = self.moveToAction[result.move.uci()]

        return action
Exemplo n.º 23
0
def eng_choose(legmoves, board, lim):
    # global args
    # if board.fullmove_number < 10 and args.polyglot_book != "":
    #     opc = opening_choice(board, args.polyglot_book)
    #     if opc is not None:
    #         return opc

    engine = chess.engine.SimpleEngine.popen_uci("stockfish")
    moves = eng_rate(legmoves, board, engine, lim)
    engine.quit()
    return moves[0][0]
Exemplo n.º 24
0
 def find_move(self):
     """
     Calculate the best move according to Stockfish
     """
     self.enginePath = self.pathField.text()
     self.time = float(self.engineTime.text())
     engine = chess.engine.SimpleEngine.popen_uci(self.enginePath)
     result = engine.play(self.board, chess.engine.Limit(time=self.time))
     self.engineResult.setText(str(result.move))
     engine.quit()
     return result.move
Exemplo n.º 25
0
 def stockfish_score(self, turn="w"):
     fen = self.convert_board_to_FEN(turn)
     root_moves = [chess.Move.from_uci(mv) for mv in self.legal_moves(turn)]
     engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_DIR)
     board = chess.Board(fen)
     info = engine.analyse(board,
                           chess.engine.Limit(time=0.5, depth=1),
                           root_moves=root_moves)
     engine.quit()
     score = info.get("score")
     return score.white(), score.black()
Exemplo n.º 26
0
async def game(board: str):
    """
    Calculate next move based on current board
    """
    b = chess.Board(board)
    engine = chess.engine.SimpleEngine.popen_uci("/usr/games/stockfish")
    result = engine.play(b, chess.engine.Limit(time=0.5))
    b.push(result.move)

    engine.quit()

    return b.fen()
Exemplo n.º 27
0
def test_stockfish_features():
    engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH)

    f = features.Stockfish10(chess.STARTING_FEN, engine)
    assert f.features() == {
        "best_mate": None,
        "best_move": "b1c3",
        "best_pv": "['b1c3', 'd7d5', 'd2d4', 'c7c6', 'c1f4', 'e7e6', 'e2e3']",
        "best_score": 115,
    }

    engine.quit()
Exemplo n.º 28
0
def engine_analyze_position():
    engine = chess.engine.SimpleEngine.popen_uci(
        "C:\Program Files (x86)\Tarrasch\Engines\stockfish_11_x64.exe")
    engine.configure({"Hash": 2048, "Threads": 8})

    board = chess.Board(
        "r1b1k1nr/p1q1ppbp/2pp2p1/2p5/4PP2/2NP1N2/PPP3PP/R1BQ1RK1 b kq - 0 8")
    info = engine.analyse(board, chess.engine.Limit(depth=40))
    print("Score:", info["score"])
    # Score: PovScore(Mate(+1), WHITE)

    engine.quit()
Exemplo n.º 29
0
def main():

    engine = chess.engine.SimpleEngine.popen_uci(
        "stockfish10/Windows/stockfish_10_x64.exe")
    X = []
    Y = []
    pgn = open("datasets/ficsgamesdb_2018_CvC_nomovetimes_51973.pgn")
    state_limit = 60
    games = 300
    evaluation_time = 1
    start = time.time()

    print(f"Parsing {games} games.")

    for i in range(games):

        game = chess.pgn.read_game(pgn)
        board = game.board()
        states = 0
        print("Game:", i + 1, f"({game.headers['Event']})")

        for next_node in game.mainline_moves():

            evaluation = engine.analyse(
                board, chess.engine.Limit(time=evaluation_time))
            score = sigmoid(
                (2 * int(board.turn) - 1) *
                (evaluation['score'].relative.score(mate_score=1000000)))
            X.append(get_bit_map(board))
            Y.append(score)
            states += 1

            board.push(next_node)

            if states >= state_limit:
                break

        end = time.time()
        print("States:", states)
        hours, rem = divmod(end - start, 3600)
        minutes, seconds = divmod(rem, 60)
        print(
            f"Time Elapsed:",
            "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds))

    engine.quit()

    print("Dataset created")
    print("Samples:", len(X), "Labels:", len(Y))
    print("Dumping to JSON")

    with open('data.json', 'w') as outfile:
        json.dump([X, Y], outfile)
Exemplo n.º 30
0
    def from_df(cls, df):
        engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH)

        feature_rows = []
        with click.progressbar(tuple(df.itertuples()),
                               label=cls.__name__) as rows:
            for row in rows:
                feature_instance = cls.from_row(row, engine)
                feature_rows.append(feature_instance.features())

        engine.quit()
        return pd.DataFrame(feature_rows)