gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:17:43 25 4
gpt4 key购买 nike

我正在为一个项目用 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 语句中 Time left: 的位置。我将如何实现这一目标?我在网上看到一些其他人使用 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 */
}

关于c - 在 ANSI C 中,如何制作计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com