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:
- both hands always seem to have the same cards and have 4 cards (not two). It seems that both
pHand
anddHand
are pointing to the same object for some reason. - If I call
deal()
again, old cards are not lost - theadd_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)