0

I'm making a basic card game (Blackjack), in Python, whereby the dealer and player will have a hand each. There is a hand class that I want to instantiate twice and name the objects dHand and pHand respectively. Because these 'hand' names will be reused (or deleted and re-assigned) after every round, I'm declaring them globally:

dHand = Hand()
pHand = Hand()

When a new round starts, these hands are populated with cards as follows:

def deal():
    global dHand, pHand

    dHand = Hand() #assigning a new object to forget about old cards
    pHand = Hand()

    dHand.add_card(deck.deal_card())
    dHand.add_card(deck.deal_card())
    pHand.add_card(deck.deal_card())
    pHand.add_card(deck.deal_card())

There are two problems:

  1. both hands always seem to have the same cards and have 4 cards (not two). It seems that both pHand and dHand are pointing to the same object for some reason.
  2. If I call deal() again, old cards are not lost - the add_card() just adds on to the old object, not a new one.

Any pointers (excuse the pun) would be appreciated.

EDIT: Hand class is defined as follows:

class Hand:
    def __init__(self, cards = []):
        # create Hand object
        self.cards = cards
        self.value = 0       

    def __str__(self):
        # return a string representation of a hand
        s = "Hand contains: "
        for card in self.cards:
            s += str(card) + " "
        return s

    def add_card(self, card):
        # add a card object to a hand
        self.cards.append(card)
NorthCat
  • 9,643
  • 16
  • 47
  • 50
Islay
  • 478
  • 4
  • 17
  • Can you add the code for `Hand` class please? – Tim May 14 '14 at 12:05
  • 1
    Your `cards = []` is shared. – Martijn Pieters May 14 '14 at 12:07
  • @MartijnPieters: Thank you! The 'duplicate' helped and I managed to understand the problem and fix it. This is my first time asking a question, what's the next step? Do I remove my question since it was duplicate, or something of the sort? – Islay May 14 '14 at 12:16

0 Answers0