首页 > 解决方案 > 在 ANSI C 中,如何制作计时器?

问题描述

我正在为一个项目用 C 语言制作游戏 Boggle。如果你不熟悉 Boggle,没关系。长话短说,每一轮都有时间限制。我把时间限制在 1 分钟。

我有一个循环显示游戏板并要求用户输入一个单词,然后调用一个函数来检查该单词是否被接受,然后再次循环返回。

    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);

while (board == 1)需要更改,使其仅循环 1 分钟。

我希望用户只能执行此操作 1 分钟。我还希望将时间显示在我剩余时间的位置:printf声明中。我将如何实现这一目标?我在网上看到了一些其他人在 C 中使用计时器的例子,我认为这是可能的唯一方法是,如果我让用户超过时间限制,但是当用户尝试输入超过时间限制的单词时,它会通知他们时间到了。还有其他方法吗?

编辑:我在 Windows 10 PC 上对此进行编码。

标签: ctimercountdownboggle

解决方案


使用标准 Ctime()获取自 Epoch (1970-01-01 00:00:00 +0000 UTC) 以来的秒数(实际时间),并计算两个值difftime()之间的秒数。time_t

对于游戏中的秒数,使用一个常数:

#define  MAX_SECONDS  60

然后,

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 */
}

推荐阅读