File size: 9,227 Bytes
27db1bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from ctypes import c_long, c_uint, c_ulong

import dds

SUIT_ORDER = {"S": 0, "H": 1, "D": 2, "C": 3}
RANK_ORDER = {
    "A": 14,
    "K": 13,
    "Q": 12,
    "J": 11,
    "T": 10,
    "9": 9,
    "8": 8,
    "7": 7,
    "6": 6,
    "5": 5,
    "4": 4,
    "3": 3,
    "2": 2,
}


RANK_STRENGTH = {
    "A": 1,
    "K": 2,
    "Q": 3,
    "J": 4,
    "T": 5,
    "9": 6,
    "8": 7,
    "7": 8,
    "6": 9,
    "5": 10,
    "4": 11,
    "3": 12,
    "2": 13,
}
SUIT_STRENGTH = {
    "S": 0,
    "H": 1,
    "D": 2,
    "C": 3,
}
RANK_TO_BIT = {rank: 2**power for rank, power in RANK_ORDER.items()}


def is_text_valid(text):
    text = (
        text.replace("1O", "T")
        .replace("10", "T")
        .replace("0", "T")
        .replace("O", "T")
        .replace("U", "J")
        .replace("1", "7")
    )
    for rank in RANK_ORDER.keys():
        if rank in text:
            return rank
    return None


def arrange_hand(hand):
    unique_hand = list(set(hand))

    sorted_hand = sorted(
        unique_hand,
        key=lambda card: (
            SUIT_ORDER.get(card[0], 99),
            -RANK_ORDER.get(card[1:], 0),
        ),
    )
    return sorted_hand


def convert2xhd(all_result, title):
    xhd = f"""<?xml version="1.0" encoding="shift_jis"?>

<HandData>

  <Prop>

    <Title>{title}</Title>

  </Prop>

"""
    for i, result in enumerate(all_result):
        if "error" in result.keys():
            continue
        xhd += f'<Board id="{i+1}">\r\n'
        xhd += convert2xhd_board(result["hands"])
        xhd += "\r\n</Board>\r\n"
    xhd += "</HandData>"
    return xhd


def convert2xhd_board(board):
    north_hand = convert2xhd_hand(board["north"])
    south_hand = convert2xhd_hand(board["south"])
    west_hand = convert2xhd_hand(board["west"])
    east_hand = convert2xhd_hand(board["east"])

    return f"<Deal>{north_hand} {east_hand} {south_hand} {west_hand}</Deal>"


def convert2xhd_hand(hand):
    arranged_cards = arrange_hand(hand)
    S, H, D, C = "", "", "", ""

    for card in arranged_cards:
        if card[0] == "S":
            S += card[1:]
        if card[0] == "H":
            H += card[1:]
        if card[0] == "D":
            D += card[1:]
        if card[0] == "C":
            C += card[1:]

    return f"{S}.{H}.{D}.{C}"


def convert2dup(all_result, _):
    num = len(all_result)
    dup = ""
    for result in all_result:
        if "error" in result.keys():
            continue
        dup += convert2dup_board(result["hands"], num)
    return dup


def convert2dup_board(board, num):
    north_hand_num = convert2dup_hand_num(board["north"])
    east_hand_num = convert2dup_hand_num(board["east"])
    south_hand_num = convert2dup_hand_num(board["south"])
    north_hand = convert2dup_hand_str(board["north"])
    south_hand = convert2dup_hand_str(board["south"])
    west_hand = convert2dup_hand_str(board["west"])
    east_hand = convert2dup_hand_str(board["east"])

    return f"{north_hand_num}{east_hand_num}{south_hand_num}{north_hand}{east_hand}{south_hand}{west_hand}YN1  1 {str(num).ljust(2)} "


def convert2dup_hand_num(hand):
    arranged_hand = arrange_hand(hand)

    cards_num = [convert_card2num(card) for card in arranged_hand]
    sorted(cards_num)

    return "".join(str(c).zfill(2) for c in cards_num)


def convert2dup_hand_str(hand):
    arranged_hand = arrange_hand(hand)
    S, H, D, C = "", "", "", ""

    for card in arranged_hand:
        if card[0] == "S":
            S += card[1]
        if card[0] == "H":
            H += card[1]
        if card[0] == "D":
            D += card[1]
        if card[0] == "C":
            C += card[1]

    return f"{S}{H}{D}{C}"


def convert_card2num(card):
    suit = SUIT_STRENGTH.get(card[0])
    rank = RANK_STRENGTH.get(card[1])
    if suit is None or rank is None:
        return -1
    return suit * 13 + rank


def convert2pbn(all_result):
    res = "% Dealer4 ver 4.82\r\n"

    for i, result in enumerate(all_result):
        if "error" in result.keys():
            continue
        res += '[Event "#"]\r\n' if i != 0 else '[Event ""]\r\n'
        res += '[Site "#"]\r\n' if i != 0 else '[Site ""]\r\n'
        res += '[Date "#"]\r\n' if i != 0 else '[Date ""]\r\n'
        res += f'[Board "{i}"]\r\n'
        res += f'[Dealer "{get_dealer(i)}"]\r\n'
        res += f'[Vulnerable "{get_vul(i)}"]\r\n'
        res += f'{convert2pbn_board(result["hands"], get_dealer(i))}\r\n\r\n'
    
    return res


def convert2pbn_board(board, dealer):
    return f'[Deal "{convert2pbn_txt(board, dealer)}"]'


def convert2pbn_txt(board, dealer):
    player_order = ["north", "south", "west", "east"]
    dealer_dict = {"N": 0, "E": 1, "S": 2, "W": 3}
    north_hand = convert2pbn_hand(board[player_order[dealer_dict[dealer]]])
    south_hand = convert2pbn_hand(
        board[player_order[(dealer_dict[dealer] + 1) % 4]]
    )
    west_hand = convert2pbn_hand(
        board[player_order[(dealer_dict[dealer] + 2) % 4]]
    )
    east_hand = convert2pbn_hand(
        board[player_order[(dealer_dict[dealer] + 3) % 4]]
    )

    return f"{dealer}:{north_hand} {east_hand} {south_hand} {west_hand}"


def convert2pbn_hand(hand):
    arranged_cards = arrange_hand(hand)
    S, H, D, C = "", "", "", ""

    for card in arranged_cards:
        if card[0] == "S":
            S += card[1:]
        if card[0] == "H":
            H += card[1:]
        if card[0] == "D":
            D += card[1:]
        if card[0] == "C":
            C += card[1:]

    return f"{S}.{H}.{D}.{C}"


def get_vul(num):
    r = num % 4
    q = (num - 1) // 4

    if (r + q) % 4 == 1:
        return "None"
    elif (r + q) % 4 == 2:
        return "NS"
    elif (r + q) % 4 == 3:
        return "EW"
    else:
        return "All"


def get_dealer(num):
    if num % 4 == 1:
        return "N"
    elif num % 4 == 2:
        return "E"
    elif num % 4 == 3:
        return "S"
    else:
        return "W"


def convert2ddTableDeal(hands_dict):
    table_deal = dds.ddTableDeal()

    # C言語の配列のように振る舞うため、このように初期化
    cards = ((c_uint * 4) * 4)()  # ddTableDealはc_uintでOK

    hand_map = {"north": 0, "east": 1, "south": 2, "west": 3}
    suit_map = {"S": 0, "H": 1, "D": 2, "C": 3}

    for player_name, hand in hands_dict.items():
        for card in hand:
            suit_char = card[0]
            rank_char = card[1:]

            player_idx = hand_map.get(player_name)
            suit_idx = suit_map.get(suit_char)

            if player_idx is not None and suit_idx is not None:
                cards[player_idx][suit_idx] |= RANK_TO_BIT.get(rank_char, 0)

    table_deal.cards = cards
    return table_deal


# DDSのdealオブジェクトを作成する最終確定版の関数
def convert_hands_to_binary_deal(hands_dict):
    from ctypes import c_uint

    deal = dds.deal()
    deal.trump = 0
    deal.first = 0
    deal.currentTrickSuit = (0, 0, 0)
    deal.currentTrickRank = (0, 0, 0)

    cards = ((c_long * 4) * 4)()
    hand_map = {"north": 0, "east": 1, "south": 2, "west": 3}
    suit_map = {"S": 0, "H": 1, "D": 2, "C": 3}

    for player_name, hand in hands_dict.items():
        for card in hand:
            suit_char = card[0]
            rank_char = card[1:]
            player_idx = hand_map.get(player_name)
            suit_idx = suit_map.get(suit_char)
            if player_idx is not None and suit_idx is not None:
                cards[player_idx][suit_idx] |= RANK_TO_BIT.get(rank_char, 0)

    deal.remainCards = cards
    return deal


def PrintTable(table):
    dcardSuit = ["S", "H", "D", "C", "N"]
    print(
        "{:5} {:<5} {:<5} {:<5} {:<5}".format(
            "", "North", "South", "East", "West"
        )
    )
    print(
        "{:>5} {:5} {:5} {:5} {:5}".format(
            "NT",
            table.resTable[0][4],
            table.resTable[2][4],
            table.resTable[1][4],
            table.resTable[3][4],
        )
    )
    for suit in range(0, dds.DDS_SUITS):
        print(
            "{:>5} {:5} {:5} {:5} {:5}".format(
                dcardSuit[suit],
                table.resTable[0][suit],
                table.resTable[2][suit],
                table.resTable[1][suit],
                table.resTable[3][suit],
            )
        )
    print("")


def reshape_table(table):
    players_map = {0: "North", 1: "East", 2: "South", 3: "West"}
    suits_map = {4: "nt", 0: "s", 1: "h", 2: "d", 3: "c"}
    res = {p_name: {} for p_name in players_map.values()}

    for i, suit in suits_map.items():
        for j, player in players_map.items():
            # new_suit = suits_map[(i + 5 * j) // 4]
            # new_player = players_map[(i + 5 * j) % 4]
            # print(
            #     suit, player, i, j, new_suit, new_player, table.resTable[j][i]
            # )
            res[player][suit] = table.resTable[i][j]
    return res