我有一個(gè) Hand() 類,其屬性 .user_hand 是他們的卡片列表,并為經(jīng)銷商和玩家創(chuàng)建了 2 個(gè)實(shí)例。.draw() 方法應(yīng)該將最上面的卡片移動(dòng)到其各自玩家的 .user_hand 中,但它似乎將它移動(dòng)到了兩個(gè)玩家。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()我的結(jié)果: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貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個(gè)贊
這是一個(gè)有趣的案例,在許多文章中已經(jīng)提到過,例如。在這里。
您使用默認(rèn)數(shù)組的 init 是問題所在。任何時(shí)候你draw()從不同的對象調(diào)用方法,你實(shí)際上填充了同一個(gè)數(shù)組。
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
...
添加回答
舉報(bào)
0/150
提交
取消