簡體   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