クラスを使用するためにクラスを使用する必要はありません (Java を使用している場合を除く)。
私がクラスにアプローチする方法は、まずどのような「オブジェクト」または「もの」が必要になるかを考え、次にそのものを定義するプロパティとメソッドを定義することです。同じものの複数のインスタンスを作成する場合は、クラスが役立ちます。インスタンスが 1 つしか必要ない場合は、モジュールまたはグローバル変数で十分でしょう。
たとえば、あなたの例では、クラスは本当に必要ありません。ただし、ゲームで複数のデッキをサポートしたい場合は、独自のカードに関するすべての情報を格納および制御できるDeckクラスを定義する必要があります。
ポーカー自体について考えてみてください。どのように機能するのでしょうか?
ディーラーがいて、プレイヤーがいて、ディーラーが 1 組以上のカードを持っています。ディーラーはシャッフルしてから、プレイヤーとテーブルにカードを配ります。これらの各プロセスをオブジェクトとしてどのように定義しますか?
実世界の例を見て、それを再利用可能な部分に分割すると、それがクラスになります。たとえば、私はおそらくそれを見て、次のように言うでしょう。
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())
などなど。
通常、これらのコードはすべて、物事を分割する方法を頭の中で視覚化する方法を示すための疑似コードです。本当に最も簡単な方法は、実際のシナリオについて考え、それがどのように機能するかを平易な英語で書き留めることです。そうすれば、クラスは自分自身を視覚化し始めます.