blackjack c++

I am a beginner and taking a required engineering program class. I am having difficulty understanding and putting these codes together correctly to make the blackjack program work. Any help would be greatly appreciated!!!!

// Blackjack.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

char CreateMainMenu();
int GetRandomCard();
void PlayGame();
void Initialize();
void PrintCard(int card);
void ShowCards();
int CalculatePoint(int cards[], int count);

char cardSuits[][15]={ {"Clubs"}, {"Diamond"}, {"Spades"}, {"Hearts"} } ;
const int MAXHAND=20;
int playerCards[MAXHAND];
int playerCardCount=0;
bool playerStand;
int playerPoint;
float playerMoney;
float bet;

int dealerCards[MAXHAND];
int dealerCardCount=0;
int dealerPoint;

// main fuction
int main(void)

char CreateMainMenu()
{
printf("=========== Blackjack ============\r\n");
printf(" 1. Play \r\n");
printf(" 2. Exit \r\n");
printf(" Your Choice (1/2): ");
char choice;
scanf("%c",&choice);
_flushall();
return choice;


/* initialize random seed: */
srand ( time(NULL) );
char choice = CreateMainMenu();
int suit, card;
if (choice=='1')
{
PlayGame();
}
if (choice =='2')
{
printf("Exit Game. ");
}
else
{
printf("Invalid input");
}
return 0;
}

void PlayGame()
{
char choice;
playerMoney=100.0;

do
{
Initialize();
printf("How much do you want to bet (max: $%.2f): $", playerMoney);
scanf("%f", &bet);
_flushall();

/* Dealer gets two cards */
dealerCards[dealerCardCount++]=GetRandomCard();
dealerCards[dealerCardCount++]=GetRandomCard();


/* Player gets two cards */
playerCards[playerCardCount++]=GetRandomCard();
playerCards[playerCardCount++]=GetRandomCard();

ShowCards();
choice=0;
int newCard;
while((playerPoint<21)&&(choice!='S'))
{
printf("Do you want to Hit or Stand?(H/S) ");
_flushall();
if (choice=='H')
{
}

printf("Your point is: %i\r\n", playerPoint);
}
playerStand=true;

if (playerPoint<=21)
{
printf("Dealer's point is: %i\r\n", dealerPoint);
while(dealerPoint<17)
{
printf("Dealer's point is: %i\r\n", dealerPoint);
}
}

printf("\r\n\r\n");
ShowCards();
if (dealerPoint = 21)
{
printf("You lost the bet!");
playerMoney-=bet;
}
else if(playerPoint == dealerPoint) {
printf("Its a draw, you will keep your bet.");
}
else if(playerPoint = 21) {
printf("Congratulations! You got a Blackjack, you won 1.5x of your bet");
playerMoney+= (bet*1.5);
}
else if(playerPoint > 21) {
printf("You lost the best!");
playerMoney-=bet;
}
else
{
printf("You won your bet!");
playerMoney+=bet;
}
printf("\r\n");
printf("You have $%.2f\r\n", playerMoney);
printf("Continue...?(Y/N) ");
scanf("%c", &choice);
_flushall();
}
while(choice!='N');
}



void PrintCard(int card)
{
int value=(card%13)+1;
if ((value>1)&&(value<=10))
{
printf("Card: %i ", value);
}
else
{
printf("Card: ");
switch(value)
{
case 1:
printf("Ace ");
break;
case 11:
printf("Jack ");
break;
case 12:
printf("Queen ");
break;
case 13:
printf("King ");
break;
};
}
printf("of %s\r\n", cardSuits[(int)floor(card/13.0)]);
}
int GetRandomCard() {
return (rand() % 52)+1;
}
void Initialize()
{
dealerCardCount=0;
playerCardCount=0;
playerStand=false;
playerPoint=0;
dealerPoint=0;
bet=0;
for(int i=0; i<MAXHAND; i++)
{
playerCards[i]=0;
dealerCards[i]=0;
}
}
int CalculatePoint(int cards[], int count) {
int points = 0;
int aces=0;
int faceValue;
for(int i=0; i<count; i++) {
faceValue = (cards[i] % 13) + 1;
if (faceValue==1) {
aces++;
}
else {
if (faceValue>10) faceValue=10;
points += faceValue;
}
}

for(int i=0; i<aces; i++) {
if (points+11<=21) {
points+=11;
}
else {
points++;
}
}

return points;
}
void ShowCards() {
if (playerStand) {
printf("Dealer has following - \r\n");
for(int i=0; i<dealerCardCount; i++) {
PrintCard(dealerCards[i]);
}
dealerPoint = CalculatePoint(dealerCards, dealerCardCount);
printf("Dealers total point is: %i\r\n", dealerPoint);
}
else {
printf("Dealer has %i cards, facedown.\r\n", dealerCardCount);
}
printf("\r\n");
printf("You have following - \r\n");
for(int i=0; i<playerCardCount; i++) {
PrintCard(playerCards[i]);
}
playerPoint = CalculatePoint(playerCards, playerCardCount);
printf("Your total point is: %i\r\n", playerPoint);
What you have there is C, not C++.

As it happens, I had to code a game in a client server scenario. For some reason, I thought of BlackJack as my game of choice.

This code I will present has no intelligent AI whatsoever but it might help you so I will post it. The actual game part was only half the battle so I coded it rather quickly. I haven't even tested it but I imagine it works well since the STD is so forgiving compared to straight C. I might be missing a few scenarios but it that's that.

You should post your code inside the <> button or the tags if you want to be taken seriously though.

*In retrospect, I did this within an hour and I don;t even type fast so just take bits and pieces from it.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

enum Suit { CLUBS, HEARTS, DIAMONDS, SPADES };
enum Rank { ONE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE };
enum Who  { PLAYER, DEALER };

struct Card 
{
	Suit suit;	
	Rank rank;
};

class BlackJack
{
	public:
	BlackJack()  
	{
	 	srand ( time(NULL) );
		playerScore = 0;
	 	dealerScore = 0;
		playerBust = false;
		dealerBust = false;

		Card tmpCard;
		for (int i = CLUBS; i < SPADES; i++)
			for (int j = ONE; j <= ACE; j++)
			{				
				tmpCard.suit = (Suit)i;
				tmpCard.rank = (Rank)j;			
				deck.push_back(tmpCard);
			}
	}	

	void ShuffleDeck() { random_shuffle(deck.begin(), deck.end()); }
	
	void Play()
	{
		bool hitMe;
		cout << "\nGame starting....\n\n";
		
		while(1)
		{	
			cout << "\nRound starting...\n\n";
			hitMe = Deal(GetCard(PLAYER), PLAYER);
			Deal(GetCard(DEALER), DEALER);
			
			while (hitMe)
			{
				hitMe = Deal(GetCard(PLAYER), PLAYER);
				Deal(GetCard(DEALER), DEALER);
			}
					
			if (playerScore > 21)
			{			
				cout << "\nYou bust!!\n";
				playerBust = true;
			}
			else if (dealerScore > 21)
			{
				cout << "\nDealer busts!!\n";			
				dealerBust = true;
			}
			else
			{
				cout << "\nYou stand at " << playerScore << endl;
				cout << "The dealer stands at " << dealerScore << endl; 
			}			

			if (playerScore > dealerScore and !playerBust)
				cout << "\nYou win!!!\n\n";
			else if (playerScore == dealerScore or !playerBust and !dealerBust)
				cout << "\nTie!!! Dealer wins!!!\n\n";
			else
				cout << "\nDealer wins!!!\n\n";			
		}
	}

	Card GetCard(Who w)
	{
		Card tmpCard;
		if (deck.size() != 0)
		{
			tmpCard = deck[deck.size()-1];
			AddScore(tmpCard, w);
			deck.pop_back();
		}
		else
		{
			cout << "\nDealer has run out of cards. Game Over....\n\n";
			exit(1);
		}

		return tmpCard;
	}

	void AddScore(Card c, Who w)
	{
		bool faceCard = false;
		int faceValue = 0;
		
		switch(c.rank)
		{
			case JACK  :
			case QUEEN :
			case KING  : faceValue = 10;
					     faceCard = true;  
				break;
			case ACE   : faceValue = 11;
					     faceCard = true;
		}
		
		switch (w)
		{
			case PLAYER :	if (faceCard)
								playerScore += faceValue;
							else 
								playerScore += c.rank; 
				break;
		 	case DEALER :  if (faceCard)
								dealerScore += faceValue;
							else 
								dealerScore += c.rank;
		}		
	}
	
	bool Deal(Card c, Who w)
	{
		if (w == PLAYER)
		{
			char answer;
			do
			{
				cout << "\nYou have been dealt a" << RankToString(c.rank) << "of" << SuitToString(c.suit) << endl;
				cout << "You stand at " << playerScore << endl;
				cout << "\nHit you? (Type Y or N or Q to quit)\n"; 			
				cin  >>	answer;
				answer = toupper(answer);		
			}	
			while (answer != 'Y' and answer != 'N' and answer != 'Q');
		
			switch (answer)
			{
				case 'Y' : return true;
	 				break;
				case 'N' : return false;
					break;
				case 'Q' : cout << "Exiting game....\n"; 
                           exit(1);
			
				return false;
			}
		}
		else
		{
			cout << "\nDealer takes a" << RankToString(c.rank)<< "of" << SuitToString(c.suit) << endl;
			cout << "Dealer stands at " << dealerScore << endl;	
		}
	}

	string SuitToString(Suit s)
	{
		switch(s)
		{
			case CLUBS    : return " clubs ";
			case HEARTS   : return " hearts ";
			case DIAMONDS : return " diamonds ";
			case SPADES   : return " spades ";
		}
	}
	
	string RankToString(Rank r)
	{
		switch(r)
		{
			case ONE   : return " one ";
			case TWO   : return " two ";
			case THREE : return " three ";
			case FOUR  : return " four ";
			case FIVE  : return " five ";
			case SIX   : return " six ";
			case SEVEN : return " seven ";
			case EIGHT : return " eight ";
			case NINE  : return " nine ";
			case TEN   : return " ten ";
			case JACK  : return " jack ";
			case QUEEN : return " queen ";
			case KING  : return " king ";
			case ACE   : return " ace ";
		}
	}

	private:
	vector<Card> deck;	
	bool playerBust;
	bool dealerBust;
	int playerScore;
	int dealerScore;
};

int main() 
{
	BlackJack game;
	game.ShuffleDeck();
	game.Play();
	
Last edited on
The blackjack program starts but then gets stuck in the while-loop where it asks you to hit or stay. It then doesn't add the new random card. It just repeats over and over. As a beginner, it is really frustrating. Any help/hints or whatever would be greatly appreciated.

thanks!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

// blackjack21.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"



#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

char CreateMainMenu();
int GetRandomCard();
void PlayGame();
void Initialize();
void PrintCard(int card);
void ShowCards();
int CalculatePoint(int cards[], int count);

char cardSuits[][15]={ {"Clubs"}, {"Diamond"}, {"Spades"}, {"Hearts"} } ;
const int MAXHAND=20;
int playerCards[MAXHAND];
int playerCardCount=0;
bool playerStand;
int playerPoint;
float playerMoney;
float bet;

int dealerCards[MAXHAND];
int dealerCardCount=0;
int dealerPoint;

int main(void)
{
	/* initialize random seed: */
	srand ( time(NULL) );
	char choice = CreateMainMenu();
	int suit, card;
	if (choice=='1') 
	{
		PlayGame();
	}
	return 0;
}

char CreateMainMenu() {
	printf("=========== Blackjack ============\r\n");
	printf(" 1. Play Game: \r\n");
	printf(" 2. Exit Game: \r\n");
	printf(" Your Choice (1/2): ");
	char choice;
	scanf("%c",&choice);
	_flushall();
	return choice;
}

void Initialize() {
	dealerCardCount=0;
	playerCardCount=0;
	playerStand=false;
	playerPoint=0;
	dealerPoint=0;	
	bet=0;
	for(int i=0; i<MAXHAND; i++) {
		playerCards[i]=0;
		dealerCards[i]=0;
	}
}

int GetRandomCard() {
	return (rand() % 52)+1;
}

void PlayGame() 
{
	char choice;
	playerMoney=100.0;

	do 
	{	
		Initialize();
		printf("How much do you want to bet (max: $%.2f): $", playerMoney);
		scanf("%f", &bet);
		_flushall();

		/* Dealer gets two cards */
		dealerCards[dealerCardCount++]=GetRandomCard();
		dealerCards[dealerCardCount++]=GetRandomCard();


		/* Player gets two cards */
		playerCards[playerCardCount++]=GetRandomCard();
		playerCards[playerCardCount++]=GetRandomCard();

		ShowCards();
		choice=0;
		int newCard;
		while((playerPoint<21)&&(choice!='S')||(choice!='s'))
		{
			printf("Do you want to Hit or Stand?(H/S) ");
			scanf("%c", &choice);
			_flushall();
			if ((choice=='H')|| (choice=='h')) 
			{
				playerCards[playerCardCount++]=GetRandomCard();
				++playerCardCount++;			 
			printf("Your point is: %i\r\n",playerPoint);
			}
			else if((choice=='S')||(choice=='s'))
			{
				printf("You have chosen to stay. Wise!", playerPoint);
				playerStand=false;
			}
			else
			{
				printf("Invalid Entry!");
			}
			int playerScore=CalculatePoint(int cards[], int count) 
			 
		}
		playerStand=true;

		if (playerScore<=21) {
			printf("Dealer's point is: %i\r\n", dealerPoint);
			while(dealerPoint<17) {
				printf("Dealer's point is: %i\r\n", dealerPoint);
			}
		}
		printf("\r\n\r\n");
		ShowCards();	
		if (dealerPoint=21) {
			printf("Bummer, you lost the bet!");
			playerMoney-=bet;
		}
		else if(dealerPoint=playerScore) {
			printf("Its a draw, you will keep your bet.");
		}
		else if(playerScore=21) {
			printf("Congratulations! Your Awesome! You got a Blackjack and won 1.5x of your bet");
			playerMoney+= (bet*1.5);
		}
		else if(playerScore>21) {
			printf("Just not your day, you lost the best! Better luck next time!");
			playerMoney-=bet;
		}
		else {
			printf("You won your bet!");
			playerMoney+=bet;
		}
		printf("\r\n");
		printf("You have $%.2f\r\n", playerMoney);
		printf("Continue...?(Y/N) ");
		scanf("%c", &choice);
		_flushall();
	}
	while(choice!='N');
	
}

int CalculatePoint(int cards[], int count) {
	int points = 0;
	int aces=0;
	int faceValue;
	for(int i=0; i<count; i++) {
		faceValue = (cards[i] % 13) + 1;
		if (faceValue==1) {
			aces++;
		}
		else {
			if (faceValue>10) faceValue=10;
			points += faceValue;
		}
	}

	for(int i=0; i<aces; i++) {
		if (points+11<=21) {
			points+=11;
		}
		else {
			points++;
		}
	}

	return points;
}

void PrintCard(int card) {
	int value=(card%13)+1;
	if ((value>1)&&(value<=10)) {
	 printf("Card: %i ", value);
	}
	else {
		printf("Card: ");
		switch(value) {
			case 1: 
				printf("Ace ");
				break;
			case 11:
				printf("Jack ");
				break;
			case 12:
				printf("Queen ");
				break;
			case 13:
				printf("King ");
				break;
		};
	}
	printf("of %s\r\n", cardSuits[(int)floor(card/13.0)]);
}

void ShowCards() {
	if (playerStand) {
		printf("Dealer has following - \r\n");
		for(int i=0; i<dealerCardCount; i++) {
			PrintCard(dealerCards[i]);
		}
		dealerPoint = CalculatePoint(dealerCards, dealerCardCount);
		printf("Dealers total point is: %i\r\n", dealerPoint);
	}
	else {
		printf("Dealer has %i cards, facedown.\r\n", dealerCardCount);
	}
	printf("\r\n");
	printf("You have following - \r\n");
	for(int i=0; i<playerCardCount; i++) {
		PrintCard(playerCards[i]);
	}
	playerPoint = CalculatePoint(playerCards, playerCardCount);
	printf("Your total point is: %i\r\n", playerPoint);
}
Topic archived. No new replies allowed.