我正在尝试用 python 创建一个扑克程序,我得到了如下所示的一手牌。我想做的就是对手进行排序,然后如果为真则返回真。我需要知道它是否是顺子以及是否是皇家同花顺。
hand=['Jc','2h','6d','Th','Kd']
def has_straight(hand):
if hand[4][0] >hand[3][0] and hand[3][0]>hand[2][0] and hand[2][0]>hand[1][0] and hand[1][0]>hand[0][0]:
return True
else:
return False
hand.sort()
print (has_straight(hand))
如果是顺子和/或同花顺,则需要排序并返回
最佳答案
不幸的是,A 可以高也可以低,这取决于什么会产生更好的牌。我最初将它们视为 14,但当我到达顺子时处理低 A。首先,将卡片转换为数字的函数。我使用 dict
来查找人脸牌的值:
FACE_CARDS = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}
def to_number(card):
if card[0].isnumeric():
return int(card[0])
else:
return FACE_CARDS[card[0]]
对牌进行排序现在很简单:
hand=['Jc','2h','6d','Th']
hand.sort(key=to_number)
print(hand)
# prints ['2h','6d','Th','Jc']
检查同花就像确保所有其他牌的花色与第一张牌的花色相匹配一样简单:
def is_flush(hand):
test_suit = hand[0][1]
return all(card[1] == test_suit for card in hand)
现在,处理顺子。首先,我们检查是否有一张 A(始终是已排序手牌的最后一张牌,因为它的值为 14)。如果有一张 A,并且手牌中最低的(排序后的第一张)牌是 2,我们假设 A 是低牌(因为这是构建顺子的唯一方法),并检查剩余的牌是否完成直的。否则,A 自动为高牌,因此我们检查每张牌的值(value)是否比前一张高:
def is_straight(hand):
hand = sorted(hand, key=to_number)
if hand[-1][0] == "A" and hand[0][0] == "2":
# Check that the remaining cards complete the straight
return list(map(to_number, hand[1:-1])) == list(range(3, len(hand)+1))
# You can skip conversion to lists for Python 2
else:
return all(to_number(hand[i])+1 == to_number(hand[i+1]) for i in range(len(hand)-1))
现在我们已经完成了最困难的部分,我们继续讨论皇家同花顺。皇家同花顺既是顺子又是同花,其中最大的牌是 A:
def is_royal_flush(hand):
hand = sorted(hand, key=to_number)
return hand[-1][0] == 'A' and is_straight(hand) and is_flush(hand)
关于python - 在Python中,如何对一手扑克(列表)进行排序并检测它是顺子还是皇家同花顺,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36525890/