Các cards chơi bài (tiếp tục)
Không giống một card riêng rẽ, một deck có hành vi đáng kể cái có thể được chỉ ra trong một giao diện. Một người
có thể shuffle deck, deal một card, và quyết định số cards còn lại trong nó. Bảng dưới liệt kê các phương thức của
một Deck class và chúng có thể làm cái gì. Sau đây là một phiên làm việc mẫu cái try out một deck:
>>> deck = Deck()
>>> print(deck)
<the print reps of 52 cards, in order of suit and rank>
>>> deck.shuffle()
>>> len(deck)
52
>>> while len(deck) > 0:card = deck.deal()
print(card)<the print reps of 52 randomly ordered cards>
>>> len(deck)
0
Suốt quá trình khởi tạo, tất cả 52 cards duy nhất được tạo và điền theo trật tự được sắp xếp vào list bên trong
các cards của deck. Deck constructor sử dụng các biến class RANKS và SUITS trong Cars class để xắp sếp trật tự
các cards mới phù hợp. Phương thức shuffle đơn giản truyền list các cards tới random.shuffle. Phương thức deal
loại bỏ và trả về card đầu tiên trong list, nếu có một cái, hay trả về giá trị None mặt khác. Hàm len, như hàm
str, gọi một phương thức (trong trường hợp này __len__) cái trả về độ dài của list cards. Sau đây là code cho Deck:
import random
# The definition of the Card class goes here
class Deck(object):
“”” A deck containing 52 cards.”””def __init__(self):
“””Creates a full deck of cards.”””
self.cards = []
for suit in Card.SUITS:for rank in Card.RANKS:
c = Card(rank, suit)
self.cards.append(c)def shuffle(self):
“””Shuffles the cards.”””
random.shuffle(self.cards)def deal(self):
“””Removes and returns the top card or None
if the deck is empty.”””
if len(self) == 0:return None
else:
return self.cards.pop(0)
def __len__(self):
“””Returns the number of cards left in the deck.”””
return len(self.cards)def __str__(self):
“””Returns the string representation of a deck.”””
result = “”
for c in self.cards:result = result + str(c) + ‘\n’
return result

