blackjack

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

    blackjack

    hi, i am making black jack code, but i am stuck, i have made start, but for reason gettin errors, which i dont seem be able to fix, below is my code wht i started.

    Code:
    import random 
        
    deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,11]*4
    player=[]
    computer=[]
    #r = random.randint
     
    computer.append(random.randint(deck))
    player.append(random.randint(deck))
    computer.append(random.randint(deck))
    print " The computer hand %d " % computer 
    player.append(random.randint(deck))
    print " The player hand %d" % player
    the error which i am getting is:

    Traceback (most recent call last):
    File "C:\Users\imran \Desktop\jack.p y", line 31, in ?
    computer.append (random.randint (deck))
    TypeError: randint() takes exactly 3 arguments (2 given)
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    random.randint takes two numbers as arguments and returns a random number that's between them. I think what you're looking for is random.choice, which selects a random item from a list:
    Code:
    computer.append(random.choice(deck))
    Another possibility is to actually shuffle the deck with random.shuffle before dealing cards:
    Code:
    random.shuffle(deck)
    computer.append(deck[0])
    player.append(deck[1])
    computer.append(deck[2])
    Hope this helps.

    Comment

    • imran akhtar
      New Member
      • Nov 2008
      • 64

      #3
      blackjack

      ok thanks no i dont have no erros,, but how would i display the players hand, computers hand.

      below is how the code looks now, but, would have to keep the code commeted out, as that think would display the, hands.

      thanks for help

      Code:
      import random 
          
      deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,11]*4
      player=[]
      computer=[]
      random.shuffle(deck) 
      computer.append(deck[0]) 
      player.append(deck[1])
      computer.append(deck[2])
       
      ##computer.append(random.choice(deck)) 
      ##player.append(random.choice(deck))
      ##
      ##computer.append(random.choice(deck))
      ##print " The computer hand %d " % computer 
      ##
      ##player.append(random.choice(deck))
      ##print " The player hand %d" % player
      Last edited by imran akhtar; Jan 16 '09, 12:26 PM. Reason: forgot

      Comment

      • imran akhtar
        New Member
        • Nov 2008
        • 64

        #4
        blackjack

        thanks for ur help before "boxfish" , i was able, proceed and pretty much complete my blackjack code. however, i have come across a minor problem, my hit function does not seem to work. do you know how i can fix this. also, does anyone know how i can fit a re-run code into my program too?

        Code:
        import random 
         
        deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
        player=[]
        computer=[]
        random.shuffle(deck)
        player.append(deck[0]) 
        player.append(deck[1])
        computer.append(deck[2])
        computer.append(deck[3])
        playerstotal = player [0]
        playerstotal2 = player [1]
        ptotal = playerstotal + playerstotal2
        comptotal = computer [0]
        comptotal2 = computer [1]
        ctotal = comptotal + comptotal2
        print "players hand", player
        print ptotal
        print "computers hand", computer
        print ctotal
         
        def game():
            options = raw_input ("do you wana [h]it / [s]tand / [q]uit: ")
            while options == 'h':
                player.append
                print ptotal
                break
            while options == 's':
                print "players hand", player
                print ptotal
                break
         
            if ctotal < 16:
                computer.append
         
            if ptotal > 21:
                print "player busted. computer wins"
            if ctotal > 21:
                print "computer busted. player wins"
            if ctotal == ptotal:
                print "draw. computer wins"
            if ptotal == 21:
                print "player gets a BlackJack. player wins"
            if ctotal == 21:
                print "computer gets a BlackJack. computer wins"
            if ptotal > ctotal:
                if ptotal < 21:
                    print "player wins"
            if ctotal > ptotal:
                if ctotal < 21:
                    print "computer wins"
         
            while options == 'q':
                print "hope you enjoyed the game, bye!!"
                break 
         
        game()
        thanks, appreciate the help.

        Comment

        • boxfish
          Recognized Expert Contributor
          • Mar 2008
          • 469

          #5
          The line in your hit function,
          player.append
          does nothing. You need to specify something to append, which means you need a way of keeping track of which card must be dealt next. One way to do this is to delete cards from the deck as you deal them, like this,
          Code:
          player.append(deck[0])
          del deck[0] 
          player.append(deck[0]) # When you delete the first card, deck[1] becomes deck[0]
          del deck[0]
          computer.append(deck[0])
          del deck[0]
          computer.append(deck[0])
          del deck[0]
          so that the next card to be dealt is always deck[0].
          Another possibility is to store the index of the next card to be dealt in a variable:
          Code:
          nextCard = 0
          player.append(deck[nextCard])
          nextCard += 1
           player.append(deck[nextCard]) # nextCard is now 1.
          nextCard += 1
           computer.append(deck[nextCard])
           nextCard += 1
           computer.append(deck[nextCard])
           nextCard += 1
          I think you need to calculate ptotal every time the player gets a new card and calculate ctotal every time the computer gets a new card. Calculating them just once at the beginning of the game won't work.

          I hope this is helpful, although your program will still need more work after you fix these problems.

          Comment

          • imran akhtar
            New Member
            • Nov 2008
            • 64

            #6
            blackjack

            i have tried the second option, but does not seem to work.


            Code:
            import random 
                
            deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
            player=[]
            computer=[]
            random.shuffle(deck)  #this will shuffle the cards in the deck
            nextCard = 0
            player.append(deck[nextCard]) 
            nextCard += 1 
            player.append(deck[nextCard]) # nextCard is now 1. 
            nextCard += 1 
            computer.append(deck[nextCard]) 
            nextCard += 1 
            computer.append(deck[nextCard]) 
            nextCard += 1 
            playerstotal = player [0]
            playerstotal2 = player [1]
            ptotal = playerstotal + playerstotal2   #this (ptotal) is the players overall total
            comptotal = computer [0]
            comptotal2 = computer [1]
            ctotal = comptotal + comptotal2         #this (ctotal) is the computers overall total
            print "players hand", player, "\tplayers total value", ptotal   #this will display the players hand
            
            #hit or stand,are players options.
            def game():
                options = raw_input ("do you wana [h]it / [s]tand / [q]uit: ")
                while options == 'h':       
                    player.append(deck[nextCard]) 
                    nextCard += 1 
                    print ptotal
                    break
                while options == 's':
                    print "players hand", player
                    print ptotal
                    break
                
                if ctotal < 16:
                    computer.append(deck[nextCard])
                    nextCard += 1
                if ptotal > 21:
                    print "player busted. computer wins"
                if ctotal > 21:
                    print "computer busted. player wins"
                if ctotal == ptotal:
                    print "draw. computer wins"
                if ptotal == 21:
                    print "player gets a BlackJack. player wins"
                if ctotal == 21:
                    print "computer gets a BlackJack. computer wins"
                if ptotal > ctotal:
                    if ptotal < 21:
                        print "player wins"
                if ctotal > ptotal:
                    if ctotal < 21:
                        print "computer wins"
                        
                while options == 'q':
                    print "hope you enjoyed the game, bye!!"
                    break 
                    
            game()

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              You can deal cards from a deck with one statement using random.choice() and list method pop().
              Example:
              Code:
              >>> hand = []
              >>> deck = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
              >>> import random
              >>> hand.append(deck.pop(random.choice(range(len(deck)))))
              >>> hand
              [10]
              >>> deck
              ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10]
              Notice one of the 10's has been removed from the deck.

              You can score aces as 1 or 11 using a function like this:
              Code:
              def hand_score(hand):
                  score = sum([card for card in hand if isinstance(card, int)])
                  aces = [card for card in hand if isinstance(card, str)]
                  score += len(aces)
                  for ace in aces:
                      if score < 12:
                          score += 10
                  return score
              The function sums all the numbers and assigns the value to variable score. Then a 1 is added to score for each ace. A for loop adds 10 to score for each ace if the current value of score is less than 12. Example:
              Code:
              >>> hand_score([6,7,'A'])
              14
              >>> hand_score(['A', 'A', 'A', 3, 4])
              20
              >>> hand_score([10, 'A'])
              21
              >>> hand_score([10, 'A', 'A'])
              12
              >>>
              HTH

              Comment

              • imran akhtar
                New Member
                • Nov 2008
                • 64

                #8
                blackjack

                thanks for your post, which may be helpful for other parts of my code, however my main problem is getting the "hit" function to work, as it is not working at the moment. have a look previous posts in this thread, and then could you be able to help me fix the "hit"?

                thanks once again.

                Comment

                • bvdet
                  Recognized Expert Specialist
                  • Oct 2006
                  • 2851

                  #9
                  What error message did you receive? When I run your code, I get this error:
                  UnboundLocalErr or: local variable 'nextCard' referenced before assignment

                  This should solve that problem:
                  Code:
                  def game():
                      global nextCard # I added this statement
                      while True:
                          options = raw_input ("do you wana [h]it / [s]tand / [q]uit: ")
                  Instead of using while statements, I suggest using an if/elif/else block for the user options.
                  Code:
                          if options == 'h':       
                              player.append(deck[nextCard]) 
                              nextCard += 1 
                              print ptotal
                  
                          elif options == 's':
                              print "players hand", player
                              print ptotal
                  
                          elif options == 'q':
                              print "hope you enjoyed the game, bye!!"
                              return

                  Comment

                  • imran akhtar
                    New Member
                    • Nov 2008
                    • 64

                    #10
                    blackjack

                    I added in what you told me to bvdet, and i get no errors, but when i 'hit', another card is not dealt and it still comes up with the previous total.

                    here is my code now:

                    Code:
                    import random 
                     
                    deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
                    player=[]
                    computer=[]
                    random.shuffle(deck)  #this will shuffle the cards in the deck
                    nextCard = 0
                    player.append(deck[nextCard]) 
                    nextCard += 1 
                    player.append(deck[nextCard]) # nextCard is now 1. 
                    nextCard += 1 
                    computer.append(deck[nextCard]) 
                    nextCard += 1 
                    computer.append(deck[nextCard]) 
                    nextCard += 1 
                    playerstotal = player [0]
                    playerstotal2 = player [1]
                    ptotal = playerstotal + playerstotal2   #this (ptotal) is the players overall total
                    comptotal = computer [0]
                    comptotal2 = computer [1]
                    ctotal = comptotal + comptotal2         #this (ctotal) is the computers overall total
                    print "players hand", player, "\tplayers total value", ptotal   #this will display the players hand
                     
                    #hit or stand,are players options.
                    def game():
                        global nextCard
                        while (True):
                            options = raw_input ("do you wana [h]it / [s]tand / [q]uit: ")
                            if options == 'h':
                                player.append(deck[nextCard]) 
                                nextCard += 1 
                                print ptotal
                                #break
                            elif options == 's':
                                print "players hand", player
                                print ptotal
                                #break
                            elif options == 'q':
                                print "hope you enjoyed the game, bye!!"
                                return
                                #break 
                     
                            if ctotal < 16:
                                computer.append(deck[nextCard])
                                nextCard += 1
                            if ptotal > 21:
                                print "player busted. computer wins"
                            if ctotal > 21:
                                print "computer busted. player wins"
                            if ctotal == ptotal:
                                print "draw. computer wins"
                            if ptotal == 21:
                                print "player gets a BlackJack. player wins"
                            if ctotal == 21:
                                print "computer gets a BlackJack. computer wins"
                            if ptotal > ctotal:
                                if ptotal < 21:
                                    print "player wins"
                            if ctotal > ptotal:
                                if ctotal < 21:
                                    print "computer wins"
                     
                    game()
                    here is what happens when i run the game:

                    Code:
                    Y [yes] to view the rules , N [no]to start the game:n
                    start game
                    players hand [8, 4]  players total value 12
                    do you wana [h]it / [s]tand / [q]uit: h
                    12
                    computer wins
                    do you wana [h]it / [s]tand / [q]uit:

                    Comment

                    • bvdet
                      Recognized Expert Specialist
                      • Oct 2006
                      • 2851

                      #11
                      A "card" is appended to list object player, but you are not updating the player's score. If the initial two cards are [6,7], the score would be sum([6,7]) = 13. If the player's hand is hit with a 3, the score would be sum([6,7,3]) = 16.

                      Comment

                      • imran akhtar
                        New Member
                        • Nov 2008
                        • 64

                        #12
                        blackjack

                        ok so it is not updating because the total itself is not updating. do you know how i can change it so the total updates?

                        thanks.

                        Comment

                        • bvdet
                          Recognized Expert Specialist
                          • Oct 2006
                          • 2851

                          #13
                          Originally posted by imran akhtar
                          ok so it is not updating because the total itself is not updating. do you know how i can change it so the total updates?

                          thanks.
                          The interpreter will do whatever you tell it to do. I suggested earlier a function to calculate the total each time. You do not need variable nextCard. Use list method pop() to return a card and remove from deck. I moved the location where the computer's hand is updated. If computer busts, player wins and there is no need to hit player. I added string method lower() to options to allow an uppercase entry. The code is by no means finished, but you should be able to take it from here.
                          Code:
                          import random
                          
                          def calc_score(hand):
                              score = sum([card for card in hand if isinstance(card, int)])
                              aces = [card for card in hand if isinstance(card, str)]
                              score += len(aces)
                              for ace in aces:
                                  if score < 12:
                                      score += 10
                              return score
                           
                          #hit or stand,are players options.
                          def game():
                          
                              deck = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
                              player=[]
                              computer=[]
                              random.shuffle(deck)  #this will shuffle the cards in the deck
                          
                              # deck.pop() will return a card and remove from deck
                              player.append(deck.pop()) 
                              computer.append(deck.pop())
                              player.append(deck.pop())
                              computer.append(deck.pop())
                          
                              player_score = calc_score(player)
                              computer_score = calc_score(computer)
                          
                              #this will display the players hand
                              print "players hand", player, "\tplayers total value", player_score
                          
                              # update computer hand until the score is >= 16 or busted
                              while computer_score < 16:
                                  computer.append(deck.pop())
                                  computer_score = calc_score(computer)
                                  
                              if computer_score > 21:
                                  # CHECK IF COMPUTER IS BUSTED HERE
                                  print "COMPUTER IS BUSTED!"
                                  return
                              
                              while True:
                                  options = raw_input ("do you want to [h]it / [s]tand / [q]uit: ")
                                  
                                  if options.lower() == 'h':       
                                      player.append(deck.pop())
                                      print player
                                      player_score = calc_score(player)
                                      print player_score
                                      # CHECK IF PLAYER IS BUSTED HERE
                                      if player_score > 21:
                                          print "PLAYER IS BUSTED!"
                                          return
                          
                                  elif options.lower() == 's':
                                      print "players hand", player
                                      print player_score
                                      # COMPARE SCORES HERE TO DETERMINE THE WINNER
                          
                                  elif options.lower() == 'q':
                                      print "hope you enjoyed the game, bye!!"
                                      return
                          game()

                          Comment

                          • imran akhtar
                            New Member
                            • Nov 2008
                            • 64

                            #14
                            blackjack

                            hey. i dont think you seem to understand. i've done my own code and would rather stick to how it is, i appreciate u writing ur own version of the code but i would rather stick with mine, and jus fix the 'hit' function. you say i can fix it by creating a function to calculate the total, how would i do that?

                            thanks.

                            Comment

                            • bvdet
                              Recognized Expert Specialist
                              • Oct 2006
                              • 2851

                              #15
                              Hey back. You don't understand that I have modified your code, not written my own. The improvements I proposed to you eliminated the awkward way you were calculating the initial score, updated the score after each hit, removed cards from the deck each time a card was dealt and eliminated the variable nextCard, eliminated the string of if statements that executed each iteration, and showed you how to count aces as 1 or 11.

                              If all you want to fix in your previous code is updating the score:
                              Code:
                                      if options == 'h':
                                           player.append(deck[nextCard])
                                           ptotal = sum(player) # <---PLAYER SCORE UPDATED HERE
                                           nextCard += 1 
                                           print ptotal
                              Good luck and HTH.

                              Comment

                              Working...