繁体   English   中英

在ANSI C中,如何制作计时器?

[英]In ANSI C, how can I make a timer?

我正在为一个项目在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上对此进行编码。

使用标准C time()获得自纪元(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 */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM