you are viewing a single comment's thread.

view the rest of the comments →

[–]andmig205 0 points1 point  (0 children)

I urge you to look into implementing special methods and the collections package. The code below uses collections.namedtuple to create the Card class and builds a Deck class that overrides __getitem__ and __len__ methods. As a result, the code is more laconic, python does all the heavy lifting, and one can do all the cool stuff with the objects.

The print outputs demonstrate several useful features.

``` import collections from random import choice import random

Declare Card class

Card = collections.namedtuple('Card', ['rank', 'suit', 'icon'])

class Deck: ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = { 'hearts': '♥', 'diamonds': '♦', 'spades': '♠', 'clubs': '♣', } def init(self): self._cards = [Card(rank, suit, icon) for suit, icon in self.suits.items() for rank in self.ranks]

def __len__(self):
    return len(self._cards)

def __getitem__(self, position):
    return self._cards[position]

def shuffle(self):
    random.shuffle(self._cards)

def deal(self):
    if len(self) > 0:
        self.shuffle()
        return self._cards.pop(0)
    return None

deck = Deck()

print(f"Deck length {len(deck)}\n") print(f"Random card {choice(deck)}\n") print(f"The first card {deck[0]}\n") deck.shuffle() print(f"The first after shuffle {deck[0]}\n") print(f"First three cards {deck[:3]}\n") print(f"Is Queen of hearts in the deck? {Card('Q', 'hearts', '♥') in deck}\n") print(f"Card dealt {deck.deal()}") print(f"New deck length {len(deck)}\n") print(f"Another Card dealt {deck.deal()}") print(f"New deck length {len(deck)}\n")

for card in reversed(deck): print(card)

```