In python how can you sort a hand of poker (list) and detect if it is a straight or a royal flush

一个人想着一个人 提交于 2020-01-03 03:47:07

问题


I am trying to create a poker program with python where I get a hand like the one below. What I want to do do is sort the hand and then return true if it True. I need to know if it is a straight as well if it is a royal flush.

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))

need to be sorted and return if it is a straight and/or is a royal flush


回答1:


Unfortunately, aces can be high or low, depending on what produces a better hand. I will initially value them as 14, but deal with low aces when I get to straights. First, a function to convert a card to a number. I use a dict to look up the value of face cards:

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]]

Sorting a hand is now simple:

hand=['Jc','2h','6d','Th']
hand.sort(key=to_number)
print(hand)
# prints ['2h','6d','Th','Jc']

Checking for a flush is as simple as making sure the suit of all other cards match the suit of the first card:

def is_flush(hand):
    test_suit = hand[0][1]
    return all(card[1] == test_suit for card in hand)

Now, to deal with straights. First, we check to see if there is an ace (always the last card of a sorted hand since it is value 14). If there is an ace and the lowest (first, when sorted) card of the hand is a two, we assume the ace is low (since that is the only way you could possibly construct a straight) and check that the remaining cards complete the straight. Otherwise, the ace is automatically high, so we check that each card's value is one higher than the previous:

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))

Now that we have the hard part done, we move on the the royal flush. A royal flush is both a straight and a flush, where the highest card is an ace:

def is_royal_flush(hand):
    hand = sorted(hand, key=to_number)
    return hand[-1][0] == 'A' and is_straight(hand) and is_flush(hand)


来源:https://stackoverflow.com/questions/36525890/in-python-how-can-you-sort-a-hand-of-poker-list-and-detect-if-it-is-a-straight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!