By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,171 Members | 809 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,171 IT Pros & Developers. It's quick & easy.

blackjack game

P: 64
i have a balckjack code, which does not seem to run, in python, it comes up with syntax error, i have try sortng it out. does not seem to work. below is my code, if anyone can work out wht wrong with it. that will be great. thereis an attched file, to see the code more cleaer.

Expand|Select|Wrap|Line Numbers
  1. from random import choice as randomcards
  2.  
  3. def total(hand):
  4.     # how many aces in the hand
  5.     aces = hand.count(11)
  6.     # to complicate things a little the ace can be 11 or 1
  7.     # this little while loop figures it out for you
  8.     t = sum(hand)
  9.     # you have gone over 21 but there is an ace
  10.     if t > 21 and aces > 0:
  11.         while aces > 0 and t > 21:
  12.             # this will switch the ace from 11 to 1
  13.             t -= 10
  14.             aces -= 1
  15.     return t
  16. # a suit of cards in blackjack assume the following values
  17. cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
  18.  
  19. # there are 4 suits per deck and usually several decks
  20. # this way you can assume the cards list to be an unlimited pool
  21.  
  22. cwin = 0  # computer win counter
  23. pwin = 0  # player win counter
  24. while True:
  25.     player = []
  26.     # draw 2 cards for the player to start
  27.     player.append(rc(cards))
  28.     player.append(rc(cards))
  29.     pbust = False  # player busted flag
  30.     cbust = False  # computer busted flag
  31. while True:
  32.         # loop for the player's play ...
  33.     tp = total(player)
  34. print "The player has these cards %s with a total value of %d" % (player, tp)
  35.  
  36. if tp > 21:
  37.             print "--> The player is busted!"
  38.             pbust = True
  39.             break
  40.  
  41. else tp == 21:
  42.             print "\a BLACKJACK!!!"
  43.             break
  44.         else:
  45.             hs = raw_input("Hit or Stand/Done (h or s): ").lower()
  46.             if 'h' in hs:
  47.                 player.append(rc(cards))
  48.             else:
  49.                 break
  50.     while True:
  51.         # loop for the computer's play ...
  52.        comp = []
  53.         comp.append(rc(cards))
  54.         comp.append(rc(cards))
  55.         # dealer generally stands around 17 or 18
  56.         while True:
  57.             tc = total(comp)                
  58.             if tc < 18:
  59.                 comp.append(rc(cards))
  60.             else:
  61.                 break
  62.         print "the computer has %s for a total of %d" % (comp, tc)
  63.         # now figure out who won ...
  64.         if tc > 21:
  65.             print "--> The computer is busted!"
  66.             cbust = True
  67.             if pbust == False:
  68.                 print "The player wins!"
  69.                 pwin += 1
  70.         elif tc > tp:
  71.            print "The computer wins!"
  72.             cwin += 1
  73.         elif tc == tp:
  74.             print "It's a draw!"
  75.         elif tp > tc:
  76.             if pbust == False:
  77.                 print "The player wins!"
  78.                 pwin += 1
  79.             elif cbust == False:
  80.                 print "The computer wins!"
  81.                 cwin += 1
  82.         break
  83.     print
  84.     print "Wins, player = %d  computer = %d" % (pwin, cwin)
  85.     exit = raw_input("Press Enter (q to quit): ").lower()
  86.     if 'q' in exit:
  87.         break
  88.     print
  89.  
  90. print "Thanks for playing blackjack with the computer!"
Attached Files
File Type: txt blackjack.txt (3.3 KB, 609 views)
Dec 17 '08 #1
Share this Question
Share on Google+
30 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Your indentation is all messed up. You have a break outside of a loop. This statement is invalid Python:
Expand|Select|Wrap|Line Numbers
  1. else tp == 21:
Function rc() is undefined.
Dec 17 '08 #2

P: 64
ok understand, how would i sort out, the "else tp ==21" cause i dont seem to understand wht the problem is. and how i solve it.
Dec 18 '08 #3

boxfish
Expert 100+
P: 469
Use elif:
Expand|Select|Wrap|Line Numbers
  1. elif tp ==21:
else cannot be used with a condition, but elif can.
Hope this helps.
Dec 18 '08 #4

P: 64
yeh, but if you see my code, i have used "elif"
Dec 19 '08 #5

P: 64
ok thnaks boxfish, i have changed to elif, but it still has syntax error.
Dec 19 '08 #6

bvdet
Expert Mod 2.5K+
P: 2,851
imran akhtar,

If you experience an error with your code, please post the error message and include all tracebacks. That will give us (and you) an idea of what the problem is. The statement "it still has syntax error" does not tell me anything that I don't already know. A syntax error could be something as simple as a missing parenthesis.

-BV
Dec 19 '08 #7

P: 64
there is still an error at this code "elif tp ==21:" and there is pop up which just displays an error with syntax.
Dec 20 '08 #8

P: 64
here is another black jack code,, it has erro message, which comes up, whic says,
Expand|Select|Wrap|Line Numbers
  1. from random import cards, games mportError: cannot import name cards
below is the code:
Expand|Select|Wrap|Line Numbers
  1. # Blackjack
  2. # From 1 to 7 players compete against a dealer
  3.  
  4. from random import cards, games     
  5.  
  6. class BJ_Card(cards.Card):
  7.     """ A Blackjack Card. """
  8.     ACE_VALUE = 1
  9.  
  10.     def get_value(self):
  11.         if self.is_face_up:
  12.             value = BJ_Card.RANKS.index(self.rank) + 1
  13.             if value > 10:
  14.                 value = 10
  15.         else:
  16.             value = None
  17.         return value
  18.  
  19.     value = property(get_value)
  20.  
  21.  
  22. class BJ_Deck(cards.Deck):
  23.     """ A Blackjack Deck. """
  24.     def populate(self):
  25.         for suit in BJ_Card.SUITS: 
  26.             for rank in BJ_Card.RANKS: 
  27.                 self.cards.append(BJ_Card(rank, suit))
  28.  
  29.  
  30. class BJ_Hand(cards.Hand):
  31.     """ A Blackjack Hand. """
  32.     def __init__(self, name):
  33.         super(BJ_Hand, self).__init__()
  34.         self.name = name
  35.  
  36.     def __str__(self):
  37.         rep = self.name + ":\t" + super(BJ_Hand, self).__str__()  
  38.         if self.total:
  39.             rep += "(" + str(self.total) + ")"        
  40.         return rep
  41.  
  42.     def get_total(self):
  43.         # if a card in the hand has value of None, then total is None
  44.         for card in self.cards:
  45.             if not card.value:
  46.                 return None
  47.  
  48.         # add up card values, treat each Ace as 1
  49.         total = 0
  50.         for card in self.cards:
  51.               total += card.value
  52.  
  53.         # determine if hand contains an Ace
  54.         contains_ace = False
  55.         for card in self.cards:
  56.             if card.value == BJ_Card.ACE_VALUE:
  57.                 contains_ace = True
  58.  
  59.         # if hand contains Ace and total is low enough, treat Ace as 11
  60.         if contains_ace and total <= 11:
  61.             # add only 10 since we've already added 1 for the Ace
  62.             total += 10   
  63.  
  64.         return total
  65.  
  66.     total = property(get_total)
  67.  
  68.     def is_busted(self):
  69.         return self.total > 21
  70.  
  71.  
  72. class BJ_Player(BJ_Hand):
  73.     """ A Blackjack Player. """
  74.     def is_hitting(self):
  75.         response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
  76.         return response == "y"
  77.  
  78.     def bust(self):
  79.         print self.name, "busts."
  80.         self.lose()
  81.  
  82.     def lose(self):
  83.         print self.name, "loses."
  84.  
  85.     def win(self):
  86.         print self.name, "wins."
  87.  
  88.     def push(self):
  89.         print self.name, "pushes."
  90.  
  91.  
  92. class BJ_Dealer(BJ_Hand):
  93.     """ A Blackjack Dealer. """
  94.     def is_hitting(self):
  95.         return self.total < 17
  96.  
  97.     def bust(self):
  98.         print self.name, "busts."
  99.  
  100.     def flip_first_card(self):
  101.         first_card = self.cards[0]
  102.         first_card.flip()
  103.  
  104.  
  105. class BJ_Game(object):
  106.     """ A Blackjack Game. """
  107.     def __init__(self, names):      
  108.         self.players = []
  109.         for name in names:
  110.             player = BJ_Player(name)
  111.             self.players.append(player)
  112.  
  113.         self.dealer = BJ_Dealer("Dealer")
  114.  
  115.         self.deck = BJ_Deck()
  116.         self.deck.populate()
  117.         self.deck.shuffle()
  118.  
  119.     def get_still_playing(self):
  120.         remaining = []
  121.         for player in self.players:
  122.             if not player.is_busted():
  123.                 remaining.append(player)
  124.         return remaining
  125.  
  126.     # list of players still playing (not busted) this round
  127.     still_playing = property(get_still_playing)
  128.  
  129.     def __additional_cards(self, player):
  130.         while not player.is_busted() and player.is_hitting():
  131.             self.deck.deal([player])
  132.             print player
  133.             if player.is_busted():
  134.                 player.bust()
  135.  
  136.     def play(self):
  137.         # deal initial 2 cards to everyone
  138.         self.deck.deal(self.players + [self.dealer], per_hand = 2)
  139.         self.dealer.flip_first_card()    # hide dealer's first card
  140.         for player in self.players:
  141.             print player
  142.         print self.dealer
  143.  
  144.         # deal additional cards to players
  145.         for player in self.players:
  146.             self.__additional_cards(player)
  147.  
  148.         self.dealer.flip_first_card()    # reveal dealer's first 
  149.  
  150.         if not self.still_playing:
  151.             # since all players have busted, just show the dealer's hand
  152.             print self.dealer
  153.         else:
  154.             # deal additional cards to dealer
  155.             print self.dealer
  156.             self.__additional_cards(self.dealer)
  157.  
  158.             if self.dealer.is_busted():
  159.                 # everyone still playing wins
  160.                 for player in self.still_playing:
  161.                     player.win()                    
  162.             else:
  163.                 # compare each player still playing to dealer
  164.                 for player in self.still_playing:
  165.                     if player.total > self.dealer.total:
  166.                         player.win()
  167.                     elif player.total < self.dealer.total:
  168.                         player.lose()
  169.                     else:
  170.                         player.push()
  171.  
  172.         # remove everyone's cards
  173.         for player in self.players:
  174.             player.clear()
  175.         self.dealer.clear()
  176.  
  177.  
  178. def main():
  179.     print "\t\tWelcome to Blackjack!\n"
  180.  
  181.     names = []
  182.     number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
  183.     for i in range(number):
  184.         name = raw_input("Enter player name: ")
  185.         names.append(name)
  186.     print
  187.  
  188.     game = BJ_Game(names)
  189.  
  190.     again = None
  191.     while again != "n":
  192.         game.play()
  193.         again = games.ask_yes_no("\nDo you want to play again?: ")
  194.  
  195.  
  196. main()
  197. raw_input("\n\nPress the enter key to exit.")
Dec 20 '08 #9

P: 64
i have sorted the problem, with the "elif tp ==21:" but know program has another error message,

when you now run the program, the error message stops here,were i have highlighted in bold, thats were the error message stops (the error message which is displayed syntax error)
while True:
# loop for the computer's play ...
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
# dealer generally stands around 17 or 18
while True
Dec 20 '08 #10

bvdet
Expert Mod 2.5K+
P: 2,851
The random module does not define names cards or games. Apparently, the author of this code added these names to his random module or created his own random module.
Dec 20 '08 #11

bvdet
Expert Mod 2.5K+
P: 2,851
This is likely an indentation error. Did you ever define function rc()?
Dec 20 '08 #12

P: 64
yeh i thought this defined the rc() "from random import choice as rc" and i dont thinnk its indetation error, as normally python, will says if it was indentation error.
Dec 20 '08 #13

P: 64
bascially i have black jack, which works, fine, but how do get the Aces count as 1 or 11. belwo is the code, which is allready made, how and were would i add in the new aces code

below is the code..
Expand|Select|Wrap|Line Numbers
  1. import random as r
  2. deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]*4
  3. computer = []
  4. player = []
  5. c = 'y'
  6.  
  7. #Clear works only if you run it from command line
  8. def clear():
  9.     import os
  10.     if os.name == 'nt':
  11.         os.system('CLS') #Pass CLS to cmd
  12.     if os.name == 'posix':
  13.         os.system('clear') #Pass clear to terminal
  14.  
  15. def showHand():
  16.     hand = 0
  17.     for i in player: hand += i #Tally up the total
  18.     print "The computer is showing a %d" % computer[0]
  19.     print "Your hand totals: %d (%s)" % (hand, player)
  20.  
  21. #Gives player and computer their cards
  22. def setup():
  23.     for i in range(2):
  24.         dealcomputer = deck[r.randint(1, len(deck)-1)]
  25.         dealPlayer = deck[r.randint(1, len(deck)-1)]
  26.         computer.append(dealcomputer)
  27.         player.append(dealPlayer)
  28.         deck.pop(dealcomputer)
  29.         deck.pop(dealPlayer)
  30. setup()
  31. while c != 'q':
  32.     showHand()
  33.     c = raw_input("[D]ealt [S]tick [Q]uit: ").lower()
  34.     clear()
  35.     if c == 'd':
  36.         dealPlayer = deck[r.randint(1, len(deck)-1)]
  37.         player.append(dealPlayer)
  38.         deck.pop(dealPlayer)
  39.         hand = 0
  40.         for i in computer: hand += i
  41.         if not hand > 17:   #computer strategy.
  42.             dealplayer = deck[r.randint(1, len(deck)-1)]
  43.             computer.append(dealplayer)
  44.             deck.pop(dealplayer)
  45.         hand = 0
  46.         for i in player: hand += i
  47.         if hand > 21:
  48.             print "BUST!"
  49.             player = []     #Clear player hand
  50.             computer = []     #Clear computer's hand
  51.             setup()         #Run the setup again
  52.         hand = 0
  53.         for i in computer: hand +=i
  54.         if hand > 21:
  55.             print "computer Busts!"
  56.             player = []
  57.             computer = []
  58.             setup()
  59.     elif c == 's':
  60.         cHand = 0           #computer's hand total
  61.         pHand = 0           #Player's hand total
  62.         for i in computer: cHand += i
  63.         for i in player: pHand += i
  64.         if pHand > cHand:
  65.             print "FTW!"    #If playerHand (pHand) is greater than computeHand (cHand) you win...
  66.             computer = []
  67.             player = []
  68.             setup()
  69.         else:
  70.             print "FTL!"    #...otherwise you loose.
  71.             computer= []
  72.             player = []
  73.             setup()
  74.     else:
  75.         if c == 'q':
  76.  
  77.  
  78.             exit = raw_input("Press Enter (q to quit): ").lower()
  79.         if 'q' in exit:
  80.             break
  81.         print
  82.  
  83.     #print "Thanks for playing blackjack with the computer!"
  84.  
  85. ##            gb = raw_input("Toodles. [Hit Enter]")
  86. ##        else:
  87. ##            print "Invalid choice."
  88.  
  89.  
  90.         #print
  91.         #print "Wins, player = %d  computer = %d" % (pwin, cwin)
  92. ##        exit = raw_input("Press Enter (q to quit): ").lower()
  93. ##        if 'q' in exit:
  94. ##            break
  95. ##        print
  96. ##
  97. ##    print "Thanks for playing blackjack with the computer!"
Dec 20 '08 #14

bvdet
Expert Mod 2.5K+
P: 2,851
imran akhtar,

I have merged the three threads you started on blackjack. It is against posting guidelines to create multiple threads on the same question. Apparently, you have obtained code from various places (none of which you wrote), and they all have problems which you are asking us to help with (with little or no effort on your part). In the future, please refrain from this type of posting.

-BV
Moderator
Dec 20 '08 #15

P: 64
ok i understand, and i would like to say sorry.
Dec 21 '08 #16

P: 64
if you can just help me with this code, i be very much obliged, with this black jack code, it which works, fine, but how do i get the Aces count as 1 or 11. belwo is the code, which is allready made, how and were would i add in the new aces code.

Expand|Select|Wrap|Line Numbers
  1. import random as r
  2. deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]*4
  3. computer = []
  4. player = []
  5. c = 'y'
  6.  
  7. #Clear works only if you run it from command line
  8. def clear():
  9.     import os
  10.     if os.name == 'nt':
  11.         os.system('CLS') #Pass CLS to cmd
  12.     if os.name == 'posix':
  13.         os.system('clear') #Pass clear to terminal
  14.  
  15. def showHand():
  16.     hand = 0
  17.     for i in player: hand += i #Tally up the total
  18.     print "The computer is showing a %d" % computer[0]
  19.     print "Your hand totals: %d (%s)" % (hand, player)
  20.  
  21. #Gives player and computer their cards
  22. def setup():
  23.     for i in range(2):
  24.         dealcomputer = deck[r.randint(1, len(deck)-1)]
  25.         dealPlayer = deck[r.randint(1, len(deck)-1)]
  26.         computer.append(dealcomputer)
  27.         player.append(dealPlayer)
  28.         deck.pop(dealcomputer)
  29.         deck.pop(dealPlayer)
  30. setup()
  31. while c != 'q':
  32.     showHand()
  33.     c = raw_input("[D]ealt [S]tick [Q]uit: ").lower()
  34.     clear()
  35.     if c == 'd':
  36.         dealPlayer = deck[r.randint(1, len(deck)-1)]
  37.         player.append(dealPlayer)
  38.         deck.pop(dealPlayer)
  39.         hand = 0
  40.         for i in computer: hand += i
  41.         if not hand > 17:   #computer strategy.
  42.             dealplayer = deck[r.randint(1, len(deck)-1)]
  43.             computer.append(dealplayer)
  44.             deck.pop(dealplayer)
  45.         hand = 0
  46.         for i in player: hand += i
  47.         if hand > 21:
  48.             print "BUST!"
  49.             player = []     #Clear player hand
  50.             computer = []     #Clear computer's hand
  51.             setup()         #Run the setup again
  52.         hand = 0
  53.         for i in computer: hand +=i
  54.         if hand > 21:
  55.             print "computer Busts!"
  56.             player = []
  57.             computer = []
  58.             setup()
  59.     elif c == 's':
  60.         cHand = 0           #computer's hand total
  61.         pHand = 0           #Player's hand total
  62.         for i in computer: cHand += i
  63.         for i in player: pHand += i
  64.         if pHand > cHand:
  65.             print "you Win!"    #If playerHand (pHand) is greater than computeHand (cHand) you win...
  66.             computer = []
  67.             player = []
  68.             setup()
  69.         else:
  70.             print "computer win!"    #...otherwise you loose.
  71.             computer= []
  72.             player = []
  73.             setup()
  74.     else:
  75.         if c == 'q':
  76.  
  77.  
  78.             gb= raw_input("Press Enter (q to quit): ").lower()
  79.             if 'q' in exit:
  80.              break
  81.  
  82.  
  83.        # print "Wins, player = %d  computer = %d" % (player, computer)
  84.  
  85.     print "Thanks for playing blackjack with the computer!"
Dec 21 '08 #17

boxfish
Expert 100+
P: 469
I don't know the rules to blackjack, but from what I read on Wikipedia, it looks like the player can choose whether to value an ace as 1 or 11 in order to increase his chance of winning; am I right? So if that's the case, do you want to prompt the user asking whether she wants to value an ace as 1 or 11, or have the computer find the best value for the card? For storing aces in your array of cards, I think you can pick any value you want, for example 1, -1, or "a", and have the program interpert that as an ace.
Dec 21 '08 #18

bvdet
Expert Mod 2.5K+
P: 2,851
Where's the "Hit Me" option? I think it would be better to actually deal cards that can be valued, and let the computer decide if an ace should be 1 or 11. I have code for Cards and Deck classes that could be used in a blackjack game. I have added to and modified them. I don't know where the original code came from.
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. class Card(object):
  4.  
  5.     suitList = ["Hearts", "Diamonds", "Clubs", "Spades"]
  6.     rankList = ["Invalid", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
  7.     scoreList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  8.  
  9.     def __init__ (self, suit=0, rank=1):
  10.         if suit >= 0 and suit <= 3:
  11.             self.suit = suit
  12.         else:
  13.             self.suit = 0
  14.         if rank >= 1 and rank <= 13:
  15.             self.rank = rank
  16.         else:
  17.             self.rank = 1
  18.         self.score = self.scoreList[self.rank]
  19.         self.cname = self.rankList[self.rank]
  20.         self.sname = self.suitList[self.suit]
  21.  
  22.     def __str__(self):
  23.         return self.rankList[self.rank] + " of " + self.suitList[self.suit]
  24.  
  25.     def __repr__(self):
  26.         return self.rankList[self.rank] + " of " + self.suitList[self.suit]
  27.  
  28.     def __cmp__(self, other):
  29.         i = cmp(self.rank, other.rank)
  30.         if i == 0:
  31.             return cmp(self.suit, other.suit)
  32.         return i
  33.  
  34. class Deck(object):
  35.     def __init__(self):
  36.         self.cards = []
  37.         for suit in range(4):
  38.             for rank in range(1,14):
  39.                 self.cards.append(Card(suit, rank))
  40.  
  41.     def __getitem__(self, i):
  42.         return self.cards[i]
  43.  
  44.     def __iter__(self):
  45.         for card in self.cards:
  46.             yield card
  47.  
  48.     def __len__(self):
  49.         return len(self.cards)
  50.  
  51.     def __str__(self):
  52.         return '\n'.join([str(c) for c in self])
  53.  
  54.     def __repr__(self):
  55.         return str(self.cards)
  56.  
  57. def deal_hand(n, deck):
  58.     '''
  59.     Randomly deal and remove n cards from a Deck object.
  60.     '''
  61.     hand = []
  62.     if len(deck) >= n:
  63.         for i in range(n):
  64.             hand.append(deck.cards.pop(random.choice(range(len(deck)))))
  65.     else:
  66.         print "There are not enough cards in the deck to deal %d cards." % n
  67.     return hand
  68.  
  69. def hit_hand(hand, deck):
  70.     if len(deck):
  71.         hand.append(deck.cards.pop(random.choice(range(len(deck)))))
  72.  
  73. def score_hand_BJ(hand):
  74.     score = sum([card.score for card in hand])
  75.     if 'Ace' in [card.cname for card in hand]:
  76.         if score <= 11:
  77.             score += 10
  78.     return score
  79.  
  80. deck1 = Deck()
  81. hand1 = deal_hand(2, deck1)
  82. hand2 = deal_hand(2, deck1)
  83. print hand1, hand2
  84. print score_hand_BJ(hand1)
  85. print score_hand_BJ(hand2)
  86.  
  87. hit_hand(hand1, deck1)
  88. print hand1
  89. print score_hand_BJ(hand1)
Sample output:
Expand|Select|Wrap|Line Numbers
  1. >>> [Jack of Diamonds, 6 of Hearts] [Ace of Hearts, Jack of Clubs]
  2. 16
  3. 21
  4. [Jack of Diamonds, 6 of Hearts, King of Spades]
  5. 26
  6. >>> hit_hand(hand2, deck1)
  7. >>> hand2
  8. [Ace of Hearts, Jack of Clubs, 8 of Spades]
  9. >>> score_hand(hand2)
  10. 19
  11. >>> 
In the output and interaction above, hand2 had an Ace, and was originally scored as 11. I hit hand2, and the Ace was scored as 1.
Dec 21 '08 #19

P: 64
thanks for ur help, but the code, above, is bit counfusing, as it runs, how do i actually play it,
Dec 22 '08 #20

bvdet
Expert Mod 2.5K+
P: 2,851
The code I posted is not a complete game, just some code that may be useful in a blackjack game. When I find some time, I'll add some to it. I've got to get some work done now.

-BV
Dec 22 '08 #21

P: 64
ok thanks, when you have time, please do so, i am very greatful, for your help.
Dec 22 '08 #22

bvdet
Expert Mod 2.5K+
P: 2,851
Following is the complete (so far) code listing of a blackjack game, using classes. At this time, there is no check for "blackjack" or "natural" (a total of 21 in your first two cards).
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. class Card(object):
  4.  
  5.     suitList = ["Hearts", "Diamonds", "Clubs", "Spades"]
  6.     rankList = ["Invalid", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
  7.     scoreList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  8.  
  9.     def __init__ (self, suit=0, rank=1):
  10.         if suit >= 0 and suit <= 3:
  11.             self.suit = suit
  12.         else:
  13.             self.suit = 0
  14.         if rank >= 1 and rank <= 13:
  15.             self.rank = rank
  16.         else:
  17.             self.rank = 1
  18.         self.score = self.scoreList[self.rank]
  19.         self.cname = self.rankList[self.rank]
  20.         self.sname = self.suitList[self.suit]
  21.  
  22.     def __str__(self):
  23.         return self.rankList[self.rank] + " of " + self.suitList[self.suit]
  24.  
  25.     def __repr__(self):
  26.         return self.rankList[self.rank] + " of " + self.suitList[self.suit]
  27.  
  28.     def __cmp__(self, other):
  29.         i = cmp(self.rank, other.rank)
  30.         if i == 0:
  31.             return cmp(self.suit, other.suit)
  32.         return i
  33.  
  34. class Deck(object):
  35.     def __init__(self):
  36.         self.cards = []
  37.         for suit in range(4):
  38.             for rank in range(1,14):
  39.                 self.cards.append(Card(suit, rank))
  40.  
  41.     def __getitem__(self, i):
  42.         return self.cards[i]
  43.  
  44.     def __iter__(self):
  45.         for card in self.cards:
  46.             yield card
  47.  
  48.     def __len__(self):
  49.         return len(self.cards)
  50.  
  51.     def __str__(self):
  52.         return '\n'.join([str(c) for c in self])
  53.  
  54.     def __repr__(self):
  55.         return str(self.cards)
  56.  
  57. class BJ(object):
  58.  
  59.     dealer_hit_threshold = 15
  60.  
  61.     def __init__(self):
  62.         '''
  63.         Designed for 2 players. Player 2 is the dealer. Dealer wins a tie.
  64.         Results are appended to self.results:
  65.         [[winner, playerhand, dealerhand], [winner, playerhand, dealerhand]]
  66.         Results are formatted for output.
  67.         '''
  68.         self.results = []
  69.         self.deck = Deck()
  70.  
  71.     def deal_hand(self, n, deck):
  72.         '''
  73.         Randomly deal and remove n cards from a Deck object.
  74.         '''
  75.         hand = []
  76.         if len(deck) >= n:
  77.             for i in range(n):
  78.                 hand.append(deck.cards.pop(random.choice(range(len(deck)))))
  79.         else:
  80.             print "There are not enough cards in the deck to deal %d cards." % n
  81.         return hand
  82.  
  83.     def hit_hand(self, hand, deck):
  84.         if len(deck):
  85.             hand.append(deck.cards.pop(random.choice(range(len(deck)))))
  86.             return True
  87.         else: return False
  88.  
  89.     def score_hand_BJ(self, hand):
  90.         score = sum([card.score for card in hand])
  91.         if 'Ace' in [card.cname for card in hand]:
  92.             if score <= 11:
  93.                 score += 10
  94.         return score
  95.  
  96.     def play(self):
  97.         playing = False
  98.         print
  99.         while True:
  100.             option = raw_input("(D)eal, (H)it Me, (S)tand, (Q)uit")
  101.             if option.upper() == "D":
  102.                 if playing:
  103.                     print "You are already playing a hand!"
  104.                 else:
  105.                     playing = True
  106.                     hand1 = self.deal_hand(2, self.deck)
  107.                     hand2 = self.deal_hand(2, self.deck)
  108.                     print "Player 1 Hand: %s\nPlayer 2 Hand: %s" % (hand1, hand2)
  109.                     print "Player 1 Score: %s\nPlayer 2 Score: %s" % (self.score_hand_BJ(hand1), self.score_hand_BJ(hand2))
  110.                     while self.score_hand_BJ(hand2) <= BJ.dealer_hit_threshold:
  111.                         if not self.deck:
  112.                             print "The deck is empty. Start over."
  113.                             self.play_over()
  114.                             return
  115.                         else:
  116.                             self.hit_hand(hand2, self.deck)
  117.                             print "Dealer took a HIT. Current HAND: %s Score: %s" % (hand2, self.score_hand_BJ(hand2))
  118.                             if self.score_hand_BJ(hand2) > 21:
  119.                                 print "Dealer BUSTS. Player wins."
  120.                                 self.results.append(["Player", hand1, hand2])
  121.                                 playing = False
  122.                                 print
  123.  
  124.             elif option.upper() == "H":
  125.                 if playing:
  126.                     if not self.deck:
  127.                         print "The deck is empty. Start over."
  128.                         self.play_over()
  129.                         return
  130.                     else:
  131.                         self.hit_hand(hand1, self.deck)
  132.                         print "Player took a HIT. Current HAND: %s Score: %s" % (hand1, self.score_hand_BJ(hand1))
  133.                         if self.score_hand_BJ(hand1) > 21:
  134.                             print "Player BUSTS. Dealer wins."
  135.                             self.results.append(["Dealer", hand1, hand2])
  136.                             playing = False
  137.                             print
  138.                 else:
  139.                     print "You must DEAL before taking a HIT"
  140.  
  141.             elif option.upper() == "S":
  142.                 if playing:
  143.                     if self.score_hand_BJ(hand1) > self.score_hand_BJ(hand2):
  144.                         print "PLAYER wins this hand. Score: %s to %s" % (self.score_hand_BJ(hand1), self.score_hand_BJ(hand2))
  145.                         self.results.append(["Player", hand1, hand2])
  146.                     else:
  147.                         print "DEALER wins this hand. Score: %s to %s" % (self.score_hand_BJ(hand1), self.score_hand_BJ(hand2))
  148.                         self.results.append(["Dealer", hand1, hand2])
  149.                 else:
  150.                     print "You must DEAL before selecting option to STAND."
  151.                 playing = False
  152.                 print
  153.  
  154.             elif option.upper() == "Q":
  155.                 self.play_over()
  156.                 return
  157.  
  158.     def play_over(self):
  159.         dd = dict.fromkeys(["Player", "Dealer"], 0)
  160.         for hand in self.results:
  161.             dd[hand[0]] += 1
  162.         playerwins = dd["Player"]
  163.         dealerwins = dd["Dealer"]
  164.         if playerwins > dealerwins:
  165.             resultList = ["", "Player won %d hand%s to %d." % (playerwins, ["", "s"][playerwins>1 or 0], dealerwins)]
  166.         elif playerwins == dealerwins:
  167.             resultList = ["There was a tie %d hand%s to %d." % (playerwins, ["", "s"][playerwins>1 or 0], dealerwins)]
  168.         else:
  169.             resultList = ["Dealer won %d hand%s to %d." % (dealerwins, ["", "s"][dealerwins>1 or 0], playerwins)]
  170.         resultList.append("Hands Played:")
  171.         if self.results:
  172.             for hand in self.results:
  173.                 resultList.append("  Player: %s   Dealer: %s" % (", ".join([str(c) for c in hand[1]]), ", ".join([str(c) for c in hand[2]])))
  174.         else:
  175.             resultList.append("No hands were played")
  176.         print '\n'.join(resultList)
  177.  
  178. if __name__ == "__main__":
  179.     g = BJ()
  180.     g.play()
Sample run:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Player 1 Hand: [8 of Clubs, 10 of Hearts]
  3. Player 2 Hand: [Ace of Diamonds, 7 of Clubs]
  4. Player 1 Score: 18
  5. Player 2 Score: 18
  6. Player took a HIT. Current HAND: [8 of Clubs, 10 of Hearts, 10 of Diamonds] Score: 28
  7. Player BUSTS. Dealer wins.
  8.  
  9. Player 1 Hand: [2 of Hearts, Queen of Hearts]
  10. Player 2 Hand: [2 of Clubs, Jack of Spades]
  11. Player 1 Score: 12
  12. Player 2 Score: 12
  13. Dealer took a HIT. Current HAND: [2 of Clubs, Jack of Spades, Ace of Clubs] Score: 13
  14. Dealer took a HIT. Current HAND: [2 of Clubs, Jack of Spades, Ace of Clubs, 3 of Clubs] Score: 16
  15. Player took a HIT. Current HAND: [2 of Hearts, Queen of Hearts, 7 of Hearts] Score: 19
  16. PLAYER wins this hand. Score: 19 to 16
  17.  
  18. Player 1 Hand: [Ace of Hearts, 4 of Diamonds]
  19. Player 2 Hand: [7 of Diamonds, 10 of Spades]
  20. Player 1 Score: 15
  21. Player 2 Score: 17
  22. Player took a HIT. Current HAND: [Ace of Hearts, 4 of Diamonds, 9 of Clubs] Score: 14
  23. Player took a HIT. Current HAND: [Ace of Hearts, 4 of Diamonds, 9 of Clubs, Queen of Spades] Score: 24
  24. Player BUSTS. Dealer wins.
  25.  
  26. Player 1 Hand: [6 of Hearts, King of Diamonds]
  27. Player 2 Hand: [6 of Diamonds, 4 of Clubs]
  28. Player 1 Score: 16
  29. Player 2 Score: 10
  30. Dealer took a HIT. Current HAND: [6 of Diamonds, 4 of Clubs, 9 of Spades] Score: 19
  31. Player took a HIT. Current HAND: [6 of Hearts, King of Diamonds, Jack of Hearts] Score: 26
  32. Player BUSTS. Dealer wins.
  33.  
  34. Player 1 Hand: [Jack of Clubs, 5 of Hearts]
  35. Player 2 Hand: [Queen of Diamonds, 5 of Clubs]
  36. Player 1 Score: 15
  37. Player 2 Score: 15
  38. Dealer took a HIT. Current HAND: [Queen of Diamonds, 5 of Clubs, 3 of Hearts] Score: 18
  39. Player took a HIT. Current HAND: [Jack of Clubs, 5 of Hearts, King of Spades] Score: 25
  40. Player BUSTS. Dealer wins.
  41.  
  42. Player 1 Hand: [4 of Spades, 6 of Spades]
  43. Player 2 Hand: [King of Hearts, 10 of Clubs]
  44. Player 1 Score: 10
  45. Player 2 Score: 20
  46. Player took a HIT. Current HAND: [4 of Spades, 6 of Spades, 5 of Spades] Score: 15
  47. Player took a HIT. Current HAND: [4 of Spades, 6 of Spades, 5 of Spades, 5 of Diamonds] Score: 20
  48. DEALER wins this hand. Score: 20 to 20
  49.  
  50. Player 1 Hand: [6 of Clubs, 8 of Spades]
  51. Player 2 Hand: [3 of Spades, 8 of Diamonds]
  52. Player 1 Score: 14
  53. Player 2 Score: 11
  54. Dealer took a HIT. Current HAND: [3 of Spades, 8 of Diamonds, Queen of Clubs] Score: 21
  55. DEALER wins this hand. Score: 14 to 21
  56.  
  57. Player 1 Hand: [8 of Hearts, King of Clubs]
  58. Player 2 Hand: [Jack of Diamonds, 9 of Hearts]
  59. Player 1 Score: 18
  60. Player 2 Score: 19
  61. Player took a HIT. Current HAND: [8 of Hearts, King of Clubs, 3 of Diamonds] Score: 21
  62. PLAYER wins this hand. Score: 21 to 19
  63.  
  64. Dealer won 6 hands to 2.
  65. Hands Played:
  66.   Player: 8 of Clubs, 10 of Hearts, 10 of Diamonds   Dealer: Ace of Diamonds, 7 of Clubs
  67.   Player: 2 of Hearts, Queen of Hearts, 7 of Hearts   Dealer: 2 of Clubs, Jack of Spades, Ace of Clubs, 3 of Clubs
  68.   Player: Ace of Hearts, 4 of Diamonds, 9 of Clubs, Queen of Spades   Dealer: 7 of Diamonds, 10 of Spades
  69.   Player: 6 of Hearts, King of Diamonds, Jack of Hearts   Dealer: 6 of Diamonds, 4 of Clubs, 9 of Spades
  70.   Player: Jack of Clubs, 5 of Hearts, King of Spades   Dealer: Queen of Diamonds, 5 of Clubs, 3 of Hearts
  71.   Player: 4 of Spades, 6 of Spades, 5 of Spades, 5 of Diamonds   Dealer: King of Hearts, 10 of Clubs
  72.   Player: 6 of Clubs, 8 of Spades   Dealer: 3 of Spades, 8 of Diamonds, Queen of Clubs
  73.   Player: 8 of Hearts, King of Clubs, 3 of Diamonds   Dealer: Jack of Diamonds, 9 of Hearts
  74. >>> 
Comments are encouraged.

-BV
Dec 24 '08 #23

P: 64
this qucik question wht does it mean , by the pontoon’ rule.
Dec 25 '08 #24

P: 64
would do u mean by "At this time, there is no check for "blackjack" or "natural" (a total of 21 in your first two cards)."
Dec 25 '08 #25

P: 64
i played the game, it is pretty good, is this the complete code.
Dec 25 '08 #26

bvdet
Expert Mod 2.5K+
P: 2,851
The code is complete, as far as what I have written. Can't you play a complete game?

If a player gets 21 with the first two cards. it is called a "natural" or "blackjack". The code does not check for this. If I add anything to the code, it will be a check for a "blackjack".

-BV
Dec 26 '08 #27

P: 64
this code is a poontoon rule, or is a stick at 16 rule.
Dec 26 '08 #28

bvdet
Expert Mod 2.5K+
P: 2,851
This is not pontoon blackjack. The dealer sticks when the value of his hand is greater than the value of variable dealer_hit_threshold.

-BV
Dec 26 '08 #29

P: 64
hi, does anyone, know the forums, email address or contanct details , i found this one "privacy@bytes.com" but does not seem to work, as i sent emails, and does seem to be a valid email address keeps failing to be sent .
Dec 28 '08 #30

bvdet
Expert Mod 2.5K+
P: 2,851
@imran akhtar
To whom do you want to send an email? Asking questions via private email is discouraged.

-BV
Moderator
Dec 29 '08 #31

Post your reply

Sign in to post your reply or Sign up for a free account.