import json
from ws4py.client.threadedclient import WebSocketClient


class ExampleClient(WebSocketClient):

    def __init__(self, url):
        super().__init__(url)
        self.name = "Agent1"

    def opened(self):
        pass
        # self.send(json.dumps({"name": self.name}))w

    def closed(self, code, reason=None):
        print("Closed down", code, reason)

    def received_message(self, message):
        content = json.loads(str(message))
       # print(content)
        if "action_list" in content and content["action_list"]:
            '''     card_type = random.choice(list(content["action_list"].keys()))
                print("Choose type ", card_type)
                rank = random.choice(list(content["action_list"][card_type].keys()))
                action = random.choice(list(content["action_list"][card_type][rank]))
                print("Choose action:", action)
                self.send(json.dumps({"action": action, "type": card_type, "rank": rank}))
            '''
            # 对牌型和点数分别设置权值
            transform = {'A': 14, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
                          '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'JOKER': 16, 'PASS': 10000000000000,
                         'Straight': 6, 'TripsPair': 1,
                         'ThreeWithTwo': 6, 'ThreePair': 1, 'Trips': 36,
                         'Pair': 1296, 'Single': 7776, 'Bomb': 279936,
                         'StraightFlush': 279936,
                         'back': 1, 'tribute':1 }

            # 初始化出的牌为 ："PASS"

            minscore = 10000000000000

            ans_action = [[0, 'PASS']]

            ans_card_type = 'PASS'

            ans_rank = 'PASS'
            # 如果不是对家出牌就压牌
            if (content["current_player"] + content["index"])%2 != 0 or  content["current_player"] == content["index"]:

                # 将当前牌权重调大
                transform[content["current_rank"]] = 15

                # num1 为每张牌在手牌中出现的次数
                num1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

                # num2 统计每种牌在可出牌型中出现的次数
                num2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

                for hand_cards in content["hand_cards"]:
                    num1[transform[hand_cards[1]]] += 1

                for hand_cards in content["hand_cards"]:
                    for card_type in list(content["action_list"].keys()):
                        for rank in list(content["action_list"][card_type].keys()):
                            if hand_cards in content["action_list"][card_type][rank]:

                                num2[transform[hand_cards[1]]] += 1

                for card_type in list(content["action_list"].keys()):
                    for rank in list(content["action_list"][card_type].keys()):
                        for action in list(content["action_list"][card_type][rank]):

                            score = transform[card_type]

                            x = 1

                            for card in action:
                                if card[1] != 'PASS':

                                    x *= (transform[card[1]]  )
                                #    如果当前牌数量>=4，则为炸弹，尽可能不要拆
                                #   if num1[transform[card[1]]] >= 4:
                                #      x *= 100
                            score *= x
                            # 每次选择得分最低的牌型打出
                            if score <= minscore:
                                minscore = score
                                ans_card_type = card_type
                                ans_rank = rank
                                ans_action = action
            print(content["hand_cards"])
            print(ans_action)
            self.send(json.dumps({"action": ans_action, "type": ans_card_type, "rank": ans_rank}))


if __name__ == '__main__':
    try:
        ws = ExampleClient('ws://192.168.1.124:23456/game/bot3')
        ws.connect()
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()
