I'm practicing C programming by making a simple guessing game. I found the problem in some notes and it is as follows:
"Write an application which plays a number guessing game: the program picks a random number between one and one hundred. The user then guesses the number and the program tells the user whether the number is higher or lower than their guess, until the user guesses correctly. Once the user has guessed the number correctly, the program should tell the user how many guesses it took, and offer to play the game again. The guesses become the score of the player. Minimum guesses become the highest score."
I coded the game and it works properly. I made a separate function to save the highest score (least guesses) in an external file and it works. The problem is that it rewrites the highest score every time. I thought of initializing the highest score to 1, but the number of guesses cannot be less than that. Note that the number of guesses is not limited. How can I resolve this issue?
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int readScore(void);
void saveScore(int score);
int main(){
int menu=0;
char name[16];
int counter=0;
int rand_num, score;
int guess=0;
FILE *fscore;
while(menu != 4){
printf("\n\n****** NUMBER GUESSING GAME MENU v1.0 ******\n");
printf("\t1.Create Player Name.\n\t2.Play.\n\t3.View Score.\n\t4.Quit.\n");
printf("***************************************\n");
printf("Your Choice: ");
scanf("%d", &menu);
if(menu == 1){
printf("Enter a player name: ");
scanf("%15s", name);
}
else if(menu == 2){
srand(time(NULL));
rand_num = 1 + rand()%100;
while(guess != rand_num){
printf("\nGuess the number picked: ");
scanf("%d", &guess);
if(guess > rand_num){
printf("\nNumber is smaller than your guess.");
}
else if(guess < rand_num){
printf("\nNumber is greater than your guess.");
}
counter++;
}
printf("\nYour guess is correct!!\n");
printf("Number of guesses: %d\n", counter);
if(counter < score){
saveScore(counter);
}
}
else if(menu == 3){
int score = readScore();
printf("\nThe best score is: %d\n", score);
}
}
return 0;
}
int readScore(void){
// Read the score from file
FILE *fscore = fopen("score.txt", "r");
int score=1;
fscanf(fscore, "%d", &score);
fclose(fscore);
return score;
}
void saveScore(int score){
// Save the score to file
FILE *fscore = fopen("score.txt", "w+");
fprintf(fscore, "%d", score);
fclose(fscore);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire