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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main()
{
char ans;
bool play = true;
srand( time( 0 ) );
while( play )
{
int total = 0, numDrawn = 0;
bool drawAgain = true;
while ( drawAgain )
{
int card = 1 + rand() % 10;
total += card;
numDrawn++;
cout << "Card: " << card << " Total: " << total << '\n';
if ( total >= 21 )
{
drawAgain = false;
cout << ( total > 21 ? "Bust!" : "Vingt et un!" ) << '\n';
}
else if ( numDrawn >= 2 )
{
cout << "Do you want another card (y/n)? ";
cin >> ans;
drawAgain = ( tolower( ans ) == 'y' );
}
}
cout << "Would you like to play again (y/n)? ";
cin >> ans;
play = ( tolower( ans ) == 'y' );
}
}
|
Fundamentally, there are two things that you do repetitively:
- play a game
and, within that,
- draw cards
I think that your nested loop structure should reflect that.
Decisions are made (by you or the rules of the game)
- as a response to drawing cards
- as a response to the end of a game
I think that your if blocks should reflect that.
The restriction not to use functions is sad, however:
- it makes the single routine main() quite long;
- it removes the opportunity for the names of functions to indicate what is going on;
- there is still unnecessary repetition (lines 31-33 and 37-39) that could be reduced.
It's a nice exercise in logic, however.