【问题标题】:In ANSI C, how can I make a timer?在 ANSI C 中,如何制作计时器?
【发布时间】:2018-10-07 19:40:56
【问题描述】:

我正在为一个项目用 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 上编写代码。

【问题讨论】:

  • getitimer()/setitimer() API 可以帮助你。
  • 你用的是什么平台?
  • 在标准 C 中没有很好的方法;您有义务使用特定于平台的代码。因此,确定平台至关重要。
  • 对不起。我忘了说我使用的是 Windows 10。
  • ANSI C中没有关于定时器的内容,你需要调用一个API。有几种方法可以做到这一点,你可以设置一个 Timer Event,但这对于初学者来说可能太多了,你想显示剩余时间,所以看看msdn.microsoft.com/en-us/library/windows/desktop/…

标签: c timer countdown boggle


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 2013-03-26
    相关资源
    最近更新 更多