Thread: File output with loops Blackjack game

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    4

    File output with loops Blackjack game

    Hey guys, I'm working on this blackjack game and I've spent hours trying different ways to print all the hands to a file. Nothing seems to be working for me. I'm pressed for time and would appreciate any input. Thanks.

    Here is the code

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    #include <time.h> //used for  srand((unsigned) time(NULL)) function
    #include <conio.h> //used for getch() function, to pause
    
    
    typedef struct card {
        int value;  /* A=1, j=11, q=12, k=13 */
        char suit;  /* Spades='S' Clubs='C' Hearts='H' Dia='D' */
    } card_t;
    
    
    typedef struct deck {
        card_t cards[208];
        int top;    // must be initialized to 0
    } deck_t;
    
    
    typedef struct hand {
        card_t cards[10]; 
        int num_cards;   /// must be initialized to 0
    } hand_t;
    
    
    //Score keeper
    typedef struct keeper {
        int win;
        int loss;
    } keeper_t;
    
    
    //Bank 
    typedef struct bank {
        int cash;
        int bet;
    } bank_t;
    
    
    //Print user's hand function
    void print_hand (hand_t x, int play) {
        int i;
        
            printf("Player %d hand:\n", play);
        for (i=0; i < x.num_cards; i++) {
            printf ("[%c%d]", x.cards[i].suit, x.cards[i].value);
        }
        printf ("\n");
    }
    //Print Dealer's Hand Function
    void print_dealer (hand_t x) {
        int i;
        printf("Dealers hand:\n");
        for (i=0; i < 1; i++) {
            
            printf ("[%c%d] [??]", x.cards[i].suit, x.cards[i].value);
        }
        printf ("\n");
    }
    
    
    
    
    //Function checks value of hand
    int handval (hand_t x, int p, int play) {
        int i,j;
        p=0;
        //printf("You have:%d cards\n", x.num_cards);//Temp code to check cards DELETE
        for (i=0; i < x.num_cards; i++){
            if (x.cards[i].value>10){ //makes all face cards = 10
                x.cards[i].value=10;}
            p =( x.cards[i].value )+p;}
        //printf ("Player %d, You have a total of %d\n", play, p);
        return p;
        
        
        }
    //Function checks value of dealer hand
    int handvald (hand_t x, int p, int c) {
        int i;
        p=0;
        //printf("You have:%d cards\n", x.num_cards);//Temp code to check cards DELETE
        if (c==0){
        for (i=0; i < x.num_cards-1; i++){
                if (x.cards[i].value>10){ //makes all face cards = 10
                    x.cards[i].value=10;}
            p =( x.cards[0].value );}
        //printf ("Dealer subtotal is %d\n", p);
        }
        else if (c!=0){
            for (i=0; i < x.num_cards; i++){
                if (x.cards[i].value>10){ //makes all face cards = 10
                    x.cards[i].value=10;}
            p =( x.cards[i].value )+p;}
            //printf ("Dealer total is %d\n", p); 
        }
        return p;
        
        
        }
    
    
    void fileresults();
    
    
    
    
    int main () {
    
    
    
    
        deck_t myDeck;
        myDeck.top = 0;
    
    
        //initialize variables
        int num_players;
        int play;
        char choice;
        char cur_suit;
        int i, j, k, p, s;
        int cash=500;
        int turn;
        int bust;
        p = 0;
        k = 0;
        
    
    
        for (i=0; i<4; i++) { // suit types
            if (i == 0) cur_suit = 'S';
            else if (i == 1) cur_suit = 'C';
            else if (i == 2) cur_suit = 'H';
            else if (i == 3) cur_suit = 'D';
    
    
            for (j=1; j    <= 13; j++) {            //Create 4 decks
                myDeck.cards[k].suit = cur_suit;
                myDeck.cards[k].value = j;
                k++;
            }
                for (j=1; j    <= 13; j++) {
                myDeck.cards[k].suit = cur_suit;
                myDeck.cards[k].value = j;
                k++;
            }
                    for (j=1; j    <= 13; j++) {
                myDeck.cards[k].suit = cur_suit;
                myDeck.cards[k].value = j;
                k++;
            }
                        for (j=1; j    <= 13; j++) {
                myDeck.cards[k].suit = cur_suit;
                myDeck.cards[k].value = j;
                k++;
            }
        }
        // Displays All four decks
        /*for (i=0; i<208; i++) {
            printf ("[%c%d]\n", myDeck.cards[i].suit, 
                    myDeck.cards[i].value);
        }*/
        while (1) {
            int user;
            printf("--------------------------------------------\n");
            printf("Welcome to Blackjack!\n");
            printf("1.Play the game!\n");
            printf("2.Rules\n");
            printf("3.Quit\n");
            printf("--------------------------------------------\n");
            printf("Please make a selection:");
            scanf (" %d", &user);
        
            switch(user) {
        
            case 1 :
            
            
            printf("Please enter the number of players:");//Ask for num players
            scanf(" %d", &num_players);
            //Initialize score keeper and bank for up to 3 players and a dealer
                    bank_t banky[3]; 
                    keeper_t playe[3], deale;
                    for (i=1; i <= num_players; i++){
                        playe[i].loss=0;
                        playe[i].win=0;
                        banky[i].cash=500;
                    }
                card_t temp;
                srand((unsigned) time(NULL));//Creates random seed for rand function
                for (i=0; i<1000; i++) {  //shuffle
                     
                    j = rand() % 208;
                    k = rand() % 208;
    
    
                    temp = myDeck.cards[j];
                    myDeck.cards[j] = myDeck.cards[k];
                    myDeck.cards[k] = temp;
                }
        //Displays decks after shuffle is done
        /*printf ("-------------------------\n");
        for (i=0; i<208; i++) {
            printf ("[%c%d]\n", myDeck.cards[i].suit, 
                    myDeck.cards[i].value);
        }
        */
    
    
        //////////// Create up to 4 hands and deal 2 cards to each player, show all player cards, but only one dealer card
                
                while (myDeck.top<208){
                hand_t player[3], dealer;
                dealer.num_cards = 0;
                
                for (j=0; j <2; j++){dealer.cards[ dealer.num_cards ] = myDeck.cards[ myDeck.top ];
                    dealer.num_cards++;
                    myDeck.top++;
                }
                bust=0;
                turn=0;
                for (i=1; i <= num_players; i++){ //Creates a hand with two cards for each player
                    player[i].num_cards = 0;
                    p = 0;
                    turn++;
                    play=i;
                
                    printf("Player %d\nYou have %d\n",play, banky[i].cash);
                    printf("Player %d \n", play);
                    printf("Okay, now how much of it do you want to lose, I mean, bet? \n");
                    scanf("%d", &banky[i].bet);
                
                    
                
                
                for (j=0; j < 2; j++) {
                    
                    player[i].cards[ player[i].num_cards ] = myDeck.cards[ myDeck.top ];
                    player[i].num_cards++;
                    
                    myDeck.top++;
                    }
                printf ("---------------\n");
                print_dealer (dealer);
                p=handvald(dealer,p, 0);
                printf ("Dealer subtotal is %d\n", p);
                
                if (handvald(dealer,p, 1) < 17){
                    dealer.cards[ dealer.num_cards ] = myDeck.cards[ myDeck.top ];
                    dealer.num_cards++;
                    myDeck.top++;
                }
                printf ("---------------\n");
                print_hand (player[i], play=i);
                printf ("---------------\n");
                
                
    
    
                //handval(player[i],p,play);
                p=handval(player[i],p,play);
                printf ("Player %d, You have a total of %d\n", play, p);
                
                
                    printf ("Player %d, would you like to stay or hit?(s/h):\n", play);
                    while (1){
                    scanf("%c", &choice);
                    
        
                if (p<21 && choice =='h'||choice =='H') {
                    player[i].cards [ player[i].num_cards ] = myDeck.cards[ myDeck.top ];
                    player[i].num_cards++;
                    myDeck.top++;
                    printf ("---------------\n");
                    print_hand (player[i], play=i);                
                    p=handval(player[i],p,play); //Without this, will not stop when cards>21.
                    printf ("Player %d, You have a total of %d\n", play, p);
                    printf ("Player %d, would you like to stay or hit?(s/h):\n", play);
                    //printf("cards used %d\n", myDeck.top);//Just being used to test how many cards used DELETE
                }
                /*else if(p==21 && handvald(dealer,p, 1)!=21){
                    printf("You got 21! You won!!\n");
                    playe[i].win++;
                    printf("You have won %d times and lost %d times\n",playe[i].win, playe[i].loss);
                    printf ("---------------\n");
                    banky[i].cash = banky[i].cash + banky[i].bet;
                    printf("Aren't you a happy little boy. You now have: $%d\n", banky[i].cash);
                    printf("Press any key to continue...\n");
                    _getch();
                    
                    break;
                }
                else if(p>21){
                    printf("Sorry you went over 21! You lose!\n"); 
                    playe[i].loss++;
                    printf("You have won %d times and lost %d times\n",playe[i].win, playe[i].loss);
                    banky[i].cash = banky[i].cash - banky[i].bet;
                    printf("Sad face %c. You now have: $%d\n", 2, banky[i].cash);
                    printf ("---------------\n");
                    bust++;
                    break;
                
                }*/
                else if( (p==21) || (p>21) || (p<21 && choice == 's' || choice== 'S')){
                    if (turn==num_players){//Needs work
                        for (i=1; i<=num_players; i++){
                            play=i;
                            printf("-------------------Player %d-------------------\n", play);
                            p=handval(player[i],p,play);
                            printf ("Player %d, You have a total of %d\n", play, p);
                            p=handvald(dealer,p, 1);
                            printf ("Dealer total is %d\n", p);//Print Dealer total
                            
                            //Player>Dealer
                            if(handval(player[i],p,play)<21 && handval(player[i],p,play)>handvald(dealer,p, 1)){ 
                                //p=handval(player[i],p,play);
                                //printf ("Player %d, You have a total of %d\n", play, p);
                                //p=handvald(dealer,p, 1);
                                //printf ("Dealer total is %d\n", p);//Print Dealer total
                                printf("Player %d won!!\n", play);
                                playe[i].win++;
                                banky[i].cash = banky[i].cash + banky[i].bet;
                                printf ("---------------\n");
                                printf("Aren't you a happy little boy. You now have: $%d\n", banky[i].cash);
                            }
                            
                            //Player=21 and dealer not 21
                            else if(handval(player[i],p,play)==21 && handvald(dealer,p, 1)!=21){                
                                printf("You got 21! You won!!\n");
                                playe[i].win++;
                                //printf("You have won %d times and lost %d times\n",playe[i].win, playe[i].loss);
                                banky[i].cash = banky[i].cash + banky[i].bet;
                                printf ("---------------\n");
                                printf("Aren't you a happy little boy. You now have: $%d\n", banky[i].cash);
                            }
                            
                            //Player>21 BUST
                            else if(handval(player[i],p,play)>21){                                                
                                printf("Sorry you went over 21! You lose!\n"); 
                                playe[i].loss++;
                                banky[i].cash = banky[i].cash - banky[i].bet;
                                printf ("---------------\n");
                                printf("Sad face %c. You now have: $%d\n", 1, banky[i].cash);
                                }        
                            
                            //Dealer>Player
                            else if(handval(player[i],p,play)<handvald(dealer,p, 1) && handvald(dealer,p, 1)<22 || handval(player[i],p,play)==handvald(dealer,p, 1)){
                                printf("The dealer won, sorry.\n", play);
                                playe[i].loss++;
                                //printf("You have won %d times and lost %d times\n",playe[i].win, playe[i].loss);
                                banky[i].cash = banky[i].cash - banky[i].bet;
                                printf ("---------------\n");
                                printf("Sad face %c. You now have: $%d\n", 1, banky[i].cash);
                            }
                            
                            //Dealer==Player-Dealer wins
                            else if(handval(player[i],p,play)==handvald(dealer,p, 1)){
                                printf("Player %d,You tied the dealer. The dealer won, sorry.\n", play);
                                playe[i].loss++;
                                banky[i].cash = banky[i].cash - banky[i].bet;
                                printf ("---------------\n");
                                printf("Sad face %c. You now have: $%d\n", 1, banky[i].cash);
                            }
                            else if(handvald(dealer,p, 1)>21 && handval(player[i],p,play)!=21 && handval(player[i],p,play)<21){
                                printf("The Dealer Busted, you win!\n");
                                playe[i].win++;
                                banky[i].cash = banky[i].cash + banky[i].bet;
                                printf ("---------------\n");
                                printf("Aren't you a happy little boy. You now have: $%d\n", banky[i].cash);
                            }
                            printf("You have won %d times and lost %d times\n",playe[i].win, playe[i].loss);
                            printf("-----------------------------------------------\n");
                        }}
                    //printf("Turns: %d\n", turn);    //Temp to check that turn is working DELETE
                    printf("Press any key to continue:\n");
                    _getch();            //Requires key be pressed before displaying more
                    printf("-----------------------------------------------\n");
                    break;}
                    
                }}
                if (myDeck.top==208){
                    break;
                    }
                }
                
                break;//Break from case 1
                
        
    case 2://Case 2 Rules of game
            printf("------\n");
            printf("--------------\n");
            printf("----------------------------------------------------------------------------------------------------\n");
            printf("Rules of Play\n");
            printf("                                      \n");
            printf("                                      \n");
            printf("1. You do not talk about Blackjack.\n");
            printf("2. You DO NOT talk about Blackjack.\n");
            printf("3. If someone says 'stop' or goes limp, taps out the fight is over.\n");
            printf("                                      \n");
            printf("                                      \n");
            printf("4. The game starts with 4 decks\n");
            printf("5. Each player begins the game with $500\n");
            printf("6. The dealer has to hit until he has a score of 17 or higher\n");
            printf("7. The Black Jack hand (Ace of Spades with a Black 10 or Face Card)\ndoubles the reward.\n");
            printf("8. When the score between a user and the dealer is tied the dealer wins.\n");
            printf("9. You can bet more than you have, but if you lose, you need to get lube and be creative to come up with the cash. The dealer doesn't like being indebted to.\n");
            printf("----------------------------------------------------------------------------------------------------\n");
            printf("--------------\n");
            printf("------\n");
            printf("Press any key to continue:");
            _getch();    
            system("cls");
            break;
        
        case 3: 
            printf("Good bye!\n");
            exit(1);
        
        default:
            printf("That is not a valid choice, please enter a number from 1-3\n");
            break;
    
    
        }
    }
    }

  2. #2
    Registered User
    Join Date
    Apr 2012
    Posts
    4
    My attempt:

    Code:
    void fileresults() //this goes before the main
    This goes at the way bottom:

    Code:
    void fileresults() { FILE *fp; //File pointer fp = fopen("GameResults.txt", "w"); //create/write to file if(fp == NULL) // If the file is missing { printf("\nError: File Missing\n"); system("pause"); exit(1); } else { fprintf(fpresults,"\n\t GameResults.txt"); fprintf(fpresults,"\n\t---------\n"); fprintf(fpresults,"\nYou Have Won %d Times\n", playe[i].won); //<---this gives me problems fprintf(fpresults,"\nYou Have Lost %d Times\n", playa[i].loss ); //<----this gives me problems fprintf(fpresults,"\nYou Rock!"); } fclose(fp); return; }

    When I try to compile, it chokes on playe[i].won and playe[i].loss

  3. #3
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    fileresults cannot magically access the playe array from main. You have to pass it to the function. Change the prototype to

    void fileresults(keeper_t *playe);

    And call it like

    fileresults(playe);


    You should really break your main up into functions, but perhaps that's for another day.

    I'm also assuming that your primary language is not English, hence the strange names. If not, then what's with the strange names? (E.g., why is there no r at the end of playe?)
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  4. #4
    Registered User
    Join Date
    Apr 2012
    Posts
    4
    Quote Originally Posted by oogabooga View Post
    fileresults cannot magically access the playe array from main. You have to pass it to the function. Change the prototype to

    void fileresults(keeper_t *playe);

    And call it like

    fileresults(playe);


    You should really break your main up into functions, but perhaps that's for another day.

    I'm also assuming that your primary language is not English, hence the strange names. If not, then what's with the strange names? (E.g., why is there no r at the end of playe?)
    No, English is my primary language and I'm proficient in it, it's just that I'm not skilled with programming yet lol.


    So, after fp=fopen...

    Code:
    fileresults(playe);
    fprintf(fp,"%d\n", playe[i].win);
    What if I wanted to add the card value and their suit? Also, I'm wondering is there any easier way to do this?

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    No, English is my primary language and I'm proficient in it, it's just that I'm not skilled with programming yet
    Clearly you're not that proficient since you didn't answer my question. What's up with the stupid names?

    So, after fp=fopen...
    I can't tell if the code you posted is correct or not. There's not enough context.

    What if I wanted to add the card value and their suit?
    What about it?

    I'm wondering is there any easier way to do this?
    Is there an easier way to do what?

    Don't assume people can read your mind. Use your proficiency in English and ask your questions more clearly.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  6. #6
    Registered User
    Join Date
    Apr 2012
    Posts
    4
    I figured it out, but wow, I guarantee you're not this big of a sarcastic prick in real life. The stupid names are there because this is my first semi major assignment and they just worked. Honestly, that's it. Instead of focusing on that you could have given some constructive criticism to what I could have changed them to. I literally only have a month programming, so I think I'm doing a decent job of grasping the material sans the stupid names. When I get to be a pro like you and start coding for Microsoft, I'll drop the stupid names. It's amazing how people tend to be ..............s over the internet when real life are far from it and are borderline cowards. I'm not one to try and give out personal attacks, and maybe I'm being overly-sensitive at the moment, so I'm acting out of nature.

    Yes, since this assignment is due in just a few hours I stressed about it and maybe, just maybe, I wasn't being clear when I rushed my response; however, I'd like to give you an apology from the deepest part of my heart. Will you forgive my, in your eyes, incompetence, pretty please? With a cherry on top?

    Good day and I honestly do appreciate the constructive responses you gave me.

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Just a heads up, when you state that something doesn't compile i.e. "When I try to compile, it chokes on playe[i].won and playe[i].loss", you should always include a copy of the exact and entire error message here.

    We realise that compiler error messages at this early stage of your learning mean as much to you as "ERROR ON LINE X", but to us they are actually completely understandable descriptions of the mistake, which allow us to see exactly what the problem is.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with a Blackjack game.
    By wipeout4wh in forum C++ Programming
    Replies: 37
    Last Post: 06-10-2011, 06:23 PM
  2. My BlackJack game
    By JoshR in forum Game Programming
    Replies: 3
    Last Post: 05-31-2005, 01:09 AM
  3. BlackJack Game
    By Squintz in forum C Programming
    Replies: 3
    Last Post: 11-12-2002, 03:31 PM
  4. Blackjack (21) Game
    By Rabidpunk in forum Game Programming
    Replies: 12
    Last Post: 01-11-2002, 03:19 AM
  5. Blackjack (21) Game Pt. 2
    By Unregistered in forum Game Programming
    Replies: 0
    Last Post: 12-19-2001, 02:53 PM