为闲家和庄家各抽 2 张牌,最终庄家和闲家都拥有相同的 4 张牌

Drawing 2 cards each for player and dealer ends up both dealer and player having the same 4 cards

我有一个 Hand() class,它有一个属性 .user_hand,这是他们的牌列表,并为庄家和闲家创建了 2 个实例。 .draw() 方法应该将顶牌移动到其各自玩家的 .user_hand 但它似乎将它移动到两个玩家。

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()

我的结果:

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

这是一个有趣的案例,已经在很多文章中提到过,例如。 here.

你的默认数组初始化是问题所在。任何时候你从不同的对象调用 draw() 方法,你实际上填充了同一个数组。

class Hand:

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

你可以这样解决:

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
...