# Card Shuffling Game¶

In [771]:
from random import shuffle

In [772]:
# define the cards
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']

In [773]:
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value

# define each card
def __repr__(self):
return f"{self.value} of {self.suit}"

In [774]:
class Deck:
# all combinations of cards
def __init__(self):
self.cards = [Card(suit, value) for suit in suits for value in values]

# count number of cards in a deck
def count(self):
return len(self.cards)

# showing the count
def __repr__(self):
return f"Deck of {self.count()} cards"

# the shuffle instance
def shuffle(self):
cards = self.cards
if self.count() < len(self.cards):
raise ValueError("Missing cards! Can't be shuffled")
else:
shuffle(cards)
return cards

# deal x number cards each time
def _deal(self, number):
count = self.count()
if number > count:
raise ValueError("No more cards to deal!")
else:
cards = self.cards[:number]
self.cards = self.cards[number:]
return cards

# deal a single card each time
def deal_card(self):
cards = self._deal(1)
return cards

# deal a list of cards each time
def deal_hand(self, number):
cards = self._deal(number)
return cards


# Checking the results¶

In [775]:
# define each card
card1 = Card("Hearts", "4")
card1

Out[775]:
4 of Hearts
In [776]:
# number of cards in a deck
deck = Deck()
deck

Out[776]:
Deck of 52 cards
In [777]:
# shuffle the deck
deck.shuffle()

Out[777]:
[2 of Diamonds,
8 of Hearts,
10 of Hearts,
K of Hearts,
3 of Clubs,
J of Hearts,
Q of Hearts,
8 of Diamonds,
J of Diamonds,
7 of Diamonds,
4 of Hearts,
Q of Clubs,
A of Hearts,
9 of Diamonds,
J of Clubs,
4 of Diamonds,
7 of Clubs,
10 of Clubs,
5 of Diamonds,
3 of Diamonds,
6 of Clubs,
8 of Clubs,
7 of Hearts,
A of Diamonds,
5 of Hearts,
2 of Hearts,
6 of Hearts,
K of Diamonds,
2 of Clubs,
10 of Diamonds,
5 of Clubs,
3 of Hearts,
6 of Diamonds,
4 of Clubs,
Q of Diamonds,
K of Clubs,
9 of Clubs,
A of Clubs,
9 of Hearts,
10 of Spades]
In [778]:
# deal a single card
deck.deal_card()

Out[778]:
[2 of Diamonds]
In [779]:
# deal several cards
deck.deal_hand(3)

Out[779]:
[8 of Hearts, 10 of Hearts, K of Hearts]
In [780]:
# deal more cards
deck._deal(10)

Out[780]:
[3 of Clubs,
J of Hearts,
Q of Clubs]
# only 38 cards left

Deck of 38 cards