/* * Prog_Practice_W6.c * * Created on: Jan 21, 2022 * Author: johnsontimoj */ //////////////////////////// // // programming practice - fns, pointers, while, for // /////////////////////////// // // Simple guessing game // //////////////////////////// #include #include void get_range(int * L, int * H); int create_target(int bot, int top); int get_limit(void); void play_game(int targ, int lim); void get_guess(int cnt, int * aa); int main(void){ setbuf(stdout, NULL); // printf issue with code composer char play; // flag to stop play yY int low; // range variables int high; int target; // target to guess int limit; // number of allowed tries // splash printf("##############################\n"); printf("\n"); printf("Welcome to Dr. Johnson's Guessing Game\n"); printf("\n"); printf("##############################\n"); // create conditional loop to allow/stop play play = 'y'; while((play == 'y') || (play == 'Y')){ // get the range for play get_range(&low, &high); // create the target random number target = create_target(low, high); // set limit on # of tries limit = get_limit(); // play game play_game(target, limit); // continue ? printf("Would you like to try again? y or n: "); scanf(" %c", &play); }// end while // splash printf("Thank you for playing - come back any time!"); return 0; }// end main void get_range(int * L, int * H){ // Function to get the range for the target in the game do{ printf("\nPlease enter the low and high range values for the game: "); scanf("%i %i", L, H); // note L and H are pointers so no & } while((*L < 0) || (*H < 0) || (*L >= *H)); return; }// end get_range int create_target(int bot, int top){ // function to generate the target number int tmp; int target; // create a random number 0 - RAND_MAX tmp = rand(); // scale the number to bot - top target = bot + (tmp % (top - bot)); return target; }// end create target int get_limit(void){ // function to get the number of tries int lim; printf("Please enter the maximum number of allowed tries: "); scanf("%i", &lim); return lim; }// end get_lim void play_game(int targ, int lim){ // function to allow a specific number of guesses // and test for correct or not int i; int guess; int win; // flag for winning win = 0; // default case for(i = 0; i < lim; i++){ get_guess(i, &guess); if(guess < targ) printf("too low\n"); else if(guess > targ) printf("too high\n"); else{ win = 1; i = lim - 1; // cause loop to terminate (other ways to do this) }// end if }// end for if(win == 0) printf("\nSorry but you FAILED!\n\n"); else printf("\nWINNER WINNER\n\n"); return; }// end play_game void get_guess(int cnt, int * aa){ // helper function to read in the guess printf("Guess %i: ", cnt + 1); scanf("%i", aa); // note aa is a pointer so no & return; }// end get_guess