training

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

autocraps.c (1379B)


      1 /* Exercise 6.20 */
      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 i;
     15    int c[2] = { 0 };
     16 
     17    srand( time(NULL) );
     18    printf("Runs\tWIN\tLOST\n");
     19    for(i = 1; i <= 1000; i++) {
     20       ++c[play() - 1];
     21       printf("%d\t%d\t%d\n", i, c[0], c[1]);
     22    }
     23 
     24    printf("Total wins: %d\nTotal loses: %d\n", c[0], c[1]);
     25 
     26    return 0;
     27 } /* E0F main */
     28 
     29 /* play a time */
     30 int play(void) {
     31    int sum, myPoint;
     32 
     33    enum Status gameStatus;
     34 
     35    //srand( time(NULL) );
     36 
     37    sum = rollDice();
     38 
     39    switch(sum) {
     40       case 7:
     41       case 11:
     42 	 gameStatus = WON;
     43 	 break;
     44       case 2:
     45       case 3:
     46       case 12:
     47 	 gameStatus = LOST;
     48 	 break;
     49       default:
     50 	 gameStatus = CONTINUE;
     51 	 myPoint = sum;
     52 	 break; /* optional */
     53    } /* end switch (sum) */
     54 
     55    while(gameStatus == CONTINUE) {
     56       sum = rollDice();
     57 
     58       if(sum == myPoint)
     59 	 gameStatus = WON;
     60       else
     61 	 if(sum == 7)
     62 	    gameStatus = LOST;
     63 
     64    } /* end while (gameStatus) */
     65 
     66    if(gameStatus == WON) {
     67       return WON;
     68    }
     69    else {
     70       return LOST;
     71    }
     72 
     73 } /* eof play() */
     74 
     75 /* launch the dice, calculate the sum and print results */
     76 int rollDice(void) {
     77    int die1, die2;
     78    int workSum;
     79 
     80    die1 = 1 + rand() % 6;
     81    die2 = 1 + rand() % 6;
     82    workSum = die1 + die2;
     83 
     84    return workSum;
     85 } /* end rollDice() */
     86