Problems getting game of 21 to work

Create a program in which a user plays a simple version of the card game 21 against the computer. Each player is initially dealt two cards from an unlimited deck. Random numbers will represent the cards from 1 to 10. After seeing their hand the user then the computer are given the opportunity to take additional cards. The hand that comes the closest to 21 without exceeding 21 wins the game. A draw results if both players have the same score.



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
//Specification: This program plays a version of
//the card game of 21.
//A human player is pitted against the computer.
//The player who is the closest to 21 without
//going over wins the hand. 
#include <iostream>
#include <ctime>
#include <string>

using namespace std;

//prototypes...
void play21(void);
int dealCards(int, string);
void hit(int &);
void determineWinner(int, int);
int Random(int, int);


void main(){

       char keepPlaying = 'n'; //loop control variable

       do {
              play21();
          
              //keep playing?
             cout << "Do you want to play anouther hand (y/n)?";
             cin >> keepPlaying;
     } while(keepPlaying == 'Y' || keepPlaying == 'y');
}

void play21(void){
        //play one hand of 21

        //randomize the cards
        srand((int) time(0));

       // deal the cards
         int person = dealCards(2, "Your Cards:");
         cout << " = " << person << endl;
         int house = dealCards(2, "Computers Cards:");
         cout << " = " << house << endl;

        // Ask if human wants a hit and keep hitting...
        hit(person);
        cout << endl;

       //Determine if computer takes a hit
       while ((house < person) && (house <= 21) && (person <= 21)) {
               house += dealCards(1, "The Computer takes a card ");
               cout << endl;
        }

       //show who won....
       determineWinner(person, house);
}

void determineWinner(int humanScore, int houseScore) {//Compare the scores to see who won
	
	while((humanScore > houseScore)&&(humanScore <=21)){
		cout<< "The winner is Player. Congratulations!";
	}
		while((houseScore > humanScore)&&(houseScore <=21)){
		cout<<"The winner is the House. You lost!";
	}
		while(houseScore==humanScore){
			cout<<"The game is a tie!";
			cout<<endl;
		}
		//end while
//possible outcomes: human wins, computer wins, tie

}

int dealCards(int numberOfCards, string message){
	int ret_val = 0, val;  
	int cards = numberOfCards;  
  
		cout << message;  
	while(cards--){  
// Values from 1 to 10 
	val = Random(1,10);  
	if( val > 10 ) val = 10;  
	if( val == 1 ) val = 11;  
		cout << val;  
	if(cards)  
		cout << ",";  
		ret_val+=val;  
}  
	return ret_val;  
}   

void hit(int &playerScore){
	char wantCard = 'n';
    
    int cardTotal = 0;
        cardTotal = playerScore;

               
        {
            while (wantCard == 'Y' || 'y')
        
            if ((cardTotal > 0 ) && (cardTotal <= 21)) 
            {
                cout << "\nYour Card Total is " << cardTotal << endl;
                cout << "\nWould you like another card(y or n)?";
                cin >> wantCard;
            }
	else (wantCard == 'N' || 'y')
			{

            
	cardTotal = cardTotal + Random(1,10);
	cout << cardTotal << endl;
            
        }
}

int Random(int lowerLimit, int upperLimit) {
//returns a random number within the given boundary
         return 1 + rand() % (upperLimit - lowerLimit + 1);
}


What I had to do was provide the required code for the following functions: dealCards, hit, and determineWinner.

Last edited on
First off, what problems are you having. It really helps if you tell it whats it doing and what it's supposed to be doing.

At first glance (I don't have a lot of time right now), I see:

You should probably put line 37 before you enter the loop. Don't know if that matters too much.

Line 110 - should be either else if(blah blah blah){} or just else{} Also you can't do what your are doing there. (and also it doesn't make much sense) You have to say something like
 
else if(wantCard == 'N' || wantCard == 'n'){}


Line 120-123 - That doesn't make much sense at all to me. If you want a random number between 1 and 10, you say
 
randomnumber = rand() % upperLimit + lowerlimit

You got that part all jumbled up even though it's doing the same thing.

You have a random curly bracket on line 101, I think it's supposed to be for the while loop though.

You have variables all over the place that have limited scope. For instance, for you hit function, you do display the correct amount that should be. But cardTotal is destroyed at the end of that function and person is unchanged. You should do something like
1
2
3
4
5
6
7
8
int Hit(int person)
{
     //make random number
     person += Random(1, 10);
     return person;
}

person = Hit(person);

or something...

Or instead of that just get rid of cardTotal altogether and use playerScore since you are passing it by reference for some reason..

That's all for now. I think you should work on it a bit, try to isolate any problems you are having and then repost your code.
Last edited on
Ok thank you for the points I will see what I can do.
Eerror C2447: '{' : missing function header (old-style formal list?) seems to be the only error I have here and I can't seem to make it go away. Any ideas on this one? It says it is on line 9


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void hit(int &playerScore){ 

		char hit = 'n';

			cout << "Do you want a card (y/n)?";
			cin >> hit;
  
}		
{		while (hit == 'Y' || hit == 'y')
		
			playerScore += dealCards(1); // Deals one card 

		if (playerScore < 21) {
			cout << playerScore;  // Displays score
			cout << "Do you want another card (y/n)?";
			cin >> endl;
			}
		else if(playerScore > 21){// busted
				cout << playerScore << "Busted" << endl;
			}
		else (playerScore < 21) || (hit !='n');
}
Last edited on
Get rid of that {

And do
1
2
3
4
while(blah)
{
    your stuff
}
Last edited on
Ok now it finally reaches a succeeded state but now will not let you choose y/n to get new card.


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
#include <iostream>
#include <ctime>
#include <string>

using namespace std;

//prototypes...
void play21(void);
int dealCards(int, string);
void hit(int &);
void determineWinner(int, int);
int Random(int, int);


void main(){

       char keepPlaying = 'n'; //loop control variable

       do {
              play21();
          
              //keep playing?
             cout << "Do you want to play anouther hand (y/n)?";
             cin >> keepPlaying;
     } while(keepPlaying == 'Y' || keepPlaying == 'y');
}

void play21(void){
        //play one hand of 21

        //randomize the cards
        srand((int) time(0));

       // deal the cards
         int person = dealCards(2, "Your Cards:");
         cout << " = " << person << endl;
         int house = dealCards(2, "Computers Cards:");
         cout << " = " << house << endl;

        // Ask if human wants a hit and keep hitting...
        hit(person);
        cout << endl;

       //Determine if computer takes a hit
       while ((house < person) && (house <= 21) && (person <= 21)) {
               house += dealCards(1, "The Computer takes a card ");
               cout << endl;
        }

       //show who won....
       determineWinner(person, house);
}

void determineWinner(int humanScore, int houseScore) {//Compare the scores to see who won
	
	while((humanScore > houseScore)&&(humanScore <=21)){
		cout<< "The winner is Player. Congratulations!";
	}
		while((houseScore > humanScore)&&(houseScore <=21)){
		cout<<"The winner is the House. You lost!";
	}
		while(houseScore==humanScore){
			cout<<"The game is a tie!";
			cout<<endl;
		}
		//end while
//possible outcomes: human wins, computer wins, tie

}

int dealCards(int numberOfCards, string message){
		int ret_val = 0, val;  
		 cout << message;  

		while(numberOfCards--){  
// Values from 1 to 10 
			val = Random(1,10);  
		if( val > 10 ) val = 10;  
			cout << val;  
		if(numberOfCards)  
			cout << ",";  
			ret_val+=val;  
}  
	return ret_val;  
}   

void hit(int &playerScore)
{ 

		char hit;

			cout << "Do you want a card (y/n)?";
			cin >> hit;

		while (hit == 'Y' || hit == 'y');
{
		
			playerScore += Random(1, 10);// Deals one card 
			

		if (playerScore < 21) 
{
			cout << playerScore;  // Displays score
			cout << "Do you want another card (y/n)?";
			cin >> hit;
}
		else if(playerScore > 21)
{// busted
				cout << playerScore << "Busted" << endl;
}
		else (playerScore < 21) || (hit !='n');
}
}
int Random(int lowerLimit, int upperLimit) {
//returns a random number within the given boundary
		return 1 + rand() % (upperLimit - lowerLimit + 1);
}
It's good practice to line up your braces. i.e

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
void hit(int &playerScore)
{ 

		char hit;

	        cout << "Do you want a card (y/n)?";
		cin >> hit;

		while (hit == 'Y' || hit == 'y');
                {
		
			playerScore += Random(1, 10);// Deals one card 
			

		        if (playerScore < 21) 
                       {
			      cout << playerScore;  // Displays score
			      cout << "Do you want another card (y/n)?";
			      cin >> hit;
                        }
		        else if(playerScore > 21)
                        {// busted
				cout << playerScore << "Busted" << endl;
                        }
		        else (playerScore < 21) || (hit !='n'); //What is this supposed to do?
                }
}
lol yah i noticed that after I posted the code here, but when I changed it still does not let you get another card could it be something small that I missed? Thank you for your help mike I would be lost without you at this point. 8) Honestly I was tring to set up a statement so when you chose not to get new card it would would show the winner. But it will not even let you choose Y for another card.
Last edited on
No semicolon after while on line 95. You should do if(playerScore <= 21) on 101. And also, dealer stands at 17+ =)

You should also break; out of the loop if the player busts. (Don't ask to hit or not after you already busted)

If you want extra points you should simulate how 10's occur more than other cards.

i.e. A 2 3 4 5 6 7 8 9 10 10 10 10

Your on your own with that one though. Is this a homework assignment or just something your working on?
Last edited on
Does not display cards that are generated from dealCards, and does not show who wins in the end. Any help that you could offer would be great.

Mike this is just a program I am working on to see if I am able to do this lol. I have always wanted to learn C++ so I am giving it a shot.


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
//Specification: This program plays a version of
//the card game of 21.
//A human player is pitted against the computer.
//The player who is the closest to 21 without
//going over wins the hand. 
#include <iostream>
#include <ctime>
#include <string>

using namespace std;

//prototypes...
void play21(void);
int dealCards(int, string);
void hit(int &);
void determineWinner(int, int);
int Random(int, int);


void main(){

       char keepPlaying = 'n'; //loop control variable

       do {
              play21();
          
              //keep playing?
             cout << "Do you want to play anouther hand (y/n)?";
             cin >> keepPlaying;
     } while(keepPlaying == 'Y' || keepPlaying == 'y');
}

void play21(void){
        //play one hand of 21

        //randomize the cards
        srand((int) time(0));

       // deal the cards
         int person = dealCards(2, "Your Cards:");
         cout << " = " << person << endl;
         int house = dealCards(2, "Computers Cards:");
         cout << " = " << house << endl;

        // Ask if human wants a hit and keep hitting...
        hit(person);
        cout << endl;

       //Determine if computer takes a hit
       while ((house < person) && (house <= 21) && (person <= 21)) {
               house += dealCards(1, "The Computer takes a card ");
               cout << endl;
        }

       //show who won....
       determineWinner(person, house);
}

void determineWinner(int humanScore, int houseScore) {//Compare the scores to see who won
	
	while((humanScore > houseScore)&&(humanScore <=21)){
		cout<< "The winner is Player. Congratulations!" << endl; break;
	}
		while((houseScore > humanScore)&&(houseScore <=21)){
		cout<<"The winner is the House. You lost!" << endl; break;
	}
		while(houseScore==humanScore){
			cout<<"The game is a tie!" << endl; break;
			cout<<endl;
		}
		//end while
//possible outcomes: human wins, computer wins, tie

}

int dealCards(int numberOfCards, string message){
		 
		int ret_val = 0, val;////// declare variables
			cout << message;  ////// output message

		while(numberOfCards--){ //////deal the number of required cards - use a for loop
			val = Random(1,10);//////////get a card by calling random
		if(numberOfCards)  //////////accumulate the card values
			cout << val << ",";  ////// display card
			ret_val+=val; ////// return total value
}  
	return ret_val;  
}   

void hit(int &playerScore)
{ 
		
		char hit = 'n';

	        cout << "\nDo you want a card (y/n)?";
		cin >> hit;

		while (hit == 'Y' || hit == 'y')
                {
		
			 cout << "Player takes a card " ;
			 playerScore += Random(1,10);// Deals one card 
			

		        if (playerScore <= 21) 
                       {
						   cout << playerScore;  // Displays score
			      cout << "\nDo you want another card (y/n)?";
			      cin >> hit;
                        }
		        else if(playerScore > 21)
                        {// busted
				cout << playerScore << "Busted" << endl; break;
                        }
		        else (playerScore < 21) || (hit !='n'); 
                }
}
int Random(int lowerLimit, int upperLimit) {
//returns a random number within the given boundary
		return 1 + rand() % (upperLimit - lowerLimit + 1);
}
I think you should take a step back. Make new functions. Make them as simple as possible. I would learn about arrays as that would make your life a bit easier. Make separate variables for the cards the each player has (an array) and a variable for the total. And name them so they are easier to understand. A big part of learning a programming language is learning how to write good code. If you do all of this, you will be much more capable of making your game do what you want it to do.

ps in determine winner, they should be if's not while's

Thank you for the tips
Last edited on
Finished Game of 21


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
#include <iostream>
#include <ctime>
#include <string>

using namespace std;

//prototypes...
void play21(void);
int dealCards(int, string);
void hit(int &);
void determineWinner(int, int);
int Random(int, int);


void main(){

       char keepPlaying = 'n'; //loop control variable

       do {
              play21();
          
              //keep playing?
             cout << "Do you want to play anouther hand (y/n)?";
             cin >> keepPlaying;
     } while(keepPlaying == 'Y' || keepPlaying == 'y');
}

void play21(void){
        //play one hand of 21

        //randomize the cards
        srand((int) time(0));

       // deal the cards
         int person = dealCards(2, "Your Cards:");
         cout << " = " << person << endl;
         int house = dealCards(2, "Computers Cards:");
         cout << " = " << house << endl;

        // Ask if human wants a hit and keep hitting...
        hit(person);
        cout << endl;

       //Determine if computer takes a hit
       while ((house < person) && (house <= 21) && (person <= 21)) {
               house += dealCards(1, "The Computer takes a card ");
               cout << endl;
        }

       //show who won....
       determineWinner(person, house);
}

//function to determine the winner scores or passed by value
void determineWinner(int humanScore, int houseScore) 
{
    //prints out both yours and the computer score
    cout << "Your score: " << humanScore << endl
        << "Computer score: " <<houseScore << endl << endl;

    //decision statement for who wins or if it is a draw
    if(humanScore>houseScore && humanScore<=21 || houseScore>21)
    {    
        cout << "You Won! Have a cookie!" << endl;
    }
    else if(humanScore<houseScore && houseScore<=21 || humanScore>21 )
    {    
		cout << "You Loose! Do better next time!" << endl;
    }
    else
    {
        cout << "Draw Game! You can do better!" << endl;
    }

}

//deals the player and computer cards, either one or two cards at a time
int dealCards(int numberOfCards, string message)
{
    //declare variables
    int randomvalue, totalPlayer = 0;

    //the message is passes by value
    cout << message << " ";
    
    //decision statement to determine the number of cards that are needed to be dealt    
    for(numberOfCards; numberOfCards > 0; numberOfCards--)
        {
            //calls the random function
            randomvalue = Random(1, 10);
            //prints out the random value
            cout << randomvalue << " ";
            //calculates the total
            totalPlayer = totalPlayer + randomvalue;
        }
    
        //returns the total
        return totalPlayer;
}

//hit passing value by reference
void hit(int &playerScore)
{
    //declaring variables
    char addCard;

    //prompt if you want another card
    cout << endl << "Do you want another card (y/n)? ";
    cin >> addCard;
    
    //decision statement on how many cards to draw
    while(toupper(addCard) == 'Y')
    {
        //calculates the total for player 
        //call the dealcards function to get another card
        playerScore += dealCards(1, "Hit:");

        //prints out new total
        cout << "Your total is " << playerScore << endl;        
        
        
        if (playerScore >21)
        {
            //prints out busted
            cout << "Busted!" <<endl;
            //ends the loop
            addCard = 'n';
        }

        else
        {    
            //ask if they want another card
            cout << endl << "Do you want another card (y/n)? ";
            cin >> addCard;
        }
    }
}



int Random(int lowerLimit, int upperLimit) {
//returns a random number within the given boundary
         return 1 + rand() % (upperLimit - lowerLimit + 1);
}

Topic archived. No new replies allowed.