Identifying straight, flush and other categories (from Poker) using Python

后端 未结 1 1836
既然无缘
既然无缘 2021-01-16 00:32

I am newbie to python and learning it from books, forums and developers. Recently, I tried to implement various hand-ranking categories in the poker program. The goal is to

相关标签:
1条回答
  • 2021-01-16 00:47

    The condition for a straight is for your five cards to have adjacent ranks, such that no two cards have the same rank. You can use two different checks to confirm this:

    1. when sorted, the difference between the top card and the bottom card is equal to the total number of cards minus one(e.g. a 4-8 straight has a difference of 4)
    2. no two cards in the straight have the same rank (thus by pigeonhole principle, all ranks between the minimum and maximum must be present

    Here's a sample implementation of that:

    def hasStraight(hand):
        # account for both low-ace and high-ace
        ranks_low = sorted([card._rank for card in hand])
        ranks_high = sorted([(14 if card._rank == 1 else card._rank) for card in hand])
    
        return (
            (
                ranks_low[-1] - (len(hand) - 1) == ranks_low[0]
                or ranks_high[-1] - (len(hand) - 1) == ranks_high[0]
            )                                                        # condition 1
            and len(set(hand)) == len(hand)                          # condition 2
        )
    

    You will also have to account for low-aces and high-aces. You can do this by, for example, doing two similar checks, once with the normal card ranks and once by doing something like `if card._rank == 1: card._rank == 14


    The condition for a flush is simply that all cards are the same suit. This is easy to verify, by simply making a set of all unique suits in the hand, and returning true if that set has only one element (thus all the suits must be the same):

    def hasFlush(hand):
        suits_set = set(*[card._suit for card in hand])
        return len(suits_set) == 1
    

    Once you have those, straight flush and royal flush are easy:

    def hasStraightFlush(hand):
        return hasStraight(hand) and hasFlush(hand)
    
    def hasRoyalFlush(hand):
        ranks = sorted([14 if card._rank == 1 else card._rank for card in hand])
        return (
            hasStraightFlush(hand)
            and ranks[0] == 10 and ranks[-1] == 14
        ) # royal flush starts at 10, ends at high-ace
    
    0 讨论(0)
提交回复
热议问题