def load_models(self, dir: str):
     conf = Configure()
     conf.get_conf()
     board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"], conf.conf_dict["n_in_a_row"])
     model_path = pathlib.Path(dir) / board_conf_str
     model_path.mkdir(parents=True, exist_ok=True)
     self.all_model_path = sorted(item for item in model_path.glob('*/') if item.is_dir())
     self.all_model_name = [path.name for path in self.all_model_path]
def start():
    conf = Configure()
    conf.get_conf()

    def player_init(player_selected, name):
        if player_selected == 1:
            return Human(name=name)
        elif player_selected == 2:
            search_times, greedy_value = set_AI_conf(search_times=2000, greedy_value=5.0)
            return AI_MCTS(name=name,
                           search_times=search_times,
                           greedy_value=greedy_value,
                           is_output_analysis=conf.conf_dict["AI_is_output_analysis"])
        elif player_selected == 3:
            network = select_network()
            search_times, greedy_value = set_AI_conf(search_times=400, greedy_value=5.0)
            return AI_MCTS_Net(name=name,
                               policy_value_function=network.predict,
                               board_to_xlabel=network.board_to_xlabel,
                               is_training=False,
                               search_times=search_times,
                               greedy_value=greedy_value,
                               is_output_analysis=conf.conf_dict["AI_is_output_analysis"])

    player1_selected, name1 = select_player("Please input first player. Press <Ctrl-C> to end\n"
                                            "1: Human\n"
                                            "2: AI with pure Monte Carlo tree search\n"
                                            "3: AI with Monte Carlo tree search & neural network\n"
                                            ": ", allowed_input=[1, 2, 3])

    player1 = player_init(player1_selected, name1)

    player2_selected, name2 = select_player("Please input second player. Press <Ctrl-C> to end\n"
                                            "1: Human\n"
                                            "2: AI with pure Monte Carlo tree search\n"
                                            "3: AI with Monte Carlo tree search & neural network\n"
                                            ": ", allowed_input=[1, 2, 3])

    player2 = player_init(player2_selected, name2)

    console_renderer = ConsoleRenderer()

    print("############### Game Start ###############")
    winner = Game.start_until_game_over(player1, player2, board_renderer=console_renderer)
    if winner == BOARD.o:
        print("Congrats! \"O\" wins.")
    elif winner == BOARD.x:
        print("Congrats! \"X\" wins.")
    else:
        print("Draw!")
    print("############### Game Over ###############")
예제 #3
0
def select_model(dir: str, is_training=False, specified_model_name=""):
    """
    选择想要使用或训练的网络模型。
    Select the network model you want to use or train.
    :param dir: 网络模型目录。 Network model directory.
    :param is_training: 是否训练。 Whether to train.
    :param specified_model_name: 指定想要选择的模型。 Specify the model you want to select.
    :return: (<bool>, <str>, <str>) 是否是新的网络模型,和网络模型路径,网络模型记录路径。
    Whether it is a new network model, and the network model path, and the network model record path.
    """
    conf = Configure()
    conf.get_conf()
    board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"],
                                      conf.conf_dict["n_in_a_row"])
    model_path = pathlib.Path(dir)
    model_path = model_path / board_conf_str
    model_path.mkdir(parents=True, exist_ok=True)
    all_model_path = sorted(item for item in model_path.glob('*/')
                            if item.is_dir())
    all_model_name = [path.name for path in all_model_path]

    if len(specified_model_name) != 0:
        model_path = model_path / specified_model_name
        model_path.mkdir(parents=True, exist_ok=True)
        model_record_path = model_path / "latest.h5"
        is_new_model = True
        if model_record_path.exists():
            is_new_model = False
        return is_new_model, str(model_path) + "/", str(model_record_path)

    if is_training:
        print(
            "请选择想要训练的网络模型。按 <Ctrl-C> 退出。\n"
            "Please select the network model you want to train. Press <Ctrl-C> to exit."
        )
        print("0: 创建新的网络模型。 Create a new network model.")
    else:
        print(
            "请选择想要使用的网络模型。按 <Ctrl-C> 退出。\n"
            "Please select the network model you want to use. Press <Ctrl-C> to exit."
        )
    for i, one_model_name in enumerate(all_model_name):
        print("{0}: {1}".format(i + 1, one_model_name))

    model_selected = select(": ",
                            allowed_input=range(0 if is_training else 1,
                                                len(all_model_path) + 1))
    if model_selected == 0:
        while True:
            new_name = input(
                "请输入新的模型名称。按 <Ctrl-C> 退出。\n"
                "Please enter a new model name. Press <Ctrl-C> to exit.\n"
                ": ")
            if len(new_name) == 0:
                print("模型名称为空,请重新输入。\n"
                      "Model name is empty, please try again.\n")
                continue
            if new_name in all_model_name:
                print("该模型名称已存在,请重新输入。\n"
                      "The model name already exists, please try again.\n")
                continue
            model_path = model_path / new_name
            model_path.mkdir(parents=True, exist_ok=True)
            return True, str(model_path) + "/", None
    else:
        model_path = all_model_path[model_selected - 1]
        model_record_path = sorted(item for item in model_path.glob('*.h5'))
        model_record_name = [path.name[:-3] for path in model_record_path]
        if is_training:
            print(
                "请选择想要训练的模型记录。按 <Ctrl-C> 退出。\n"
                "Please select the model record you want to train. Press <Ctrl-C> to exit."
            )
        else:
            print(
                "请选择想要使用的模型记录。按 <Ctrl-C> 退出。\n"
                "Please select the model record you want to use. Press <Ctrl-C> to exit."
            )
        for i, one_model_record_name in enumerate(model_record_name):
            print("{0}: {1}".format(i + 1, one_model_record_name))
        model_record_selected = select(": ",
                                       allowed_input=range(
                                           1,
                                           len(model_record_path) + 1))
        return False, str(model_path) + "/", str(
            model_record_path[model_record_selected - 1])
예제 #4
0
import numpy as np

from Game.BoardRenderer import BoardRenderer
from Function import coordinates_set
from configure import Configure

conf = Configure()
conf.get_conf()

# Fixed Configuration.
o = conf.conf_dict["o"]
x = conf.conf_dict["x"]
empty = conf.conf_dict["empty"]

# Changeable Configuration.
n_in_a_row = conf.conf_dict["n_in_a_row"]  # How many pieces in a row.
o_win = n_in_a_row
x_win = -n_in_a_row
start_player = conf.conf_dict["start_player"]  # start player
board_size = conf.conf_dict["board_size"]  # The size of the board.


class Board:
    def __init__(self):
        self.board = np.zeros((board_size, board_size))
        self.available_actions = coordinates_set(board_size, board_size)
        self.last_action = None  #  Last move.
        self.current_player = start_player  # current player

    def __copy__(self):
        new_board = Board()
예제 #5
0
def select_model(dir: str, is_training=False, specified_model_name=""):
    conf = Configure()
    conf.get_conf()
    board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"],
                                      conf.conf_dict["n_in_a_row"])
    model_path = pathlib.Path(dir)
    model_path = model_path / board_conf_str
    model_path.mkdir(parents=True, exist_ok=True)
    all_model_path = sorted(item for item in model_path.glob('*/')
                            if item.is_dir())
    all_model_name = [path.name for path in all_model_path]

    if len(specified_model_name) != 0:
        model_path = model_path / specified_model_name
        model_path.mkdir(parents=True, exist_ok=True)
        model_record_path = model_path / "latest.h5"
        is_new_model = True
        if model_record_path.exists():
            is_new_model = False
        return is_new_model, str(model_path) + "/", str(model_record_path)

    if is_training:
        print(
            "Please select the network model you want to train. Press <Ctrl-C> to exit."
        )
        print("0: Create a new network model.")
    else:
        print(
            "Please select the network model you want to use. Press <Ctrl-C> to exit."
        )
    for i, one_model_name in enumerate(all_model_name):
        print("{0}: {1}".format(i + 1, one_model_name))

    model_selected = select(": ",
                            allowed_input=range(0 if is_training else 1,
                                                len(all_model_path) + 1))
    if model_selected == 0:
        while True:
            new_name = input(
                "Please enter a new model name. Press <Ctrl-C> to exit.\n"
                ": ")
            if len(new_name) == 0:
                print("Model name is empty, please try again.\n")
                continue
            if new_name in all_model_name:
                print("The model name already exists, please try again.\n")
                continue
            model_path = model_path / new_name
            model_path.mkdir(parents=True, exist_ok=True)
            return True, str(model_path) + "/", None
    else:
        model_path = all_model_path[model_selected - 1]
        model_record_path = sorted(item for item in model_path.glob('*.h5'))
        model_record_name = [path.name[:-3] for path in model_record_path]
        if is_training:
            print(
                "Please select the model record you want to train. Press <Ctrl-C> to exit."
            )
        else:
            print(
                "Please select the model record you want to use. Press <Ctrl-C> to exit."
            )
        for i, one_model_record_name in enumerate(model_record_name):
            print("{0}: {1}".format(i + 1, one_model_record_name))
        model_record_selected = select(": ",
                                       allowed_input=range(
                                           1,
                                           len(model_record_path) + 1))
        return False, str(model_path) + "/", str(
            model_record_path[model_record_selected - 1])