7
\$\begingroup\$

I am working on Jupyter Notebook and I am new to Python. I have created this BlackJack Game (This is my 2nd Project as I am Learning Python. See my 1st - Tic Tac Toe

from IPython.display import clear_output
import time
import random
colors = []
faces = []
values = {}
deck = []
ip=[0]
id=[0]
def shufflecards():
    global colors,faces,values,deck
    colors = ['spades', 'hearts', 'diamonds', 'clubs']
    faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
    values = dict(zip(faces, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]))
    deck = [face + ' of ' + color for color in colors for face in faces]

    random.shuffle(deck)
class Black_Jack_Bank(object):

    def __init__(self,bankroll=100):
        self.bankroll = bankroll

    def add_money(self,add=20):
        self.bankroll += add

    def sub_money(self,sub=10):

        trymoney = self.bankroll - sub

        if(trymoney<0):

            while True :
                try:
                    clear_output()
                    print"You have Gone Broke. So What? You Were Born to Overcome. You are not Destined to Lose."
                    val = int(raw_input("1. Enter Money to Bank\n2.GO Broke:P\nEnter Your Choice : "))
                except:
                    print "Looks like you did not enter a valid choice !\nTry Some Numbers."
                    continue
                else:
                    if(val == 1):
                        while True :
                            try:
                                print"You have Gone Broke. So What? You Were Born to Overcome. You are not Destined to Lose."
                                self.new_amount = int(raw_input("Empty Your Pockets :) Add Money To Casion Bank ! : "))
                            except:
                                print "Looks like you did not enter a valid choice !\nTry Some Numbers."
                                continue
                            else:
                                self.bankroll = self.new_amount
                                break

                        if(val == 2):
                            continue



                        break

        while True:
                try:
                    self.bet = int(raw_input("\nPlease enter your Bet : "))
                except:
                    print "Oops ! Thats not a valid Bet ! \nTry Some Numbers"
                    continue
                else:
                    trymoney1 = self.bankroll - self.bet
                    if(trymoney1<0):
                        print "Do Not Spend MONEY you don't have."
                        print "Your Current Balance is : "
                        print self.bankroll
                        continue
                    self.bankroll -= self.bet
                    break 

    def get_money(self):
        return self.bankroll

    def get_bet(self):
        return self.bet

    def blackjack_sub(self,sub):
        self.bet = sub
        self.bankroll -= self.bet

class Black_Jack_Gameplay(object):

    def __init__(self):
        self.player_card = []
        self.valuep = 0
        self.dealer_card = []
        self.valued = 0

    def dealer_hand_initial(self):
        for i in range(2):
            a_card = deck.pop()
            self.dealer_card.append(a_card)
            self.valued += values[a_card.split()[0]]
        print '\nDealers Cards are : '
        print"[' * ', '{a}']".format(a=self.dealer_card[1])

    def player_hand_initial(self):
        for i in range(2):
            a_card = deck.pop()
            self.player_card.append(a_card)
            self.valuep += values[a_card.split()[0]]
        print '\nYour Initial Cards are : '
        print self.player_card
        print self.valuep

    def player_hand_hit(self):

        if(ip[0] == 0):
            if( self.player_card[0] == 'A of spades' or self.player_card[0] == 'A of hearts' or
                self.player_card[0] == 'A of diamonds' or self.player_card[0] == 'A of clubs' or 
                self.player_card[1] == 'A of spades' or self.player_card[1] == 'A of hearts' or
                self.player_card[1] == 'A of diamonds' or self.player_card[1] == 'A of clubs'):
                values['A']=1
                ip[0] = 1
                self.valuep = self.valuep - 10
        a_card = deck.pop()
        self.player_card.append(a_card)
        self.valuep += values[a_card.split()[0]]
        clear_output()
        print '\nDealers Card are :'
        print"[' * ', '{a}']".format(a=self.dealer_card[1])
        print '\nYour Cards are : '
        print self.player_card
        print self.valuep

    def dealer_hand_hit(self):

        if(self.valued>=17):
            clear_output()
            print '\nYour Cards are : '
            print self.player_card
            print '\nDealers Cards are :'
            print self.dealer_card
            print self.valued

        while self.valued < 17 :

            #Once Player Stands The Dealer will play till Soft Hand is Reached
            if(id[0] == 0):

                if( self.dealer_card[0] == 'A of spades' or self.dealer_card[0] == 'A of hearts' or 
                   self.dealer_card[0] == 'A of diamonds' or self.dealer_card[0] == 'A of clubs' or 
                    self.dealer_card[1] == 'A of spades' or self.dealer_card[1] == 'A of hearts' or 
                   self.dealer_card[1] == 'A of diamonds' or self.dealer_card[1] == 'A of clubs'
                  ):
                    values['A']=1
                    id[0] =1
                    self.valued = self.valued - 10

            a_card = deck.pop()
            self.dealer_card.append(a_card)
            self.valued += values[a_card.split()[0]]
            clear_output()
            print '\nYour Cards are :'
            print self.player_card
            print '\nDealers Cards are : '
            print self.dealer_card
            print self.valued

    def player_win(self):
        if (self.valuep == 21):
            clear_output()
            print '\nDealers Cards are :'
            print self.dealer_card
            print '\nYour Cards are : '
            print self.player_card
            print self.valuep
            return 'Win'

        if(self.valuep > 21):
            clear_output()
            print '\nDealers Cards are :'
            print self.dealer_card
            print '\nYour Cards are : '
            print self.player_card
            print self.valuep
            return 'Burst'

        if(self.valuep < 21):
            return 'C'

    def dealer_win(self):
        if (self.valued == 21):
            return 'BJ'

        if(self.valued > 21):
            return 'B'

        if (self.valued > self.valuep):
            return 'W'

        if(self.valued < self.valuep):
            return 'L'

        if(self.valued == self.valuep):
            return 'D'
player_name = raw_input("Please Enter Your Name : ")
game_on = True

input1 = 0
gamebet1=0

while True:
    try:
        gamebet1 = int(raw_input("Empty Your Pockets :) Add Money To Casion Bank ! : "))
    except:
        print "Oops ! Thats not a valid Amount ! \nTry Some Numbers"
        continue
    else:
        player_bank = Black_Jack_Bank(gamebet1)
        break


while game_on:
    clear_output()
    print 'Welcome To Black Jack'
    player_bank = Black_Jack_Bank(gamebet1)


    gamebet = player_bank.sub_money()
    gamebet1 = player_bank.get_money()
    gamebet2 = player_bank.get_bet()


    print'Shuffling Cards . . . & Counting Money'
    time.sleep(3)
    shufflecards()

    clear_output()
    print"Dealer's Card are as follows"
    player_name = Black_Jack_Gameplay()

    player_name.dealer_hand_initial()
    player_name.player_hand_initial()

    z = player_name.player_win()
    if(z == 'Win'):
        print "Yipee ! Its BlackJack"
        player_bank.add_money((gamebet2)*2.5)
        gamebet1 = player_bank.get_money()
        print "Your Balance is : %s "%(gamebet1)
        time.sleep(7)
        continue

    y = player_name.dealer_win()
    if(y == 'BJ'):
        print "Yipee ! Its BlackJack"
        player_bank.blackjack_sub((gamebet2)*0.5)
        gamebet1 = player_bank.get_money()
        print "Your Balance is : %s "%(gamebet1)
        time.sleep(7)
        continue

    while True:

        try:
            val = int(raw_input("Please enter \n1. Hit\n2. Stand\n3. Current Balanace\n4. Exit Game\nPlease Enter Your Choice : "))
        except:
            print "Looks like you did not enter a Valid Choice!"
            continue
        else:
            if(val == 1):
                player_name.player_hand_hit()
                z = player_name.player_win()
                if(z == 'Win'):
                    print "Yipee ! You Win !"
                    player_bank.add_money((gamebet2)*2)
                    gamebet1 = player_bank.get_money()
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(z == 'Burst'):
                    print"Woopsie ! It's a burst"
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(z == 'C'):
                    continue

            if(val == 2):
                player_name.dealer_hand_hit()
                y = player_name.dealer_win()
                if(y == 'B'):
                    print'Dealer Bursts ! You Win'
                    player_bank.add_money((gamebet2)*2)
                    gamebet1 = player_bank.get_money()
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'BJ'):
                    print"Hmmm ! Dealer Wins"
                    player_bank.add_money(gamebet2)
                    gamebet1 = player_bank.get_money()
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'W'):
                    print'Hmmm ! Dealer Wins'
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'L'):
                    print'Yipee ! You Win'
                    player_bank.add_money((gamebet2)*2)
                    gamebet1 = player_bank.get_money()
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'D'):
                    print"Woah !It's a Draw"
                    player_bank.add_money(gamebet2)
                    gamebet1 = player_bank.get_money()
                    print "Your Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break


            if(val == 3):
                print gamebet1

            if(val == 4):         
                player_name.dealer_hand_hit()
                y = player_name.dealer_win()
                if(y == 'B'):
                    print'Dealer Bursts ! You Win'
                    player_bank.add_money((gamebet2)*2)
                    gamebet1 = player_bank.get_money()
                    print "Your CheckOut Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'BJ'):
                    print"Hmmm ! Dealer Wins"
                    player_bank.add_money(gamebet2)
                    gamebet1 = player_bank.get_money()
                    print "Your CheckOut Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'W'):
                    print'Hmmm ! Dealer Wins'
                    print "Your CheckOut Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'L'):
                    print'Yipee ! You Win'
                    player_bank.add_money((gamebet2)*2)
                    gamebet1 = player_bank.get_money()
                    print "Your CheckOut Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break
                if(y == 'D'):
                    print"Woah !It's a Draw"
                    player_bank.add_money(gamebet2)
                    gamebet1 = player_bank.get_money()
                    print "Your CheckOut Balance is : %s "%(gamebet1)
                    time.sleep(7)
                    break

I want help to make it better. Any code optimization with explanation is welcome. If you know any major rules that this code does not follow or some bugs in code, please mention.

P.S. I have tried using Object Oriented Programming. Due to gettting frustrated at the end due to errors. At the end the name of variables might be confusing.

\$\endgroup\$
3
  • 4
    \$\begingroup\$ You've used 4 Python tags. 'This will most definitely not run on Python 3.x and you don't need the 2.6 tag if it runs on 2.7. \$\endgroup\$
    – Mast
    Commented Jun 22, 2017 at 20:13
  • 1
    \$\begingroup\$ Also, your indentation looked like it had a copy-paste mistake in it. My edit should've fixed it. If your actual code looks different, please comment. \$\endgroup\$
    – Mast
    Commented Jun 22, 2017 at 20:15
  • \$\begingroup\$ @Mast please check the code again i have made the changes . See if its indentation is proper. \$\endgroup\$
    – mvrht
    Commented Jun 23, 2017 at 7:14

1 Answer 1

4
\$\begingroup\$

After a quick glance I see there are a few blocks that are repeated. They can be put into functions instead to reduce repetition and make it more readable. The sections are:

1)

if(ip[0] == 0):
    if( self.player_card[0] == 'A of spades' or self.player_card[0] == 'A of hearts' or
            self.player_card[0] == 'A of diamonds' or self.player_card[0] == 'A of clubs' or 
            self.player_card[1] == 'A of spades' or self.player_card[1] == 'A of hearts' or
            self.player_card[1] == 'A of diamonds' or self.player_card[1] == 'A of clubs'):
            values['A']=1
            ip[0] = 1

2)

print "Yipee ! Its BlackJack"
player_bank.add_money((gamebet2)*2.5)
gamebet1 = player_bank.get_money()
print "Your Balance is : %s "%(gamebet1)
time.sleep(7)
continue

3)

print "Yipee ! You Win !"
player_bank.add_money((gamebet2)*2)
gamebet1 = player_bank.get_money()
print "Your Balance is : %s "%(gamebet1)
time.sleep(7)

4)

print '\nDealers Cards are :'
print self.dealer_card
print '\nYour Cards are : '
print self.player_card

Also making the dealer and player into their own classes would at least help with readability and logically grouping your methods, since their methods are both currently in the Black_Jack_Gameplay class. With their similarities you could even find a way to use one class as both, or make one a parent class and one a child class (so you can practice some inheritance).

As a side note, if you use github and don't mind your practice programs being open source, there are a few free automated code review tools that can pick out things like repeated code and bad practices for you.

\$\endgroup\$
2
  • \$\begingroup\$ could you tell me more about the "automated code review tools that can pick out things like repeated code and bad practices for you." \$\endgroup\$
    – mvrht
    Commented Jun 28, 2017 at 18:56
  • \$\begingroup\$ @mvrht A couple examples are codacy and travis ci. They do a static analysis of your code and point out things like repeated code across your project, when you're not following general best practices, potential security vulnerabilities, etc. They were made to help you improve the quality of the code that you write. \$\endgroup\$
    – paperplate
    Commented Jun 29, 2017 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.