Exemplo 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')
Exemplo n.º 2
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()
Exemplo n.º 3
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 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}
Exemplo n.º 5
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'
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}
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}