我有一个 Hand() 类,其属性 .user_hand 是他们的卡片列表,并为经销商和玩家创建了 2 个实例。.draw() 方法应该将最上面的卡片移动到其各自玩家的 .user_hand 中,但它似乎将它移动到了两个玩家。class Card:def __init__(self, suit, rank): self.suit = suit self.rank = rankdef __str__(self): return self.rank + ' of ' + self.suitdef __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 = windef 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 SpadesSix of DiamondsNine of ClubsSix of SpadesYour hand:Queen of SpadesSix of DiamondsNine of ClubsSix of SpadesTotal value: 31
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
这是一个有趣的案例,在许多文章中已经提到过,例如。在这里。
您使用默认数组的 init 是问题所在。任何时候你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
...
添加回答
举报
0/150
提交
取消