---
description: Python OOP - Deck of Cards
---

# Deck of Cards

{% embed url="https://youtu.be/t8YkjDH86Y4" %}

**Source Code:**

```python
import random

class Card(object):
    def __init__(self, suit, val):
        self.suit = suit
        self.value = val

    # Implementing build in methods so that you can print a card object
    def __unicode__(self):
        return self.show()
    def __str__(self):
        return self.show()
    def __repr__(self):
        return self.show()
        
    def show(self):
        if self.value == 1:
            val = "Ace"
        elif self.value == 11:
            val = "Jack"
        elif self.value == 12:
            val = "Queen"
        elif self.value == 13:
            val = "King"
        else:
            val = self.value

        return "{} of {}".format(val, self.suit)


class Deck(object):
    def __init__(self):
        self.cards = []
        self.build()

    # Display all cards in the deck
    def show(self):
        for card in self.cards:
            print card.show()

    # Generate 52 cards
    def build(self):
        self.cards = []
        for suit in ['Hearts', 'Clubs', 'Diamonds', 'Spades']:
            for val in range(1,14):
                self.cards.append(Card(suit, val))

    # Shuffle the deck
    def shuffle(self, num=1):
        length = len(self.cards)
        for _ in range(num):
            # This is the fisher yates shuffle algorithm
            for i in range(length-1, 0, -1):
                randi = random.randint(0, i)
                if i == randi:
                    continue
                self.cards[i], self.cards[randi] = self.cards[randi], self.cards[i]
            # You can also use the build in shuffle method
            # random.shuffle(self.cards)

    # Return the top card
    def deal(self):
        return self.cards.pop()


class Player(object):
    def __init__(self, name):
        self.name = name
        self.hand = []

    def sayHello(self):
        print "Hi! My name is {}".format(self.name)
        return self

    # Draw n number of cards from a deck
    # Returns true in n cards are drawn, false if less then that
    def draw(self, deck, num=1):
        for _ in range(num):
            card = deck.deal()
            if card:
                self.hand.append(card)
            else: 
                return False
        return True

    # Display all the cards in the players hand
    def showHand(self):
        print "{}'s hand: {}".format(self.name, self.hand)
        return self

    def discard(self):
        return self.hand.pop()

# Test making a Card
# card = Card('Spades', 6)
# print card

# Test making a Deck
myDeck = Deck()
myDeck.shuffle()
# deck.show()

bob = Player("Bob")
bob.sayHello()
bob.draw(myDeck, 5)
bob.showHand()
```



## Blackjack with Python

{% embed url="https://www.youtube.com/watch?v=yJz2at4Hco4" %}

Learn how to code a command line game of Blackjack with the Python programming language.

CHECK OUT THE FOLLOW ON VIDEO TO TURN THIS SAME CODE BASE INTO A BEST OF FIVE GAME https://youtu.be/fn61C\_GQUwQ

You know Blackjack. Also, referred to as 21.

In this game, you play against the dealer. You are both dealt hands and you can Hit or Stay based on the knowledge of your cards and the one card you can see of the dealers.&#x20;

Welcome to Las Vegas or Atlantic City!! We are going to bring that to your Terminal :)

The source code for this program can be found here on Github https://github.com/techBytesIO/python...

Other cool coding and tech things can be found here https://techbytes.io/

The Python programming language can be found here https://www.python.org/

Winner, Winner, Chicken Dinner!! :)



## &#x20;Create a Blackjack game with Python

{% embed url="https://www.youtube.com/watch?v=G7RrQW2Gu98" %}

&#x20;🔥 Link to my website: [http://www.jimshapedcoding.com](https://www.youtube.com/redirect?redir_token=QUFFLUhqbXRlcGh6cUlMVllPcmhxdDV3SllSc0hyQ3loQXxBQ3Jtc0ttS081M05FYWQ2Q2lac2Z1OV9BTjFTYkdIaElEYVBzemlqVy1jTkNLYjV0b3VHX2s1RWx4ZDI5aUNVSGZaaW5JUm4temk2aTlKclBKdDlnSGk2dzBTXzZmMU5IazE0U3RWRHFPMGdtdVJLSGtIeWg4cw%3D%3D\&q=http%3A%2F%2Fwww.jimshapedcoding.com\&v=G7RrQW2Gu98\&event=video_description)&#x20;

🔥 Link to the code from github: [https://github.com/jimdevops19/Blackjack](https://www.youtube.com/redirect?redir_token=QUFFLUhqbExrVmZsbURBakhKa0J3cVRwWjNkNnliTFlUUXxBQ3Jtc0trTGlyZk5LSW9oNmZEYlo0SHhzbzZKWV9FTl9yeHFZbXdwVkE4cWpiRmNCMDRuSFBFb3hhT05neTlmQVVEeUVSSU9INUZIRUVRckx5NVRHLTh0NklnT0tQU25iY0NMbE1CWDN0UmJyMEp5MUNsb0QtQQ%3D%3D\&q=https%3A%2F%2Fgithub.com%2Fjimdevops19%2FBlackjack\&v=G7RrQW2Gu98\&event=video_description)&#x20;

🔥 Link to download the game as executable file: [https://easyupload.io/ewbpkg](https://www.youtube.com/redirect?redir_token=QUFFLUhqbVMyT0piYmN1RnRTWkp4bThaaXBqWEpjT3p6UXxBQ3Jtc0tuM1pGVjV1LVFKYlYyX1lHTnM2LVh6SjBqN1loWkxaSEZZT0xWSnFXNU5kTDhSaEhqZ2N6dE5NS205NFh6WWRuOTg4ajVSVFZiZWhDUjRza1k5bjdpWE96aHR3N2ZCVVVhblBtS0o2WEpVZVU1SkkxTQ%3D%3D\&q=https%3A%2F%2Feasyupload.io%2Fewbpkg\&v=G7RrQW2Gu98\&event=video_description)
