2
\$\begingroup\$

I am learning Python for a few weeks. Last time I started object-oriented programming and I feel like it is really hard for me to write relation between methods and attributes different objects.

I tried to write simpler version BlackJack card game only with Hit or Stand option.

Could you have a look at my code and possibly give me some advices what should i change or improve?

import random

SUITS = ['Heart','Diamond','Club','Pike']
FIGURES = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
MONEY = 200
MIN_BET = 2

class Card:
    '''
    Single card class
    Use it in loop to make full french deck of card
    print return 'Figure of suit'
    '''

    def __init__(self,suit,figure):
        self.suit = suit
        self.figure = figure

        if self.figure == "A":
            self.value = 11
        elif self.figure in ['J','Q','K']:
            self.value = 10
        else:
            self.value = int(self.figure)

    def __str__(self):
        return f'{self.figure} of {self.suit}'

    def __repr__(self):
        return f'{self.figure} of {self.suit}'


class Deck:

    def __init__(self):
        self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]

    def shuffle(self):
        random.shuffle(self.deck)

    def draw(self):
        return self.deck.pop(0)

    def restart(self):
        self.deck = [Card(suit, figure) for suit in SUITS for figure in FIGURES]

class Hand:
    def __init__(self):
        self.cards = []
        self.value = 0
        self.aces = 0    

    def add_card(self, card):
        self.cards.append(card)
        self.check_aces()

    def check_value(self):
        '''
        Change self.value
        Doesnt return any value
        '''
        ace = self.aces
        self.value = 0

        for i in range(len(self.cards)):
            self.value += self.cards[i].value

            while self.value > 21 and ace > 0:
                self.value -= 10
                ace -= 1

        if self.value > 21:
            self.isBusted = True

        return self.value

    def check_aces(self):
        '''
        Check if 'A' in Hand 
        '''
        self.aces = 0

        for i in range(len(self.cards)):
            if self.cards[i].figure == 'A':
                self.aces += 1

    # I know i should make new class dealer inherit from Hand with this function
    def dealer_ai(self,d):
        self.check_value()
        while self.value < 17:
            self.add_card(d.draw())
            self.check_value()
        print(f'Dealer cards: {self.cards} ')

    def restart(self):
        self.cards = []
        self.value = 0
        self.aces = 0  

class Bank:

    def __init__(self, money, min_bet):
        self.money = money
        self.min_bet = min_bet
        self.play = True
        self.pool = 0

        self.check_money()
        print(self)


    def __str__(self):
        return f'You have {self.money}$'

    def check_money(self):
        if self.money < self.min_bet:
            self.play = False
        else:
            self.play = True

    def bet(self):
        print(f'You have {self.money}$.')

        while True:
            try:
                bet = int(input('Tell me your bet (should be lower or equal then your money)'))
            except:
                continue
            else:
                break

        if bet>self.money:
            self.bet()

        else:
            self.pool = 2*bet
            self.money -= bet
            print(f'Your new balance: {self.money}$')

    def deposite(self,depo):
        self.money += depo

    def player_win(self):
            self.deposite(self.pool)
            print(f'You won: {self.pool}$ \nYour new balance is {self.money}.')
            self.pool = 0

    def player_lose(self):
            print(f'Sorry! You lose {self.pool/2}.\nYour new balance is {self.money}')
            self.pool = 0


def play_choice():
    choice = ''
    while True:
        choice = input('Do you want to play? Y or N: ')
        if choice.lower() == "y":
            return True
        elif choice.lower() == 'n':
            return False
        else:
            play_choice()

def main():

    print('Welcome in Blackjack game! There is only two options - hit or stand')
    print('If you dont know rules - google for Blackjack')

    ##Creating Objects
    deck = Deck()
    player_hand = Hand()
    dealer_hand = Hand()
    bank = Bank(MONEY,MIN_BET)

    winner = True
    is_playing = play_choice()
    ##1 round -> Draw, hit/stand -> dealer -> check if win   
    while is_playing:


        while True:
            deck.restart()
            player_hand.restart()
            dealer_hand.restart()
            deck.shuffle()
            bank.bet()

            #Lets draw 4 cards - 2 For you, 2 for Dealer
            player_hand.add_card(deck.draw())
            player_hand.add_card(deck.draw())
            dealer_hand.add_card(deck.draw())
            dealer_hand.add_card(deck.draw())
            player_hand.check_value()
            print(f'\n\nYour cards: {player_hand.cards} with {player_hand.value} value')
            print(f'Dealer first card: {dealer_hand.cards[0]} ')
            choice = input('\n\nWhats your choice? - "h" for hit / "s" for stand')
            while choice.lower() == 'h':
                player_hand.add_card(deck.draw())
                player_hand.check_value()
                print(f'\n\nYour cards: {player_hand.cards} with {player_hand.value} value')
                if player_hand.value >= 21:
                    break
                choice = input('\n\nWhats your choice? - "h" for hit / "s" for stand')

            ###
            ## Check for player value
            if player_hand.value == 21:
                winner = True
                break
            elif player_hand.value > 21:
                winner = False
                break

            dealer_hand.dealer_ai(deck)


            if dealer_hand.value > 21:
                winner = True
                break
            elif dealer_hand.value == 21:
                winner = False
                break

            elif player_hand.value > dealer_hand.value:
                winner = True
                break
            else:
                winner = False
                break

        if winner:
            bank.player_win()
        else:
            bank.player_lose()


        is_playing = play_choice()

if __name__ == "__main__":
    main()
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.