blackjack game

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • imran akhtar
    New Member
    • Nov 2008
    • 64

    blackjack game

    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.

    Code:
    from random import choice as randomcards
     
    def total(hand):
        # how many aces in the hand
        aces = hand.count(11)
        # to complicate things a little the ace can be 11 or 1
        # this little while loop figures it out for you
        t = sum(hand)
        # you have gone over 21 but there is an ace
        if t > 21 and aces > 0:
            while aces > 0 and t > 21:
                # this will switch the ace from 11 to 1
                t -= 10
                aces -= 1
        return t
    # a suit of cards in blackjack assume the following values
    cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
     
    # there are 4 suits per deck and usually several decks
    # this way you can assume the cards list to be an unlimited pool
     
    cwin = 0  # computer win counter
    pwin = 0  # player win counter
    while True:
        player = []
        # draw 2 cards for the player to start
        player.append(rc(cards))
        player.append(rc(cards))
        pbust = False  # player busted flag
        cbust = False  # computer busted flag
    while True:
            # loop for the player's play ...
        tp = total(player)
    print "The player has these cards %s with a total value of %d" % (player, tp)
    
    if tp > 21:
                print "--> The player is busted!"
                pbust = True
                break
    
    else tp == 21:
                print "\a BLACKJACK!!!"
                break
            else:
                hs = raw_input("Hit or Stand/Done (h or s): ").lower()
                if 'h' in hs:
                    player.append(rc(cards))
                else:
                    break
        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:
                tc = total(comp)                
                if tc < 18:
                    comp.append(rc(cards))
                else:
                    break
            print "the computer has %s for a total of %d" % (comp, tc)
            # now figure out who won ...
            if tc > 21:
                print "--> The computer is busted!"
                cbust = True
                if pbust == False:
                    print "The player wins!"
                    pwin += 1
            elif tc > tp:
               print "The computer wins!"
                cwin += 1
            elif tc == tp:
                print "It's a draw!"
            elif tp > tc:
                if pbust == False:
                    print "The player wins!"
                    pwin += 1
                elif cbust == False:
                    print "The computer wins!"
                    cwin += 1
            break
        print
        print "Wins, player = %d  computer = %d" % (pwin, cwin)
        exit = raw_input("Press Enter (q to quit): ").lower()
        if 'q' in exit:
            break
        print
    
    print "Thanks for playing blackjack with the computer!"
    Attached Files
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Your indentation is all messed up. You have a break outside of a loop. This statement is invalid Python:
    Code:
    else tp == 21:
    Function rc() is undefined.

    Comment

    • imran akhtar
      New Member
      • Nov 2008
      • 64

      #3
      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.

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Use elif:
        Code:
        elif tp ==21:
        else cannot be used with a condition, but elif can.
        Hope this helps.

        Comment

        • imran akhtar
          New Member
          • Nov 2008
          • 64

          #5
          yeh, but if you see my code, i have used "elif"

          Comment

          • imran akhtar
            New Member
            • Nov 2008
            • 64

            #6
            ok thnaks boxfish, i have changed to elif, but it still has syntax error.

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              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

              Comment

              • imran akhtar
                New Member
                • Nov 2008
                • 64

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

                Comment

                • imran akhtar
                  New Member
                  • Nov 2008
                  • 64

                  #9
                  blackjack game code

                  here is another black jack code,, it has erro message, which comes up, whic says,
                  Code:
                  from random import cards, games mportError: cannot import name cards
                  below is the code:
                  Code:
                  # Blackjack
                  # From 1 to 7 players compete against a dealer
                  
                  from random import cards, games     
                  
                  class BJ_Card(cards.Card):
                      """ A Blackjack Card. """
                      ACE_VALUE = 1
                      
                      def get_value(self):
                          if self.is_face_up:
                              value = BJ_Card.RANKS.index(self.rank) + 1
                              if value > 10:
                                  value = 10
                          else:
                              value = None
                          return value
                  
                      value = property(get_value)
                  
                  
                  class BJ_Deck(cards.Deck):
                      """ A Blackjack Deck. """
                      def populate(self):
                          for suit in BJ_Card.SUITS: 
                              for rank in BJ_Card.RANKS: 
                                  self.cards.append(BJ_Card(rank, suit))
                      
                  
                  class BJ_Hand(cards.Hand):
                      """ A Blackjack Hand. """
                      def __init__(self, name):
                          super(BJ_Hand, self).__init__()
                          self.name = name
                  
                      def __str__(self):
                          rep = self.name + ":\t" + super(BJ_Hand, self).__str__()  
                          if self.total:
                              rep += "(" + str(self.total) + ")"        
                          return rep
                       
                      def get_total(self):
                          # if a card in the hand has value of None, then total is None
                          for card in self.cards:
                              if not card.value:
                                  return None
                          
                          # add up card values, treat each Ace as 1
                          total = 0
                          for card in self.cards:
                                total += card.value
                  
                          # determine if hand contains an Ace
                          contains_ace = False
                          for card in self.cards:
                              if card.value == BJ_Card.ACE_VALUE:
                                  contains_ace = True
                                  
                          # if hand contains Ace and total is low enough, treat Ace as 11
                          if contains_ace and total <= 11:
                              # add only 10 since we've already added 1 for the Ace
                              total += 10   
                                  
                          return total
                  
                      total = property(get_total)
                  
                      def is_busted(self):
                          return self.total > 21
                  
                  
                  class BJ_Player(BJ_Hand):
                      """ A Blackjack Player. """
                      def is_hitting(self):
                          response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
                          return response == "y"
                  
                      def bust(self):
                          print self.name, "busts."
                          self.lose()
                  
                      def lose(self):
                          print self.name, "loses."
                  
                      def win(self):
                          print self.name, "wins."
                  
                      def push(self):
                          print self.name, "pushes."
                  
                          
                  class BJ_Dealer(BJ_Hand):
                      """ A Blackjack Dealer. """
                      def is_hitting(self):
                          return self.total < 17
                  
                      def bust(self):
                          print self.name, "busts."
                  
                      def flip_first_card(self):
                          first_card = self.cards[0]
                          first_card.flip()
                  
                  
                  class BJ_Game(object):
                      """ A Blackjack Game. """
                      def __init__(self, names):      
                          self.players = []
                          for name in names:
                              player = BJ_Player(name)
                              self.players.append(player)
                  
                          self.dealer = BJ_Dealer("Dealer")
                  
                          self.deck = BJ_Deck()
                          self.deck.populate()
                          self.deck.shuffle()
                  
                      def get_still_playing(self):
                          remaining = []
                          for player in self.players:
                              if not player.is_busted():
                                  remaining.append(player)
                          return remaining
                  
                      # list of players still playing (not busted) this round
                      still_playing = property(get_still_playing)
                  
                      def __additional_cards(self, player):
                          while not player.is_busted() and player.is_hitting():
                              self.deck.deal([player])
                              print player
                              if player.is_busted():
                                  player.bust()
                             
                      def play(self):
                          # deal initial 2 cards to everyone
                          self.deck.deal(self.players + [self.dealer], per_hand = 2)
                          self.dealer.flip_first_card()    # hide dealer's first card
                          for player in self.players:
                              print player
                          print self.dealer
                  
                          # deal additional cards to players
                          for player in self.players:
                              self.__additional_cards(player)
                  
                          self.dealer.flip_first_card()    # reveal dealer's first 
                  
                          if not self.still_playing:
                              # since all players have busted, just show the dealer's hand
                              print self.dealer
                          else:
                              # deal additional cards to dealer
                              print self.dealer
                              self.__additional_cards(self.dealer)
                  
                              if self.dealer.is_busted():
                                  # everyone still playing wins
                                  for player in self.still_playing:
                                      player.win()                    
                              else:
                                  # compare each player still playing to dealer
                                  for player in self.still_playing:
                                      if player.total > self.dealer.total:
                                          player.win()
                                      elif player.total < self.dealer.total:
                                          player.lose()
                                      else:
                                          player.push()
                  
                          # remove everyone's cards
                          for player in self.players:
                              player.clear()
                          self.dealer.clear()
                          
                  
                  def main():
                      print "\t\tWelcome to Blackjack!\n"
                      
                      names = []
                      number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
                      for i in range(number):
                          name = raw_input("Enter player name: ")
                          names.append(name)
                      print
                          
                      game = BJ_Game(names)
                  
                      again = None
                      while again != "n":
                          game.play()
                          again = games.ask_yes_no("\nDo you want to play again?: ")
                  
                  
                  main()
                  raw_input("\n\nPress the enter key to exit.")

                  Comment

                  • imran akhtar
                    New Member
                    • Nov 2008
                    • 64

                    #10
                    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

                    Comment

                    • bvdet
                      Recognized Expert Specialist
                      • Oct 2006
                      • 2851

                      #11
                      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.

                      Comment

                      • bvdet
                        Recognized Expert Specialist
                        • Oct 2006
                        • 2851

                        #12
                        This is likely an indentation error. Did you ever define function rc()?

                        Comment

                        • imran akhtar
                          New Member
                          • Nov 2008
                          • 64

                          #13
                          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.

                          Comment

                          • imran akhtar
                            New Member
                            • Nov 2008
                            • 64

                            #14
                            blackjack code

                            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..
                            Code:
                            import random as r
                            deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]*4
                            computer = []
                            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 computer is showing a %d" % computer[0]
                                print "Your hand totals: %d (%s)" % (hand, player)
                            
                            #Gives player and computer their cards
                            def setup():
                                for i in range(2):
                                    dealcomputer = deck[r.randint(1, len(deck)-1)]
                                    dealPlayer = deck[r.randint(1, len(deck)-1)]
                                    computer.append(dealcomputer)
                                    player.append(dealPlayer)
                                    deck.pop(dealcomputer)
                                    deck.pop(dealPlayer)
                            setup()
                            while c != 'q':
                                showHand()
                                c = raw_input("[D]ealt [S]tick [Q]uit: ").lower()
                                clear()
                                if c == 'd':
                                    dealPlayer = deck[r.randint(1, len(deck)-1)]
                                    player.append(dealPlayer)
                                    deck.pop(dealPlayer)
                                    hand = 0
                                    for i in computer: hand += i
                                    if not hand > 17:   #computer strategy.
                                        dealplayer = deck[r.randint(1, len(deck)-1)]
                                        computer.append(dealplayer)
                                        deck.pop(dealplayer)
                                    hand = 0
                                    for i in player: hand += i
                                    if hand > 21:
                                        print "BUST!"
                                        player = []     #Clear player hand
                                        computer = []     #Clear computer's hand
                                        setup()         #Run the setup again
                                    hand = 0
                                    for i in computer: hand +=i
                                    if hand > 21:
                                        print "computer Busts!"
                                        player = []
                                        computer = []
                                        setup()
                                elif c == 's':
                                    cHand = 0           #computer's hand total
                                    pHand = 0           #Player's hand total
                                    for i in computer: cHand += i
                                    for i in player: pHand += i
                                    if pHand > cHand:
                                        print "FTW!"    #If playerHand (pHand) is greater than computeHand (cHand) you win...
                                        computer = []
                                        player = []
                                        setup()
                                    else:
                                        print "FTL!"    #...otherwise you loose.
                                        computer= []
                                        player = []
                                        setup()
                                else:
                                    if c == 'q':
                                        
                            
                                        exit = raw_input("Press Enter (q to quit): ").lower()
                                    if 'q' in exit:
                                        break
                                    print
                            
                                #print "Thanks for playing blackjack with the computer!"
                                        
                            ##            gb = raw_input("Toodles. [Hit Enter]")
                            ##        else:
                            ##            print "Invalid choice."
                            
                            
                                    #print
                                    #print "Wins, player = %d  computer = %d" % (pwin, cwin)
                            ##        exit = raw_input("Press Enter (q to quit): ").lower()
                            ##        if 'q' in exit:
                            ##            break
                            ##        print
                            ##
                            ##    print "Thanks for playing blackjack with the computer!"

                            Comment

                            • bvdet
                              Recognized Expert Specialist
                              • Oct 2006
                              • 2851

                              #15
                              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

                              Comment

                              Working...