コード例 #1
0
def play_game(agent):
    logger = Logger.get_instance()

    player_color = True if random.random() >= 0.5 else False
    logger.debug(f"Player is white: {player_color}")

    gam = Game(player_color=player_color)
    agent.color = player_color

    if player_color is False:
        # Make the oponent move
        gam.move(agent.best_move(gam, real_game=True))

    # Play until finish
    while gam.get_result() is None:
        start = timer()
        bm, am = agent.best_move(gam,
                                 real_game=False,
                                 ai_move=True,
                                 max_iters=900)
        gam.move(bm)  # Make our move
        gam.move(am)  # Make oponent move
        end = timer()
        elapsed = round(end - start, 2)
        logger.debug(f"\tMade move: {bm}, took: {elapsed} secs")
    logger.debug(gam.get_history())

    return gam
コード例 #2
0
def main():
    parser = argparse.ArgumentParser(description="Plays some chess games,"
                                     "stores the result and trains a model.")
    parser.add_argument('stockfish_bin', metavar='stockbin',
                        help="Stockfish binary path")
    parser.add_argument('data_path', metavar='datadir',
                        help="Path of .JSON dataset.")
    parser.add_argument('--games', metavar='games', type=int,
                        default=10)
    parser.add_argument('--depth', metavar='depth', type=int,
                        default=1, help="Stockfish tree depth.")
    parser.add_argument('--random_depth',
                        action='store_true',
                        default=False,
                        help="Use normal distribution of depths with "
                        "mean --depth.")
    parser.add_argument('--debug',
                        action='store_true',
                        default=False,
                        help="Log debug messages on screen. Default false.")

    args = parser.parse_args()

    logger = Logger.get_instance()
    logger.set_level(1)

    if args.debug:
        logger.set_level(0)

    gen_data(args.stockfish_bin, args.data_path, args.games)
コード例 #3
0
def gen_data(stockfish_bin, save_path, num_games=100, workers=2,
             random_dep=False):
    logger = Logger.get_instance()
    d = DatasetGame()
    pbar = tqdm(total=num_games)

    with ThreadPoolExecutor(max_workers=workers) as executor:
        for _ in range(num_games):
            executor.submit(play_game,
                            stockfish_bin=stockfish_bin,
                            dataset=d,
                            tqbar=pbar)
    pbar.close()
    logger.info("Saving dataset...")
    d.save(save_path)
コード例 #4
0
def main():
    parser = argparse.ArgumentParser(description="Plays some chess games,"
                                     "stores the result and trains a model.")
    parser.add_argument('model_dir',
                        metavar='modeldir',
                        help="where to store (and load from)"
                        "the trained model and the logs")
    parser.add_argument('--games', metavar='games', type=int, default=1)
    parser.add_argument('--threads', metavar='threads', type=int, default=6)
    parser.add_argument('--debug',
                        action='store_true',
                        default=False,
                        help="Log debug messages on screen. Default false.")

    args = parser.parse_args()

    logger = Logger.get_instance()
    logger.set_level(1)

    if args.debug:
        logger.set_level(0)

    model_path = get_model_path(args.model_dir)

    endpoint = ('localhost', 9999)
    worker = PredictWorker(model_path=model_path, endpoint=endpoint)

    manager = multiprocessing.Manager()
    return_dict = manager.dict()

    for i in range(args.games):
        worker.start()
        logger.info(f"Game {i+1} of {args.games}")
        proci = multiprocessing.Process(target=play_game_job,
                                        args=(endpoint, return_dict,
                                              args.threads))
        proci.start()
        proci.join()

        logger.debug("Stopping worker")
        worker.stop()

        logger.info(f"\tTraining {i+1} of {args.games}")
        proci = multiprocessing.Process(target=train_model_job,
                                        args=(return_dict['game'], model_path,
                                              args.model_dir))
        proci.start()
        proci.join()
コード例 #5
0
def benchmark(model_dir, workers=1, games=10, stockfish_depth=10, log=False):
    """ Plays N games and gets stats about the results.

    Parameters:
        model_dir: str. Directory where the neural net weights and training
            logs will be saved.
        workers: number of concurrent games (workers which will play the games)
    """
    multiprocessing.set_start_method('spawn', force=True)

    if log:
        logger = Logger.get_instance()
        logger.info(f"Setting up {workers} concurrent games.")

    model_path = get_model_path(model_dir)

    with ProcessPoolExecutor(workers, initializer=process_initializer)\
            as executor:

        results = []
        for i in range(games):
            results.append(
                executor.submit(play_game_job,
                                *[i, model_path, stockfish_depth]))
    results = [r.result() for r in results]
    if log:
        logger.debug("Calculating stats.")
    won = [
        1 if x['color'] is True and x['result'] == 1
        or x['color'] is False and x['result'] == -1 else 0  # noqa:W503
        for x in results
    ]

    if log:
        print("##################### SUMMARY ###################")
        print(f"Games played: {games}")
        print(f"Games won: {len([x for x in won if x == 1])}")
        print(f"Games drawn: {len([x for x in results if x['result'] == 0])}")
        print("#################################################")

    return dict(played=games,
                won=len([x for x in won if x == 1]),
                drawn=len([x for x in results if x['result'] == 0]))
コード例 #6
0
def play_game_job(id: int, model_path, stockfish_depth, log=False):
    """ Plays a game and returns the result..

    Parameters:
        id: Play ID (i.e. worker ID).
        model_path: path to the .h5 model. If it not exists, it will play with
        a fresh one.
        stockfish_depth: int. Difficulty of stockfish.
    """
    logger = Logger.get_instance()

    agent_is_white = True if random.random() <= .5 else False
    chess_agent = Agent(color=agent_is_white)
    game_env = GameStockfish(player_color=agent_is_white,
                             stockfish='../../res/stockfish-10-64',
                             stockfish_depth=stockfish_depth)

    try:
        chess_agent.load(model_path)
    except OSError:
        logger.error("Model not found. Exiting.")
        return None

    if log:
        logger.info(f"Starting game {id}")

    try:
        timer_start = timer()
        while game_env.get_result() is None:
            agent_move = chess_agent.best_move(game_env, real_game=True)
            game_env.move(agent_move)
        timer_end = timer()

        if log:
            logger.info(f"Game {id} done. Result: {game_env.get_result()}. "
                        f"took {round(timer_end-timer_start, 2)} secs")
    except Exception:
        logger.error(traceback.format_exc())

    res = {'color': agent_is_white, 'result': game_env.get_result()}
    game_env.tearup()
    return res