Scoring Blackjack in C++: Handling Aces in a Card Game Program

  • Context: Comp Sci 
  • Thread starter Thread starter wahaj
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 3K views
wahaj
Messages
154
Reaction score
2

Homework Statement



I am writing a program in c++ where it inputs card values from the user and stores it in a char type variable. valid inputs are numbers 1-9, t,k,q,j for ten, kind, queen, jack respectively and a for ace. after inputting all the values the program goes like this
Code:
if (!(card1 == 'a'))
	{
		switch (card1)
		{
		case '1':
			score = score + 1;
			break;
		case '2':
			score = score + 2;
			break;
		case '3':
			score = score + 3;
			break;
		case '4':
			score = score +4;
			break;
		case '5':
			score = score + 5;
			break;
		case '6':
			score = score + 6;
			break;
		case '7':
			score = score + 7;
			break;
		case '8':
			score = score + 8;
			break;
		case '9':
			score = score + 9;
			break;
		case 't':
		case 'j':
		case 'k':
		case 'q':
			score = score + 10;
			break;
		default:
			break;
		}
the code is the same for card 2,3,4, and 5. The problem I am having is that I don't know how to deal with aces. if there is only one ace I can simply go like this
Code:
if (card1 == 'a' || card2 == 'a' || card3 == 'a' || card 4 == 'a' || card5 = 'a')
{
      if (21-score <= 11)
         {
              score = score + 11;
          }
       else 
            {
               score = score +1;
             }
}
but what if there are multiple aces? then I have to decide which ace counts as 1 and which 11. I can do that by reiterating the above statement. but I don't know how to find out how many aces I have aside from using brute force where I list 20 cases for every combination of cards that might end up being aces.
On a side note I have never played blackjack before so I am just going by the brief description of the game given in the question. Also this is my first time using switch statement so I don't know I did used it right.
 
Physics news on Phys.org
Hi wahaj! :smile:

Why don't you count each ace as 1 point?
But do keep track if you have at least one ace.
At the end, if the score is 11 or lower, and you have at least one ace, add 10 points.

Your switch statement is fine.
However, duplicating it 5 times is bad programming practice.
 
hmm that might work. Also do you by any chance have a better solution to the switch statements. After all no body wants to read 300 lines of switch statements.
 
Right, except arrays are still 3 chapters away . I probably should have mentioned that I only know loops and if else statements and variables so far. Thanks anyways.