Search code examples
pythonpython-3.xblackjackplaying-cards

Programming Noob needs OOP advice


I have been making a blackjack game for a project in python and have has got as far as making a deck of cards (see below). But I want to improve it using objects instead as I think I will help me to improve my skills more.

I was wondering if anyone knows how , or where I can get some resources to help me to learn OOP (if that makes any scene, sorry if it doesn't I'm new at this).

import random

deck = []
hand = []

def MakeDeck(deck):
    suits = ['♠','♣','♥','♦']
    values = ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']

    for suit in suits:
        for value in values:
            deck.append((value,suit))

def DrawCard(deck, hand):
    card1 = random.choice(deck)
    deck.remove(card1)
    card2 = random.choice(deck)
    deck.remove(card2)

    hand.append(card1)
    hand.append(card2)

    print("Your hand:\n", hand)


MakeDeck(deck)
DrawCard(deck, hand)

Solution

  • Try this : https://realpython.com/python3-object-oriented-programming/

    And then you can read the official python documentation : https://docs.python.org/3.7/tutorial/classes.html

    For your example, some tips to make a OOP oriented blackjack game :

    • Your game needs a deck of card, I think a class Deck will be a good start.
    • This class should contains cards, and you can create a class representing cards. You will somewhere instantiate 52 objects and store them inside your instantiated Deck.
    • Your can create methods inside your Deck class to manage your deck. For example, shuffle, or drawing a card
    • Then you have a game, the blackjack. Remember that you may reuse your classes Card and Deck for other games. So everything about the rules of blackjack (for example, values of your cards) should be described inside the BlackJack class. Here you can instantiate your deck of 52 cards, as other games sometimes use less/more. Then implement the rules of the game (turns, who wins, ....)
    • You probably will create a class Player to store informations about players.

    Last advice, avoid special characters in your code

    suits = ['♠','♣','♥','♦']
    

    This will cause you trouble.