I'm currently trying to make a simple Blackjack program that is single player and only has cards from 1-10. The issue that I'm having is that whenever I ask for a new card for the third time, it doesn't total up my cards properly. The program also doesn't restart properlyHere is an example of the output:
Welcome to Blackjack!
Here are your first cards: 10, 2
Your total is 12.
Would you like to draw another card? (y/n)
y
You got a new card with a value of 6.
Your total is now 18.
Would you like to draw another card? (y/n)
y
You got a new card with a value of 4.
Your total is now 16.
Would you like to draw another card? (y/n)
n
Welcome to Blackjack!
Here are your first cards: 6, 4
Your total is 10.
Would you like to draw another card? (y/n)
I have tried using a do-while loop so that it asks for a new card whenever the total < 21 but it ends up the same way. I'm at a loss at how to solve this.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int getCard(int);
int main()
{
srand(time(0));
int total, card1, card2, newTotal = 0;
char choice, playAgain = 'y';
while (playAgain == 'y')
{
cout << "Welcome to Blackjack!\n";
card1 = rand() % 10 + 1;
card2 = rand() % 10 + 1;
total = card1 + card2;
cout << "Here are your first cards: " << card1 << ", " << card2 << endl;
cout << "Your total is " << total << "." << endl;
cout << "Would you like to draw another card? (y/n)\n";
cin >> choice;
while (choice == 'y')
{
newTotal = getCard(total);
if (newTotal > 21)
{
cout << "Bust!" << endl;
choice = 'n';
}
else if (newTotal < 21)
{
cout << "Would you like to draw another card? (y/n)\n";
cin >> choice;
}
else
{
cout << "Congratulations, you won!\n";
choice = 'n';
}
}
}
cout << "Would you like to play again? (y/n)\n";
cin >> playAgain;
return 0;
}
int getCard(int total)
{
int addCard, newTotal;
addCard = rand() % 10 + 1;
newTotal = total + addCard;
cout << "You got a new card with a value of " << addCard << "." <<
endl;
cout << "Your total is now " << newTotal << "." << endl;
return newTotal;
}
The program is expected to start the player off with 2 cards and then ask them if they'd like to draw another one. If they input 'y' then it would do so and retotal the cards up. If they say no, then the game just ends. If they say yes and the new cards makes the total > 21 then it returns "bust." If it makes the total become 21 then it tells the player that it wins. At the end of each game, it should ask the player if they would like to play again.