1
pull/1/head
wsy182 2024-11-30 22:18:55 +08:00
parent ee8bf46701
commit e58e890ccb
2 changed files with 24 additions and 8 deletions

View File

@ -1,5 +1,7 @@
from collections import defaultdict
from collections import defaultdict
class Hand:
def __init__(self):
# 存储所有的牌
@ -24,14 +26,14 @@ class Hand:
""" 获取手牌中某张牌的数量 """
return self.tile_count[tile]
def can_pong(self, tile):
""" 判断是否可以碰(即是否有3张相同的牌 """
return self.tile_count[tile] >= 2
def can_peng(self, tile):
""" 判断是否可以碰(即是否已经有2张相同的牌摸一张牌后可以碰 """
return self.tile_count[tile] == 2 # 摸一张牌后总数为 3 张,才可以碰
def can_gang(self, tile):
""" 判断是否可以杠(即是否有4张相同的牌 """
return self.tile_count[tile] >= 3
""" 判断是否可以杠(即是否已经有3张相同的牌摸一张牌后可以杠 """
return self.tile_count[tile] == 3 # 摸一张牌后总数为 4 张,才可以杠
def __repr__(self):
""" 返回手牌的字符串表示 """
return f"手牌: {self.tiles}, 牌的数量: {dict(self.tile_count)}"
return f"手牌: {self.tiles}, 牌的数量: {dict(self.tile_count)}"

View File

@ -32,19 +32,33 @@ def test_hand():
print("添加 1条 后的手牌:", hand)
# 测试是否可以碰
assert hand.can_pong("1条") == True, f"测试失败1条应该可以碰"
assert hand.can_pong("3条") == False, f"测试失败3条不可以碰"
assert hand.can_peng("1条") == True, f"测试失败1条应该可以碰"
print("可以碰 1条 的牌:", hand.can_peng("1条"))
assert hand.can_peng("3条") == False, f"测试失败3条不可以碰"
print("不可以碰 3条 的牌:", hand.can_peng("3条"))
# 测试是否可以杠
assert hand.can_gang("1条") == False, f"测试失败1条不可以杠"
print("不可以杠 1条 的牌:", hand.can_gang("1条"))
assert hand.can_gang("2条") == False, f"测试失败2条不可以杠"
print("不可以杠 2条 的牌:", hand.can_gang("2条"))
# 添加更多牌来形成杠
hand.add_tile("2条")
print("添加牌后手牌:", hand)
hand.add_tile("2条")
print("添加牌后手牌:", hand)
assert hand.can_gang("2条") == False, f"测试失败2条不可以杠" # still not enough for gang
# 添加一张更多的 2条 来形成杠
hand.add_tile("2条")
print("添加一张2条后:", hand)
assert hand.can_gang("2条") == True, f"测试失败2条应该可以杠"
print("所有测试通过!")
# 运行测试
test_hand()