2
我正在嘗試編寫一個處理卡片的程序,並且我遇到問題,即當我將卡片對象交給一個玩家時,所有玩家都會在其課程中收到對象屬性「手」。僅在指定了一個對象時將對象添加到多個對象類屬性
代碼如下,任何幫助表示讚賞!我道歉,如果我沒有正確地遵循stackoverflow縮進格式。這是我第一次發佈一個問題。
import random
class Player(object):
def __init__(self,name,balance=100,hand=[]):
self.name = name
self.balance = balance
self.hand = hand
def reveal_all(self):
'''
This method prints out a player's hand.
'''
reveal = []
for x in self.hand:
reveal = reveal + [x.name]
print(reveal)
class Card(object):
def __init__(self,name,val):
self.name = name
self.val = val
card_ob1 = Card('2 of Hearts',2)
card_ob2 = Card('3 of Hearts',3)
card_ob3 = Card('4 of Hearts',4)
card_ob4 = Card('5 of Hearts',5)
card_ob5 = Card('6 of Hearts',6)
card_ob6 = Card('7 of Hearts',7)
card_ob7 = Card('8 of Hearts',8)
card_ob8 = Card('9 of Hearts',9)
deck = [card_ob1,card_ob2,card_ob3,card_ob4,card_ob5,card_ob6,card_ob7,card_ob8]
def plyr1_geta_card():
card = random.choice(deck)
player1obj.hand += [card]
deck.remove(card)
def dealer_geta_card():
card = random.choice(deck)
dealerobj.hand.append(card)
deck.remove(card)
player1obj = Player('Me',100)
dealerobj = Player('The House')
# Player 1 gets a card
plyr1_geta_card()
# The card is added to both the dealer and player hand attribute for some reason!
dealerobj.reveal_all()
player1obj.reveal_all()
謝謝你minhhn2910。這解決了我的問題,我會閱讀教程鏈接。並感謝您改進我的plyr1_geta_card函數。我這樣做的方式需要爲每個玩家對象分別設置一個函數。你的方式更清潔。 –
@black_lab_fan請考慮upvote或標記爲正確的答案,如果可能的話:) – minhhn2910
我沒有投票給你。我被告知它被記錄了,但沒有公開發布,因爲我在stackoverflow上的貢獻少於15。我錯過了複選框,現在點擊它。 –