Python Forum
Variable sorting methods for Enum DataClasses
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable sorting methods for Enum DataClasses
#1
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
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Return a string or byte object from Enum class? Calab 5 1,846 May-14-2025, 05:21 PM
Last Post: snippsat
  ValueError in dataclasses.py - Please help! andrewk 4 2,595 Feb-17-2025, 11:21 AM
Last Post: andrewk
  ValueError in dataclasses.py - using staking-deposit-cli andrewk 0 747 Feb-10-2025, 09:51 PM
Last Post: andrewk
  Alarm system with state, class, enum. Frankduc 0 2,390 May-04-2022, 01:26 PM
Last Post: Frankduc
Question Having trouble writing an Enum with a custom __new__ method stevendaprano 3 10,024 Feb-13-2022, 06:37 AM
Last Post: deanhystad
  Enum help SephMon 3 2,774 Nov-19-2021, 09:39 AM
Last Post: Yoriz
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 7,263 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  enum from typelib Erhy 2 3,338 Jan-26-2019, 05:37 PM
Last Post: Erhy
  Python error? Enum and strings tycarac 3 5,315 Dec-15-2018, 10:39 AM
Last Post: tycarac

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.