Files
mjAi/src/engine/hand.py
2024-11-30 22:44:50 +08:00

50 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from src.engine.mahjong_tile import MahjongTile
from collections import defaultdict
class Hand:
def __init__(self):
# 存储所有的 MahjongTile 对象
self.tiles = []
# 存储每种牌的数量,键为 MahjongTile 对象,值为数量
self.tile_count = defaultdict(int)
def add_tile(self, tile):
""" 向手牌中添加一张牌 """
if not isinstance(tile, MahjongTile):
raise ValueError("必须添加 MahjongTile 类型的牌")
self.tiles.append(tile) # 将牌添加到手牌中
self.tile_count[tile] += 1 # 增加牌的数量
def remove_tile(self, tile):
""" 从手牌中移除一张牌 """
if not isinstance(tile, MahjongTile):
raise ValueError("必须移除 MahjongTile 类型的牌")
if self.tile_count[tile] > 0:
self.tiles.remove(tile)
self.tile_count[tile] -= 1
else:
raise ValueError(f"手牌中没有该牌: {tile}")
def get_tile_count(self, tile):
""" 获取手牌中某张牌的数量 """
if not isinstance(tile, MahjongTile):
raise ValueError("必须是 MahjongTile 类型的牌")
return self.tile_count[tile]
def can_peng(self, tile):
""" 判断是否可以碰即是否已经有2张相同的牌摸一张牌后可以碰 """
if not isinstance(tile, MahjongTile):
raise ValueError("必须是 MahjongTile 类型的牌")
return self.tile_count[tile] == 2 # 摸一张牌后总数为 3 张,才可以碰
def can_gang(self, tile):
""" 判断是否可以杠即是否已经有3张相同的牌摸一张牌后可以杠 """
if not isinstance(tile, MahjongTile):
raise ValueError("必须是 MahjongTile 类型的牌")
return self.tile_count[tile] == 4 # 摸一张牌后总数为 4 张,才可以杠
def __repr__(self):
""" 返回手牌的字符串表示 """
tiles_str = ", ".join(str(tile) for tile in self.tiles)
return f"手牌: [{tiles_str}], 牌的数量: {dict(self.tile_count)}"