Exemplo n.º 1
0
 def calc_amp2(self, img, phase=0):
     # 対称形 x2 を考慮して確率計算
     amp_prob = self.sess.run(self.prob_op[phase],
                              feed_dict={self.x_placeholder: img})
     prob = np.zeros(go.IMAGE_SIZE, dtype=np.float32)
     for x in range(go.IMAGE_LENGTH):
         for y in range(go.IMAGE_LENGTH):
             pb = 0
             pb += amp_prob[0][go.XYtoZ(x, y)]
             pb += amp_prob[1][go.XYtoZ(go.IMAGE_LENGTH - 1 - x,
                                        go.IMAGE_LENGTH - 1 - y)]
             prob[go.XYtoZ(x, y)] = pb / 2
     return prob
Exemplo n.º 2
0
 def test_check(self):
     self.assertEqual(go.VALID, self.board.check(go.WHITE, s2z('C1')))
     self.assertEqual(go.OUT, self.board.check(go.WHITE, go.XYtoZ(1, 19)))
     self.assertEqual(go.DOUBLE, self.board.check(go.WHITE, s2z('E16')))
     self.assertEqual(go.SUICIDE, self.board.check(go.WHITE, s2z('K1')))
     self.assertEqual(go.EYE, self.board.check(go.BLACK, s2z('K1')))
     self.assertEqual(go.VALID, self.board.check(go.WHITE, s2z('E1')))
Exemplo n.º 3
0
 def test_z(self):
     for x in range(23):
         for y in range(23):
             z = go.XYtoZ(x, y)
             self.assertEqual(x, go.ZtoX(z))
             self.assertEqual(y, go.ZtoY(z))
             if 2 <= x <= 20 and 2 <= y <= 20:
                 self.assertTrue(go.is_on_board_z(z, 19))
             else:
                 self.assertFalse(go.is_on_board_z(z, 19))
Exemplo n.º 4
0
    def play(self, my_color):
        print('Engine.play()')

        print("remained time = %s" % self.time_limit)
        tstart = time.time()
        """vmoves = 0
        for z in range(1, go.IMAGE_SIZE):
            validity = self.board.checkRoot(my_color, z)
            if validity == go.VALID: # 合法である
                vmoves = 1
                break
        if vmoves == 0:
            print("no valid move.")
            self.time_limit -= time.time() - tstart
            return go.PASS"""

        sc2 = self.board.count_chinese_score2()
        print("current chinese score x 2 = %d" % sc2)
        if self.board.lastZ == go.PASS:
            #if self.board.turn >= 200:
            #    return go.PASS
            if my_color == go.BLACK and sc2 > 0:
                self.time_limit -= time.time() - tstart
                return go.PASS
            elif my_color == go.WHITE and sc2 < 0:
                self.time_limit -= time.time() - tstart
                return go.PASS

        img = go.to_image(self.board, my_color)

        amp_img = go.amplify_image8(img)
        prob = self.policy.calc_amp8(amp_img)

        print(go.colorString[my_color])
        for ix in range(self.board.length):
            print([
                int(prob[go.XYtoZ(ix + self.board.padding,
                                  iy + self.board.padding)] * 100)
                for iy in range(self.board.length)
            ])

        vlist = []
        for z in range(1, go.IMAGE_SIZE):
            validity = self.board.checkRoot(my_color, z)
            if validity == go.VALID:  # 合法である
                vlist.append((z, prob[z]))
        if len(vlist) == 0:
            print("no valid move.")
            self.time_limit -= time.time() - tstart
            return go.PASS

        np.random.shuffle(vlist)  # 同一局面を避けるために先にランダムに並べ替え
        sorted_vlist = sorted(vlist, key=lambda x: -x[1])
        self.time_limit -= time.time() - tstart
        return sorted_vlist[0][0]
Exemplo n.º 5
0
def s2board(board, s):
    board.clear()
    ls = s.split('\n')
    assert len(ls) == 22
    for y in range(go.LENGTH):
        for x in range(go.LENGTH):
            c = ls[19 - y][x * 2 + 3]
            z = go.XYtoZ(go.PADDING + x, go.PADDING + y)
            board.cell[z] = c2cell[c]
    if ls[21][0:5] == 'White': board.turn = 1
    elif ls[21][0:5] == 'Black': board.turn = 0
    else: raise 'Unknown color'
Exemplo n.º 6
0
def test(img_file, mdl_file):

    # 精度テスト
    policy = PolicyClient(mdl_file)

    # 画像ログの読み込み
    middle_image_logs = go.load_middle_image_logs(img_file)

    phase_index_vector = [[] for _ in range(N_PHASES)]
    for i, il in enumerate(middle_image_logs):
        phase_index_vector[0].append(i)
    phase_data_num = [len(v) for v in phase_index_vector]
    for ph in range(N_PHASES):
        np.random.shuffle(phase_index_vector[ph])

    image_vector = [
        np.empty((phase_data_num[ph], go.IMAGE_LENGTH, go.IMAGE_LENGTH,
                  go.IMAGE_PLAINS),
                 dtype=np.float32) for ph in range(N_PHASES)
    ]
    move_vector = [
        np.zeros((phase_data_num[ph], go.IMAGE_SIZE), dtype=np.float32)
        for ph in range(N_PHASES)
    ]

    for ph in range(N_PHASES):
        for i in range(phase_data_num[ph]):
            il = middle_image_logs[phase_index_vector[ph][i]]
            for x in range(go.IMAGE_LENGTH):
                for y in range(go.IMAGE_LENGTH):
                    val = il['img'][x][y]
                    for p in range(go.IMAGE_PLAINS):
                        b = (val >> p) & 1
                        image_vector[ph][i][x][y][p] = b
            move_vector[ph][i][il['mv']] = 1

    for ph in range(N_PHASES):
        for i, img in enumerate(image_vector[ph]):
            prob = policy.calc(img)
            print(i)
            for x in range(go.IMAGE_LENGTH):
                print([
                    int(prob[go.XYtoZ(x, y)] * 100)
                    for y in range(go.IMAGE_LENGTH)
                ])
Exemplo n.º 7
0
def gtp_main(my_id, my_version, config_directory, model_path):

    engine = Engine(1800)
    ingame = False
    end = False

    engine.init_all([model_path])

    while not end:
        rmsg_str = recv_msg()
        if len(rmsg_str) == 0:
            print_error("disconnected...")
            end = True
        rmsg_list = str(rmsg_str).split('\n')
        for command in rmsg_list:
            if len(command) == 0:
                continue
            print_error("Server >> %s" % command)
            com_list = command.split(' ')
            com = com_list[0].lower()
            # メッセージが複雑なのでこちらで分岐する
            if com == "boardsize":
                l = int(com_list[1])
                engine.set_length(l)
                ingame = False
                send_msg("= \n\n")
            elif com == "clear_board":
                # ログアウト判定
                #if ingame and os.path.isfile(config_directory + "stop_signal"):
                #    end = True
                engine.init_game([])
                send_msg("= \n\n")
            elif com == "name":
                send_msg("= " + my_id + "\n\n")
            elif com == "version":
                send_msg("= " + my_version + "\n\n")
            elif com == "genmove":
                move_z = go.RESIGN
                if com_list[1].lower() == "b":
                    move_z = engine.play(go.BLACK)
                    engine.recv_play(go.BLACK, move_z)
                elif com_list[1].lower() == "w":
                    move_z = engine.play(go.WHITE)
                    engine.recv_play(go.WHITE, move_z)
                send_msg("= " + to_GTP_move_string(engine.length, move_z) +
                         "\n\n")
            elif com == "play":
                move_z = go.RESIGN
                if com_list[2].lower().find("resign") >= 0:
                    end = True
                else:
                    if com_list[2].lower().find("pass") >= 0:
                        move_z = go.PASS
                    else:
                        padding = go.PADDING + (go.MAX_LENGTH -
                                                engine.length) // 2
                        x = go.char_to_ix(com_list[2][0].upper()) + padding
                        y = int(com_list[2][1:]) - 1 + padding
                        move_z = go.XYtoZ(x, y)

                    if com_list[1].lower() == "b":
                        engine.recv_play(go.BLACK, move_z)
                    elif com_list[1].lower() == "w":
                        engine.recv_play(go.WHITE, move_z)
                send_msg("= \n\n")
            elif com == "final_status_list":
                send_msg("= \n\n")
            elif com == "list_commands":
                lst = [
                    "boardsize", "clear_board", "name", "version", "genmove",
                    "play", "list_commands"
                ]
                send_msg("= " + '\n'.join(lst) + "\n\n")
            else:
                send_msg("= \n\n")
    return
Exemplo n.º 8
0
def nngs_main(length,
              my_color,
              host=DEFAULT_HOST,
              port=DEFAULT_PORT,
              my_id="julie",
              ops_id="noName"):

    buf_size = 1024

    engine = Engine(length, 30 * 60)
    ingame = False
    end = False

    host = socket.gethostbyname_ex(host)[0]

    #model_path = "/Users/ohto/documents/data/go/tfmodel/rn170317_b/tf_policy_cnn.ckpt"
    model_path = "/Users/ohto/documents/data/go/tfmodel/rn170405/tf_policy_cnn.ckpt"

    engine.init_all([model_path])

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    with closing(sock):
        sock.connect((host, port))
        send_msg(sock, my_id + '\n')  # ログイン
        while not end:
            rmsg_str = recv_msg(sock, buf_size)
            if len(rmsg_str) == 0:
                print("disconnected...")
                end = True
            rmsg_list = str(rmsg_str).split('\n')
            for command in rmsg_list:
                print("Server >> %s" % command)
                # メッセージが複雑なのでこちらで分岐する
                if command.find("No Name Go Server") >= 0:
                    send_msg(sock, "set client TRUE\n")  # シンプルな通信モードに
                if command.find("Set client to be True") >= 0:
                    if my_color == go.BLACK and not ingame:
                        ingame = True
                        engine.init_game([])
                        send_msg(sock, "match " + ops_id + " B " +
                                 str(length) + " 30 0\n")  # 黒番の場合に、試合を申し込む
                if command.find("Match [" + str(length) + "x" + str(length) +
                                "]") >= 0:
                    if my_color == go.WHITE and not ingame:
                        ingame = True
                        engine.init_game([])
                        send_msg(sock, "match " + ops_id + " W " +
                                 str(length) + " 30 0\n")  # 白番の場合に、試合を受ける
                if my_color == go.BLACK and command.find(
                        "accepted.") >= 0:  # 白が応じたので初手を送る
                    move_z = engine.play(my_color)
                    engine.recv_play(my_color, move_z)
                    send_msg(sock,
                             to_NNGS_move_string(move_z, length) +
                             "\n")  # 手を送る
                if command.find("Illegal") >= 0:
                    break
                if command.find(
                        "You can check your score"
                ) >= 0:  # Passが連続した場合に来る(PASSした後の相手からのPASSは来ない)
                    send_msg(sock, "done\n")
                    end = True
                if command.find("9 {Game") >= 0 and command.find(
                        "resigns.") >= 0:
                    if command.find(my_id + " vs " + ops_id) >= 0:
                        end = True  # game end
                    if command.find(ops_id + " vs " + my_id) >= 0:
                        end = True  # game end
                if command.find("forfeits on time") >= 0 and command.find(
                        my_id) >= 0 and command.find(ops_id) >= 0:
                    #どちらかの時間切れ
                    end = True
                if command.find("{" + ops_id + " has disconnected}") >= 0:
                    end = True  # 通信切断
                if command.find("(" + go.colorChar[go.flip_color(my_color)] +
                                "): ") >= 0:
                    # 相手の通常の手を受信
                    index = command.find("(" + go.colorChar[go.flip_color(
                        my_color)] + "): ") + 5
                    tstr = command[index:]

                    move_z = go.RESIGN
                    if tstr.find("Pass") >= 0:
                        move_z = go.PASS
                    else:
                        padding = go.PADDING + (go.MAX_LENGTH -
                                                engine.board.length) // 2
                        x = go.char_to_ix(tstr[0]) + padding
                        y = int(tstr[1:]) - 1 + padding
                        move_z = go.XYtoZ(x, y)

                    engine.recv_play(go.flip_color(my_color), move_z)
                    move_z = engine.play(my_color)
                    engine.recv_play(my_color, move_z)

                    send_msg(sock,
                             to_NNGS_move_string(move_z, length) +
                             "\n")  # 手を送る
    return
Exemplo n.º 9
0
def s2z(s):
    x = go.xChar.find(s[0])
    y = int(s[1:]) - 1
    return go.XYtoZ(go.PADDING + x, go.PADDING + y)