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
  • 8,997
  • 16
  • 45
  • 49
Islay
  • 468
  • 4
  • 16

0 Answers0