Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdbool.h>
- #include <string.h>
- #include <stdlib.h>
- #include <time.h>
- #include <ctype.h>
- const int iMaxAttempts = 4;
- char output[11];
- bool bCorrect = false;
- int iAttempt = 0;
- void correct(int iRandom, int guess){
- if(guess == iRandom){
- strncpy(output,"Correct!\n", 10);
- bCorrect = true;
- }
- else if(guess < iRandom){
- strncpy(output, "Too low!\n", 10);
- bCorrect = false;
- }else if(guess > iRandom){
- strncpy(output, "Too high!\n", 11);
- bCorrect = false;
- }
- }
- void gameplay(void){
- int guess = 0,iRandom = 0;
- iAttempt = 0;
- srand(time(NULL));
- iRandom = (rand() %128) + 1;
- while(iAttempt < iMaxAttempts){
- //Asking for a number
- printf("Please enter a guess between 1 and 128 \n");
- printf("I think the number is: ");
- //get input
- scanf("%d", &guess);
- //cleaning up text so next text will be the output will be on a new line
- printf("\n");
- //checks if input is recieved
- if(guess <= 0)continue;
- iAttempt++;
- //check if number is right
- correct(iRandom, guess);
- if(bCorrect){
- printf("%s You guessed correctly within %d ties! \n", output, iAttempt);
- bCorrect= true;
- break;
- }else{
- printf("%s You have %d tries left ", output, iMaxAttempts - iAttempt);
- }
- }
- if(!bCorrect)printf("Unlucky, the random number was %d, better luck next time!\n", iRandom);
- }
- bool playAgain(void){
- char cRetry[2];
- cRetry[0] = '\0';
- while(cRetry != "y" && cRetry != "n"){
- printf("Would you like to try again? [y/n]");
- fflush(stdout);
- fgets(cRetry, 2, stdin);
- if(cRetry[0]){
- cRetry[0] = tolower(cRetry[0]);
- }
- }
- return (cRetry[0] == "y");
- }
- void printRatio(int wins, int loses, int attempts){
- printf("Wins: %d | Loses: %d | Attempts: %d \n", wins, loses, attempts);
- float avAttempts = attempts / wins;
- printf("You have a win ratio of: %d/%d and an average attempts per win of: %f \n", wins, loses, avAttempts);
- }
- int main(void){
- int *iTotalAttempts, *iTotalLoses, *iTotalWins;
- while(true){
- //Allocating memory
- iTotalAttempts = (int *)malloc(sizeof(int));
- iTotalLoses = (int *)malloc(sizeof(int));
- iTotalWins = (int *)malloc(sizeof(int));
- gameplay();
- //Reallocating memory and storying data
- if(bCorrect){
- iTotalAttempts = (int *)realloc(iTotalAttempts, sizeof(*iTotalAttempts + iAttempt));
- *iTotalAttempts+= iAttempt;
- iTotalWins = (int *)realloc(iTotalWins, sizeof(*iTotalWins + 1));
- *iTotalWins+= 1;
- }
- else{
- iTotalLoses = (int *)realloc(iTotalLoses, sizeof(*iTotalWins + 1));
- *iTotalLoses+= 1;
- }
- //checking to see if they want to play again and acting accordingly
- bool bPlayAgain = playAgain();
- if(!bPlayAgain)break;
- }
- printRatio(*iTotalWins, *iTotalLoses, *iTotalAttempts);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement