2
\$\begingroup\$

Below is the Blackjack program code. How do I make the code look nicer?

I feel like the code is super messy and I was wondering how I could make it look better or if there are better ways to write some parts of the code.

(I have been running the code on replit.com and in visual studio code.)

#include <iostream>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;
void deal(int,int&,int& ,int[][2],int&,int[][2] );
void deal(int,int&,int&,int&,int[][2],int&,int[][2] );
int getbet(int);
void filldeck(int[][2],int);
void shuffle(int[][2],int);
void printhand(int,int[][2]);
int main()
{
string card[13]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
int totdealer,totplayer,upto=0;
int money,bet,aces,decks=2,j;
int deck[52*decks][2];
int dealhand[20][2],playhand[20][2],playcards,dealcards;
char yesno='Y';
bool again;
srand(time(0));
filldeck(deck,decks);
 
shuffle(deck,decks);
   
cout<<"How much money betting do you have? ";
cin>>money;
while(money>0&&toupper(yesno)=='Y')
{bet=getbet(money);
totdealer=0;
playcards=0;
dealcards=0;
cout<<"\nDealer cards\n";
deal(2,totdealer,upto,deck,dealcards,dealhand);
printhand(dealcards,dealhand);
aces=0;
totplayer=0;
cout<<"\nPlayer cards\n";
deal(2,aces,totplayer,upto,deck,playcards,playhand);
printhand(playcards,playhand);
cout<<"\nYour total is "<<totplayer<<endl;
cout<<"You have "<<aces<<" aces"<<endl;
again=false;
while(totdealer<21&&totplayer<21&&!again)
    {
    cout<<"\ndo you want another card? (y/n) ";
     cin>>yesno;   
     if(toupper(yesno)=='Y')
          {cout<<"\nPlayer cards\n";
          deal(1,aces,totplayer,upto,deck,playcards,playhand);
          printhand(playcards,playhand);
           cout<<"\nYour total is "<<totplayer<<endl;
           cout<<"You have "<<aces<<" aces"<<endl;
           }
     else
         again=true;
     }
cout<<"Dealer total: "<<totdealer<<endl;
cout<<"Your total: "<<totplayer<<endl;
if(totdealer>totplayer||totplayer>21)
      money-=bet;
else if(totdealer<totplayer&&totplayer<=21)
      money+=bet;
cout<<"\nGame over\nYou have $"<<money<<" left\n";
if(money>0)
     {cout<<"\nPlay again (Y/N)?";
     cin>>yesno;
     }
}
system("pause");
return 0;
}
void printhand(int m,int deck[][2])
{int i;
string card[13]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
for(i=0;i<m;i++)
   cout<<card[deck[i][1]]<<endl;

}
void deal(int num,int& tot,int& upto,int deck[][2],int& m,int p[][2])
{int i,n;

 for(i=0;i<num;i++)
     {n=deck[upto][1];
     n++;
     if(n>10)
         n=10;
       p[m][1]=deck[upto][1];
     p[m][0]=deck[upto][0];
     m++;   
         
      if(n==1)
          tot+=11;
      else if(n>=10)
          tot+=10;
      else
          tot+=n;
      upto++;
       }

}
void deal(int num,int& aces,int &tot,int& upto,int deck[][2],int& m,int p[][2])
{int i,n;
 for(i=0;i<num;i++)
     {n=deck[upto][1];
     n++;
     if(n>10)
         n=10;
     p[m][1]=deck[upto][1];
     p[m][0]=deck[upto][0];
     m++;
      if(n==1)
         {aces++;
          tot+=11;
          }
      else if(n>=10)
          tot+=10;
      else
          tot+=n;
      upto++;
          }
if(tot>21)
    if(aces==0)
         return;
    else
        {aces--;
        tot-=10;
        }
}
int getbet(int money)
{int bet;
cout<<"You have $"<<money<<"  place your bet: ";
cin>>bet;
while(bet>money)
    {cout<<"You cannot bet more then you have!!!\n";
     cout<<"You have $"<<money<<" enter your bet: ";
     cin>>bet;
     }
return bet;
}
void shuffle(int deck[][2],int decks)                  
{
int i,num1,type1,num2,type2,temp;
for(i=0;i<100*decks;i++)
   {num1=rand()%(13*decks);
    num2=rand()%(13*decks);
    type1=rand()%4;
    type2=rand()%4;
    temp=deck[type1][0];
    deck[type1][0]=deck[type2][0];
    deck[type2][0]=temp;
    temp=deck[num1][1];
    deck[num1][1]=deck[num2][1];
    deck[num2][1]=temp;
    }
      
}

      
void filldeck(int deck[][2],int decks)                  
{
    bool cards[4][13][decks];
int i,j,k,num,type,d;
for(i=0;i<4;i++)
   for(j=0;j<13;j++)
         for(k=0;k<decks;k++)
             cards[i][j][k]=false;
             
   for(j=0;j<52*decks;j++)
        {do
           {
            num=rand()%13;
            type=rand()%4;
            d=rand()%decks;
            }while(cards[type][num][d]);
         deck[j][0]=type;
         deck[j][1]=num;
         cards[type][num][d]=true; 
         }


}
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Is the indentation of your code in the question how it's in your development environment as well or did a lot of space get lost during the copy-paste and formatting? \$\endgroup\$
    – Mast
    Commented Feb 12, 2022 at 22:47

1 Answer 1

2
\$\begingroup\$

As mentioned by one of the moderators on this site, the code indentation is inconsistent. Making the code indentation consistent would go a long way to making the code look better.

Random Number Generation

The C programming language is limited to the random number generator rand() which is not very random, the C++ programming language has better random number generation:

#include <random>
#include <iostream>

int main()
{
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(1,6); // distribution in range [1, 6]

    std::cout << dist6(rng) << std::endl;
}

Magic Numbers

There are Magic Numbers in the main() function (2, 21, 20, 52), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.

constexpr int DECK_SIZE = 52;
constexpr int BEST_HAND = 21;
constexpr int MAX_HAND_SIZE = 20;

Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.

Avoid using namespace std;

If you are coding professionally you probably should get out of the habit of using the using namespace std; directive. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail.

Variable Declarations and Initialization

To make the code easier to read and maintain it would be better if each variable was declared and initialized on its own line. All variable should be initialized before they are used, C++ does not have default value for variables that haven't been initialized.

Variables should be declared as they are needed rather than declaring all the variables at the top of the function. Most of the variables declared at the top of the main() function can be declared in the game loop. See the code example in Complexity.

The variable decks should probably be a constant so that it can be used to declare the C style arrays.

Complexity

The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:

that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

Please note in the following example PlayBlackJack() is still too complex and could be broken down into smaller functions as well, an example would be to move the inner loop into a function.

void PlayBlackJack(int deck[][])
{
    int dealhand[20][2];
    int playhand[20][2];
    char yesno = 'Y';
    int money = 0;
    cout << "How much money betting do you have? ";
    cin >> money;
    while (money > 0 && toupper(yesno) == 'Y')
    {
        bool again = false;
        int bet = getbet(money);
        int totdealer = 0;
        int playcards = 0;
        int dealcards = 0;
        int upto = 0;
        cout << "\nDealer cards\n";
        deal(2, totdealer, upto, deck, dealcards, dealhand);
        printhand(dealcards, dealhand);
        int aces = 0;
        int totplayer = 0;
        cout << "\nPlayer cards\n";
        deal(2, aces, totplayer, upto, deck, playcards, playhand);
        printhand(playcards, playhand);
        cout << "\nYour total is " << totplayer << endl;
        cout << "You have " << aces << " aces" << endl;
        again = false;
        while (totdealer < 21 && totplayer < 21 && !again)
        {
            cout << "\ndo you want another card? (y/n) ";
            cin >> yesno;
            if (toupper(yesno) == 'Y')
            {
                cout << "\nPlayer cards\n";
                deal(1, aces, totplayer, upto, deck, playcards, playhand);
                printhand(playcards, playhand);
                cout << "\nYour total is " << totplayer << endl;
                cout << "You have " << aces << " aces" << endl;
            }
            else
                again = true;
        }
        cout << "Dealer total: " << totdealer << endl;
        cout << "Your total: " << totplayer << endl;
        if (totdealer > totplayer || totplayer > 21)
            money -= bet;
        else if (totdealer < totplayer && totplayer <= 21)
            money += bet;
        cout << "\nGame over\nYou have $" << money << " left\n";
        if (money > 0)
        {
            cout << "\nPlay again (Y/N)?";
            cin >> yesno;
        }
    }

}

int main()
{
    int decks = 2;
    int deck[DECKSIZE * DECK_COUNT][2];
    srand(time(0));
    filldeck(deck, decks);

    shuffle(deck, decks);

    PlayBlackJack(deck);

    system("pause");
    return 0;
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.