python胡牌算法代码
时间: 2024-05-26 10:09:30 浏览: 223
麻将胡牌算法(源代码)
5星 · 资源好评率100%
麻将胡牌算法是麻将AI中的重要组成部分,下面是Python实现的麻将胡牌算法代码:
```python
# coding=utf-8
import itertools
# 判断是否可胡
def is_win(hand_tiles):
# 刻子
kezi = []
# 顺子
shunzi = []
# 对子
duizi = 0
# 拆牌,统计每张牌出现的次数
count_dict = {}
for tile in hand_tiles:
if tile in count_dict:
count_dict[tile] += 1
else:
count_dict[tile] = 1
# 检查刻子和对子
for tile, count in count_dict.items():
if count >= 3:
kezi.append(tile)
elif count == 2:
duizi += 1
# 如果对子数为1,检查顺子
if duizi == 1:
# 拆出所有顺子
for i in range(1, 10):
if i not in count_dict or count_dict[i] == 0:
continue
if i + 1 not in count_dict or count_dict[i + 1] == 0:
continue
if i + 2 not in count_dict or count_dict[i + 2] == 0:
continue
shunzi.append((i, i + 1, i + 2))
count_dict[i] -= 1
count_dict[i + 1] -= 1
count_dict[i + 2] -= 1
# 如果顺子数加刻子数加对子数等于4,则可以胡牌
return len(kezi) + len(shunzi) + duizi == 4
# 获取所有可能的手牌组合
def get_all_combinations():
tiles = [1, 2, 3, 4, 5, 6, 7, 8, 9,
11, 12, 13, 14, 15, 16, 17, 18, 19,
21, 22, 23, 24, 25, 26, 27]
combinations = list(itertools.combinations(tiles, 13))
return combinations
# 测试所有手牌组合,输出可以胡牌的手牌组合和剩余牌
def test_all_combinations():
combinations = get_all_combinations()
for combination in combinations:
if is_win(combination):
print("可以胡牌的手牌:", combination)
remaining_tiles = [i for i in range(1, 28) if i not in combination]
print("剩余牌:", remaining_tiles)
# 测试代码
test_all_combinations()
```
以上代码实现了一个简单的麻将胡牌算法,通过获取所有可能的手牌组合并逐一测试,输出可以胡牌的手牌组合和剩余牌。
阅读全文