Вы можете улучшить качество своей жизни с помощью этих карт, применяя методы dunder (также известные как маги c методы) для объекта. Используя некоторые свободы, я реализовал один из возможных способов сравнения карт. После того, как вы внедрили методы Dunder, вы можете сравнить Card
s, как вы бы str
s или int
s.
import random
tolvuspil = []
notandaspil = []
stokkur = []
boblisti = []
class Card:
values = ["ace", "2", "3", "4", "5", "6", "7", "8", "9", "10" ,"Jock", "Quenn", "King"] # in order, least valuable to most.
suits = ['Tígul', 'Laufa', 'Hjarta', 'Spaða'] # in order, least valuable to most.
def __init__(self, suit, val):
suit = str(suit) # input normalization
val = str(val) # input normalization
assert suit in self.suits, "Suit [found %s] must be in suits: %s" % (suit, ", ".join(self.suits))
assert val in self.values, "Value [found %s] must be in values: %s" % (val, ", ".join(self.values))
self.suit = suit
self.value = val
def show(self):
print(self)
def __eq__(self, other): # == operator
return other.suit == self.suit and other.value == self.value
def __ne__(self, other): # != operator
return not (self == other)
def __lt__(self, other): # < operator
if self.value == other.value: # first, compare the face value
# if they have the same face value, compare their suits
return self.suits.index(self.suit) < self.suits.index(other.suit)
return self.values.index(self.value) < self.values.index(other.value)
def __le__(self, other): # <= operator
return self == other or self < other
def __gt__(self, other): # > operator
if self.value == other.value: # first, compare the face value
# if they have the same face value, compare their suits
return self.suits.index(self.suit) > self.suits.index(other.suit)
return self.values.index(self.value) > self.values.index(other.value)
def __ge__(self, other): # >= operator
return self == other or self > other
def __str__(self): # str() implementation
return "{} {}".format(self.suit, self.value)
class deck:
def __init__(self):
self.cards = []
self.build()
def build(self):
for s in ['Hjarta', 'Spaða', 'Tígul', 'Laufa']:
for v in range(1, 14):
if v == 11:
v = "Jock"
elif v == 1:
v = "ace"
elif v == 12:
v = "Quenn"
elif v == 13:
v = "King"
self.cards.append(Card(s, v))
def show(self):
for c in self.cards:
print(c)
def shuffle(self):
for i in range(len(self.cards) - 1, 0, -1):
r = random.randint(0, i)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
def drawcard(self):
return self.cards.pop()
class player:
def __init__(self, name):
self.name = name
self.hand = []
def draw(self, deck):
self.hand.append(deck.drawcard())
return self
def showhand(self):
for card in self.hand:
card.show()
xyz = deck()
xyz.shuffle()
xyz.show()
a = xyz.drawcard()
b = xyz.drawcard()
print(a, b)
print("a < b:", a < b)
print("a <= b:", a <= b)
print("a > b:", a > b)
print("a >= b:", a >= b)
print("a == b:", a == b)
print("a != b:", a != b)