Deck.py
Deck.py · 3.2 KB
From the archive smeef-card-contest.zip
Download the archive « Back to the archive contents
from random import shuffle
class Card:
suits = ['S', 'D', 'C', 'H']
def __init__(self, r, s):
self.rank = r
self.suit = s
def __eq__(self, other):
return other.rank == self.rank
def __cmp__(self, other):
if self.rank < other.rank:
return -1
elif self.rank > other.rank:
return 1
else:
return 0
def __repr__(self):
if self.rank == 0:
ret = 'A'
elif self.rank == 12:
ret = 'K'
elif self.rank == 11:
ret = 'Q'
elif self.rank == 10:
ret = 'J'
else:
ret = str(self.rank + 1)
ret += self.suits[self.suit]
return ret
class CardCollection:
'makes empty list for cards'
def __init__(self):
self.cards = []
'Allows human-friendly printing of CardCollections'
def __repr__(self):
ret = ''
for c in self.cards:
ret += str(c) + ','
return ret[:-1]
'-method to return values of the cards in the deck ( H6, C3, SK, etc ), a list of Cards'
def getCards(self):
return self.cards[:]
'-method to return a value with total number of cards'
def numCards(self):
return len( self.cards )
class Deck(CardCollection):
'-method for the creation of a deck with 52 cards'
def __init__(self):
self.reset()
'-method to reset the deck to 52 cards'
def reset(self):
self.cards = []
for s in range(4):
for r in range(13):
self.cards.append( Card(r, s) )
self.shuffle()
'-method to shuffle a deck of cards'
def shuffle(self):
shuffle(self.cards)
'-method to return the top card of a deck and removes it from the deck'
def pop(self):
return self.cards.pop(0)
'-method to add a card to the bottom of the deck (the card should not already be in the deck)'
def add(self, new_card):
for el in self.cards:
if el == new_card:
return
self.cards.append( new_card )
class Hand(Deck):
def __init__(self):
self.cards = []
'-method to add a new empty hand to a player'
def addToAvatar(self, avatar):
avatar.__hand = self
self.__avatar = avatar
'-method to add a card to a players hand'
def add(self, card):
self.cards.append(card)
'-method to remove a particular card from a hand.'
def removeCard(self, out_card):
for c in self.cards[:]:
if c == out_card:
self.cards.remove(out_card)
'-method that returns true if the hand contains one or more cards of a given value'
def hasRankedCard(self, rank):
for c in self.cards:
if c.rank == rank:
return True
return False
'-method that returns true if the hand contains one or more cards of a given suit'
def hasSuitedCard(self, suit):
for c in self.cards:
if c.suit == suit:
return True
return False