// Fig. 3.10: fig03_10.cpp // Craps #include #include #include int rollDice( void ); // function prototype enum Status { CONTINUE, WON, LOST }; Status playAGame(); int rolls = 0; int main( int argc, char* argv[] ) { int numPlays = 1; if ( argc > 1 ) { numPlays = atoi( argv[1] ); } unsigned int t = time( 0 ); srand( t ); int wins = 0; int n = numPlays; while ( n-- > 0 ) { if ( playAGame() == WON ) wins++; } cout << numPlays << " games were played." << endl; cout << "Winning percentage was " << wins/(double)numPlays << endl; cout << "Dice rolls per game averaged " << (double)rolls/numPlays << endl; cout << "Total number of rolls of the dice pair was " << rolls << endl; } Status playAGame() { int sum, myPoint; Status gameStatus; sum = rollDice(); // first roll of the dice switch ( sum ) { case 7: case 11: // win on first roll gameStatus = WON; break; case 2: case 3: case 12: // lose on first roll gameStatus = LOST; break; default: // remember point gameStatus = CONTINUE; myPoint = sum; //cout << "Point is " << myPoint << endl; break; // optional } while ( gameStatus == CONTINUE ) { // keep rolling sum = rollDice(); if ( sum == myPoint ) // win by making point gameStatus = WON; else if ( sum == 7 ) // lose by rolling 7 gameStatus = LOST; else ; //just continue } return gameStatus; } int rollDice( void ) { int die1, die2; rolls++; die1 = 1 + rand() % 6; die2 = 1 + rand() % 6; return die1 + die2; }