hi i have made a blackjack code and need a some help on it. it seems to work overall but there are a few bits here and there that need sorting out, and im kinda stuck on it so was wondering if i could get some help? (Would be HUGELY appreciated)

the things I need help are on:

- stopping the program going back to the code (you will know what i mean when you play it)
- how to add the re-run code in it and where
- how I can count the ace as 1 and 11 (as in my code it only counts as 11)
- how I can add the different suites like diamonds, clubs, hearts and spades, because my program only displays the numbers not the suites with it
- how I can show the cards played after each round
- how I can shuffle the cards
- how I can track what cards have been dealt so that each card is only dealt once

my code is here is attached.

thanks guys

I would have sworn I saw starting code almost identical to this a few weeks ago.

Did you search for prior solutions?
Did any of them have the same problems?
Have you applied any of the advice in those threads?

Generally speaking, we would prefer you to post your code into your message rather than attaching it unless it is very large.

If you do post code, remember to use python code tags:
[code=Python] # your code here

[/code]

Inside your if c == 'H': you have logic to deal the computer cards. The computer should get no cards until the player selectets 's' to stand.

(PS- c will never be 'H', you forced all input to lower case)

Inside the elif c == 's': you need to have the code for the computer to take one or more cards until his hand is 17 or more.

It might be a good idea to break some of the code out to where you have a funtion to run a complete hand. It could:

  1. deal
  2. show cards
  3. prompt for user input
  4. perform user action
  5. if not 'stay' return to step 2
  6. perform computer action
  7. compare hands and determine winner

Then from the main loop, you just do:

  1. Prompt for instructions
  2. Display instructions if selected
  3. play a hand
  4. prompt for play again
  5. return to 3 if they want to play again
  6. print farewell message (i.e., "Thanks for playing")

It also might be beneficial to have a function to 'score' a hand. It could just add all of the card values up, then if the total was over 21 it could subtract 10 from your score (once per ace) until the total was under 21 or there were no more aces. That would address your 'ace' problem.

For making sure a card is not re-dealt, you could use random.shuffle() on a copy of a starter deck and then use pop() to remove a card from the deck. (If the card is removed, it is really hard to re-select it.)

Adding suits to the cards you have would be a bit of trouble. You would either need to make each card a tuple or list (value, suit). Then you have to work harder to score the hands. If you go to the trouble of adding suits, you probably want to distinguish between 10s, Jacks, Queens and Kings as well. Then you have to decide how many parts you want the cards in. You have the point value, the 'face' and the 'suit'. Is that two values or three? (Implementation is really up to you)

I would have sworn I saw starting code almost identical to this a few weeks ago.

Did you search for prior solutions?
Did any of them have the same problems?
Have you applied any of the advice in those threads?

Generally speaking, we would prefer you to post your code into your message rather than attaching it unless it is very large.

If you do post code, remember to use python code tags:
[code=Python] # your code here

[/code]

Inside your if c == 'H': you have logic to deal the computer cards. The computer should get no cards until the player selectets 's' to stand.

(PS- c will never be 'H', you forced all input to lower case)

Inside the elif c == 's': you need to have the code for the computer to take one or more cards until his hand is 17 or more.

It might be a good idea to break some of the code out to where you have a funtion to run a complete hand. It could:

  1. deal
  2. show cards
  3. prompt for user input
  4. perform user action
  5. if not 'stay' return to step 2
  6. perform computer action
  7. compare hands and determine winner

Then from the main loop, you just do:

  1. Prompt for instructions
  2. Display instructions if selected
  3. play a hand
  4. prompt for play again
  5. return to 3 if they want to play again
  6. print farewell message (i.e., "Thanks for playing")

It also might be beneficial to have a function to 'score' a hand. It could just add all of the card values up, then if the total was over 21 it could subtract 10 from your score (once per ace) until the total was under 21 or there were no more aces. That would address your 'ace' problem.

For making sure a card is not re-dealt, you could use random.shuffle() on a copy of a starter deck and then use pop() to remove a card from the deck. (If the card is removed, it is really hard to re-select it.)

Adding suits to the cards you have would be a bit of trouble. You would either need to make each card a tuple or list (value, suit). Then you have to work harder to score the hands. If you go to the trouble of adding suits, you probably want to distinguish between 10s, Jacks, Queens and Kings as well. Then you have to decide how many parts you want the cards in. You have the point value, the 'face' and the 'suit'. Is that two values or three? (Implementation is really up to you)

Hi.

Firslty I would like to thank you for spending your time to check out my code, appreciate it buddy :). Secondly, the error with the H/Hit there was, I have slightly fixed and changed and you will see the difference in the new updated code I will upload.

On another note, I have searched and looked at the previous thread, and I do not think I have found problems similar to mine. One of the main errors with my code is that it keeps going back to the code itself (back to the Python editor) when playing a game (did you come across that?). Like when I run the code and play a game, for example if I press the "Q" key to exit, then I will see the CMD shell window pop up for like half a second, and then it will take me back to my code (Python Editor). For me to be able to continute using my code I have to minimise the Python Editor and go back onto te Python Shell. Get what I mean now? Do you know how I can fix that? And would you know how I could fix any of the other issues/problems I posted in my first post? I am not that experienced in Python, I know more in VB, so yeah I do not know alot in Python. My friend helped me create this code as I struggled, and he has gone on a vacation so he cannot help me out, which sucks. I may sound like a "n00b" but I guess that's what I am in Python. Thanks once again. If you could help me out, I would be very grateful and would appreciate it alot. Btw I have uploaded a newer version of my code, it is slightly different in terms of there is no "Hit" anymore (do you know how I could add that though because when I did it went wrong :(). If you could check it out I would be very grateful. Thanks once again dude.

Thanks once again.

I believe your 'switch' back to the editor may be related to the clear() function you are using to clear the screen. It requires a task switch to function, and the task may not be switching back as you like.

What is this code supposed to be doing?

if c == 'q':
            gb= raw_input("Press Enter (q to quit): ").lower()
            if 'q' in exit:
             break

Specifically, what is if 'q' in exit supposed to be testing?

PS- my python didn't like your instructions, it was complaining about the 'word style' quotes with no encoding specified. I had to change them to get your code to run.

I believe your 'switch' back to the editor may be related to the clear() function you are using to clear the screen. It requires a task switch to function, and the task may not be switching back as you like.

What is this code supposed to be doing?

if c == 'q':
            gb= raw_input("Press Enter (q to quit): ").lower()
            if 'q' in exit:
             break

Specifically, what is if 'q' in exit supposed to be testing?

PS- my python didn't like your instructions, it was complaining about the 'word style' quotes with no encoding specified. I had to change them to get your code to run.

Oh ok, so if I get rid of that clear() code it should stop switching back yeah? But won't it mess anything up?

When you play the game, when you press "q", then it will come up saying if you want to quit the game press 'Enter'. So when you do press 'Enter' the game will end - with a message saying thank you for playing blackjack.

Thanks for spending your time trying to help me out, appreciate it buddy.

I guess I need to be more specific... if 'q' in exit: is NOT a valid syntax.

I get:

Traceback (most recent call last):
File "path_to_your_file.py", line 108, in <module>
if 'q' in exit:
TypeError: argument of type 'Quitter' is not iterable

(The line numbers between your copy and mine may not match as I had to change the instructions)

This may be a good time to learn to use a class as it works much better for this type of program. Here is some simple code to get you started. If it is easier to understand, you could also use a dictionary to hold the deck of cards, with the index being some abbreviation of the card, pointing to the value of that card.

import random

class BlackJack:
   def __init__(self):
      self.testing = True
      self.card_number = 0
      self.players_hand = []
      self.dealers_hand = []
      self.shuffle_deck()

      ## initial deal the hand
      for j in range( 0, 2):
         self.deal_one_card(self.players_hand)
         self.deal_one_card(self.dealers_hand)
      self.calculate_totals()

      ## ask player for another card
      ask = 1      ## simulate player asking for another card
      while ask:
         self.deal_one_card(self.players_hand)
         ask = 0       ## simulate player only asked for one card
      self.calculate_totals()

      if self.testing:
         print "initial players hand", self.players_hand
         print "initial dealers hand", self.dealers_hand


   def calculate_totals(self):
      players_total = self.calculate_totals_generic(self.players_hand)
      print "players hand totals", players_total
      dealers_total = self.calculate_totals_generic(self.dealers_hand)
      print "dealers hand totals", dealers_total


   def calculate_totals_generic(self, list_to_total):
      card_total = 0
      suit = 0
      for card in list_to_total:
         ##   numer = 0 = clubs
         ##           1 = diamonds
         ##           2 = hearts
         ##           3 = spades
         ##   denominator = face value
         numer, denom = divmod(card, 13)
         print "N/D =", card, numer, denom
         if 1 == denom: 
            print "\n-----> Ace Found\n"
         card_total += denom
      return card_total


   def deal_one_card(self, hand):
      hand.append(self.deck[self.card_number])
      self.card_number += 1


   def shuffle_deck(self):
      """ 1=Ace of clubs
          11=Jack of clubs
          12=Queen of clubs
          13=King of clubs

          14=Ace of diamonds
          26=King of diamonds

          27=Ace of hearts
          39=King of hearts

          40=Ace of spades
          52=King of spades
      """
      self.deck = [x for x in range(1, 53)]
      if self.testing:
         print "deck before shuffling", self.deck
      random.shuffle(self.deck)
      self.suit_list = [ "Club", "Diamond", "Heart", "Spade" ]
      if self.testing:
         print "\ndeck AFTER shuffling ", self.deck

if __name__ == "__main__":
   another_game = "Y"
   while another_game == "Y":
      BJ = BlackJack()
      another_game = raw_input("Another game? (Y or N) ").upper()

I guess I need to be more specific... if 'q' in exit: is NOT a valid syntax.

I get:

Traceback (most recent call last):
File "path_to_your_file.py", line 108, in <module>
if 'q' in exit:
TypeError: argument of type 'Quitter' is not iterable

(The line numbers between your copy and mine may not match as I had to change the instructions)

Are you saying you recieve a syntax error with that? Because I don't.

It is a run-time syntax error, aren't you running your program to see how it works?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.