0

I have a Hand() class, with an attribute .user_hand which is a list of their cards, and have created 2 instances for dealer and player. The .draw() method should move the top card to the .user_hand of its respective player but it seems to move it to both players instead.

class Card:

def __init__(self, suit, rank):
    self.suit = suit
    self.rank = rank

def __str__(self):
    return self.rank + ' of ' + self.suit

def __int__(self):
    global list_of_ranks
    return list_of_ranks[self.rank]


class Deck:

def __init__(self, deck_cards=[]):
    self.deck_cards = deck_cards
    for suit in list_of_suits:
        for rank in list_of_ranks:
            self.deck_cards.append(Card(suit,rank))

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


class Hand:

def __init__(self, user_hand=[], turn=True, blackjack=False, win=False):
    self.blackjack = blackjack
    self.user_hand = user_hand
    self.blackjack = blackjack
    self.win = win

def draw(self):
    self.user_hand.append(new_deck.deck_cards[0])
    new_deck.deck_cards.remove(new_deck.deck_cards[0])

def show_hand(self):
    print('\n\nDealer\'s hand:')
    for x in dealer_hand.user_hand:
        print(x)
    print('\nYour hand:')
    for x in new_hand.user_hand:
        print(x)
    print('Total value: {}'.format(calc(self.user_hand)))

...

new_hand.draw()
dealer_hand.draw()
new_hand.draw()
dealer_hand.draw()

new_hand.show_hand()

my result:

Dealer's hand:
Queen of Spades
Six of Diamonds
Nine of Clubs
Six of Spades

Your hand:
Queen of Spades
Six of Diamonds
Nine of Clubs
Six of Spades
Total value: 31
Adam O
  • 15
  • 4
  • 1
    It would be good if you also give the code for the deck. The element `new_deck` doesn't seem to be defined in `.draw()` method. – Mathieu Oct 04 '19 at 09:56
  • @Mathieu I have updated it – Adam O Oct 04 '19 at 09:59
  • 1
    Your `Hand` class references several external (presumably global) variables (i.e. `new_deck`, `new_hand` and `dealer_hand`). This breaks encapsulation and makes it difficult to debug / predict the expected behavior. Especially as you still haven't shown the code where those variables are defined/created. – PeterE Oct 04 '19 at 10:27

1 Answers1

4

This is an interesting case which was already mentioned in many articles, eg. here.

Your init with default array is the problem. Any time you call draw() method from different objects you actually fill the same array.

class Hand:

def __init__(self, user_hand=[], turn=True, blackjack=False, win=False):
...

You could solve it like this:

class Hand:

def __init__(self, user_hand=None, turn=True, blackjack=False, win=False):
    if user_hand is None:
        self.user_hand = []
    else:
         self.user_hand = user_hand
...
makozaki
  • 3,772
  • 4
  • 23
  • 47