training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

craps.c (1667B)


      1 /* Exercise 5.51 */
      2 
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 #include <time.h>
      6 
      7 enum Status { CONTINUE, WON, LOST };
      8 
      9 int rollDice(void);
     10 int play(void);
     11 
     12 int main()
     13 {
     14    int bankBalance = 1000, wager;
     15 
     16    while(bankBalance) {
     17 
     18       do {
     19          printf("Bank balance: $%d\n", bankBalance);
     20          printf("Enter your wager: ");
     21          scanf("%d", &wager);
     22       } while(wager > bankBalance || wager <= 0);
     23 
     24       if(play() == WON)
     25          bankBalance += wager;
     26       else
     27          bankBalance -= wager;
     28    }
     29 
     30    printf("Bank balance: $0\n");
     31 
     32    return 0;
     33 } /* E0F main */
     34 
     35 /* play a time */
     36 int play(void) {
     37    int sum, myPoint;
     38 
     39    enum Status gameStatus;
     40 
     41    srand( time(NULL) );
     42 
     43    sum = rollDice();
     44 
     45    switch(sum) {
     46       case 7:
     47       case 11:
     48 	 gameStatus = WON;
     49 	 break;
     50       case 2:
     51       case 3:
     52       case 12:
     53 	 gameStatus = LOST;
     54 	 break;
     55       default:
     56 	 gameStatus = CONTINUE;
     57 	 myPoint = sum;
     58 	 printf("Point is %d\n", myPoint);
     59 	 break; /* optional */
     60    } /* end switch (sum) */
     61 
     62    while(gameStatus == CONTINUE) {
     63       sum = rollDice();
     64 
     65       if(sum == myPoint)
     66 	 gameStatus = WON;
     67       else
     68 	 if(sum == 7)
     69 	    gameStatus = LOST;
     70 
     71    } /* end while (gameStatus) */
     72 
     73    if(gameStatus == WON) {
     74       printf("Player wins\n");
     75       return WON;
     76    }
     77    else {
     78       printf("Player loses\n");
     79       return LOST;
     80    }
     81 
     82 } /* eof play() */
     83 
     84 /* launch the dice, calculate the sum and print results */
     85 int rollDice(void) {
     86    int die1, die2;
     87    int workSum;
     88 
     89    die1 = 1 + rand() % 6;
     90    die2 = 1 + rand() % 6;
     91    workSum = die1 + die2;
     92 
     93    printf("Player rolled %d + %d = %d\n", die1, die2, workSum);
     94 
     95    return workSum;
     96 } /* end rollDice() */
     97