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

brann22

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

名义动物

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章