您不需要为了使用类而使用类(除非您使用的是 Java)
我处理类的方式是,我首先考虑我需要什么“对象”或“事物”,然后定义将定义该事物的属性和方法。如果我要创建同一事物的多个实例,那么一个类很有用。如果我只需要 1 个实例,那么一个模块或全局变量很可能就足够了。
例如,在您的示例中,您实际上并不需要类。但是,如果您想要为您的游戏支持多个套牌,那么您可能需要定义一个Deck类,该类可以包含和控制有关其自己的卡牌的所有信息。
想想扑克本身——它是如何运作的?
你有一个庄家,你有玩家,一个庄家有一副或多副牌。庄家洗牌,然后向玩家和牌桌发牌。您希望如何将这些过程中的每一个定义为对象?
我会查看现实世界的示例并将其分解为可重用的部分,这将成为您的类。例如,我可能会看着它说:
class Deck(object):
""" class for managing a deck of cards """
class Player(object):
""" defines properties and methods that an individual player would have """
def __init__( self ):
self._cards = [] # hold a player current cards
self._chips = 10 # define how much money a player has
def clearCards( self ):
self._cards = []
def dealCard( self, card ):
self._cards.append(card)
class Dealer(object):
""" defines properties and methods that a dealer would have """
def __init__( self ):
self._decks = [] # hold multiple decks for playing with
self._stack = [] # holds all the shuffled cards as a
def nextCard( self ):
""" pop a card off the stack and return it """
return self._stack.pop()
def shuffle( self ):
for deck in self._decks:
deck.shuffle() # shuffle each individual deck
# re-populate a shuffled stack of cards
self._stack = []
# randomly go through each deck and put each card into the stack
def deal( self, *players ):
""" Create a new hand based on the current deck stack """
# determine if i need to shuffle
if ( len(self._stack) < self._minimumStackCount ):
self.shuffle()
return Hand(self, *players)
class Hand(object):
def __init__( self, dealer, *players ):
self._dealer = dealer # points back to the dealer
self._players = players # defines all the players in the hand
self._table = [] # defines the cards on the table
self._round = 1
for player in players:
player.clearCards()
self.deal()
def deal( self ):
# in holdem, each round you get a different card combination per round
round = self._round
self._round += 1
# deal each player 2 cards in round 1
if ( round == 1 ):
for i in range(2):
for player in players:
player.dealCard( self._dealer.nextCard() )
# deal the table 3 cards in round 2 (flop)
elif ( round == 2 ):
self._table = [self._dealer.nextCard() for i in range(3)]
# deal the table 1 card in round 2 (turn)
elif ( round == 3 ):
self._table.append(self._dealer.nextCard())
# deal the table 1 card in round 3 (river)
else:
self._table.append(self._dealer.nextCard())
等等等等。
所有这些代码通常都是伪代码,用于说明如何在心理上可视化分解事物的方式。真正最简单的方法是考虑现实生活中的场景并用简单的英语写下它是如何工作的,然后课程将开始可视化自己。