443,907 Members | 2,031 Online
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

blackjack

 P: 64 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. Expand|Select|Wrap|Line Numbers 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.py", line 31, in ? computer.append(random.randint(deck)) TypeError: randint() takes exactly 3 arguments (2 given) Jan 15 '09 #1
21 Replies

 Expert 100+ P: 469 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: Expand|Select|Wrap|Line Numbers computer.append(random.choice(deck)) Another possibility is to actually shuffle the deck with random.shuffle before dealing cards: Expand|Select|Wrap|Line Numbers random.shuffle(deck) computer.append(deck[0]) player.append(deck[1]) computer.append(deck[2]) Hope this helps. Jan 16 '09 #2

 P: 64 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 Expand|Select|Wrap|Line Numbers 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 Jan 16 '09 #3

 P: 64 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? Expand|Select|Wrap|Line Numbers 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. Jan 16 '09 #4

 Expert 100+ P: 469 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, Expand|Select|Wrap|Line Numbers 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: Expand|Select|Wrap|Line Numbers 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. Jan 16 '09 #5

 P: 64 i have tried the second option, but does not seem to work. Expand|Select|Wrap|Line Numbers 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() Jan 16 '09 #6

 Expert Mod 2.5K+ P: 2,851 You can deal cards from a deck with one statement using random.choice() and list method pop(). Example: Expand|Select|Wrap|Line Numbers >>> 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: Expand|Select|Wrap|Line Numbers 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: Expand|Select|Wrap|Line Numbers >>> 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 Jan 16 '09 #7

 P: 64 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. Jan 16 '09 #8

 Expert Mod 2.5K+ P: 2,851 What error message did you receive? When I run your code, I get this error: UnboundLocalError: local variable 'nextCard' referenced before assignment This should solve that problem: Expand|Select|Wrap|Line Numbers 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. Expand|Select|Wrap|Line Numbers         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 Jan 16 '09 #9

 P: 64 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: Expand|Select|Wrap|Line Numbers 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: Expand|Select|Wrap|Line Numbers 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:  Jan 17 '09 #10

 Expert Mod 2.5K+ P: 2,851 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. Jan 17 '09 #11

 P: 64 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. Jan 17 '09 #12

 Expert Mod 2.5K+ P: 2,851 @imran akhtar 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. Expand|Select|Wrap|Line Numbers 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() Jan 17 '09 #13

 P: 64 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. Jan 17 '09 #14

 Expert Mod 2.5K+ P: 2,851 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: Expand|Select|Wrap|Line Numbers         if options == 'h':              player.append(deck[nextCard])              ptotal = sum(player) # <---PLAYER SCORE UPDATED HERE              nextCard += 1               print ptotal Good luck and HTH. Jan 17 '09 #15

 P: 64 thnaks for ur help with updating the score, it now works, but i have two main problem, firstly how would i now get the ace to be 1 and 11, and a way of displaying the total hands played at the end of the game. thanks for the help below is my code, Expand|Select|Wrap|Line Numbers 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  ptotal = sum(player) ctotal = sum(computer) 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])               ptotal = sum(player)                nextCard += 1                print "players hand", player, "\tplayers total value", ptotal           elif options == 's':             ptotal = sum(player)             print "players hand", player, "\tplayers total value", ptotal             break         elif options == 'q':             playAgain = raw_input ("do u wana play again, [y] / [n]")             if playAgain == "y":                 game()             elif playAgain == "n":                 print "see ya later, bye!"                 return                 break        while (True):         if ctotal < 16:             computer.append(deck[nextCard])             nextCard += 1         if ptotal > 21:             print "computer hand", computer, "\tcomputers total value", ctotal             print "player busted. computer wins"             break         if ctotal > 21:             print "computer hand", computer, "\tcomputers total value", ctotal             print "computer busted. player wins"             break         if ctotal == ptotal:             print "computer hand", computer, "\tcomputers total value", ctotal             print "draw. computer wins"             break         if ptotal == 21:             print "computer hand", computer, "\tcomputers total value", ctotal             print "player gets a BlackJack. player wins"             break         if ctotal == 21:             print "computer hand", computer, "\tcomputers total value", ctotal             print "computer gets a BlackJack. computer wins"             break         if ptotal > ctotal:             if ptotal < 21:                 print "computer hand", computer, "\tcomputers total value", ctotal                 print "player wins"                 break         if ctotal > ptotal:             if ctotal < 21:                 print "computer hand", computer, "\tcomputers total value", ctotal                 print "computer wins"                 break   game()         Jan 17 '09 #16

 Expert Mod 2.5K+ P: 2,851 I showed you how to count an ace as 1 or 11 already by defining a deck of cards with an "A" instead of a 1 and 11, and defining a function to determine the score of a hand. Here is another way, using a 1 instead of an "A". Expand|Select|Wrap|Line Numbers >>> def sum_score(hand): ...     score = sum(hand) ...     for card in hand: ...         if card == 1 and score < 12: ...             score += 10 ...     return score ...  >>> deck = [1,2,3,4,5,6,7,8,9,10,10,10,10]*4 >>> import random >>> random.shuffle(deck) >>> hand1 = [deck.pop() for i in range(3)] # a hand with 3 cards >>> hand2 = [deck.pop() for i in range(3)] # another hand with 3 cards >>> hand1 [5, 10, 10] >>> sum_score(hand1) 25 >>> hand2 [1, 4, 5] >>> sum_score(hand2) 20 >>>  hand2 contains a 1 which represents an ace. Function sum_score() adds 10 to the score because the initial sum is less than 12. -BV Jan 17 '09 #17

 P: 64 yeh thanks, after few changes it is now wroking, is there a way of how i would display total hands played, at the end of game, for both computer and player Jan 17 '09 #18

 Expert Mod 2.5K+ P: 2,851 Your code is designed for one hand. You will need a way to deal additional hands, therefore another option is required. Create an empty list at the beginning of the script, and append each hand's results to it. -BV Jan 17 '09 #19

 P: 64 ok, a bit confused, dont understand how i would start it, thanks Jan 17 '09 #20

 P: 64 so is it possiable of you can explain bit more, how i would display the hands. thanks Jan 18 '09 #21

 Expert Mod 2.5K+ P: 2,851 Create an empty list names results, and append the result of each hand to the list after the winner of the hand is determined. When the user decides to quit playing, ite3rate on the list to display the all results. Expand|Select|Wrap|Line Numbers results = [] results.append(['player',[1,5,5],[6,9,4]]) results.append(['computer',[6,5,6],[9,10]]) for result in results:     print "Winner: %s" % result[0]     print "    Player hand: %s" % (', '.join([str(i) for i in result[1]]))     print "    Computer hand: %s" % (', '.join([str(i) for i in result[2]])) Jan 18 '09 #22