Thread: Blackjack Program

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    30

    Blackjack Program

    I decided to do this out of curiosity and boredom...
    Can anyone check it out and report if there are any bugs and/or problems? Just please don't tell me where I wen't wrong with my code, just explain the bug so I can find and fix it myself to improve my C knowledge. Thanks!

    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <time.h>
    
    
    int main(){
        char combination [5][14]={0};
        char color,card,hit='y',temp;
        int hand=0,dealer,card_v,soft=0;
    
    
    printf ("Blackjack\n\n\n");
    printf ("Dealer stands at all (hard or soft) 17's!\n\n\n");
    
    
    srand (time(0));
    
    
    while (hit=='y'){
    
    
        do{
            color = 3+rand()%(6-3+1);
            card = 1+rand()%(13-1+1);
        }
        while (combination[color-3][card]==1);
        combination [color-3][card] = 1;
    
    
        switch (card){
            case 1: 
                card = 'A'; card_v=11; soft=1; 
                break;
            case 2: 
                card = '2'; card_v=2; 
                break;
            case 3: 
                card = '3'; card_v=3; 
                break;
            case 4: 
                card = '4'; card_v=4; 
                break;
            case 5: 
                card = '5'; card_v=5; 
                break;
            case 6: 
                card = '6'; card_v=6; 
                break;
            case 7: 
                card = '7'; card_v=7; 
                break;
            case 8: 
                card = '8'; card_v=8;
                break;
            case 9: 
                card = '9'; card_v=9; 
                break;
            case 10: 
                card = 'X'; card_v=10; 
                break;
            case 11: 
                card = 'J'; card_v=10; 
                break;
            case 12: 
                card = 'Q'; card_v=10;
                break;
            case 13: 
                card = 'K'; card_v=10;
                break;
        }
    
    
        printf ("%c%c\n",color,card);
    
    
        hand=hand+card_v;
    
    
        if (hand>21 && soft && card_v==11)
            hand -= 10;
    
    
        printf ("Hand = %d\n", hand);
    
    
        if (hand>21) {
            printf ("You lost!");return 0;
            }
        if (hand == 21) {
            printf ("Blackjack!");return 0;
            }
        printf ("Hit?(y/n)"); scanf (" %c", &hit);
    }
    
    
    dealer = 17+rand()%(26-17+1);
    
    
    if (dealer>hand && dealer<=21)
        printf ("Dealer has %d!You lost!",dealer);
    else
        printf ("Dealer has %d! Congratulations!",dealer);
    
    
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You should work on your testing abilities, so you can check for bugs/problems yourself . That being said, your first line of defense against bugs is to compile with the warnings turned all the way up. Fix all errors and warnings before running your code.

    Actually, your first line of defense is probably a good design and programming process. Make sure you understand the problem well, then devise a good solution on paper. Break that solution down into it's parts, and put each part in it's own module/function to isolate the problems. Writing small amounts of code and testing as you go is very helpful here too.

    Normally we don't want to go around pretending to be a compiler or a QA department, debugging code for somebody, we prefer them to indicate their problem and what they've tried, and we'll help them the rest of the way. That being said, you have a few problems and things you could do to clean it up a bit:
    1. Your array is bigger than it needs to be, there are 4 suits and 13 card values. Just use zero-based arrays. It works better with rand() and % anyhow.
    2. You initialize combination incorrectly. It's a 2-d array, so you need a double set of curly braces.
    3. You "shuffle" the cards in a very inefficient manner. Look into the Fisher-Yates algorithm.
    4. You should actually track which cards the player and dealer have.
    5. The dealer isn't actually dealt a card from the deck, he's just given a random number between 17 and 24, so the value of his hand is suspect, i.e. it's perfectly possible for the dealer to have a 16, hit, get a 10 and end up with 26 for starters. Just "deal" him like you did the player.
    6. There are 2 colors, red and black, but 4 suits, clubs, spades, diamonds and hearts. You should rename "color" to "suit".
    7. You set color = 3 + rand..., which results in values from 3 to 6, but then subtract 3 when you use it, which is pretty pointless. The only time you don't subtract 3 is when you print.
    8. You can't actually print the color, since the numbers 3, 4, 5 and 6 don't produce printable ASCII characters (i.e., they're not the same as '3', '4', '5' and '6'), so you'll likely bork your terminal. You should print 'C', 'S', 'H' or 'D' for the suits instead.
    That's all I have for now, should keep you busy for a bit.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    30
    WOW that's more than I expected :O Thank you so much for such a detailed explanation.

    1. I defined it bigger because somewhere in the code I went wrong and only king of clubs and king of spades displayed incorrectly, instead of their suit there was a smiley face...
    2. Thanks, didn't know that! charcombination [5][14]={{0}};
    3. Thanks again!
    4. I am aware of that, this is just a beginners code (obviously) so don't take it too seriously...
    5. Look at point 4!
    6. English isn't my native language, sorry about that.
    7. If i get suit randomized as 6 it couldn't be stored into the array, so i substracted it by 3.
    8. Not sure what you mean by that?

    EDIT: Just looked at the fisher-yates algorithm. I find it difficult to understand after only few weeks of working with C.[FONT=Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace][/FONT]
    Last edited by turke92; 11-21-2011 at 05:10 PM.

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    1. This is probably due to a math error somewhere in your code. I think the smiley faces are for values 1 and 2, so you probably subtracted one too many.
    2 & 3. You're welcome.
    4 & 5. Not taking it too seriously, but thought it worth mentioning since I didn't know your general programming/problem solving skill level. If nothing else, it's a feature to add to this program as your skills develop.
    6. No problem. Your English is excellent, much better than any of my auxiliary languages.
    7 & 8. I forgot, many implementations print the symbol for clubs, spades, hearts and diamonds for 3-6. Note that this is not portable, for example it didn't display correctly on my work computer today. If it works for your purposes, keep doing it, just keep in mind for later, that it wont work everywhere.

    The concept of the Fisher-Yates algorithm is quite simple. You take a deck of cards, pick one at random, and place it in a pile. From the remaining 51 cards, you pick another at random, and place it on top of the pile. Do likewise from the remaining 50 cards. Keep doing this until you are all out of cards, having placed them in the pile in the order you drew them from the original deck. If it seems beyond your programming abilities for now, come back when you're ready.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    30
    Now I get what you mean by ASCII symbols, I'll keep that in mind for future programs.
    Maybe the Fisher-Yates algorithm indeed is simple, but for my 3-4 weeks of C learning it's still a bit hard, but after I learn more about pointers, I will get to it since all the snippets I found on google did this with array pointers.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by turke92 View Post
    Now I get what you mean by ASCII symbols, I'll keep that in mind for future programs.
    Maybe the Fisher-Yates algorithm indeed is simple, but for my 3-4 weeks of C learning it's still a bit hard, but after I learn more about pointers, I will get to it since all the snippets I found on google did this with array pointers.
    FWIW... here's a simple way to intialize and deal a deck of cards without duplicates...

    Code:
    // deck of cards demonstration
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    #define CARDS 52
    
    const char *face[] = {"Ace","Two","Three","Four","Five","Six","Seven",
                          "Eight","Nine","Ten","Jack","Queen","King" };
    
    const char *suit[] = {"Spades","Hearts","Clubs","Diamonds"};
    
    
    // function to shuffle the deck
    int Shuffle(int *deck)
      { 
        int i, temp, card; 
    
        printf("\nShuffling...\n\n");
        for (i = CARDS - 1; i > 0; i--)
          { 
            card = rand() % i;
            temp = deck[i];
            deck[i] = deck[card];
            deck[card] = temp;
    
          }
        return 0;
      }
          
    
    // program entry point
    int main (void)
      { 
        int deck[CARDS];        // deck
        int card = CARDS + 1;   // card
        int fac, sut;           // face and suit
        int i;                  // counter
        char ch = 0;            // keyboard
        
        srand(time(NULL));
    
        printf("Card dealer simulation... \n\n");
    
        //initialize the deck
        for (i = 0; i < CARDS; i++)
          deck[i] = i;
    
        // deal cards  
        do
          {
            if ( card >= CARDS )  
              card = Shuffle(deck);
    
            // face and suit
            fac = deck[card] % 13;
            sut = deck[card] / 13;
    
            // display the card
            printf("%2d > %s of %s\t\t",deck[card],face[fac],suit[sut]);
            
            // set up for next card
            card++;
    
            // wait for user input
            printf("(Enter to deal, Q to quit)\n");
            ch = getchar();
          }
        while( toupper(ch) != 'Q');
        return 0;
      }

  7. #7
    Registered User
    Join Date
    Oct 2011
    Posts
    30
    Thanks man, I see pointers again but would you mind explaining why face and suit have to be declared as pointers rather than normal variables? Thanks in advance!

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by turke92 View Post
    Thanks man, I see pointers again but would you mind explaining why face and suit have to be declared as pointers rather than normal variables? Thanks in advance!
    Because they are pointers to strings. I could have declared them as arrays but they would have worked from copies of the strings so that the actual text was in memory twice... once as the initializers in the program image and again as data on the program's heap... this way I can work directly from the original copies in the image.

  9. #9
    Registered User
    Join Date
    Oct 2011
    Posts
    30
    Thanks, just had this on college today, I finally understand the purpose of pointers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C program Blackjack
    By mjf_03 in forum Game Programming
    Replies: 7
    Last Post: 04-25-2011, 02:25 PM
  2. Need Help With a BlackJack Program in C
    By Jp2009 in forum C Programming
    Replies: 15
    Last Post: 03-30-2009, 10:06 AM
  3. blackjack program
    By mackieinva in forum C Programming
    Replies: 8
    Last Post: 09-20-2007, 03:46 AM
  4. Help with Blackjack program
    By sugie in forum C++ Programming
    Replies: 1
    Last Post: 04-30-2005, 12:30 AM
  5. BlackJack Program...
    By 67stangman in forum C++ Programming
    Replies: 3
    Last Post: 05-06-2002, 10:44 PM