Ejemplo n.º 1
0
 def initialize(self):
     try:
         n = PolicyNetwork(use_cpu=True)
         instance = PolicyNetworkBestMovePlayer(n, self.moudle_file)
         self.gtp_engine = gtp_lib.Engine(instance)
     except BaseException as e:
         raise Exception('Initialization of policy network failed')
Ejemplo n.º 2
0
def make_gtp_instance(board_size,
                      read_file,
                      readouts_per_move=100,
                      verbosity=1,
                      cgos_mode=False):
    n = DualNetRunner(read_file)
    instance = MCTSPlayer(board_size,
                          n,
                          simulations_per_move=readouts_per_move,
                          verbosity=verbosity,
                          two_player_mode=True)
    gtp_engine = gtp.Engine(instance)
    if cgos_mode:
        instance = CGOSPlayer(board_size,
                              n,
                              seconds_per_move=5,
                              verbosity=verbosity,
                              two_player_mode=True)
    else:
        instance = MCTSPlayer(board_size,
                              n,
                              simulations_per_move=readouts_per_move,
                              verbosity=verbosity,
                              two_player_mode=True)
    name = 'Somebot-' + os.path.basename(read_file)
    gtp_engine = gtp_extensions.GTPDeluxe(instance, name=name)
    return gtp_engine
Ejemplo n.º 3
0
def gtp(strategy, read_file=None):
    n = PolicyNetwork(use_cpu=True)
    if strategy == 'random':
        instance = RandomPlayer()
    elif strategy == 'policy':
        instance = PolicyNetworkBestMovePlayer(n, read_file)
    elif strategy == 'randompolicy':
        instance = PolicyNetworkRandomMovePlayer(n, read_file)
    elif strategy == 'mcts':
        instance = MCTS(n, read_file)
    else:
        sys.stderr.write("错误")
        sys.exit()

    gtp_engine = gtp_lib.Engine(instance)
    sys.stderr.write("GTP\n")
    sys.stderr.flush()
    while not gtp_engine.disconnect:
        inpt = input()

        try:
            cmd_list = inpt.split("\n")
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            engine_reply = gtp_engine.send(cmd)

            sys.stdout.write(engine_reply)
            sys.stdout.flush()
Ejemplo n.º 4
0
def gtp(strategy, read_file=None):
    n = PolicyNetwork(use_cpu=True)
    if strategy == 'random':
        instance = RandomPlayer()
    elif strategy == 'policy':
        instance = PolicyNetworkBestMovePlayer(n, read_file)
    elif strategy == 'randompolicy':
        instance = PolicyNetworkRandomMovePlayer(n, read_file)
    elif strategy == 'mcts':
        instance = MCTS(n, read_file)
    else:
        sys.stderr.write("Unknown strategy")
        sys.exit()
    gtp_engine = gtp_lib.Engine(instance)
    sys.stderr.write("GTP engine ready\n")
    sys.stderr.flush()
    while not gtp_engine.disconnect:
        inpt = input()
        # handle either single lines at a time
        # or multiple commands separated by '\n'
        try:
            cmd_list = inpt.split("\n")
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            engine_reply = gtp_engine.send(cmd)
            sys.stdout.write(engine_reply)
            sys.stdout.flush()
Ejemplo n.º 5
0
def main():
    sys.setrecursionlimit(500000)
    engine = gtp.Engine(Engine(30, resnet.Policy()))
    while True:
        cmd = sys.stdin.readline()
        if cmd:
            engine_reply = engine.send(cmd)
            print(engine_reply)
            sys.stdout.flush()
def AI(msg):
    global read_file

    # 提取信息
    x = msg['msg'][2].upper()
    y = string.index(msg['msg'][3])
    color = ''
    if msg['msg'][0] == 'B':
        color = 'W'
    else:
        color = 'B'

# 初始化策略网络
    n = PolicyNetwork(use_cpu=True)
    instance = PolicyNetworkBestMovePlayer(n, read_file)
    gtp_engine = gtp_lib.Engine(instance)
    # sys.stderr.write("GTP Enginene ready\n")
    AI_cmd = parse_AI_instruction(color)

    # 查看是否已经开始下棋并记录
    if os.path.exists(data_file):
        rfile = open(data_file, 'r')
        cmd_list = rfile.readlines()
        for cmd in cmd_list:
            cmd = cmd.strip('\n ')
            if cmd == '':
                continue
            gtp_engine.send(cmd)
            # sys.stdout.write(cmd)
            # sys.stdout.flush()
        rfile.close()

    # 解析对方下棋指令,写进data
    wfile = open(data_file, 'a')
    player_cmd = parse_player_input(msg['msg'][0], x, y)
    wfile.write(player_cmd + '\n')
    gtp_engine.send(player_cmd)
    # sys.stdout.write(player_cmd + '\n')
    # sys.stdout.flush()

    gtp_reply = gtp_engine.send(AI_cmd)
    gtp_cmd = parse_AI_input(color, gtp_reply)
    wfile.write(gtp_cmd)
    wfile.close()
    # sys.stdout.write(gtp_reply)
    # sys.stdout.flush()

    response = color + '[' + gtp_reply[2].lower() + string[int(
        gtp_reply[3:])] + ']'
    # sys.stdout.write(response)
    # sys.stdout.flush()

    return {'game_id': msg['game_id'], 'msg': response}
Ejemplo n.º 7
0
def AI(msg):
    global read_file  # Extract information

    data_file = data_file_path + '[2]' + msg['game_id']

    x, y, color = parse_input_msg(msg)
    print(x, y, color)

    # Initialize the policy network
    n = PolicyNetwork(use_cpu=True)
    instance = PolicyNetworkBestMovePlayer(n, read_file)
    gtp_engine = gtp_lib.Engine(instance)
    # sys.stderr.write("GTP Enginene ready\n")
    AI_cmd = parse_AI_instruction(color)

    # To see if it has started playing chess and logging
    if os.path.exists(data_file):
        rfile = open(data_file, 'r')
        cmd_list = rfile.readlines()
        for cmd in cmd_list:
            cmd = cmd.strip('\n ')
            if cmd == '':
                continue
            gtp_engine.send(cmd)
        # sys.stdout.write(cmd + '\n')
        # sys.stdout.flush()
        rfile.close()

    # Parse the other side of the chess instructions, write into the record file
    wfile = open(data_file, 'a')
    if msg['msg'][2].lower() == 't' and msg['msg'][3].lower() == 't':
        pass
    else:
        player_cmd = parse_player_input(msg['msg'][0], x, y)
        wfile.write(player_cmd + '\n')
        gtp_engine.send(player_cmd)
    # sys.stdout.write(player_cmd + '\n')
    # sys.stdout.flush()

    gtp_reply = gtp_engine.send(AI_cmd)
    gtp_cmd = parse_AI_input(color, gtp_reply)
    wfile.write(gtp_cmd)
    wfile.close()
    # sys.stdout.write(gtp_reply + '\n')
    # sys.stdout.flush()

    AI_x, AI_y = parse_AI_reply(gtp_reply)

    response = color + '[' + AI_x + AI_y + ']'
    # sys.stdout.write(response)
    # sys.stdout.flush()

    return {'game_id': msg['game_id'], 'msg': response}
def make_gtp_instance(strategy_name, flags, hps):
    n = Network(flags, hps)
    if strategy_name == 'random':
        instance = RandomPlayer()
    elif strategy_name == 'greedypolicy':
        instance = GreedyPolicyPlayer(n)
    elif strategy_name == 'randompolicy':
        instance = RandomPolicyPlayer(n)
    elif strategy_name == 'mctspolicy':
        instance = MCTSPlayer(n)
    else:
        return None
    gtp_engine = gtp.Engine(instance)
    return gtp_engine
Ejemplo n.º 9
0
def go_gtp():
    gtp_engine = gtp_lib.Engine(GtpInterface())
    sys.stderr.write('GTP engine ready\n')
    sys.stderr.flush()
    while not gtp_engine.disconnect:
        inpt = input()
        try:
            cmd_list = inpt.split('\n')
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            engine_reply = gtp_engine.send(cmd)
            sys.stdout.write(engine_reply)
            sys.stdout.flush()
Ejemplo n.º 10
0
def make_gtp_instance(strategy_name, read_file):
    n = PolicyNetwork(use_cpu=True)
    n.initialize_variables(read_file)
    if strategy_name == 'random':
        instance = RandomPlayer()
    elif strategy_name == 'policy':
        instance = GreedyPolicyPlayer(n)
    elif strategy_name == 'randompolicy':
        instance = RandomPolicyPlayer(n)
    elif strategy_name == 'mcts':
        instance = MCTSPlayer(n)
    else:
        return None
    gtp_engine = gtp.Engine(instance)
    return gtp_engine
Ejemplo n.º 11
0
def gtp(strategy, read_file=None):
    network = PolicyNetwork()
    instance = MCTS(network, read_file)
    gtp_engine = gtp_lib.Engine(instance)
    print('gtp engine ready')
    while not gtp_engine.disconnect:
        inpt = input()
        try:
            cmd_list = inpt.split('\n')
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            print('sending cmd %s' % cmd)
            engine_reply = gtp_engine.send(cmd)
            print(engine_reply)
Ejemplo n.º 12
0
def run_gtp(player_obj, inpt_fn=None):
    gtp_game = GTPGameConnector(player_obj)
    gtp_engine = gtp.Engine(gtp_game)
    if inpt_fn is None:
        inpt_fn = raw_input

    sys.stderr.write("GTP engine ready\n")
    sys.stderr.flush()
    while not gtp_engine.disconnect:
        inpt = inpt_fn()
        # handle either single lines at a time
        # or multiple commands separated by '\n'
        try:
            cmd_list = inpt.split("\n")
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            engine_reply = gtp_engine.send(cmd)
            sys.stdout.write(engine_reply)
            sys.stdout.flush()
Ejemplo n.º 13
0
    def __init__(self, game_id, mode=0, moudle_file=DEFAULT_AI_MOUDLE_FILE, debug=False):
        '''
        :param mode:
            mode==0 -> human vs AI
            mode==1 -> AI    vs AI
        :param game_id:
            string
        :param moudle_file:
            string
            the AI moudle file
        '''

        # Activate Logging Debug Information
        self.debug = debug

        # initialize
        self.game_id = game_id
        self.command_list = []

        if not (mode == 1 or mode == 0):
            raise Exception('Invalid Game Mode')
        else:
            self.mode = mode

        self.moudle_file = moudle_file

        try:
            n = PolicyNetwork(use_cpu=True)
            instance = PolicyNetworkBestMovePlayer(n, self.moudle_file)
            self.gtp_engine = gtp_lib.Engine(instance)
        except BaseException as e:
            raise Exception('Initialization of policy network failed')

        # TODO: Remove the code below if using remote database
        # Using path 'game_database/data/' to store game data.
        # Make sure the path exists !
        self.local_data_filepath = 'game_database/data/'

        self.data_file = self.local_data_filepath + self.game_id + '.data'
Ejemplo n.º 14
0
def make_engine(net):
    instance = MCTSPlayer(net, simulations_per_move=1600, num_parallel=1, th=0)
    #instance = CGOSPlayerMixin(network=net)
    instance.initialize_game()
    engine = gtp.Engine(instance)
    return engine
Ejemplo n.º 15
0
def self_play(strategy, read_file=None):
    n = PolicyNetwork(use_cpu=True)
    if strategy == 'random':
        instance = RandomPlayer()
    elif strategy == 'policy':
        instance = PolicyNetworkBestMovePlayer(n, read_file)
    elif strategy == 'randompolicy':
        instance = PolicyNetworkRandomMovePlayer(n, read_file)
    elif strategy == 'mcts':
        instance = MCTS(n, read_file)
    else:
        sys.stderr.write("Unknown strategy")
        sys.exit()
        #instance神经网络
    gtp_engine = gtp_lib.Engine(instance)
    sys.stderr.write("GTP engine ready\n")
    sys.stderr.flush()

    p1 = -1
    save = ''
    inpt = 'genmove b'
    n = 500
    while n > 0:
        inpt = 'genmove b'
        if n % 2 == 1:
            inpt = 'genmove b'
        else:
            inpt = 'genmove w'
        try:
            cmd_list = inpt.split("\n")
        except:
            cmd_list = [inpt]
        for cmd in cmd_list:
            engine_reply = gtp_engine.send(cmd)
            sys.stdout.write(engine_reply)
            if engine_reply == '= pass\n\n':
                #engine_reply == '= pass\n\n'
                n = 0
            else:
                o1 = ''
                if len(engine_reply) == 7:
                    o1 = engine_reply[3] + engine_reply[4]
                else:
                    o1 = engine_reply[3]

                if n % 2 == 1:
                    o2 = ch.change(engine_reply[2]) + ch.change(o1)
                    save = save + ';B[' + ch.change(
                        engine_reply[2]) + ch.change(o1) + ']'
                else:
                    o2 = ch.change(engine_reply[2]) + ch.change(o1)
                    save = save + ';W[' + ch.change(
                        engine_reply[2]) + ch.change(o1) + ']'

            sys.stdout.flush()

        n = n - 1
    p7 = instance.position.result()
    save2 = '(;GM[1]\n SZ[19]\nPB[go1]\nPW[go2]\nKM[6.50]\nRE[' + p7[0] + ']\n'

    save2 = save2 + save + ')'

    wenjian = ''

    wenjian = str(time.time())
    p3 = '4'
    save_t.make_folder(wenjian + '_selfplay')
    save_t.save_txt(wenjian + '_selfplay', p3, save2)
def AI(msg):
    print("AI(msg) called.")
    global read_file  # Extract information

    data_file = data_file_path + msg['game_id']
    x, y, color = parse_input_msg(msg)
    print(x, y, color)

    # Initialize the policy network
    n = PolicyNetwork(use_cpu=True)
    print("PolicyNetwork init.")
    print("n,read_file:", n, read_file)
    try:
        instance = PolicyNetworkBestMovePlayer(n, read_file)
    except Exception:
        print(traceback.format_exc())
    #instance = PolicyNetworkRandomMovePlayer(n, read_file)
    print("PolicyNetwork instanced.", instance)
    try:
        global gtp_engine
        gtp_engine = gtp_lib.Engine(instance)
        print("GTP Engine get ready.", gtp_engine)
    except Exception:
        print(traceback.format_exc())
    #sys.stderr.write("GTP Enginene ready\n")
    AI_cmd = parse_AI_instruction(color)
    print("AI_cmd parsed.")
    # To see if it has started playing chess and logging
    try:
        data_file_exist = os.path.exists(data_file)
    except Exception:
        print(traceback.format_exc())
    print("os.path.exists?", data_file_exist)
    #sys.setdefaultencoding('utf-8')
    if os.path.exists(data_file):
        print("os.path.exists(data_file)!")
        rfile = open(data_file, 'r')
        cmd_list = rfile.readlines()
        for cmd in cmd_list:
            cmd = cmd.strip('\n ')
            if cmd == '':
                continue
            print("gtp_engine.send(cmd):", cmd)
            gtp_engine.send(cmd)
        # sys.stdout.write(cmd + '\n')
        # sys.stdout.flush()
        rfile.close()
    # Parse the other side of the chess instructions, write into the record file
    wfile = open(data_file, 'a')
    print("wfiled!!!")
    if msg['msg'][2].lower() == 't' and msg['msg'][3].lower() == 't':
        pass
    else:
        player_cmd = parse_player_input(msg['msg'][0], x, y)
        wfile.write(player_cmd + '\n')
        gtp_engine.send(player_cmd)
    # sys.stdout.write(player_cmd + '\n')
    # sys.stdout.flush()

    gtp_reply = gtp_engine.send(AI_cmd)
    gtp_cmd = parse_AI_input(color, gtp_reply)
    wfile.write(gtp_cmd)
    wfile.close()
    # sys.stdout.write(gtp_reply + '\n')
    # sys.stdout.flush()

    AI_x, AI_y = parse_AI_reply(gtp_reply)

    response = color + '[' + AI_x + AI_y + ']'
    # sys.stdout.write(response)
    # sys.stdout.flush()

    return {'game_id': msg['game_id'], 'msg': response}
Ejemplo n.º 17
0
def AI(msgs, model=DEFAULT_MODEL_PATH, strategy=None):
    print("AI(msg) called,strategy:", strategy)

    # data_file = data_file_path + msg
    lastMsg = msgs[len(msgs) - 1]
    x, y, color = parse_input_msg(lastMsg)
    print('AI(lastMsg) parsed:', x, y, color)

    # Initialize the policy network
    n = PolicyNetwork(use_cpu=True)
    print("PolicyNetwork init.")
    # global read_file
    # read_file = read_file_prefix+str(RANK)+"/savedmodel"
    print("n,read_file:", n, model)

    if strategy == 'random':
        global instance
        instance = RandomPlayer()
    elif strategy == 'best_move':
        global instance
        instance = PolicyNetworkBestMovePlayer(n, model)
    elif strategy == 'random_move':
        global instance
        instance = PolicyNetworkRandomMovePlayer(n, model)
    elif strategy == 'mcts':
        global instance
        instance = MCTS(n, model)
    #instance = PolicyNetworkRandomMovePlayer(n, read_file)
    print("PolicyNetwork instanced.", instance)
    try:
        global gtp_engine
        gtp_engine = gtp_lib.Engine(instance)
    except Exception:
        print(traceback.format_exc())
    print("GTP Engine get ready.")
    #sys.stderr.write("GTP Enginene ready\n")
    AI_cmd = parse_AI_instruction(color)
    print("AI_cmd parsed.")
    # To see if it has started playing chess and logging
    # try:
    #     data_file_exist = os.path.exists(data_file)
    # except Exception:
    #     print(traceback.format_exc())
    # print("os.path.exists?",data_file_exist)
    #sys.setdefaultencoding('utf-8')
    # if os.path.exists(data_file):
    #     print("os.path.exists(data_file)!")
    #     rfile = open(data_file, 'r')
    #     cmd_list = rfile.readlines()
    #     for cmd in cmd_list:
    #         cmd = cmd.strip('\n ')
    #         if cmd == '':
    #             continue
    #         print("gtp_engine.send(cmd):", cmd)
    #         gtp_engine.send(cmd)
    #     # sys.stdout.write(cmd + '\n')
    #     # sys.stdout.flush()
    #     rfile.close()
    # # Parse the other side of the chess instructions, write into the record file
    # wfile = open(data_file, 'a')
    # print("wfiled!!!")
    # if msg['msg'][2].lower() == 't' and msg['msg'][3].lower() == 't':
    #     pass
    # else:
    #     player_cmd = parse_player_input(msg['msg'][0], x, y)
    #     wfile.write(player_cmd + '\n')
    #     gtp_engine.send(player_cmd)
    # sys.stdout.write(player_cmd + '\n')
    # sys.stdout.flush()
    for msg in msgs:
        x, y, color = parse_input_msg(msg)
        player_cmd = parse_player_input(color, x, y)
        print("gtp_engine.send(cmd):", player_cmd)
        gtp_engine.send(player_cmd)

    gtp_reply = gtp_engine.send(AI_cmd)
    gtp_cmd = parse_AI_input(color, gtp_reply)
    # wfile.write(gtp_cmd)
    # wfile.close()
    # sys.stdout.write(gtp_reply + '\n')
    # sys.stdout.flush()

    AI_x, AI_y = parse_AI_reply(gtp_reply)

    response = color + '[' + AI_x + AI_y + ']'
    # sys.stdout.write(response)
    # sys.stdout.flush()

    return {'game_id': msg['game_id'], 'msg': response}