I’ve met a problem with time function in C.
This program is a game which I just learned from a book, and its part function is: Showing user some numbers for 1 second, then hide them. But when I run this program, the numbers Never display, just be hidden directly. I put the relevant block out then the program runs properly without time function, but I can’t find the problem, I don’t know where is wrong in this block.
Here is code:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
const unsigned int delay = 1;
char play_again = 'Y';
int number = 0; // user's input;
int tries = 0; // attempt
int digits = 0; // number of digits in sequence
time_t seed = 0; // seed value for random number sequence
time_t wait_start = 0; // stores current time
bool correct = true;
int score = 0;
int total_digits = 0;
int game_time = 0;
clock_t start_time = 0;
printf("\nWelcome to this game, i think you know"
" the rules,so press enter to play:"
"remember, number only display %us!",
delay);
scanf("%c", &play_again);
do {
// initialize game
correct = true;
tries = 0;
digits = 2;
start_time = clock();
// inner loop for game
while (correct) {
++tries; // a new attempt
wait_start = clock();
// generate a sequence of digits and display them
srand(time(&seed));
for (int i = 1; i <= digits; ++i)
printf("%d ", rand() % 10); // output a random digit
/*this block has a problem but I can’t find it neither I understand
it...*/
{
// wait one second
for (; clock() - wait_start < delay * CLOCKS_PER_SEC;)
;
// overwrite the digit sequence
printf("\r");
for (int i = 1; i <= digits; i++)
printf(" ");
if (tries == 1)
printf("\nEnter the sequence\n");
else
printf("\r");
}
// input sequence and check it against the original
srand(seed); // reinitialize sequence
for (int i = 1; i <= digits; i++) {
scanf("%d", &number);
getchar();
if (number != rand() % 10) {
correct = false;
break;
}
}
// on every third successful try, increase length
if (correct && ((tries % 3) == 0))
++digits;
printf("%s\n", correct ? "Correct!" : "Wrong!");
}
// output the score when game finished
score = 10 * (digits - ((tries % 3) == 1));
total_digits = digits * (((tries % 3) == 0) ? 3 : tries % 3);
if (digits > 2)
total_digits += 3 * ((digits - 1) * (digits - 2) / 2 - 1);
game_time = (clock() - start_time) / CLOCKS_PER_SEC - tries * delay;
if (total_digits > game_time)
score += 10 * (game_time - total_digits);
printf("\n\nGame time was %ds,"
" Your score is %d\n",
game_time, score);
fflush(stdin);
// check if user required new game
printf("\nDo you want to play again?(y/n):");
scanf("%c", &play_again);
} while (tolower(play_again) == 'y');
return 0;
}