Python Forum

Full Version: Variable sorting methods for Enum DataClasses
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So i'm trying to simulate a deck of cards using dataclasses. The suit and rank of a card are represented as a enum.Enum DataClass. Together they make the Card DataClass. A list of cards makes a Deck. Now the wall i've hit lies in the fact that different games using cards have different rules. So in the one game it could be that the hearts are trump and thus a 2 of hearts is higher than a king of spades. While in an other game the rank solely dictates the ordering. How can I define the ordering of a set of cards in de dataclass Deck? Is this even possible?

Here some sample code:

@dataclass
class Suit(enum.Enum):
    HEARTS='hearts'
    SPADES='spades'
    DIAMONDS='diamonds'
    CLUBS='clubs'


@dataclass
class Card():
    suit:Suit
    rank:int

    def __repr__(self):
        return f'{self.suit}{self.rank}'
    
    def __gt__(self, other):
        # IF (for example) Deck.orderingtype == some_ordering_type:
        if self.suit == other.suit:
            return self.rank > other.rank
        else:
            return self.suit > other.suit
        # ELSE: ....
    
@dataclass
class Deck():
    cards:list
    trump:Suit
As you noted in your post, cards do not have an intrinsic value. The value of a card is determined by the card game. I would have the card game assign a value to the cards that is used for comparison. You can default this value to the rank, but the card game can change the value.

What is your plan for aces? These can be the highest or lowest value card in some games, and which is decided by the game, not the card.