我是Python新手,這是我第一次問一個stackoverflow問題,但是很長時間的讀者。我正在開發一個簡單的基於卡片的遊戲,但在管理我的Hand類的實例時遇到了麻煩。如果你看下面你可以看到手類是一個簡單的卡片容器(這只是int值),每個Player類都包含一個手類。但是,無論何時創建我的Player類的多個實例,它們都似乎操縱Hand類的單個實例。從我在C和Java中的經驗看來,我似乎讓我的Hand類變成靜態的。如果有人可以幫助解決這個問題,我將非常感激。在Python中管理實例
謝謝 薩德
澄清:這種情況的一個例子是
P = player.Player()
P1 = player.Player()
p.recieveCard(15 )
p1.recieveCard(21)
p.viewHand()
,這將導致: [15,21]
即使只有一個卡被向對
手工類:
class Hand:
index = 0
cards = [] #Collections of cards
#Constructor
def __init__(self):
self.index
self.cards
def addCard(self, card):
"""Adds a card to current hand"""
self.cards.append(card)
return card
def discardCard(self, card):
"""Discards a card from current hand"""
self.cards.remove(card)
return card
def viewCards(self):
"""Returns a collection of cards"""
return self.cards
def fold(self):
"""Folds the current hand"""
temp = self.cards
self.cards = []
return temp
Player類
import hand
class Player:
name = ""
position = 0
chips = 0
dealer = 0
pHand = []
def __init__ (self, nm, pos, buyIn, deal):
self.name = nm
self.position = pos
self.chips = buyIn
self.dealer = deal
self.pHand = hand.Hand()
return
def recieveCard(self, card):
"""Recieve card from the dealer"""
self.pHand.addCard(card)
return card
def discardCard(self, card):
"""Throw away a card"""
self.pHand.discardCard(card)
return card
def viewHand(self):
"""View the players hand"""
return self.pHand.viewCards()
def getChips(self):
"""Get the number of chips the player currently holds"""
return self.chips
def setChips(self, chip):
"""Sets the number of chips the player holds"""
self.chips = chip
return
def makeDealer(self):
"""Makes this player the dealer"""
self.dealer = 1
return
def notDealer(self):
"""Makes this player not the dealer"""
self.dealer = 0
return
def isDealer(self):
"""Returns flag wether this player is the dealer"""
return self.dealer
def getPosition(self):
"""Returns position of the player"""
return self.position
def getName(self):
"""Returns name of the player"""
return self.name
非常感謝!我無法告訴你有多大的幫助。 – BeensTheGreat 2010-06-03 14:22:15