COMP1721 - Higher Computing 1B

Higher Computing 1B - Week Laboratory Exercises


/*
 * Allow a user to compete with the computer in the game of 42
 * The highest score wins, but if you pass 42 you lose!
 * written by Andrew Taylor andrewt@cse.unsw.edu.au
 * August 2001 as a COMP1721 lab exercise.
 */
 
#include 
#include 
#include 

#define TARGET 42
#define MAX_NUMBER 21
#define COMPUTER_LIMIT 32

int
main(void) {
    int number, userScore, computerScore;
    char answer;
    
    srand(time(NULL));
    for (userScore = 0; userScore <= TARGET; userScore += number) {
        printf("Your score is: %d\n", userScore);
        printf("Do you want to take another number [y or n]? ");
        answer= getchar();
        if (answer != 'y')
            break;
        getchar(); /* throw away the newline - might be better to be more careful here */
        /*
         * % MAX_NUMBER uses the lower order bits which may  be predictable
         * safer is: 1+(int)(1.0*MAX_NUMBER*rand())/(RAND_MAX+1.0)
         */
        number = 1+(rand() % MAX_NUMBER); 
        printf("You get the number: %d\n", number);
    }
    
    if (userScore > TARGET) {
        printf("Your score is: %d\n", userScore);
        printf("You bust.\n");
        return 0;
    }
    
    printf("Now the computer plays");
    
    for (computerScore = 0; computerScore < COMPUTER_LIMIT; computerScore += number) {
        number = 1+(int)(MAX_NUMBER*rand()/(RAND_MAX+1.0));
        printf("The computer gets the number: %d\n", number);
    }
    
    printf("The computer's score is: %d\n", computerScore);
    
    if (computerScore > TARGET) {
        printf("The computer busts.\n");
        return 0;
    }
    
    if (computerScore < userScore)
        printf("You win.\n");
    else if (computerScore == userScore)
        printf("Its a draw.\n");
    else
        printf("The computer wins.\n");
    return 0;
}


Andrew Taylor (andrewt@cse.unsw.edu.au)
Higher Computing 1B, Computer Science & Engineering, UNSW