我在Python中制作基本的纸牌游戏(Blackjack),经销商和玩家各自拥有hand
。我想要实例化两次hand
类,并分别命名对象dHand
和pHand
。因为这些' hand'在每一轮之后,名称将被重复使用(或删除并重新分配),我将在全球范围内宣布这些名称:
dHand = Hand()
pHand = Hand()
当新一轮比赛开始时,这些牌将用以下牌填充:
def deal():
global dHand, pHand
dHand = Hand() #assigning a new object to forget about old cards
pHand = Hand()
dHand.add_card(deck.deal_card())
dHand.add_card(deck.deal_card())
pHand.add_card(deck.deal_card())
pHand.add_card(deck.deal_card())
有两个问题:
pHand
和dHand
由于某种原因指向同一个对象。deal()
,旧卡片不会丢失 - add_card()
只会添加旧对象,而不是新对象。任何指针(借口双关语)都会受到赞赏。
编辑:手类定义如下:
class Hand:
def __init__(self, cards = []):
# create Hand object
self.cards = cards
self.value = 0
def __str__(self):
# return a string representation of a hand
s = "Hand contains: "
for card in self.cards:
s += str(card) + " "
return s
def add_card(self, card):
# add a card object to a hand
self.cards.append(card)