In ANSI C, how can I make a timer?

638 Views Asked by At

I'm making the game Boggle in C for a project. If you're not familiar with Boggle, that's okay. Long story short, there's a time limit on each round. I'm making the time limit 1 minute.

I have a loop that displays the game board and asks the user to enter a word, then calls a function that checks to see if the word is accepted, and then it loops back again.

    while (board == 1)
{

    if (board == 1)
    {
        printf(display gameboard here);
        printf("Points: %d                  Time left: \n", player1[Counter1].score);

        printf("Enter word: ");
        scanf("%15s", wordGuess);

        pts = checkWord(board, wordGuess);

The while (board == 1) needs to be changed so that it loops only for 1 minute.

I want the user to only be able to do this for 1 minute. I also would like for the time to be displayed where I have Time left: in the printf statement. How would I achieve that? I've seen some examples online of others using a timer in C and the only way I'm thinking this is possible is if I let the user go past the time limit but when the user tries to enter a word past the time limit, it will notify them that time is up. Is there any other way?

EDIT: I'm coding this on a Windows 10 PC.

1

There are 1 best solutions below

0
Nominal Animal On BEST ANSWER

Use standard C time() to obtain the number of seconds (real-world time) since Epoch (1970-01-01 00:00:00 +0000 UTC), and difftime() to count the number of seconds between two time_t values.

For the number of seconds in a game, use a constant:

#define  MAX_SECONDS  60

Then,

char    word[100];
time_t  started;
double  seconds;
int     conversions;

started = time(NULL);
while (1) {

    seconds = difftime(time(NULL), started);
    if (seconds >= MAX_SECONDS)
        break;

    /* Print the game board */

    printf("You have about %.0f seconds left. Word:", MAX_SECONDS - seconds);
    fflush(stdout);

    /* Scan one token, at most 99 characters long. */
    conversions = scanf("%99s", word);
    if (conversions == EOF)
        break;    /* End of input or read error. */
    if (conversions < 1)
        continue; /* No word scanned. */

    /* Check elapsed time */
    seconds = difftime(time(NULL), started);
    if (seconds >= MAX_SECONDS) {
        printf("Too late!\n");
        break;
    }

    /* Process the word */
}