/* Craps, from "C++, How to Program" by Deitel and Deitel, */ /* copyright 1994 by Prentice-Hall, all rights reserved. */ /* This demonstration program appears on page 154 of that text. */ /* */ /* Fair use for educational purposes. */ /* Copied for use in Computer Science 101 at USC by Rick Wagner. */ /* */ /* Craps is played with two dice, a player against the house. */ /* The player rolls two dice for their sum. If the sum is 7 or */ /* 11 on the first roll, the player wins. If the sum is */ /* snake eyes (2), 3, or box cars (12), the player loses. Other */ /* sums become the player's "point" in which case the player */ /* continues rolling until the sum is equal to his point (in */ /* which case he wins) or until the sum is equal to 7, in which */ /* case he loses. */ /* */ /* Program translated from C++ to C by Rick Wagner, */ /* March 15, 1999. Last updated March 15, 1999. */ #include #include #include /* For a random seed */ #include /* For tolower() */ typedef enum {CONTINUE, WON, LOST} Status; /* Function prototype: */ int rollDice(void); int play(void); void main() { int balance = 0; char cChoice = 'y'; while (cChoice == 'y') { balance += play(); printf("Your balance is %d dollars. Play again? (y/n) "); scanf("%c", &cChoice); fflush(stdin); cChoice = (char) tolower((int) cChoice); printf("\n"); } if (balance < 0) { printf("Thanks for playing. Be sure to pay the proprietor on your way out.\n\n"); } else { printf("Thanks for playing. Be sure to collect your winnings on your way out.\n\n"); } } int play() { Status gameStatus; int sum = 0; int myPoint = 0; int score = 0; /* Seed the random number generator with the system time. */ srand(time(NULL)); /* NULL is defined in stdlib.h. */ sum = rollDice(); /* First roll of the dice . */ switch (sum) { case 7: case 11: /* Win on the first roll. */ { gameStatus = WON; break; } case 2: case 3: case 12: /* Lose on the first roll. */ { gameStatus = LOST; break; } default: /* Remember the player's point. */ { gameStatus = CONTINUE; myPoint = sum; printf("Point is %d\n", myPoint); break; } } while (gameStatus == CONTINUE) { sum = rollDice(); if (sum == myPoint) { gameStatus = WON; } else { if (sum == 7) { gameStatus = LOST; } } } if (gameStatus == WON) { printf("Player wins.\n"); score = 1; } else { printf("Player loses.\n"); score = -1; } return score; } int rollDice(void) { int die1 = 0; int die2 = 0; int workSum = 0; die1 = 1 + (rand() % 6); die2 = 1 + (rand() % 6); workSum = die1 + die2; printf("Player rolled %d + %d = %d\n", die1, die2, workSum); return workSum; }