Search code examples
pythonlistblackjackplaying-cards

Implement a Deck of cards in python. Problem when trying to print all cards while calling list.pop()


class Card:
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

    def show(self):
#         print(f"{self.value} of {self.suit}")
        return (self.suit, self.value)


class Deck(Card):
    """
    Deck is collection of 52 cards.
    """

    colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
    rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
    def __init__(self):

        d = []
        for s in Deck.colour:
            for r in Deck.rank:
                c = Card(s,r)
                d.append(c)
        self.pack = d

    def draw(self):
        return self.pack.pop()


mydeck = Deck()
j =1
for i in mydeck.pack:
    print(j, "\t", mydeck.draw().show(), " count remaining ", len(mydeck.pack))
    j +=1

while trying to print the contents of mydeck.deck, which is a list, it only prints half of total values. If run again it prints next half of values.

Please help me to figure out why all content is not printed?

I am a beginner and any feedback is very much appreciated. Thanks in advance.


Solution

  • I fixed this way :

    class Card:
        def __init__(self, suit, value):
            self.suit = suit
            self.value = value
    
        def show(self):
    #         print(f"{self.value} of {self.suit}")
            return (self.suit, self.value)
    
    
    class Deck():
        """
        Deck is collection of 52 cards.
        """
    
        colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
        rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
        def __init__(self):
            d = []
            for s in Deck.colour:
                for r in Deck.rank:
                    c = Card(s,r)
                    d.append(c)
            self.pack = d
    
        def draw(self):
            return self.pack.pop()
    
    
    mydeck = Deck()
    j =1
    breakpoint()
    for i in mydeck.pack:
        print(j, "\t", i.show(), " count remaining ", len(mydeck.pack)-j)
        j +=1
    
    

    OUTPUT

    1        ('Hearts', 'Two')  count remaining  51
    2        ('Hearts', 'Three')  count remaining  50
    3        ('Hearts', 'Four')  count remaining  49
    4        ('Hearts', 'Five')  count remaining  48
    5        ('Hearts', 'Six')  count remaining  47
    6        ('Hearts', 'Seven')  count remaining  46
    7        ('Hearts', 'Eight')  count remaining  45
    8        ('Hearts', 'Nine')  count remaining  44
    9        ('Hearts', 'Ten')  count remaining  43
    10       ('Hearts', 'Jack')  count remaining  42
    ......................