card-deck
This module can be used to create small card games such as BlackJack etc..
To initialize the deck, use:
Deck()
To shuffle the deck, use:
Deck().shuffle()
To restart/renew the deck, use:
Deck().restart()
To draw a card from the deck, use:
Deck().draw()
This returns a list[tuple[str, int]]
, it could look something like [("Hearts", 5)]
.
Classes | Methods/Properties | Paremeters/Arguments |
---|---|---|
Deck | Method: shuffle, draw, restart | optional: draw(amount=1), restart(shuffle=True) |
Card | Properties: name, value, suit | required: Card(tuple[str, int]) |
Try to except EmptyDeckError
and CardAmountError
when drawing a card since the deck can end up being empty at some point or you maybe try to draw more cards than what the deck has.
Examples
from card_deck import Deck, Card, EmptyDeck
# Instantiating and initializing the deck
deck = Deck()
# Shuffling the deck so it becomes in random orders when drawing a card
deck.shuffle()
# Creating the hand of a player
player_hand = []
while True:
# Asking if the user wants to draw a card
inp = input("Do you wanna draw a card? (yes/no): ")
if inp == "yes":
try:
player_hand.append(deck.draw())
except EmptyDeckError: # If the Deck is empty, deck.draw() will raise a EmptyDeckError
break
else:
break
# Lets say we draw a card two times, player_hand would look like: [[("Hearts", 5)], [("Spades", 10)]]
# So what we can do to pretty print it is to iterate through player_hand
for cards in player_hand:
card = Card(cards[0]) # Since Cards only takes a tuple of str and int, we need to do cards[0]
print(card.suit, card.name, card.value)