#| default_exp deck
A deck of playing cards
#| export
from nbdev_cards.card import *
from fastcore.utils import *
import random
#| hide
from nbdev.showdoc import *
from fastcore.test import *
#| export
class Deck:
"A deck of 52 cards, not including jokers"
def __init__(self): self.cards = [Card(s, r) for s in range(4) for r in range(1, 14)]
def __len__(self): return len(self.cards)
def __str__(self): return '; '.join(map(str, self.cards))
def __contains__(self, card): return card in self.cards
__repr__=__str__
def shuffle(self):
"Shuffles the cards in this deck"
random.shuffle(self.cards)
When we initially create a deck, all of the cards will be present:
deck = Deck()
deck
A♣️; 2♣️; 3♣️; 4♣️; 5♣️; 6♣️; 7♣️; 8♣️; 9♣️; 10♣️; J♣️; Q♣️; K♣️; A♦️; 2♦️; 3♦️; 4♦️; 5♦️; 6♦️; 7♦️; 8♦️; 9♦️; 10♦️; J♦️; Q♦️; K♦️; A❤️; 2❤️; 3❤️; 4❤️; 5❤️; 6❤️; 7❤️; 8❤️; 9❤️; 10❤️; J❤️; Q❤️; K❤️; A♠️; 2♠️; 3♠️; 4♠️; 5♠️; 6♠️; 7♠️; 8♠️; 9♠️; 10♠️; J♠️; Q♠️; K♠️
That should be 52 cards.
test_eq(len(deck), 52)
As a reminder, these are the suits we defined for a Card
:
suits
['♣️', '♦️', '❤️', '♠️']
We can check if, say, the Ace of Clubs is in the deck:
Card(1,1) in deck
True
#| export
@patch
def pop(self:Deck,
idx:int=-1): # The index of the card to remove, defaulting to the last one
"Remove one card from the deck"
return self.cards.pop(idx)
deck = Deck()
test_eq(deck.pop(), Card(3,13)) # K♠️
There are 51 cards left in the deck now.
test_eq(len(deck), 51)
#|export
@patch
def remove(self:Deck,
card:Card): # Card to remove
"Removes `card` from the deck or raises exception if it is not there"
self.cards.remove(card)
card23 = Card(2, 3)
deck.remove(card23)
assert card23 not in deck
show_doc(Deck.shuffle)
#|export
def draw_n(n:int, # number of cards to draw
replace:bool=True): # whether or not draw with replacement
"Draw `n` cards, with replacement iif `replace`"
d = Deck()
d.shuffle()
if replace: return [d.cards[random.choice(range(len(d.cards)))] for _ in range(n)]
else: return d.cards[:n]
draw_n(13, replace=False)
[Q♠️, 8❤️, 3♦️, 7♣️, 2♣️, 9♦️, 9♠️, 7♠️, 4♠️, K♣️, A♣️, 4♣️, 5♦️]