-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathMahjongKit.py
2192 lines (1971 loc) · 98.2 KB
/
MahjongKit.py
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import json
import random
from copy import deepcopy
import os
import requests
import bs4
import sqlite3
__author__ = "Jianyang Tang"
__email__ = "[email protected]"
class Tile:
"""
--------------------------------------------------------------------------------------------------------------
The intentions of using this class:
As you should have already known, when you decide to develop an AI agent of Mahjong, there are 34 kinds of
different Mahjong tiles, i.e. 1-9 man, 1-9 pin, 1-9 suo, 7 character tiles(ESWNBFC). Another fact is that
for each kind of tiles we have four identical copies, this makes a total of 136 tiles.
Tiles are however represented in quite different ways for different situaions.
For example, in the server for real-time human-to-human battling, tiles are represented in 136-form. By
applying 136-form, each copy of a kind of tile is even identified with an ID. E.g.
0,1,2,3 <=> the four 1 man tiles
16,17,18,19 <=> the four 5 man tiles
In the game log, where one can crawl from the tenhou.net, they use a more compact, yet not the most
efficient way to represent tiles. The projection from tiles to its representation is as follows:
11-19 <=> 1-9 man
21-29 <=> 1-9 pin
31-39 <=> 1-9 suo
41-47 <=> ESWNBFC
51,52,53 <=> red 5 man, pin, suo
For developing your AI agent for Japanese Riichi Mahjong, we suggest to use the most compact 34-form. The
mapping rule is quite easy:
0-8 <=> 1-9 man
9-17 <=> 1-9 pin
18-26 <=> 1-9 suo
27-33 <=> ESWNBFC
34,35,36 <=> red 5 man,pin,suo
So this class provides different class methods and attributes for converting between these three different
representation systems.
--------------------------------------------------------------------------------------------------------------
Class attributes (Explanation):
<-- TYPE: list of list ------------------------------------------>
index_to_chow id --> the tiles which make a chow in 34-form
<-- TYPE: dictionary -------------------------------------------->
his_to_34_dic tiles in game history form --> 34-form
bns_ind_bd_dic bonus indicating tiles at border --> corresponding bonus tiles
<-- TYPE: list -------------------------------------------------->
to_graph_list 34-form --> unicode graph form
tile_desc_list 34-form --> string from description
WINDS all wind tiles in 34-form
THREES all dragon tiles in 34-form
HONORS all character tiles in 34-form
ONES all tiles with number 1 in 34-form
NINES all tiles with number 9 in 34-form
TERMINALS all tiles either with number 1 or number 9 in 34-form
ONENINE terminal tiles plus character tiles in 34-form
GREENS all tiles that are pure green in color in 34-form
RED_BONUS all red bonus tiles in 136-form
<-- TYPE: integer ----------------------------------------------->
EAST, SOUTH, WEST, NORTH wind tile in 34-form
BLANK, FORTUNE, CENTER dragon tile in 34-form
RED_MAN, RED_PIN, RED_SOU red bonus tile in 136-form
--------------------------------------------------------------------------------------------------------------
"""
his_to_34_dic = {11: 0, 12: 1, 13: 2, 14: 3, 15: 4, 16: 5, 17: 6, 18: 7, 19: 8,
21: 9, 22: 10, 23: 11, 24: 12, 25: 13, 26: 14, 27: 15, 28: 16, 29: 17,
31: 18, 32: 19, 33: 20, 34: 21, 35: 22, 36: 23, 37: 24, 38: 25, 39: 26,
41: 27, 42: 28, 43: 29, 44: 30, 45: 31, 46: 32, 47: 33,
51: 4, 52: 13, 53: 22}
his34_to_34_dic = {34: 4, 35: 13, 36: 22}
bns_ind_bd_dic = {8: 0, 17: 9, 26: 18, 30: 27, 33: 31, 34: 5, 35: 14, 36: 23}
to_graph_list = [
"🀇", "🀈", "🀉", "🀊", "🀋", "🀌", "🀍", "🀎", "🀏", "🀙", "🀚", "🀛", "🀜", "🀝", "🀞", "🀟", "🀠", "🀡",
"🀐", "🀑", "🀒", "🀓", "🀔", "🀕", "🀖", "🀗", "🀘", "🀀", "🀁", "🀂", "🀃", "🀆", "🀅", "🀄", "[🀋]", "[🀝]",
"[🀔]"
]
EAST, SOUTH, WEST, NORTH, BLANK, FORTUNE, CENTER = 27, 28, 29, 30, 31, 32, 33
WINDS, THREES, HONORS = [27, 28, 29, 30], [31, 32, 33], [27, 28, 29, 30, 31, 32, 33]
ONES, NINES, TERMINALS = [0, 9, 18], [8, 17, 26], [0, 8, 9, 17, 18, 26]
ONENINE = [0, 8, 9, 17, 18, 26, 27, 28, 29, 30, 31, 32, 33]
GREENS = [19, 20, 21, 23, 25, 32]
RED_MAN, RED_PIN, RED_SOU = 16, 52, 88
RED_BONUS = [16, 52, 88]
index_to_chow = [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8],
[9, 10, 11], [10, 11, 12], [11, 12, 13], [12, 13, 14], [13, 14, 15], [14, 15, 16], [15, 16, 17],
[18, 19, 20], [19, 20, 21], [20, 21, 22], [21, 22, 23], [22, 23, 24], [23, 24, 25], [24, 25, 26]]
tile_desc_list = ['1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m', '9m',
'1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p',
'1s', '2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s',
'E', 'S', 'W', 'N', 'B', 'F', 'C']
@staticmethod
def cal_bonus_tiles(bonus_indicators_34):
"""
Convert bonus indicators in 34-form to the corresponding bonus tiles in 34-form.
:param bonus_indicators_34: a single integer or a list of integer
:return: a list of the corresponding bonus tiles
"""
if isinstance(bonus_indicators_34, int):
return [Tile.bns_ind_bd_dic.get(bonus_indicators_34, bonus_indicators_34 + 1)]
if isinstance(bonus_indicators_34, list):
res = []
for b in bonus_indicators_34:
res.append(Tile.bns_ind_bd_dic.get(b, b + 1))
return res
@staticmethod
def t34_to_str(tiles):
"""
Convert a list of tiles in 34-form to string description
:param tiles: a list of tiles in 34-form
:return: a represenation of the tiles in string
"""
tiles.sort()
man = [t for t in tiles if t < 9]
pin = [t - 9 for t in tiles if 9 <= t < 18]
suo = [t - 18 for t in tiles if 18 <= t < 27]
chr = [t for t in tiles if t >= 27]
m = man and (''.join([str(m + 1) for m in man]) + 'm') or ''
p = pin and ''.join([str(p + 1) for p in pin]) + 'p' or ''
s = suo and ''.join([str(b + 1) for b in suo]) + 's' or ''
z = chr and ''.join([Tile.tile_desc_list[ch] for ch in chr]) or ''
return m + p + s + z
@staticmethod
def t136_to_str(tiles):
"""
Convert a list of tiles in 136-form to string description
:param tiles: a list of tiles in 136-form
:return: a represenation of the tiles in string
"""
tiles34 = [t // 4 for t in tiles]
return Tile.t34_to_str(tiles34)
@staticmethod
def t34_to_grf(tiles):
"""
Convert tiles in 34-form to unicode graph representation
:param tiles: a list of tiles or a single tile in 34-form
:return: a string of the tiles' unicode graph
"""
if isinstance(tiles, int):
if tiles >= 0:
return Tile.to_graph_list[tiles]
if isinstance(tiles, list):
if len(tiles) > 0 and isinstance(tiles[0], list):
graphs = ""
for meld in tiles:
graphs += ''.join([Tile.to_graph_list[t] for t in meld if t >= 0]) + " "
return graphs
else:
graphs = [Tile.to_graph_list[t] for t in tiles if t >= 0]
return ''.join(graphs)
@staticmethod
def t136_to_grf(tiles):
"""
Convert tiles in 136-form to unicode graph representation
:param tiles: a list of tiles or a single tile in 136-form
:return: a string of the tiles' unicode graph
"""
tiles34 = None
if isinstance(tiles, int):
tiles34 = tiles // 4
if isinstance(tiles, list):
if len(tiles) > 0 and isinstance(tiles[0], list):
tiles34 = [[t // 4 for t in m] for m in tiles]
else:
tiles34 = [t // 4 for t in tiles]
if tiles34:
return Tile.t34_to_grf(tiles34)
else:
return ""
@staticmethod
def his_to_34(tiles):
"""
Convert tiles in game log data form to 34-form. In game logs, tiles are represented as follows:
11-19 <=> 1-9 man
21-29 <=> 1-9 pin
31-39 <=> 1-9 suo
41-47 <=> E, S, W, N, B, F, C
51, 52, 53 <=> red 5 man, red 5 pin, red 5 suo
:param tiles: a single tile or a list of tiles in game log data form
:return: a list of tiles in 34-form
"""
if isinstance(tiles, int):
return Tile.his_to_34_dic[tiles]
elif isinstance(tiles, list):
return [Tile.his_to_34_dic[t] for t in tiles]
else:
raise TypeError
@staticmethod
def t60_to_bns(tiles60):
"""
Convert bonus indicators in game log form to the corresponding bonus tiles in 34-form
:param tiles60: a single tile or a list of tiles in game log form
:return: a single or a list of bonus tiles in 34-form
"""
if isinstance(tiles60, int):
return Tile.bns_ind_bd_dic.get(Tile.his_to_34(tiles60), Tile.his_to_34(tiles60) + 1)
elif isinstance(tiles60, list):
return [Tile.bns_ind_bd_dic.get(t, t + 1) for t in Tile.his_to_34(tiles60)]
else:
print("Wrong parameters: Tile.indicator_to_bonus(tiles60)")
@staticmethod
def self_wind(dealer):
"""
Calculate self bonus wind given the seat number of the dealer. The bot always has seat number 0, the player
right next to the bot has seat number 1, and vice versa...
:param dealer: the seat number of dealer
:return: bot's self bonus wind in 34-form
"""
return Tile.WINDS[(4 - dealer):] + Tile.WINDS[0:(4 - dealer)]
@staticmethod
def same_type(tile34_1, tile34_2):
"""
Check whether the two observed tiles are of the same tile type.
:param tile34_1: the first tile in 34-form
:param tile34_2: the second tile in 34-form
:return: a boolean which indicates whether they are of the same type
"""
return tile34_1 // 9 == tile34_2 // 9
class Meld:
"""
Intention of using this class:
A meld is a set of tiles which satisfy a certain constraint. Mahjong is a contraints satisfactory
optimisation problem. Basically one can represent a meld just by a list of integers, where each integer
stands for a certain kind of tile. This class pack other information along with the tiles together to
satisfy the needs of the client of tenhou.net
"""
CHI = 'chi'
PON = 'pon'
KAN = 'kan'
CHANKAN = 'chankan'
NUKI = 'nuki'
def __init__(self, type=None, tiles=None, open=True, called=None, from_whom=None, by_whom=None):
"""
To initialise a class instance of meld.
:param type: the type of the meld, can be chi, pon, kan, chankan
:param tiles: all the meld tiles in 136 form, e.g. a pon: 4(2m),5(2m),7(2m)
:param open: all pons and chows are open, but kan can be closed, a closed kan is when one makes a kan all by
self drawn tiles
:param called: the tile in 136-form, which was a opponent's discard and one has made the meld with this tile
:param from_whom: indicates which opponent's discard was taken
:param by_whom: indicates who has called the meld
"""
self.type = type
self.tiles = tiles
self.open = open
self.called_tile = called
self.from_whom = from_whom
self.by_whom = by_whom
def __str__(self):
"""
Represent the meld in unicode graph form
:return: a string of unicode graph form of the meld
"""
return '{}, {}'.format(
self.type, Tile.t136_to_grf(self.tiles), self.tiles
)
def __repr__(self):
return self.__str__()
@property
def tiles_34(self):
"""
Getter: Convert the meld tiles to 34-form
:return: a list of meld tiles in 34-form
"""
return [x//4 for x in self.tiles]
@property
def tiles_graph(self):
"""
Getter: Convert the meld tiles to unicode graph form
:return: a string of unicode graph representation of the meld tiles
"""
return Tile.t136_to_grf(self.tiles)
@property
def tiles_string(self):
"""
Getter: Convert the meld tiles to string form
:return: a string which represents the meld tiles
"""
return Tile.t136_to_str(self.tiles)
class Partition:
@staticmethod
def _partition_single_type(tiles34):
"""
Partition tiles of one type into melds, half-finished melds and singles
:param tiles34: tiles of the same type
:return: a list of multiple partition results, each partition result is a list of list, where each list in a
partition represents a partitioned component
"""
len_t = len(tiles34)
# no tiles of this type
if len_t == 0:
return [[]]
# one tile, or two tile which can be parsed into an open set
if len_t == 1 or (len_t == 2 and abs(tiles34[0] - tiles34[1]) < 3):
return [[tiles34]]
# two separate tiles
if len_t == 2:
return [[tiles34[0:1], tiles34[1:2]]]
res = []
# parse a pon meld
if tiles34[0] == tiles34[1] == tiles34[2]:
tmp_res = Partition._partition_single_type(tiles34[3:])
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([tiles34[0:3]] + tile_set)
# parse a chow meld
if tiles34[0] + 1 in tiles34 and tiles34[0] + 2 in tiles34:
rec_tiles = deepcopy(tiles34)
rec_tiles.remove(tiles34[0])
rec_tiles.remove(tiles34[0] + 1)
rec_tiles.remove(tiles34[0] + 2)
tmp_res = Partition._partition_single_type(rec_tiles)
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([[tiles34[0], tiles34[0] + 1, tiles34[0] + 2]] + tile_set)
# parse an two-headed half-finished meld
if tiles34[0] + 1 in tiles34:
rec_tiles = deepcopy(tiles34)
rec_tiles.remove(tiles34[0])
rec_tiles.remove(tiles34[0] + 1)
tmp_res = Partition._partition_single_type(rec_tiles)
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([[tiles34[0], tiles34[0] + 1]] + tile_set)
# parse an dead half-finished meld
if tiles34[0] + 2 in tiles34:
rec_tiles = deepcopy(tiles34)
rec_tiles.remove(tiles34[0])
rec_tiles.remove(tiles34[0] + 2)
tmp_res = Partition._partition_single_type(rec_tiles)
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([[tiles34[0], tiles34[0] + 2]] + tile_set)
# parse a pair
if tiles34[0] == tiles34[1]:
tmp_res = Partition._partition_single_type(tiles34[2:])
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([tiles34[0:2]] + tile_set)
tmp_res = Partition._partition_single_type(tiles34[1:])
if len(tmp_res) > 0:
for tile_set in tmp_res:
res.append([tiles34[0:1]] + tile_set)
tuned_res = []
min_len = min([len(p) for p in res])
for p in res:
if len(p) <= min_len and p not in tuned_res:
tuned_res.append(p)
return tuned_res
@staticmethod
def partition(tiles34):
"""
Partition a set of tiles in 34-form into finished melds, half-finished melds and singles.
:param tiles34:
a list of tiles in 34-form
:return:
a list of partition results of the input tiles, each partition is a list of list,
where each list represents a partitioned component
"""
p_man = Partition._partition_single_type([t for t in tiles34 if 0 <= t < 9])
p_pin = Partition._partition_single_type([t for t in tiles34 if 9 <= t < 18])
p_suo = Partition._partition_single_type([t for t in tiles34 if 18 <= t < 27])
h_chr = [t for t in tiles34 if 27 <= t < 34]
p_chr = [[[chr_tile] * h_chr.count(chr_tile) for chr_tile in set(h_chr)]]
res = []
for pm in p_man:
for pp in p_pin:
for ps in p_suo:
for pc in p_chr:
res.append(pm + pp + ps + pc)
return res
@staticmethod
def partition_winning_tiles(hand34, final_tile):
hand_total = hand34 + [final_tile]
hand_total_set = set(hand_total)
res = []
@staticmethod
def _shantin_normal(partitions, called_meld_num):
def geo_vec_normal(p):
geo_vec = [0] * 6
def incre(set_type):
geo_vec[set_type] += 1
for m in p:
len(m) == 1 and incre(0)
len(m) == 2 and abs(m[0] - m[1]) == 0 and incre(3)
len(m) == 2 and abs(m[0] - m[1]) == 1 and incre(2 if m[0] % 9 > 0 and m[1] % 9 < 8 else 1)
len(m) == 2 and abs(m[0] - m[1]) == 2 and incre(1)
len(m) == 3 and incre(5 if m[0] == m[1] else 4)
return geo_vec
def shantin_n(p):
geo_vec = geo_vec_normal(p)
needed_set = (4 - called_meld_num) - geo_vec[4] - geo_vec[5]
if geo_vec[3] > 0:
if geo_vec[1] + geo_vec[2] + geo_vec[3] - 1 >= needed_set:
return needed_set - 1
else:
return 2 * needed_set - (geo_vec[1] + geo_vec[2] + geo_vec[3] - 1) - 1
else:
if geo_vec[1] + geo_vec[2] >= needed_set:
return needed_set
else:
return 2 * needed_set - (geo_vec[1] + geo_vec[2])
return min([shantin_n(p) for p in partitions])
@staticmethod
def shantin_normal(tiles34, called_melds):
"""
Calculate the normal shantin of a list of tiles.
Normal shantin means that there is no any extra constraint on the winning tiles' pattern.
:param tiles34:
a list of tiles in 34-form, normally it is meant to be the tiles in hand
:param called_melds:
the ever called melds
:return:
the normal shantin.
"""
return Partition._shantin_normal(Partition.partition(tiles34), len(called_melds))
@staticmethod
def _shantin_pinhu(partitions, called_meld_num, bonus_chrs):
if called_meld_num:
return 10
def geo_vec_pinhu(p):
geo_vec = [0] * 6
def incre(set_type):
geo_vec[set_type] += 1
for m in p:
len(m) == 1 and incre(0)
len(m) == 2 and abs(m[0] - m[1]) == 0 and m[0] not in bonus_chrs and incre(3)
len(m) == 2 and abs(m[0] - m[1]) == 1 and incre(2 if m[0] % 9 > 0 and m[1] % 9 < 8 else 1)
len(m) == 2 and abs(m[0] - m[1]) == 2 and incre(1)
len(m) == 3 and incre(5 if m[0] == m[1] else 4)
return geo_vec
def shantin_ph(p):
geo = geo_vec_pinhu(p)
need_chow = 4 - geo[4]
if geo[1] + geo[2] >= need_chow:
return (geo[3] == 0) + need_chow - 1 + (geo[2] == 0)
else:
return (geo[3] == 0) + need_chow - 1 + need_chow - geo[1] - geo[2]
return min(shantin_ph(p) for p in partitions)
@staticmethod
def shantin_no_triplets(tiles34, called_melds, bonus_chrs):
"""
Calculate the shantin of reaching a "no triplets" waiting hand.
(1) A "No triplets" hand means the expected winning hand tiles has no pons(triplets)
(2) There can be only chows(sequences),
(3) The pair should not be any kind of bonus character tiles!
:param tiles34:
A list of tiles in 34-form, usually the tiles in hand
:param called_melds:
The ever called melds.
When any kind of meld if called, the form "pinhu" is not any more constructable
:param bonus_chrs:
A list of character tiles that are the bot's yaki tiles
:return:
The shantin of "No triplets" form
"""
partitions = Partition.partition(tiles34)
return Partition._shantin_pinhu(partitions, len(called_melds), bonus_chrs)
@staticmethod
def _shantin_no19(partitions, called_melds):
for m in called_melds:
if any(tile in Tile.ONENINE for tile in m):
return 10
def geo_vec_no19(p):
geo_vec = [0] * 6
def incre(set_type):
geo_vec[set_type] += 1
for m in p:
if m[0] > 26:
continue
len(m) == 1 and 0 < m[0] % 9 < 8 and incre(0)
len(m) == 2 and abs(m[0] - m[1]) == 0 and 0 < m[0] % 9 < 8 and incre(3)
len(m) == 2 and abs(m[0] - m[1]) == 1 and m[0] % 9 > 1 and m[1] % 9 < 7 and incre(2)
len(m) == 2 and abs(m[0] - m[1]) == 1 and (m[0] % 9 == 1 or m[1] % 9 == 7) and incre(1)
len(m) == 2 and abs(m[0] - m[1]) == 2 and m[0] % 9 > 0 and m[1] % 9 < 8 and incre(1)
len(m) == 3 and m[0] == m[1] and 0 < m[0] % 9 < 8 and incre(5)
len(m) == 3 and m[0] != m[1] and incre(4 if m[0] % 9 > 0 and m[2] % 9 < 8 else 1)
return geo_vec
def shantin_no19(p):
geo_vec = geo_vec_no19(p)
needed_set = (4 - len(called_melds)) - geo_vec[4] - geo_vec[5]
if geo_vec[3] > 0:
if geo_vec[1] + geo_vec[2] + geo_vec[3] - 1 >= needed_set:
return needed_set - 1
else:
need_single = needed_set - (geo_vec[1] + geo_vec[2] + geo_vec[3] - 1)
if geo_vec[0] >= need_single:
return 2 * needed_set - (geo_vec[1] + geo_vec[2] + geo_vec[3] - 1) - 1
else:
return 2 * needed_set - (geo_vec[1] + geo_vec[2] + geo_vec[3] - 1) - 1 + need_single - geo_vec[
0]
else:
if geo_vec[1] + geo_vec[2] >= needed_set:
return needed_set + (geo_vec[0] == 0)
else:
need_single = needed_set - (geo_vec[1] + geo_vec[2]) + 1
if geo_vec[0] >= need_single:
return 2 * needed_set - (geo_vec[1] + geo_vec[2])
else:
return 2 * needed_set - (geo_vec[1] + geo_vec[2]) + need_single - geo_vec[0]
return min(shantin_no19(p) for p in partitions)
@staticmethod
def shantin_no_19(tiles34, called_melds):
"""
Calculate the shantin of "no19" form.
A "no19" hand mean the expected winning hand tiles only contain tiles from number 2 to 8.
:param tiles34:
A list of tiles in 34-form, usually the tiles in hand
:param called_melds:
The ever called melds
:return:
The shantin of no19 form
"""
partitions = Partition.partition(tiles34)
return Partition._shantin_no19(partitions, called_melds)
@staticmethod
def shantin_no_sequences(tiles34, called_melds):
"""
Calculate the shantin of "No sequence" form.
A "No sequence" from means that the expected winning tiles has no chow(sequence) melds
:param tiles34:
A list of tiles in 34-form, usually the hand tiles
:param called_melds:
The ever called melds
:return:
The shantin of pph form
"""
if any(len(m) > 1 and m[0] != m[1] for m in called_melds):
return 10
num_kezi = len([tile for tile in set(tiles34) if tiles34.count(tile) == 3])
num_pair = len([tile for tile in set(tiles34) if tiles34.count(tile) == 2])
need_kezi = 4 - len(called_melds) - num_kezi
return (need_kezi - 1) if (num_pair >= need_kezi + 1) else (2 * need_kezi - num_pair)
@staticmethod
def shantin_seven_pairs(tiles34, called_melds):
"""
Calculate shantin of form "Seven pairs".
A "Seven pairs" form means the expected winning tiles are 7 pairs
:param tiles34:
A list of tiles in 34-form, usually the hand tiles
:param called_melds:
The ever called melds
:return:
The shantin of form "Seven pairs"
"""
if len(called_melds) > 0:
return 10
else:
num_pair = len([tile for tile in set(tiles34) if tiles34.count(tile) >= 2])
return 6 - num_pair
@staticmethod
def _shantin_pure_color(tiles34, called_melds, partitions):
qh_type = []
if len(called_melds) > 0:
meld_types = []
for m in called_melds:
if m[0] // 9 == 3:
continue
if m[0] // 9 not in meld_types:
meld_types.append(m[0] // 9)
if len(meld_types) > 1:
return 10
else:
qh_type = meld_types
if (len(qh_type) == 0 and len(called_melds) > 0) or len(called_melds) == 0:
type_geo = [
len([t for t in tiles34 if 0 <= t < 9]),
len([t for t in tiles34 if 9 <= t < 18]),
len([t for t in tiles34 if 18 <= t < 27])
]
max_num = max(type_geo)
qh_type = [i for i in range(3) if type_geo[i] == max_num]
if len(qh_type) == 0:
return 10
def geo_vec_qh(p, tp):
allowed_types = [tp, 3]
geo_vec = [0] * 6
def incre(set_type):
geo_vec[set_type] += 1
for m in p:
if m[0] // 9 in allowed_types:
len(m) == 1 and incre(0)
len(m) == 2 and abs(m[0] - m[1]) == 0 and incre(3)
len(m) == 2 and abs(m[0] - m[1]) == 1 and incre(2 if m[0] % 9 > 0 and m[1] % 9 < 8 else 1)
len(m) == 2 and abs(m[0] - m[1]) == 2 and incre(1)
len(m) == 3 and incre(5 if m[0] == m[1] else 4)
return geo_vec
def shantin_n(p, tp):
geo_vec = geo_vec_qh(p, tp)
# print(geo_vec)
s, p, o, f = geo_vec[0], geo_vec[3], geo_vec[1] + geo_vec[2], geo_vec[4] + geo_vec[5]
if p > 0:
p -= 1
st = 0
needed_set = 3 - len(called_melds) - f
while needed_set > 0:
if o > 0:
needed_set, o, st = needed_set - 1, o - 1, st + 1
elif p > 0:
needed_set, p, st = needed_set - 1, p - 1, st + 1
elif s > 0:
needed_set, st, s = needed_set - 1, st + 2, s - 1
else:
needed_set, st = needed_set - 1, st + 3
return st if (o + p) > 0 else (st + 1 if s > 0 else st + 2)
else:
st = 0
needed_set = 4 - len(called_melds) - f
while needed_set > 0:
if o > 0:
needed_set, o, st = needed_set - 1, o - 1, st + 1
elif s > 0:
needed_set, st, s = needed_set - 1, st + 2, s - 1
else:
needed_set, st = needed_set - 1, st + 3
return st if s > 0 else st + 1
def shantin_qh(p):
return min([shantin_n(p, t) for t in qh_type])
return min([shantin_qh(p) for p in partitions])
@staticmethod
def shantin_pure_color(tiles34, called_melds):
"""
Calculate the shantin of "pure color" form.
A "pure color" form means the expected winning tiles contain only character tiles and one other type of tiles.
:param tiles34:
A list of tiles in 34-form
:param called_melds:
The ever called melds
:return:
The shantin of "pure color"
"""
partitions = Partition.partition(tiles34)
return Partition._shantin_pure_color(tiles34, called_melds, partitions)
@staticmethod
def shantin_multiple_forms(tiles34, called_melds, bonus_chrs):
"""
Calculate shantin of different forms.
It's an assemble of the various single shantin calculation function
:param tiles34:
A list of tiles in 34-form
:param called_melds:
The ever called melds
:param bonus_chrs:
A list of bonus character tiles
:return:
A dictionary, which has the special form name as key and the corresponding shantin as value
"""
res = {}
partitions = Partition.partition(tiles34)
res["normal______"] = Partition._shantin_normal(partitions, len(called_melds))
res["no_triplets_"] = Partition._shantin_pinhu(partitions, len(called_melds), bonus_chrs)
res["no_19_______"] = Partition._shantin_no19(partitions, called_melds)
res["no_sequences"] = Partition.shantin_no_sequences(tiles34, called_melds)
res["seven_pairs_"] = Partition.shantin_seven_pairs(tiles34, called_melds)
res["pure_color__"] = Partition._shantin_pure_color(tiles34, called_melds, partitions)
return res
class WinWaitCal:
@staticmethod
def score_calculation_base(han, fu, is_dealer, is_zimo):
"""
Calculate the base score knowing the han and fu value.
Fu is a value which stands for a base point, and han is the exponential factor of final scores.
The very basic score calculation is as follows, while it involves more other details.
---------------------------------------------------
| base_score = fu * (2 ** (han + 2)) |
---------------------------------------------------
:param han:
A han is the unit of yaku, yaku is a special pattern that the winning tiles have satisfied.
Multiples yakus can be achieved at the same time, and thus han is the sum of all yaku values.
Please check in this namespace the the function han_calculation(...)
:param fu:
Fu is the unit for base points, the calculation of fu is beyong complicated
For calculation of Fu please check the function fu_calculation(...) in this namespace
:param is_dealer:
whether the observed player is a dealer
:param is_zimo:
whether the observed player has won by self drawn tile or not
:return:
a tuple (integer score, string description)
"""
if han == 0:
return 0, ''
elif han < 5: # when han < 5, the fu has influence on the final point
if (fu >= 40 and han >= 4) or (fu >= 70 and han >= 3):
if is_dealer:
return 12000, "満貫4000点∀" if is_zimo else "満貫12000点"
else:
return 8000, "満貫2000-4000点" if is_zimo else "満貫8000点"
base_score = fu * (2 ** (han + 2))
if is_zimo:
if is_dealer:
each = ((base_score * 2 - 1) // 100 + 1) * 100
return each * 3, "{}符{}Han{}点∀".format(fu, han, each)
else:
dscore = ((base_score * 2 - 1) // 100 + 1) * 100
xscore = ((base_score - 1) // 100 + 1) * 100
return dscore + 2 * xscore, "{}符{}Han{}-{}点".format(fu, han, xscore, dscore)
else:
score = ((base_score * 6 - 1) // 100 + 1) * 100 if is_dealer else ((base_score * 4 - 1) // 100 + 1) * 100
return score, "{}符{}Han{}点".format(fu, han, score)
elif han == 5: # when han >= 5, the fu does not make any difference to final score
if is_dealer:
return 12000, "満貫4000点∀" if is_zimo else "満貫12000点"
else:
return 8000, "満貫2000-4000点" if is_zimo else "満貫8000点"
elif 6 <= han <= 7:
if is_dealer:
return 18000, "跳满6000点∀" if is_zimo else "跳满18000点"
else:
return 12000, "跳满3000-6000点" if is_zimo else "跳满12000点"
elif 8 <= han <= 10:
if is_dealer:
return 24000, "倍满8000点∀" if is_zimo else "倍满24000点"
else:
return 16000, "倍满4000-8000点" if is_zimo else "倍满16000点"
elif 11 <= han <= 12:
if is_dealer:
return 36000, "三倍满12000点∀" if is_zimo else "三倍满36000点"
else:
return 24000, "三倍满6000-12000点" if is_zimo else "三倍满24000点"
else:
if is_dealer:
return 48000, "役满16000点∀" if is_zimo else "役满48000点"
else:
return 32000, "役满8000-16000点" if is_zimo else "役满32000点"
@staticmethod
def fu_calculation(hand_partition, final_tile, melds, minkan, ankan, is_zimo, player_wind, round_wind):
"""
Calculate the Fu of the winning tiles.
Fu is sort of multiplier for the base socre, since base_score = fu * (2 ** (han + 2))
:param hand_partition:
List of list, it's a partition of hand tiles
:param final_tile:
Integer, the final tile with which the observed player has won
:param melds:
List of list, triplets and sequences melds of the observed player
:param minkan:
List of list, minkan melds of the observed player
:param ankan:
List of list, ankan melds of the observed player
:param is_zimo:
Boolean, Whether the observed player has won by self drawn tile or not
:param player_wind:
Integer, indicates what is the wind tile which adds yaku for the observed player
:param round_wind:
Integer, indicates what is the wind tiles which ass yaku for all players at table
:return:
A dict, {description of the value : value}
res["fu"] = a dict, key=fu type, value=fu value
res["fu_sum"] = integer, raw sum of fu values
res["fu_round"] = integer, rounded sum of fu values
res["fu_desc"] = string, showing what fu types are achieved
"""
if len(hand_partition) == 7:
return {"fu": {"七对(25Fu)": 25}, "fu_sum": 25, "fu_round": 25, "fu_desc": "七对(25Fu)"}
if len(hand_partition) + len(melds) == 5:
chows = [m for m in hand_partition + melds if m[0] != m[1]]
pair = [m for m in hand_partition if len(m) == 2][0]
if len(chows) == 4 and pair[0] not in Tile.THREES + [player_wind, round_wind]:
chows_with_final = [chow for chow in chows if final_tile in chow]
if any((chw[0] == final_tile and chw[0] % 9 != 6) or (chw[2] == final_tile and chw[2] % 9 != 2)
for chw in chows_with_final):
if is_zimo and len(melds) == 0:
return {"fu": {"門前清自摸和平和(20Fu)": 20}, "fu_sum": 20, "fu_round": 20, "fu_desc": "門前清自摸和平和(20Fu)"}
if not is_zimo and len(melds) > 0:
return {"fu": {"非门清平和荣和(30Fu)": 30}, "fu_sum": 30, "fu_round": 30, "fu_desc": "非门清平和荣和(30Fu)"}
fu = {}
def add_base(b, b_desc):
fu[b_desc] = b
def check_kezi():
for meld in hand_partition:
if len(meld) == 3:
if meld[0] == meld[1] == meld[2]:
if meld[0] in Tile.ONENINE:
if is_zimo or final_tile != meld[0]:
add_base(8, "幺九暗刻(8Fu)")
else:
add_base(4, "幺九明刻(4Fu)")
else:
if is_zimo or final_tile != meld[0]:
add_base(4, "中张暗刻(4Fu)")
else:
add_base(2, "中张明刻(2Fu)")
for meld in melds:
if meld[0] == meld[1]:
if meld[0] in Tile.ONENINE:
add_base(4, "幺九明刻(4Fu)")
else:
add_base(2, "中张明刻(2Fu)")
def check_kans():
for mk in minkan:
if mk[0] in Tile.ONENINE:
add_base(16, "幺九明杠(16Fu)")
else:
add_base(8, "中张明杠(8Fu)")
for ak in ankan:
if ak[0] in Tile.ONENINE:
add_base(32, "幺九暗杠(32Fu)")
else:
add_base(16, "中张暗杠(16Fu)")
def check_pair(p):
if p[0] in Tile.THREES:
add_base(2, "役牌雀头(2Fu)")
if p[0] == player_wind:
add_base(2, "自风雀头(2Fu)")
if p[0] == round_wind:
add_base(2, "场风雀头(2Fu)")
def check_waiting_type(p):
chws = [m for m in hand_partition + melds if m[0] != m[1]]
chws_with_final = [chow for chow in chws if final_tile in chow]
if p[0] == final_tile and len(chws_with_final) == 0:
add_base(2, "单吊(2Fu)")
elif len(chws_with_final) > 0:
if all((chw[1] == final_tile or (chw[0] == final_tile and chw[2] % 9 == 8)
or (chw[2] == final_tile and chw[0] % 9 == 0)) for chw in chws_with_final):
add_base(2, "边张嵌张胡牌(2Fu)")
def check_win_type():
if is_zimo:
add_base(2, "自摸(2Fu)")
if not is_zimo and len(melds + minkan) == 0:
add_base(10, "门前清荣胡(10Fu)")
pair = [m for m in hand_partition if len(m) == 2][0]
check_kezi()
check_kans()
check_pair(pair)
check_waiting_type(pair)
check_win_type()
res = dict()
res["fu"] = fu
res["fu_sum"] = sum([v for k, v in fu.items()])
res["fu_round"] = ((res["fu_sum"] - 1) // 10 + 1) * 10
res["fu_desc"] = " ".join([k for k, v in fu.items()])
return res
@staticmethod
def han_calculation(hand_partition, final_tile, melds, minkan, ankan, is_zimo, player_wind, round_wind, reach):
"""
Calculate the han value.
Han is a unit of yaku.
Yakuman is another unit of yaku, which means maxi!
A Yaku is a special pattern that the winning tiles satisfy.
Each extra han would potentially double the final point up to a limit, since
---------------------------------------------------
| base_score = fu * (2 ** (han + 2)) |
---------------------------------------------------
See score_calculation() in this class
:param hand_partition:
List of list, it's a partition of hand tiles
:param final_tile:
Integer, the final tile with which the observed player has won
:param melds:
List of list, triplets and sequences melds of the observed player
:param minkan:
List of list, minkan melds of the observed player
:param ankan:
List of list, ankan melds of the observed player
:param is_zimo:
Boolean, Whether the observed player has won by self drawn tile or not
:param player_wind:
Integer, indicates what is the wind tile which adds yaku for the observed player
:param round_wind:
Integer, indicates what is the wind tiles which ass yaku for all players at table
:param reach:
Boolean, whether the observed player has called Riichi
:return:
A dict, {description of the value : value}
res["han"] = a dict, key=the yaku, value=the corresponding han value
res["ykman"] = a dict, key=the yakuman, value=the corresponding yakuman value
res["han_sum"] = integer, sum of all han values
res["yk_sum"] = integer, sum of yakumans
res["han_desc"] = string, all yakus that are achieved
"""
han, ykman = {}, {}
def add_han(h, h_desc):
han[h_desc] = h
def add_yakuman(m, m_desc):
ykman[m_desc] = m
all_melds = hand_partition + melds + minkan + ankan
all_melds_no_kan = hand_partition + melds
all_tiles = [tile for meld in all_melds for tile in meld]
is_menqing = len(melds + minkan) == 0
len_open = len(melds + minkan + ankan)
len_total = len_open + len(hand_partition)
def check_all_single_one_nine():
if len(hand_partition) == 13:
add_yakuman(1, "国士無双(Maxi)")
def check_seven_pairs():
if len(hand_partition) == 7:
add_han(2, "七対子(2Han)")
def check_win_type():