Ожидание нажатия клавиши определенное время - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Здравствуйте, пишу игру на си - Hit the mole. Смысл в том, что каждые 5 секунд, например, нужно генерировать число случайное, выводить на экран и ожидать ввод этого числа с клавиатуры. Как сделать ожидание нажатия клавиши в течение 5 секунд?

Решение задачи: «Ожидание нажатия клавиши определенное время»

textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define _GNU_SOURCE
#include <pthread.h>
#include <time.h>
#include <stdio_ext.h>
 
bool get_number(const char *prompt, int *num, int sec_timeout);
 
int main(void)
{
    srand(time(NULL));
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
 
    bool done = false;
    int guess;
 
    int secret = rand() % 1000 + 1;
 
    puts("I'm thinking about a number between 1 and 1000.");
 
    while(!done)
    {
        if(!get_number("Take a guess: ", &guess, 5))
        {
            puts("\nYou're late! Now I'm thinking about another number.");
            secret = rand() % 1000 + 1;
            continue;
        }
 
        if(guess < secret)
            puts("Too low, guess again!");
        else if(guess > secret)
            puts("Too high, guess again!");
        else
        {
            puts("Bingo!");
            done = true;
        }
    }
 
    exit(0);
}
 
void *thread_fun(void *args)
{
    int *num = args;
    scanf("%d", num);
    return NULL;
}
 
 
bool get_number(const char *prompt, int *num, int sec_timeout)
{
    bool got = true;
    pthread_t thread;
    struct timespec ts;
 
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += 5;
 
    fputs(prompt, stdout);
    fflush(stdout);
 
    __fpurge(stdin);
 
    pthread_create(&thread, NULL, thread_fun, num);
 
    if(pthread_timedjoin_np(thread, NULL, &ts) != 0)
    {
        got = false;
        pthread_cancel(thread);
    }
 
    __fpurge(stdin);
 
    return got;
}

Оцени полезность:

12   голосов , оценка 3.75 из 5
Похожие ответы