ActiveState Code

Recipe 522992: Blackjack


Text based command line blackjack. Hit and Stand are the only available options. Clean, commented code. Comment out any "clear()" statements you see if you want to run it in Idle.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#Blackjack by Mike McGowan
#It's Monday, June 25, 2007 as of now, but I'm pretty sure I finished this
#a week or two ago. I cleaned it up yesterday.

import random as r
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]*4
dealer = []
player = []
c = 'y'

#Clear works only if you run it from command line
def clear():
    import os
    if os.name == 'nt':
        os.system('CLS') #Pass CLS to cmd
    if os.name == 'posix':
        os.system('clear') #Pass clear to terminal
    
def showHand():
    hand = 0
    for i in player: hand += i #Tally up the total
    print "The dealer is showing a %d" % dealer[0]
    print "Your hand totals: %d (%s)" % (hand, player)

#Gives player and dealer their cards
def setup():
    for i in range(2):
        dealDealer = deck[r.randint(1, len(deck)-1)]
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        dealer.append(dealDealer)
        player.append(dealPlayer)
        deck.pop(dealDealer)
        deck.pop(dealPlayer)
setup()
while c != 'q':
    showHand()
    c = raw_input("[H]it [S]tand [Q]uit: ").lower()
    clear()
    if c == 'h':
        dealPlayer = deck[r.randint(1, len(deck)-1)]
        player.append(dealPlayer)
        deck.pop(dealPlayer)
        hand = 0
        for i in dealer: hand += i
        if not hand > 17:   #Dealer strategy.
            dealDealer = deck[r.randint(1, len(deck)-1)]
            dealer.append(dealDealer)
            deck.pop(dealDealer)
        hand = 0
        for i in player: hand += i
        if hand > 21:
            print "BUST!"
            player = []     #Clear player hand
            dealer = []     #Clear dealer's hand
            setup()         #Run the setup again
        hand = 0
        for i in dealer: hand +=i
        if hand > 21:
            print "Dealer Busts!"
            player = []
            dealer = []
            setup()
    elif c == 's':
        dHand = 0           #Dealer's hand total
        pHand = 0           #Player's hand total
        for i in dealer: dHand += i
        for i in player: pHand += i
        if pHand > dHand:
            print "FTW!"    #If playerHand (pHand) is greater than dealerHand (dHand) you win...
            dealer = []
            player = []
            setup()
        else:
            print "FTL!"    #...otherwise you loose.
            dealer = []
            player = []
            setup()
    else:
        if c == 'q':
            gb = raw_input("Toodles. [Hit Enter]")
        else:
            print "Invalid choice."

Discussion

Why text blackjack? I wanted to make my first complicated program. I was watching Pirates of Silicon Valley and I got to the scene where one guy goes "I just made blackjack!" and then I wanted to make blackjack.

Issues: *Occasional IndexError. A try/except statement should help fix that.

Comments

  1. 1. At 2:18 a.m. on 8 jul 2007, Symon Polley said:

    an oo version?? i think it would be easier to understand and even funner to program if you used an object oriented aproach with class's give me a couple days and i'll submit one :)

    and pirates of silicon valley rocked :)

  2. 2. At 1:50 p.m. on 18 aug 2007, Joe Fidler said:

    Fun game. I think there is a problem in the following sequence.

    dealPlayer = deck[r.randint(1, len(deck)-1)] player.append(dealPlayer) deck.pop(dealPlayer)

    dealDealer is a card value, but the list pop() is an offset, and here refers the position of the card in the deck. The effect is that the card that is pop'ed is not the one that has been delt.

    I enjoyed the game (thanks Mike) so has a go at a re-write:

    import random as r

    class deck_of_cards:

    def __init__(self): self.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]*4

    def random_card_from_deck(self): # select a random card in the deck position_in_deck = r.randint(0, len(self.cards)-1) # take the card from the deck card = self.cards[position_in_deck] self.cards.pop(position_in_deck) return card

    class hand:

    def __init__(self,owner="Player"): self.cards = [] self.owner = owner

    def showHand(self): if self.owner == "Player": print "Your Hand : (%s) Totals: %d" % (self.cards,self.tally()) #If this instance belongs to the dealer then show dealers first card elif self.owner == "Dealer": print "The Dealer is showing %s " % self.cards[1] else: print "I'm confused about who owns this hand"

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

    def tally(self): #total the value of the cards in this hand hand = 0 for i in self.cards: hand += i return hand

    def newgame(): #Lets play !! print "dealing new cards" global deck, dealer_hand , player_hand deck = deck_of_cards() dealer_hand = hand("Dealer") player_hand = hand("Player")

    Give player and dealer 2 cards to start the game for i in range(2):

    dealer_hand.append(deck.random_card_from_deck()) player_hand.append(deck.random_card_from_deck())

    newgame() c = 'y' while c != 'q': player_hand.showHand() dealer_hand.showHand() c = raw_input("[H]it [S]tand [Q]uit: ").lower()

    if c == 'h': # Hit player_hand.append(deck.random_card_from_deck())

    if not dealer_hand.tally() > 17: #Dealer's strategy. dealer_hand.append(deck.random_card_from_deck())

    if player_hand.tally() > 21: print "You BUST!" newgame()

    if dealer_hand.tally() > 21: print "Dealer Busts!" newgame()

    elif c == 's': # Stand if player_hand.tally() > dealer_hand.tally(): print "You Win!!" newgame() else: print "You Loose!!"

    elif c == 'q': # Quit gb = raw_input("Toodles. [Hit Enter]")

    else: print "Invalid choice."

  3. 3. At 3:33 p.m. on 18 aug 2007, Joe Fidler said:
    <!--
        @page { size: 8.5in 11in; margin: 0.79in }
        P { margin-bottom: 0.08in }
        PRE { font-family: "Times New Roman" }
    -->
    
    Apologies for the previous unreadable post – I guess you have to post in HTML to retain formatting - so I learnt something new today.
    Anyway I enjoyed the game a lot (thanks Mike), so had a go at a re-write and spotted the probable
     cause for the index error.  I think the  problem lies in the following sequence.
    
    dealPlayer = deck[r.randint(1, len(deck)-1)]
    player.append(dealPlayer)
    deck.pop(dealPlayer)
    
    dealDealer is the face value of a card, but the list pop() is an
     offset, and here refers the position of the card in the deck.
    The effect is that the card that is pop'ed is not the one that has been delt.
    
    import random as r
    
    class deck_of_cards:
    
        def __init__(self):
            self.cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]*4
    
        def random_card_from_deck(self):
            # select a random card in the deck
            position_in_deck = r.randint(0, len(self.cards)-1)
            # take the card from the deck
            card = self.cards[position_in_deck]
            self.cards.pop(position_in_deck)
            return card
    
    
    class hand:
    
        def __init__(self,owner=&quot;Player&quot;):
            self.cards = []
            self.owner = owner
    
        def showHand(self):
            if self.owner == &quot;Player&quot;:
               print &quot;Your Hand :  (%s)  Totals: %d&quot; % (self.cards,self.tally())
            #If this instance belongs to the dealer then show dealers first card
            elif self.owner == &quot;Dealer&quot;:
                print &quot;The Dealer is showing %s &quot; % self.cards[1]
            else: print &quot;I'm confused about who owns this hand&quot;
    
        def append(self,card):
            self.cards.append(card)
    
        def tally(self):
            #total the value of the cards in this hand
            hand = 0
            for i in self.cards: hand += i
            return hand
    
    def newgame():
        #Lets play !!
        print &quot;dealing new cards&quot;
        global deck, dealer_hand , player_hand
        deck = deck_of_cards()
        dealer_hand = hand(&quot;Dealer&quot;)
        player_hand = hand(&quot;Player&quot;)
    
        #Give player and dealer 2 cards to start the game
        for i in range(2):
            dealer_hand.append(deck.random_card_from_deck())
            player_hand.append(deck.random_card_from_deck())
    
    
    newgame()
    c = 'y'
    while c != 'q':
        player_hand.showHand()
        dealer_hand.showHand()
        c = raw_input(&quot;[H]it [S]tand [Q]uit: &quot;).lower()
    
        if c == 'h':
        # Hit
            player_hand.append(deck.random_card_from_deck())
    

    (comment continued...)

  4. 4. At 3:33 p.m. on 18 aug 2007, Joe Fidler said:

    (...continued from previous comment)

            if not dealer_hand.tally() &gt; 17:   #Dealer's strategy.
                dealer_hand.append(deck.random_card_from_deck())
    
    
            if player_hand.tally() &gt; 21:
                print &quot;You BUST!&quot;
                newgame()
    
    
            if dealer_hand.tally() &gt; 21:
                print &quot;Dealer Busts!&quot;
                newgame()
    
    
        elif c == 's':
        # Stand
            if player_hand.tally() &gt; dealer_hand.tally():
                print &quot;You Win!!&quot;
                newgame()
            else:
                print &quot;You Loose!!&quot;
    
        elif c == 'q':
        # Quit
                gb = raw_input(&quot;Toodles. [Hit Enter]&quot;)
    
    
        else:
                print &quot;Invalid choice.&quot;
    

Sign in to comment