【问题标题】:Drawing 2 cards each for player and dealer ends up both dealer and player having the same 4 cards玩家和庄家各抽 2 张牌,庄家和玩家都拥有相同的 4 张牌
【发布时间】:2020-02-02 15:33:19
【问题描述】:

我有一个 Hand() 类,其属性 .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

【问题讨论】:

  • 如果你也能给出牌组的代码就好了。 new_deck 元素似乎没有在 .draw() 方法中定义。
  • @Mathieu 我已经更新了
  • 您的Hand 类引用了几个外部(可能是全局)变量(即new_decknew_handdealer_hand)。这会破坏封装并使其难以调试/预测预期行为。尤其是您还没有显示定义/创建这些变量的代码。

标签: python blackjack


【解决方案1】:

这是一个有趣的案例,已经在很多文章中提到过,例如。 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
...

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 2014-09-21
    • 2015-04-27
    • 2023-01-22
    • 1970-01-01
    • 2023-04-02
    • 2013-05-09
    • 1970-01-01
    • 2017-10-06
    相关资源
    最近更新 更多