c - 在 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 上对此进行编码。
解决方案
使用标准 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 */
}
推荐阅读
- python - 如何与条形图一起显示百分比
- microsoft-teams - Teams Tab API 访问 Sharepoint 文件内容导致 405 选项调用
- javascript - 当节点js中的休息调用失败时如何超时功能?
- c# - 在 C# Mono 中以编程方式访问 Unity sharedassets.assets 文件中的项目
- azure - 无法更新数据源凭据:未找到表的“budgetAmount”列 - Power BI Azure 成本管理连接器
- r - 适用于 lapply 的函数为 parLapply 返回错误
- android - 除了 Android Emulator,如何进行虚拟设备测试?
- javascript - 我的 javascript 函数仅在 html 文件中有效,但如果将其移动到自己的文件中不起作用,为什么?
- javascript - Nest.js - 根据标头值跳过中间件
- javascript - 选择元素单击上的 JQuery 单击事件在 Linux 上的 chrome 中不起作用(Windows 上的 chrome 起作用)