DeckOfCards
¶NUMBER_OF_CARDS
represents the number of Card
s in a deck_current_card
keeps track of which Card
will be dealt next (0
–5
1) _deck
is a list of 52 Card
objects__init__
¶_deck
of Card
sfor
statement fills the list _deck
by appending new Card
objects, each initialized with two strings—one from the list Card.FACES
and one from Card.SUITS
# deck.py
"""Deck class represents a deck of Cards."""
import random
from card import Card
class DeckOfCards:
NUMBER_OF_CARDS = 52 # constant number of Cards
def __init__(self):
"""Initialize the deck."""
self._current_card = 0
self._deck = []
for count in range(DeckOfCards.NUMBER_OF_CARDS):
self._deck.append(Card(Card.FACES[count % 13],
Card.SUITS[count // 13]))
shuffle
¶_current_card
to 0
, then shuffles the Card
s in _deck
using the random
module’s shuffle
functiondef shuffle(self):
"""Shuffle deck."""
self._current_card = 0
random.shuffle(self._deck)
deal_card
¶Card
from _deck
None
when there are no more Card
s to dealdef deal_card(self):
"""Return one Card."""
try:
card = self._deck[self._current_card]
self._current_card += 1
return card
except:
return None
__str__
¶Card
left aligned in a field of 19 charactersdef __str__(self):
"""Return a string representation of the current _deck."""
s = ''
for index, card in enumerate(self._deck):
s += f'{self._deck[index]:<19}'
if (index + 1) % 4 == 0:
s += '\n'
return s
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.