Just as a learning exercise, I am implementing a poker game simulator. I am purposefully not searching for ready made tutorials showing how to do this, relying mostly on the python docs - that way I hope to learn in a more memorable, albeit slower, way. I'm looking for advice on how to code the comparison between cards, so that e.g. Five beats Four.
My current implementation works, but I feel it is a little hacky and very inefficient in one particular detail and there must be a better way. In the Card class init, I am setting an attribute order which is just a list of the members of the CardValue enum, in the order they are declared.
While I could just use enum.auto(), or manually set the values as integers and hence simply use those for comparisons (still with eq etc), that would lose me the ability to make use of the enum values to form the human readable card value names.
Is there a better way to go about this than the below code? I feel like the comparison operators should be in the enum itself, but so far have not worked out how to get that to work with my meaningful values for the members of the enum.
from enum import Enum from functools import total_ordering class CardValue(Enum): TWO = "2" THREE = "3" ... ... KING = "King" ACE = "Ace" @total_ordering class Card: def __init__(self, value, suit): self.value = value self.suit = suit self.order = [en for en in CardValue] ### This seems wrong and very inefficient! def __eq__(self, other): if self.__class__ is other.__class__: return self.order.index(self.value) == self.order.index(other.value) def __lt__(self, other): if self.__class__ is other.__class__: return self.order.index(self.value) < self.order.index(other.value)